Js2Py icon indicating copy to clipboard operation
Js2Py copied to clipboard

Safe_Eval: Aborting Eval after timeout

Open prasad83 opened this issue 10 months ago • 0 comments

I wanted to abort JS code with time-limit. Here is the approach I tried. Please suggest if there better way.

import queue
import threading
import js2py
import ctypes

"""
Execute JS code using thread so execution
will be aborted after expected timeout (30 sec default).
"""
def safe_evaljs(code, timeout=30):
    # event to receive after js_run start through thread.
    js_done = threading.Event()

    # thread safe queue to track response from js_run
    js_ret_queue = queue.Queue()

    def js_run(js_code):
        try:
            js_shell = js2py.EvalJs()
            js_shell.execute(js_code)
            js_ret_queue.put("Done")
        except Exception as e:
            js_ret_queue.put(e)            
        finally:
            js_done.set()

    js_thread = threading.Thread(target=js_run, args=[code])
    js_thread.start()

    # gracefully wait for js_thread to finish through signal
    js_done.wait(timeout=timeout)

    # force kill js_thread if not done yet
    if js_thread.is_alive():
        # ctypes signal
        ctypes.pythonapi.PyThreadState_SetAsyncExc(
            ctypes.c_long(js_thread.ident), ctypes.py_object(SystemExit)
        )
        # ensure safe thread closure
        js_thread.join(timeout=1)
        js_ret_queue.put(Exception("Aborted"))

    if js_thread.is_alive():
        # todo: force kill failed.
        raise Exception("Could not abort JS Thread")

    js_ret = None
    
    while not js_ret_queue.empty():
        js_ret = js_ret_queue.get()
        if isinstance(js_ret, Exception):
            raise js_ret
        break # we are only interested in 
        
    return js_ret
    
if __name__ == "__main__":
    try:
        ret = safe_evaljs("""
            console.log("JS Started");
            while (1); /* long-blocking code */
            console.log("JS Ended");
        """)
        print (ret)
    except Exception as e:
        print (f"Error: {e}")

prasad83 avatar Feb 22 '25 05:02 prasad83