Skip to content

Commit

Permalink
FIX Check if future is done before trying to set a result on it
Browse files Browse the repository at this point in the history
Otherwise, future raises invalid state error.
Question: should we try to avoid getting to the point where we call this in the
first place??
  • Loading branch information
hoodmane committed Jun 4, 2024
1 parent f95577e commit f50144a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/core/jsproxy.c
Original file line number Diff line number Diff line change
Expand Up @@ -2637,6 +2637,7 @@ wrap_promise(JsVal promise, JsVal done_callback, PyObject* js2py_converter)
{
bool success = false;
PyObject* loop = NULL;
PyObject* helpers = NULL;
PyObject* set_result = NULL;
PyObject* set_exception = NULL;

Expand All @@ -2648,9 +2649,11 @@ wrap_promise(JsVal promise, JsVal done_callback, PyObject* js2py_converter)
result = _PyObject_CallMethodIdNoArgs(loop, &PyId_create_future);
FAIL_IF_NULL(result);

set_result = _PyObject_GetAttrId(result, &PyId_set_result);
helpers = PyImport_ImportModule("_pyodide._future_helpers");
FAIL_IF_NULL(helpers);
set_result = Py_XNewRef(PyTuple_GetItem(helpers, 0));
FAIL_IF_NULL(set_result);
set_exception = _PyObject_GetAttrId(result, &PyId_set_exception);
set_exception = Py_XNewRef(PyTuple_GetItem(helpers, 1));
FAIL_IF_NULL(set_exception);

promise = JsvPromise_Resolve(promise);
Expand All @@ -2663,6 +2666,7 @@ wrap_promise(JsVal promise, JsVal done_callback, PyObject* js2py_converter)
success = true;
finally:
Py_CLEAR(loop);
Py_CLEAR(helpers);
Py_CLEAR(set_result);
Py_CLEAR(set_exception);
if (!success) {
Expand Down
13 changes: 13 additions & 0 deletions src/py/_pyodide/_future_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def set_result(fut, val):
if fut.done():
return
fut.set_result(val)

def set_exception(fut, val):
if fut.done():
return
fut.set_result(val)


def get_future_resolvers(fut):
return (set_result.__get__(fut), set_exception.__get__(fut))

0 comments on commit f50144a

Please sign in to comment.