Diffinery

homeflare/celldpublic

212 lines · 7.5 KBRaw History
1// Entrypoint of a Python Worker bundle built by `celld deploy`.
2//
3// Adapted from workerd at commit da46ad950c54b19158c5ea5cb997a9727491ca17
4// (v1.20260926.1): src/pyodide/python-entrypoint-helper.ts. Copyright (c)
5// 2026 Cloudflare, Inc. (Apache-2.0). As there, the default export is a
6// WorkerEntrypoint class whose constructor creates one instance of the Python
7// `Default` class per invocation, `fetch` calls it with the SDK's RPC
8// conversions, and a Python awaitable given to waitUntil is kept alive
9// until it settles. Changed for celld: the interpreter comes from the
10// upstream Pyodide loader, and only `fetch` is dispatched.
11//
12// celld cannot evaluate an asynchronous module top level, so the interpreter
13// starts on the first invocation of the isolate instead of at load. Every
14// concurrent first invocation shares that one start. A failed start is kept:
15// the interpreter is never started twice in one isolate, so a callback of an
16// earlier interpreter can never reach a later one.
17import { WorkerEntrypoint } from "cloudflare:workers";
18import * as cloudflareWorkers from "cloudflare:workers";
19import * as cloudflareSockets from "cloudflare:sockets";
20import "./pyodide.asm.js";
21import { loadPyodide } from "./pyodide.mjs";
22import workerSource from "./worker.py";
23import files from "./files.bin";
24import { COMPATIBILITY_FLAGS, LOCK, MAIN_MODULE, PROCESS_PTH_FILES } from "./config.js";
25import { RUNTIME_URL } from "./shims.js";
26import { fatalGate } from "./fatal.js";
27import { condemnIsolate } from "celld:python";
28
29// A hard termination inside Wasm abandons the interpreter's frames, and
30// celld keeps the isolate in use afterwards, so the next entry would run
31// on a broken interpreter. `process.exit()` is the only termination a
32// Worker can reach itself, so it throws here instead.
33if (globalThis.process) {
34 globalThis.process.exit = function exit() {
35 throw new Error("process.exit() is not supported in Python Workers on celld");
36 };
37}
38
39// Files are `u32 count`, then for each file `u32 path length`, the UTF-8
40// path under /session/metadata, `u32 size` and the bytes (little endian).
41function unpack(bytes) {
42 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
43 const decoder = new TextDecoder();
44 let offset = 0;
45 const u32 = () => {
46 const value = view.getUint32(offset, true);
47 offset += 4;
48 return value;
49 };
50 const entries = [];
51 for (let count = u32(); count > 0; count--) {
52 const pathLength = u32();
53 const path = decoder.decode(bytes.subarray(offset, offset + pathLength));
54 offset += pathLength;
55 const size = u32();
56 entries.push([path, bytes.subarray(offset, offset + size)]);
57 offset += size;
58 }
59 return entries;
60}
61
62// Cloudflare stops the isolate on a fatal interpreter error. celld condemns
63// it instead: placement stops choosing it, and the pool frees it once the
64// calls in flight drain. The gate fails those calls and the background work,
65// and refuses any entry that still reaches this module. Callbacks that
66// Python already registered on JS promises are not fenced.
67const fatal = fatalGate();
68
69// A Python awaitable passed to waitUntil is a borrowed proxy that Python
70// releases when the call returns. Take an owned copy synchronously and
71// release it when it settles (workerd getPatchedWaitUntil). The gate ends
72// the wait on a fatal error, because the awaitable can no longer settle and
73// the invocation would otherwise stay open.
74function retaining(waitUntil) {
75 return (awaitable) => {
76 waitUntil((async () => {
77 if (awaitable && typeof awaitable.copy === "function") awaitable = awaitable.copy();
78 try {
79 await fatal.guard(awaitable);
80 } finally {
81 if (awaitable && typeof awaitable.destroy === "function") release(awaitable);
82 }
83 })());
84 };
85}
86
87const patched = new WeakSet();
88function patchWaitUntil(ctx) {
89 if (ctx === null || typeof ctx !== "object" || patched.has(ctx)) return;
90 if (typeof ctx.waitUntil !== "function") return;
91 ctx.waitUntil = retaining(ctx.waitUntil.bind(ctx));
92 patched.add(ctx);
93}
94
95const workersWaitUntil = retaining(cloudflareWorkers.waitUntil);
96const cloudflareWorkersModule = new Proxy(cloudflareWorkers, {
97 get(target, property, receiver) {
98 return property === "waitUntil"
99 ? workersWaitUntil
100 : Reflect.get(target, property, receiver);
101 },
102});
103
104const entrypointHelper = {
105 cloudflareWorkersModule,
106 cloudflareSocketsModule: cloudflareSockets,
107 patchWaitUntil,
108 doAnImport(name) {
109 throw new Error(`JavaScript module import is not supported in Python Workers on celld: ${name}`);
110 },
111 patch_env_helper() {
112 throw new Error("workers.patch_env is not supported in Python Workers on celld");
113 },
114};
115
116let started;
117function describe(error) {
118 try {
119 return String(error);
120 } catch {
121 return "an error that cannot be printed";
122 }
123}
124
125async function start() {
126 const pyodide = await loadPyodide({
127 indexURL: RUNTIME_URL,
128 lockFileContents: LOCK,
129 jsglobals: globalThis,
130 // workerd's interpreter environment. The fixed hash seed makes string
131 // hashing, and so set iteration order, match Cloudflare.
132 env: { HOME: "/session", PYTHONHASHSEED: "111" },
133 });
134 pyodide._api.on_fatal = (error) => {
135 const reason = `Python Worker fatal error: ${describe(error)}`;
136 fatal.fail(new Error(reason));
137 condemnIsolate(reason);
138 };
139 pyodide.loadPackage = () => {
140 throw new Error("pyodide.loadPackage is disabled");
141 };
142 for (const [path, contents] of unpack(files)) {
143 const full = `/session/metadata/${path}`;
144 pyodide.FS.mkdirTree(full.slice(0, full.lastIndexOf("/")));
145 pyodide.FS.writeFile(full, contents);
146 }
147 pyodide.registerJsModule("_pyodide_entrypoint_helper", entrypointHelper);
148 pyodide.registerJsModule("_cloudflare_compat_flags", COMPATIBILITY_FLAGS);
149 const namespace = pyodide.globals.get("dict")();
150 pyodide.runPython(workerSource, { globals: namespace, filename: "<celld-python-worker>" });
151 namespace.get("setup_python_search_path")(PROCESS_PTH_FILES);
152 const main = pyodide.pyimport(MAIN_MODULE);
153 return {
154 Default: namespace.get("default_entrypoint")(main),
155 callMethod: namespace.get("call_method"),
156 };
157}
158
159function runtime() {
160 if (fatal.error !== null) throw fatal.error;
161 return started ??= start();
162}
163
164// Release a proxy after a call. A release that throws in `finally` would
165// replace the call's own result or error, and the caller must see that
166// instead: a failed release costs a leaked proxy at worst, and a fatal
167// interpreter error still refuses every later entry through the gate.
168function release(proxy) {
169 if (fatal.error !== null) return;
170 try {
171 proxy.destroy();
172 } catch {
173 // Keep the call's outcome.
174 }
175}
176
177async function call(entry, name, args) {
178 const { callMethod } = await runtime();
179 const instance = await entry;
180 try {
181 if (fatal.error !== null) throw fatal.error;
182 const future = callMethod(name === "fetch", instance, name, ...args);
183 try {
184 return await fatal.guard(future);
185 } finally {
186 release(future);
187 }
188 } finally {
189 release(instance);
190 }
191}
192
193export default class Default extends WorkerEntrypoint {
194 #instance;
195
196 constructor(ctx, env) {
197 super(ctx, env);
198 this.#instance = (async () => {
199 const { Default: cls } = await runtime();
200 if (cls === undefined || cls === null) {
201 throw new Error("Handler does not export a fetch() function.");
202 }
203 return cls(ctx, env);
204 })();
205 // A failed start is reported by the method call that awaits it.
206 this.#instance.catch(() => {});
207 }
208
209 fetch(request) {
210 return call(this.#instance, "fetch", [request]);
211 }
212}