Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve minifier error handling #6

Merged
merged 2 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
""" Leaphy compiler and minifier backend webservice """
import asyncio
import tempfile
import base64
import tempfile
from os import path

import aiofiles
Expand Down Expand Up @@ -115,19 +115,27 @@ async def minify_python(program: PythonProgram, session_id: Session) -> PythonPr
sessions[session_id] += 1
try:
# Check if this code was minified before
code = base64.b64decode(program.source_code).decode()
try:
code = base64.b64decode(program.source_code).decode()
except Exception as ex:
raise HTTPException(
422, f"Unable to base64 decode program: {str(ex)}"
) from ex

cache_key = get_code_cache_key(code)
if minified_code := code_cache.get(cache_key):
# It was -> return cached result
return minified_code

# Nope -> minify and store in cache
async with semaphore:
program.source_code = base64.b64encode(
minify(
code, filename=program.filename, remove_annotations=False
).encode()
)
try:
code = minify(code, filename=program.filename, remove_annotations=False)
except Exception as ex:
raise HTTPException(
422, f"Unable to minify python program: {str(ex)}"
) from ex
program.source_code = base64.b64encode(code.encode())
code_cache[cache_key] = program
return program
finally:
Expand Down
2 changes: 1 addition & 1 deletion models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ class Sketch(BaseModel):
class PythonProgram(BaseModel):
"""Model representing a python program"""

source_code: str # Base64 encoded program
source_code: bytes # Base64 encoded program
filename: str = ""