Skip to content

Commit

Permalink
Python workers: Better error handling when the handler is not defined (
Browse files Browse the repository at this point in the history
  • Loading branch information
hoodmane authored Feb 7, 2025
1 parent 6d7815a commit b51f49e
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/pyodide/python-entrypoint-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,14 @@ function makeHandler(pyHandlerName: string): Handler {
'prep_python',
async () => await preparePython()
);

const handler = mainModule[pyHandlerName];
if (!handler) {
throw new Error(
`Python entrypoint "${MAIN_MODULE_NAME}" does not export a handler named "${pyHandlerName}"`
);
}
const result = await enterJaegerSpan('python_code', () => {
return mainModule[pyHandlerName].callRelaxed(...args);
return handler.callRelaxed(...args);
});

// Support returning a pyodide.ffi.FetchResponse.
Expand Down
9 changes: 9 additions & 0 deletions src/workerd/server/tests/python/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,12 @@ gen_import_tests(
],
},
)

py_wd_test(
"undefined-handler",
# TODO: Requires a new bundle deploy
skip_python_flags = [
"0.26.0a2",
"0.27.1",
],
)
2 changes: 2 additions & 0 deletions src/workerd/server/tests/python/undefined-handler/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def test():
pass
11 changes: 11 additions & 0 deletions src/workerd/server/tests/python/undefined-handler/server.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { rejects } from 'node:assert';

export default {
async test(ctrl, env) {
await rejects(env.pythonWorker.fetch(new Request('http://example.com')), {
name: 'Error',
message:
'Python entrypoint "undefined_handler.py" does not export a handler named "on_fetch"',
});
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Workerd = import "/workerd/workerd.capnp";

const undefinedHandler :Workerd.Worker = (
modules = [
(name = "undefined_handler.py", pythonModule = embed "undefined_handler.py")
],
compatibilityDate = "2024-10-01",
compatibilityFlags = [%PYTHON_FEATURE_FLAGS],
);

const server :Workerd.Worker = (
modules = [
(name = "server.js", esModule = embed "server.mjs")
],
bindings = [
( name = "pythonWorker", service = "undefinedHandler" ),
],
compatibilityDate = "2024-10-01",
compatibilityFlags = ["nodejs_compat"],
);


const unitTests :Workerd.Config = (
services = [
( name = "external",
network = (
tlsOptions = (trustBrowserCas = true)
)
),
( name = "server",
worker = .server
),
( name = "undefinedHandler",
worker = .undefinedHandler
),
],
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def test():
pass

0 comments on commit b51f49e

Please sign in to comment.