Skip to content

Commit 90ce1c2

Browse files
committed
catch timeouts in solution code
1 parent 55160d7 commit 90ce1c2

2 files changed

Lines changed: 34 additions & 3 deletions

File tree

public/main.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# main.py
22
from pyscript import PyWorker, document, window
3+
import js
34

45
# ---- Initialize Ace Editor from Python ----
56
# Create the editor
@@ -21,9 +22,40 @@
2122
await worker.ready
2223

2324
async def run(event):
25+
global worker
26+
2427
code = editor.getValue()
25-
result = await worker.sync.evaluate(code)
26-
document.getElementById("output").innerText = f"Results:\n {result}"
28+
document.getElementById("output").innerText = "⏳ Running..."
29+
30+
# ---- TIMEOUT HANDLING ----
31+
timeout_ms = 1500 # 1.5 second limit
32+
33+
# Create a promise that wraps worker.sync.evaluate
34+
eval_promise = worker.sync.evaluate(code)
35+
36+
# Create the timeout promise
37+
timeout_promise = window.Promise.new(
38+
lambda resolve, reject:
39+
window.setTimeout(lambda: reject(Exception("timeout")), timeout_ms)
40+
)
41+
42+
try:
43+
# Race the worker call vs. timeout
44+
result = await window.Promise.race([eval_promise, timeout_promise])
45+
46+
document.getElementById("output").innerText = f"{result}"
47+
48+
except Exception as e:
49+
if str(e) == "Error: timeout":
50+
# ---- Worker hung. Kill it. ----
51+
worker.terminate()
52+
worker = make_worker() # start fresh
53+
await worker.ready
54+
document.getElementById("output").innerText = (
55+
"💥 Your code took too long (possible infinite loop). Worker reset."
56+
)
57+
else:
58+
document.getElementById("output").innerText = f"💥 Error: {e}"
2759

2860
document.getElementById("run").addEventListener("click", run)
2961

public/worker.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ def check_for_multiplication(code):
1818

1919
def evaluate(code):
2020
code = code.replace("\t", " ")
21-
print(code)
2221
namespace = {}
2322
try:
2423
exec(code, namespace)

0 commit comments

Comments
 (0)