| 1 | // The DO object model and the Cloudflare-compatible runtime surface, run |
| 2 | // once per isolate by `js.rs::install_harness` after the Web-API prelude. |
| 3 | // Lived as a 4,000-line raw string inside js.rs until 2026-07-29; it is a |
| 4 | // JavaScript program and belongs in a .js file, like the rest of src/js/. |
| 5 | function __bodyBytes(body) { |
| 6 | if (body == null) return new Uint8Array(); |
| 7 | if (body && body.__celldBodyBytes instanceof Uint8Array) |
| 8 | return body.__celldBodyBytes.slice(); |
| 9 | if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0)); |
| 10 | if (ArrayBuffer.isView(body)) |
| 11 | return new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice(); |
| 12 | return new TextEncoder().encode(String(body)); |
| 13 | } |
| 14 | // Bodies that carry their own Content-Type. A Blob's is its `type`, a |
| 15 | // FormData serializes to multipart with a generated boundary, and a |
| 16 | // URLSearchParams to urlencoded. Returns null for every other body so the |
| 17 | // caller falls through to __bodyBytes. Blob, File, FormData and |
| 18 | // URLSearchParams are all installed later in this file; this runs per |
| 19 | // request, long after that. |
| 20 | function __typedBody(body) { |
| 21 | if (body == null || typeof body !== "object") return null; |
| 22 | if (globalThis.Blob && body instanceof Blob) |
| 23 | return { bytes: body._bytes.slice(), type: body.type }; |
| 24 | if (globalThis.FormData && body instanceof FormData) |
| 25 | return __multipartBody(body); |
| 26 | if (globalThis.URLSearchParams && body instanceof URLSearchParams) |
| 27 | return { |
| 28 | bytes: new TextEncoder().encode(String(body)), |
| 29 | type: "application/x-www-form-urlencoded;charset=UTF-8", |
| 30 | }; |
| 31 | return null; |
| 32 | } |
| 33 | // The WHATWG escape for a multipart field name or filename. It is one-way: |
| 34 | // a parser does not undo it, so a name containing a quote round-trips as |
| 35 | // `%22` rather than the original character. |
| 36 | function __mimeEscape(value) { |
| 37 | value = String(value); |
| 38 | // A trailing backslash would escape the closing quote of the parameter and |
| 39 | // run the header into the part body, so it is refused rather than encoded. |
| 40 | // Workerd refuses it with this exact message. |
| 41 | if (value.endsWith("\\")) |
| 42 | throw new TypeError("Name or filename can't end with backslash"); |
| 43 | return value |
| 44 | .replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); |
| 45 | } |
| 46 | // Serialize a FormData into a multipart/form-data body. The boundary must |
| 47 | // not occur in any part; 16 random bytes make that collision unreachable, |
| 48 | // and the delimiter stays unquoted so a `boundary=` parameter needs no |
| 49 | // quoting. |
| 50 | function __multipartBody(form) { |
| 51 | const random = new Uint8Array(16); |
| 52 | if (globalThis.crypto && crypto.getRandomValues) crypto.getRandomValues(random); |
| 53 | else for (let i = 0; i < random.length; i++) |
| 54 | random[i] = Math.floor(Math.random() * 256); |
| 55 | const boundary = "----celldFormBoundary" + |
| 56 | Array.from(random, (byte) => byte.toString(16).padStart(2, "0")).join(""); |
| 57 | const encoder = new TextEncoder(); |
| 58 | const chunks = []; |
| 59 | for (const [name, value] of form) { |
| 60 | let header = `--${boundary}\r\nContent-Disposition: form-data; name="${ |
| 61 | __mimeEscape(name) |
| 62 | }"`; |
| 63 | if (value instanceof Blob) { |
| 64 | header += `; filename="${__mimeEscape(value.name)}"`; |
| 65 | header += `\r\nContent-Type: ${value.type || "application/octet-stream"}`; |
| 66 | } |
| 67 | chunks.push(encoder.encode(`${header}\r\n\r\n`)); |
| 68 | chunks.push(value instanceof Blob ? value._bytes : encoder.encode(value)); |
| 69 | chunks.push(encoder.encode("\r\n")); |
| 70 | } |
| 71 | chunks.push(encoder.encode(`--${boundary}--\r\n`)); |
| 72 | let total = 0; |
| 73 | for (const chunk of chunks) total += chunk.byteLength; |
| 74 | const bytes = new Uint8Array(total); |
| 75 | let offset = 0; |
| 76 | for (const chunk of chunks) { |
| 77 | bytes.set(chunk, offset); |
| 78 | offset += chunk.byteLength; |
| 79 | } |
| 80 | return { bytes, type: `multipart/form-data; boundary=${boundary}` }; |
| 81 | } |
| 82 | function __chunkBytes(chunk) { |
| 83 | if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk); |
| 84 | if (ArrayBuffer.isView(chunk)) |
| 85 | return new Uint8Array( |
| 86 | chunk.buffer, chunk.byteOffset, chunk.byteLength); |
| 87 | throw new TypeError( |
| 88 | "Iterable bodies must produce ArrayBuffer or " + |
| 89 | "ArrayBufferView chunks"); |
| 90 | } |
| 91 | // Workerd's "gen" bodies: async iterables become a body stream; |
| 92 | // sync iterables of buffers/views concatenate eagerly. Called only |
| 93 | // for object bodies that are not streams or Blobs -- an object with |
| 94 | // a custom toString/@@toPrimitive stringifies instead, unless it is |
| 95 | // an array or async-iterable (Workerd's precedence). Returns null |
| 96 | // for the string-coercion path. |
| 97 | function __iterableBody(body) { |
| 98 | if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) |
| 99 | return null; |
| 100 | const asyncIter = body[Symbol.asyncIterator]; |
| 101 | if (typeof asyncIter === "function") { |
| 102 | const iterator = asyncIter.call(body); |
| 103 | return new ReadableStream({ |
| 104 | async pull(controller) { |
| 105 | const result = await iterator.next(); |
| 106 | if (result.done) { controller.close(); return; } |
| 107 | controller.enqueue(__chunkBytes(result.value)); |
| 108 | }, |
| 109 | cancel(reason) { |
| 110 | if (typeof iterator.return === "function") |
| 111 | iterator.return(reason); |
| 112 | }, |
| 113 | }, { highWaterMark: 0 }); |
| 114 | } |
| 115 | if (!Array.isArray(body) && |
| 116 | (body.toString !== Object.prototype.toString || |
| 117 | body[Symbol.toPrimitive] !== undefined)) |
| 118 | return null; |
| 119 | if (typeof body[Symbol.iterator] !== "function") return null; |
| 120 | const chunks = []; |
| 121 | let length = 0; |
| 122 | for (const chunk of body) { |
| 123 | if (!(chunk instanceof ArrayBuffer) && !ArrayBuffer.isView(chunk)) |
| 124 | return null; |
| 125 | const view = __chunkBytes(chunk); |
| 126 | chunks.push(view); |
| 127 | length += view.byteLength; |
| 128 | } |
| 129 | const bytes = new Uint8Array(length); |
| 130 | let offset = 0; |
| 131 | for (const view of chunks) { |
| 132 | bytes.set(view, offset); |
| 133 | offset += view.byteLength; |
| 134 | } |
| 135 | return bytes; |
| 136 | } |
| 137 | // Drain a Request/Response body stream, caching the result on the |
| 138 | // instance so later consumers see the materialized bytes. |
| 139 | async function __drainBody(target) { |
| 140 | const chunks = []; |
| 141 | let length = 0; |
| 142 | const reader = target.body.getReader(); |
| 143 | for (;;) { |
| 144 | const result = await reader.read(); |
| 145 | if (result.done) break; |
| 146 | chunks.push(result.value); |
| 147 | length += result.value.byteLength; |
| 148 | } |
| 149 | const bytes = new Uint8Array(length); |
| 150 | let offset = 0; |
| 151 | for (const chunk of chunks) { |
| 152 | bytes.set(chunk, offset); |
| 153 | offset += chunk.byteLength; |
| 154 | } |
| 155 | target._bodyBytes = bytes; |
| 156 | // text() memoizes into _body on demand. Decoding here charges every |
| 157 | // binary passthrough the cost of a string it never reads. |
| 158 | target._body = undefined; |
| 159 | return bytes; |
| 160 | } |
| 161 | class CelldBodyStream extends ReadableStream { |
| 162 | constructor(owner) { |
| 163 | // Couple the stream to its buffered owner, so _bodyBytes and the stream |
| 164 | // cannot be installed from different arrays. Copying the owner's bytes |
| 165 | // again here doubles the external memory held for every constructed body. |
| 166 | if (!(owner instanceof globalThis.Request) && |
| 167 | !(owner instanceof globalThis.Response)) |
| 168 | throw new TypeError("CelldBodyStream requires a buffered body owner"); |
| 169 | const bytes = owner._bodyBytes; |
| 170 | if (!(bytes instanceof Uint8Array)) |
| 171 | throw new TypeError("CelldBodyStream owner requires buffered body bytes"); |
| 172 | const st = { bytes, off: 0 }; |
| 173 | super({ |
| 174 | pull(controller) { |
| 175 | if (st.off >= st.bytes.byteLength) { |
| 176 | controller.close(); |
| 177 | return; |
| 178 | } |
| 179 | const end = Math.min(st.off + 64 * 1024, st.bytes.byteLength); |
| 180 | controller.enqueue(st.bytes.subarray(st.off, end)); |
| 181 | st.off = end; |
| 182 | }, |
| 183 | }, { highWaterMark: 0 }); |
| 184 | this._st = st; |
| 185 | this.__celldBodyBytes = bytes; |
| 186 | // Known length, so re-using this stream as a subrequest body |
| 187 | // still advertises Content-Length. |
| 188 | this._expectedLength = bytes.byteLength; |
| 189 | } |
| 190 | get __celldBodyText() { return new TextDecoder().decode(this.__celldBodyBytes); } |
| 191 | // Workerd body streams are internal streams, so BYOB readers |
| 192 | // work on them. Naming ReadableStreamBYOBReader compiles the |
| 193 | // lazy byte-stream prelude; a worker that never asks for byob |
| 194 | // mode never pays for it. |
| 195 | getReader(options) { |
| 196 | if (options !== undefined && options !== null && |
| 197 | options.mode !== undefined) { |
| 198 | if (String(options.mode) !== "byob") |
| 199 | throw new TypeError(`Invalid reader mode '${options.mode}'`); |
| 200 | if (this._ictl === undefined) |
| 201 | this._ictl = ReadableStreamBYOBReader._buffered(this._st); |
| 202 | return new ReadableStreamBYOBReader(this); |
| 203 | } |
| 204 | return super.getReader(options); |
| 205 | } |
| 206 | // Cancelling a body stream poisons later consumption: text() |
| 207 | // and friends reject, as they would over a real socket. |
| 208 | _cancel(reason) { |
| 209 | this._cancelled = true; |
| 210 | return super._cancel(reason); |
| 211 | } |
| 212 | } |
| 213 | class CelldHttpBodyStream extends ReadableStream { |
| 214 | constructor(streamId) { |
| 215 | const id = Number(streamId); |
| 216 | super({ |
| 217 | async pull(controller) { |
| 218 | // A chunk arrives as a Uint8Array. The host moves it in without |
| 219 | // a copy. The end of the stream arrives as a string. |
| 220 | const chunk = await __http_stream_read(id); |
| 221 | if (typeof chunk === "string") controller.close(); |
| 222 | else controller.enqueue(chunk); |
| 223 | }, |
| 224 | cancel() { __http_stream_cancel(id); }, |
| 225 | }, { highWaterMark: 0 }); |
| 226 | this.__celldStreamId = id; |
| 227 | } |
| 228 | tee() { |
| 229 | if (this.locked) throw new TypeError("ReadableStream is locked"); |
| 230 | this._locked = true; |
| 231 | this._disturbed = true; |
| 232 | const [left, right] = JSON.parse( |
| 233 | __http_stream_tee(this.__celldStreamId), |
| 234 | ); |
| 235 | return [ |
| 236 | new CelldHttpBodyStream(left), |
| 237 | new CelldHttpBodyStream(right), |
| 238 | ]; |
| 239 | } |
| 240 | } |
| 241 | // Body streams expose the standard constructor to consumers. In particular, |
| 242 | // the Python Workers SDK validates JS body types by constructor.name. |
| 243 | // Keep the internal prototypes and their specialized read/tee behavior. |
| 244 | for (const bodyStream of [CelldBodyStream, CelldHttpBodyStream]) { |
| 245 | Object.defineProperty(bodyStream.prototype, "constructor", { |
| 246 | value: ReadableStream, writable: true, configurable: true, |
| 247 | }); |
| 248 | } |
| 249 | globalThis.Response = class Response { |
| 250 | constructor(body, init = {}) { |
| 251 | // Streaming/iterable detection runs only for object bodies, so |
| 252 | // the common string path skips every instanceof below. |
| 253 | let stream = null; |
| 254 | let typed = null; |
| 255 | if (body !== null && typeof body === "object") { |
| 256 | if (body instanceof ReadableStream) stream = body; |
| 257 | else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ } |
| 258 | else { |
| 259 | const iterable = __iterableBody(body); |
| 260 | if (iterable instanceof ReadableStream) stream = iterable; |
| 261 | else if (iterable !== null) body = iterable; |
| 262 | } |
| 263 | } |
| 264 | this._bodyBytes = stream !== null |
| 265 | ? null |
| 266 | : typed ? typed.bytes : __bodyBytes(body); |
| 267 | // Never decoded eagerly: a whole-body UTF-8 decode costs seconds for a |
| 268 | // large binary body (an archive, a git pack) and can exceed V8's string |
| 269 | // length. On Response the field is deliberately write-only -- text() |
| 270 | // decodes fresh from _bodyBytes and only Request.text() memoizes into |
| 271 | // _body -- but the assignment stays: __drainBody and __adoptBody assign |
| 272 | // _body on both classes, so defining it here keeps the hidden-class |
| 273 | // shape stable. Do not add a Response reader; do not "simplify" this |
| 274 | // away. |
| 275 | this._body = undefined; |
| 276 | // Hono rebuilds a response after middleware with |
| 277 | // `new Response(response.body, response)`; the held stream (or a |
| 278 | // fresh CelldBodyStream) preserves the payload across that |
| 279 | // standard clone shape. |
| 280 | this.body = body == null |
| 281 | ? null |
| 282 | : stream !== null |
| 283 | ? stream |
| 284 | : new CelldBodyStream(this); |
| 285 | this.status = init.status === undefined ? 200 : Number(init.status); |
| 286 | this.statusText = init.statusText === undefined ? "" : String(init.statusText); |
| 287 | this.headers = new Headers(init.headers); |
| 288 | if (typed && typed.type && !this.headers.has("content-type")) |
| 289 | this.headers.set("content-type", typed.type); |
| 290 | this.webSocket = init.webSocket ?? null; |
| 291 | this._wsTarget = init.__wsTarget || init._wsTarget || null; |
| 292 | this.ok = this.status >= 200 && this.status <= 299; |
| 293 | this.redirected = false; |
| 294 | this.type = "default"; |
| 295 | this.url = ""; |
| 296 | this.bodyUsed = false; |
| 297 | if (init.cf !== undefined) this.cf = init.cf; |
| 298 | } |
| 299 | static json(data, init = {}) { |
| 300 | const headers = new Headers(init.headers || {}); |
| 301 | if (!headers.has("content-type")) |
| 302 | headers.set("content-type", "application/json"); |
| 303 | return new Response(JSON.stringify(data), { ...init, headers }); |
| 304 | } |
| 305 | static redirect(url, status = 302) { |
| 306 | const input = String(url); |
| 307 | const statusCode = Number(status) | 0; |
| 308 | if (![301, 302, 303, 307, 308].includes(statusCode)) { |
| 309 | throw new RangeError( |
| 310 | `${statusCode} is not a redirect status code. ` + |
| 311 | "It must be one of: 301, 302, 303, 307, or 308."); |
| 312 | } |
| 313 | const response = new Response(null, { |
| 314 | status: statusCode, |
| 315 | headers: { Location: new URL(input).href }, |
| 316 | }); |
| 317 | // A redirect response owns a guarded header list. Without the guard, an |
| 318 | // application can rewrite Location after construction, which differs |
| 319 | // from both Fetch and Workerd even though the initial response is valid. |
| 320 | Object.defineProperty(response.headers, "_immutable", { value: true }); |
| 321 | return response; |
| 322 | } |
| 323 | static error() { |
| 324 | const response = new Response(null); |
| 325 | response.status = 0; |
| 326 | response.ok = false; |
| 327 | response.type = "error"; |
| 328 | return response; |
| 329 | } |
| 330 | async _consume() { |
| 331 | if (this._bodyBytes !== null) { |
| 332 | if (this.body !== null && this.body._cancelled) |
| 333 | throw new TypeError( |
| 334 | "Body has already been used. It can only be used once. " + |
| 335 | "Use tee() first if you need to read it multiple times."); |
| 336 | return this._bodyBytes; |
| 337 | } |
| 338 | return __drainBody(this); |
| 339 | } |
| 340 | async text() { |
| 341 | this.bodyUsed = true; |
| 342 | return new TextDecoder().decode(await this._consume()); |
| 343 | } |
| 344 | async json() { return JSON.parse(await this.text()); } |
| 345 | async formData() { |
| 346 | // The undecoded bytes, not `text()`: a UTF-8 decode replaces each invalid |
| 347 | // sequence in a binary file part with one U+FFFD, so both the bytes and |
| 348 | // the length change. |
| 349 | this.bodyUsed = true; |
| 350 | return __celld.__parseFormData( |
| 351 | await this._consume(), this.headers.get('content-type')); |
| 352 | } |
| 353 | async arrayBuffer() { |
| 354 | this.bodyUsed = true; |
| 355 | return (await this._consume()).slice().buffer; |
| 356 | } |
| 357 | async blob() { |
| 358 | return new Blob([await this.arrayBuffer()], |
| 359 | { type: this.headers.get("content-type") || "" }); |
| 360 | } |
| 361 | clone() { |
| 362 | if (this.bodyUsed) throw new TypeError("Body has already been consumed"); |
| 363 | // Streaming body (Homeflare patch): tee it as Request.clone() does and |
| 364 | // as workerd does, keeping one branch and giving the clone the other. |
| 365 | // `cache.put(key, response.clone())` on a fetched response is the usual |
| 366 | // case. |
| 367 | let clonedBody; |
| 368 | if (this.body === null) clonedBody = null; |
| 369 | else if (this._bodyBytes === null) { |
| 370 | const [left, right] = this.body.tee(); |
| 371 | this.body = left; |
| 372 | clonedBody = right; |
| 373 | } else clonedBody = this._bodyBytes; |
| 374 | const response = new Response( |
| 375 | clonedBody, |
| 376 | { |
| 377 | status: this.status, statusText: this.statusText, headers: this.headers, |
| 378 | webSocket: this.webSocket, __wsTarget: this._wsTarget, cf: this.cf, |
| 379 | }, |
| 380 | ); |
| 381 | response.type = this.type; |
| 382 | return response; |
| 383 | } |
| 384 | }; |
| 385 | // Hoisted: this would otherwise allocate an array and scan it on |
| 386 | // every Request construction, which is the HTTP hot path. |
| 387 | const __HTTP_METHODS = new Set( |
| 388 | ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]); |
| 389 | const __FETCH_REDIRECT_MODES = new Set(["follow", "manual", "error"]); |
| 390 | globalThis.Request = class Request { |
| 391 | constructor(input, init = {}) { |
| 392 | const prior = input instanceof Request ? input : null; |
| 393 | const suppliedSignal = init.signal !== undefined; |
| 394 | // The cache option needs the cache_option_enabled compat flag, |
| 395 | // which Cells does not implement (Workerd's cache-disabled path). |
| 396 | if (init.cache !== undefined) |
| 397 | throw new Error("The 'cache' field on 'RequestInitializerDict' " + |
| 398 | "is not implemented."); |
| 399 | this.url = prior ? prior.url : String(input); |
| 400 | { |
| 401 | // Workers upper-cases every method (the |
| 402 | // upper_case_all_http_methods flag) but rejects anything outside |
| 403 | // the known set, reporting the original casing. |
| 404 | const raw = String(init.method === undefined |
| 405 | ? (prior ? prior.method : "GET") : init.method); |
| 406 | const upper = raw.toUpperCase(); |
| 407 | if (!__HTTP_METHODS.has(upper)) |
| 408 | throw new TypeError(`Invalid HTTP method string: ${raw}`); |
| 409 | this.method = upper; |
| 410 | } |
| 411 | const hasBody = |
| 412 | Object.prototype.hasOwnProperty.call(init, "body"); |
| 413 | let body = hasBody ? init.body : null; |
| 414 | let stream = null; |
| 415 | let typed = null; |
| 416 | if (hasBody && body !== null && typeof body === "object") { |
| 417 | if (body instanceof ReadableStream) stream = body; |
| 418 | else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ } |
| 419 | else { |
| 420 | const iterable = __iterableBody(body); |
| 421 | if (iterable instanceof ReadableStream) stream = iterable; |
| 422 | else if (iterable !== null) body = iterable; |
| 423 | } |
| 424 | } |
| 425 | if (!hasBody && prior && prior._bodyBytes === null) { |
| 426 | // Adopt the prior request's stream; per spec the prior body |
| 427 | // is disturbed by the new request. |
| 428 | stream = prior.body; |
| 429 | prior.bodyUsed = true; |
| 430 | } |
| 431 | this._bodyBytes = stream !== null |
| 432 | ? null |
| 433 | : hasBody |
| 434 | ? (typed ? typed.bytes : __bodyBytes(body)) |
| 435 | : (prior ? prior._bodyBytes.slice() : new Uint8Array()); |
| 436 | // Body text is decoded on the first text()/json(), not here: a request |
| 437 | // whose body is never read never pays the decode. |
| 438 | this._body = undefined; |
| 439 | // Headers are stored raw and built on the first `.headers` access. The |
| 440 | // hot paths -- a hello world, a Worker that only forwards to a cell -- |
| 441 | // read none, so `new Headers` and the JSON.parse behind it never run. |
| 442 | if (init.__headersJson !== undefined) { |
| 443 | this._headersJson = init.__headersJson; |
| 444 | this._headersInit = undefined; |
| 445 | } else if (init.headers === undefined && prior) { |
| 446 | this._headersJson = prior._headersJson; |
| 447 | // Per spec `new Request(request)` copies the header list. The prior |
| 448 | // request's `Headers` object cannot stand in for it: `new Headers(h)` |
| 449 | // reads `h` through its iterator, which sorts, lower-cases and |
| 450 | // combines, so forwarding a request whose headers were read would |
| 451 | // undo the wire shape the outbound paths preserve. |
| 452 | this._headersInit = prior._headers |
| 453 | ? prior._headers.__celldHeaderList |
| 454 | : prior._headersInit; |
| 455 | } else { |
| 456 | this._headersJson = undefined; |
| 457 | this._headersInit = init.headers; |
| 458 | } |
| 459 | this._headers = null; |
| 460 | // A typed body's default content-type must land now; only user-built |
| 461 | // typed bodies reach this, never the incoming request path. |
| 462 | if (typed && typed.type && !this.headers.has("content-type")) { |
| 463 | this.headers.set("content-type", typed.type); |
| 464 | } |
| 465 | this.bodyUsed = false; |
| 466 | // The body stream and the signal stay eager, own properties: the RPC and |
| 467 | // storage serializers fall back to the lift-into-marker path only when a |
| 468 | // value is not directly structured-cloneable, and a Request's un-cloneable |
| 469 | // body stream (or AbortSignal) is what triggers that. Making them lazy |
| 470 | // getters let `__sc_encode` clone the Request into a broken plain object |
| 471 | // and skip the lift -- the serializeHttpTypes conformance failure. |
| 472 | this.body = stream !== null |
| 473 | ? stream |
| 474 | : ["GET", "HEAD"].includes(this.method) |
| 475 | ? null : new CelldBodyStream(this); |
| 476 | this.redirect = String(init.redirect === undefined |
| 477 | ? (prior ? prior.redirect : "follow") |
| 478 | : init.redirect); |
| 479 | if (!__FETCH_REDIRECT_MODES.has(this.redirect)) { |
| 480 | throw new TypeError(`Invalid redirect mode: ${this.redirect}`); |
| 481 | } |
| 482 | const cf = init.cf === undefined |
| 483 | ? (prior ? prior.cf : undefined) : init.cf; |
| 484 | if (cf !== undefined) this.cf = cf; |
| 485 | this.signal = suppliedSignal |
| 486 | ? init.signal |
| 487 | : (prior ? prior.signal : new AbortController().signal); |
| 488 | this._signalForSubrequests = init.__celldIncomingSignal |
| 489 | ? null |
| 490 | : suppliedSignal |
| 491 | ? this.signal |
| 492 | : (prior ? prior._signalForSubrequests : null); |
| 493 | } |
| 494 | get headers() { |
| 495 | if (this._headers === null) { |
| 496 | const src = this._headersJson !== undefined |
| 497 | ? JSON.parse(this._headersJson) |
| 498 | : this._headersInit; |
| 499 | this._headers = new Headers(src); |
| 500 | this._headersJson = undefined; |
| 501 | this._headersInit = undefined; |
| 502 | } |
| 503 | return this._headers; |
| 504 | } |
| 505 | set headers(value) { |
| 506 | this._headers = value instanceof Headers ? value : new Headers(value); |
| 507 | this._headersJson = undefined; |
| 508 | this._headersInit = undefined; |
| 509 | } |
| 510 | async _consume() { |
| 511 | if (this._bodyBytes !== null) return this._bodyBytes; |
| 512 | return __drainBody(this); |
| 513 | } |
| 514 | async text() { |
| 515 | this.bodyUsed = true; |
| 516 | const bytes = await this._consume(); |
| 517 | return this._body ??= new TextDecoder().decode(bytes); |
| 518 | } |
| 519 | async json() { return JSON.parse(await this.text()); } |
| 520 | async formData() { |
| 521 | // The undecoded bytes, not `text()`: a UTF-8 decode replaces each invalid |
| 522 | // sequence in a binary file part with one U+FFFD, so both the bytes and |
| 523 | // the length change. |
| 524 | this.bodyUsed = true; |
| 525 | return __celld.__parseFormData( |
| 526 | await this._consume(), this.headers.get('content-type')); |
| 527 | } |
| 528 | async arrayBuffer() { |
| 529 | this.bodyUsed = true; |
| 530 | return (await this._consume()).slice().buffer; |
| 531 | } |
| 532 | async blob() { |
| 533 | return new Blob([await this.arrayBuffer()], |
| 534 | { type: this.headers.get("content-type") || "" }); |
| 535 | } |
| 536 | clone() { |
| 537 | if (this.bodyUsed) throw new TypeError("Body has already been consumed"); |
| 538 | if (this._bodyBytes === null) { |
| 539 | // Streaming body: tee, keep one branch, clone the other. |
| 540 | const [left, right] = this.body.tee(); |
| 541 | this.body = left; |
| 542 | return new Request(this, { body: right }); |
| 543 | } |
| 544 | return new Request(this); |
| 545 | } |
| 546 | }; |
| 547 | const __makeRequest = __celld.__makeRequest = ( |
| 548 | url, method, body, headersJson = "[]", signal = undefined, |
| 549 | incomingSignal = false, |
| 550 | ) => new Request(url, { |
| 551 | // The raw header JSON, not a parsed object: an incoming request whose |
| 552 | // handler never reads `.headers` (a hello world, or a Worker that only |
| 553 | // routes to a cell) then never parses it. See `get headers()`. |
| 554 | // celld cannot prove Cloudflare edge metadata, so the object stays empty. |
| 555 | // In particular, no client-controlled header becomes a country or a colo; |
| 556 | // the forwarded-authority trust flag does not establish geolocation trust. |
| 557 | method, body, __headersJson: headersJson, signal, cf: {}, |
| 558 | __celldIncomingSignal: incomingSignal, |
| 559 | }); |
| 560 | const __fmt = (a) => a.map((x) => { |
| 561 | if (typeof x === "string") return x; |
| 562 | if (x instanceof Error) return x.stack || (x.name + ": " + x.message); |
| 563 | try { return JSON.stringify(x); } catch { return String(x); } |
| 564 | }).join(" "); |
| 565 | const __consoleNoop = () => {}; |
| 566 | globalThis.console = { |
| 567 | debug: (...a) => __log("debug", __fmt(a)), |
| 568 | error: (...a) => __log("error", __fmt(a)), |
| 569 | info: (...a) => __log("info", __fmt(a)), |
| 570 | log: (...a) => __log("log", __fmt(a)), |
| 571 | warn: (...a) => __log("warn", __fmt(a)), |
| 572 | clear: __consoleNoop, |
| 573 | count: __consoleNoop, |
| 574 | group: __consoleNoop, |
| 575 | table: __consoleNoop, |
| 576 | trace: __consoleNoop, |
| 577 | assert: __consoleNoop, |
| 578 | countReset: __consoleNoop, |
| 579 | dir: __consoleNoop, |
| 580 | dirxml: __consoleNoop, |
| 581 | groupCollapsed: __consoleNoop, |
| 582 | groupEnd: __consoleNoop, |
| 583 | profile: __consoleNoop, |
| 584 | profileEnd: __consoleNoop, |
| 585 | time: __consoleNoop, |
| 586 | timeEnd: __consoleNoop, |
| 587 | timeLog: __consoleNoop, |
| 588 | timeStamp: __consoleNoop, |
| 589 | createTask: () => { |
| 590 | throw new Error("console.createTask() is not implemented"); |
| 591 | }, |
| 592 | }; |
| 593 | |
| 594 | // async-op shims: outbound fetch + timers, driven by the host event loop. |
| 595 | // Move one request body through a host subrequest seam. A body that already |
| 596 | // names a host stream keeps that stream incremental. An ordinary JavaScript |
| 597 | // stream has no host owner, so it uses the existing byte fallback. |
| 598 | const __subrequestBody = async (req, absent = false) => { |
| 599 | if (absent) return { body: undefined, streamId: undefined }; |
| 600 | if (req._bodyBytes !== null) |
| 601 | return { body: req._bodyBytes, streamId: undefined }; |
| 602 | const streamId = req.body?.__celldStreamId; |
| 603 | if (streamId === undefined) { |
| 604 | req.bodyUsed = true; |
| 605 | return { body: await req._consume(), streamId: undefined }; |
| 606 | } |
| 607 | // The receiver now owns the one host source. Lock the wrapper so a later |
| 608 | // read fails instead of racing the receiver, and expose the transfer through |
| 609 | // the standard Body flag. |
| 610 | req.bodyUsed = true; |
| 611 | req.body.getReader(); |
| 612 | return { body: new Uint8Array(), streamId }; |
| 613 | }; |
| 614 | // A data: URL carries its response inline; RFC 2397 percent-decoding |
| 615 | // happens byte-wise, so a payload that is deliberately invalid UTF-8 |
| 616 | // survives to the consumer (HTMLRewriter's own suite depends on it). |
| 617 | const __dataUrlResponse = (url) => { |
| 618 | // The URL parser strips leading and trailing C0 controls and spaces |
| 619 | // before doing anything else; a literal trailing space in a data: URL |
| 620 | // is therefore not part of the payload, while an encoded %20 is. |
| 621 | url = url.replace(/^[\x00-\x20]+/, "").replace(/[\x00-\x20]+$/, ""); |
| 622 | const match = /^data:([^,]*),([\s\S]*)$/.exec(url); |
| 623 | if (!match) throw new TypeError("Invalid data: URL"); |
| 624 | let [, meta, payload] = match; |
| 625 | const base64 = /;base64$/i.test(meta); |
| 626 | if (base64) meta = meta.replace(/;base64$/i, ""); |
| 627 | let bytes; |
| 628 | if (base64) { |
| 629 | // The data: URL processor percent-decodes the body before it decodes the |
| 630 | // base64, so `data:text/plain;base64,YQ%3D%3D` carries the padding of |
| 631 | // "YQ==". Decode byte-wise, as the non-base64 branch below does: a `%` |
| 632 | // that does not start a valid escape stays literal and the base64 decode |
| 633 | // rejects it. |
| 634 | payload = payload.replace( |
| 635 | /%([0-9a-f]{2})/gi, |
| 636 | (_, hex) => String.fromCharCode(parseInt(hex, 16)), |
| 637 | ); |
| 638 | const bin = atob(payload); |
| 639 | bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0)); |
| 640 | } else { |
| 641 | const out = []; |
| 642 | for (let i = 0; i < payload.length; i++) { |
| 643 | const c = payload[i]; |
| 644 | if (c === "%" && /^[0-9A-Fa-f]{2}$/.test(payload.slice(i + 1, i + 3))) { |
| 645 | out.push(parseInt(payload.slice(i + 1, i + 3), 16)); |
| 646 | i += 2; |
| 647 | } else { |
| 648 | out.push(payload.charCodeAt(i) & 0xff); |
| 649 | } |
| 650 | } |
| 651 | bytes = Uint8Array.from(out); |
| 652 | } |
| 653 | return new Response(bytes, { |
| 654 | headers: { "content-type": meta || "text/plain;charset=US-ASCII" }, |
| 655 | }); |
| 656 | }; |
| 657 | globalThis.fetch = async (input, init) => { |
| 658 | const rawUrl = typeof input === "string" ? input : input?.url; |
| 659 | if (typeof rawUrl === "string" && rawUrl.startsWith("data:")) { |
| 660 | return __dataUrlResponse(rawUrl); |
| 661 | } |
| 662 | const req = new Request(input, init); |
| 663 | // `fetch(url, { headers: { Upgrade: "websocket" } })` is the other way |
| 664 | // Cloudflare opens an outbound socket, and the one most examples use. |
| 665 | if ((req.headers.get("upgrade") ?? "").toLowerCase() === "websocket") { |
| 666 | return await __fetchWebSocketUpgrade(req); |
| 667 | } |
| 668 | // The caller's signal, never the incoming request's own. |
| 669 | const signal = req._signalForSubrequests; |
| 670 | if (signal?.aborted) throw signal.reason; |
| 671 | // The bytes go to the host as a typed array, the same way every other |
| 672 | // subrequest op takes a body. Encoding them as a JSON number array cost |
| 673 | // roughly ten times the body in transient allocation, and it corrupted |
| 674 | // nothing only because the host decoded the same shape back. |
| 675 | const { body, streamId } = await __subrequestBody( |
| 676 | req, ["GET", "HEAD"].includes(req.method)); |
| 677 | // The header list, not the iterator: the iterator sorts, lower-cases and |
| 678 | // combines, so `Array.from(req.headers)` would send one `X-Trace: a, b` |
| 679 | // for two appends and put celld's casing on the wire in place of the |
| 680 | // author's. `op_fetch` builds the request with `RequestBuilder::header`, |
| 681 | // which appends, so repeats survive. |
| 682 | let raw; |
| 683 | try { |
| 684 | const dispatch = __op_fetch( |
| 685 | req.method, req.url, body, |
| 686 | JSON.stringify(req.headers.__celldHeaderList), req.redirect, |
| 687 | streamId, signal != null, |
| 688 | ); |
| 689 | if (signal) { |
| 690 | // An abort and the response can cross, leaving a body stream nobody |
| 691 | // reads holding its upstream connection until the sweeper expires it. |
| 692 | // Every arm is silenced because the caller already owns both outcomes. |
| 693 | dispatch.then((late) => { |
| 694 | if (!signal.aborted) return; |
| 695 | const abandoned = JSON.parse(late).streamId; |
| 696 | if (abandoned !== undefined) __http_stream_cancel(abandoned); |
| 697 | }, () => {}).catch(() => {}); |
| 698 | } |
| 699 | raw = await (signal ? __awaitCancellableDoCall(dispatch, signal) : dispatch); |
| 700 | } catch (error) { |
| 701 | // An abort is the caller's reason, not a network error, so it skips |
| 702 | // every translation below. |
| 703 | if (signal?.aborted && error === signal.reason) throw error; |
| 704 | // The Fetch API represents a redirect refusal as a network error, which |
| 705 | // rejects with TypeError. Keep the host message for diagnostics. |
| 706 | if (req.redirect === "error") { |
| 707 | throw new TypeError(error?.message ?? String(error)); |
| 708 | } |
| 709 | throw error; |
| 710 | } |
| 711 | const r = JSON.parse(raw); |
| 712 | // Direct network responses always carry a stream id. A transferred |
| 713 | // globalOutbound Fetcher can answer with an inline body, as service |
| 714 | // bindings do, so preserve both response representations. |
| 715 | const responseBody = r.streamId !== undefined |
| 716 | ? new CelldHttpBodyStream(r.streamId) |
| 717 | : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); |
| 718 | const response = new Response( |
| 719 | responseBody, |
| 720 | { status: r.status, headers: r.headers }, |
| 721 | ); |
| 722 | response.url = req.url; |
| 723 | return response; |
| 724 | }; |
| 725 | const __fetchWebSocketUpgrade = __celld.__fetchWebSocketUpgrade = |
| 726 | async (req) => { |
| 727 | const scope = __currentActorScope(); |
| 728 | const id = __ws_alloc(); |
| 729 | const socket = __makeSocket(id); |
| 730 | socket._outbound = true; |
| 731 | socket._polled = !scope; |
| 732 | socket.url = req.url; |
| 733 | socket.readyState = WebSocket.READY_STATE_CONNECTING; |
| 734 | __sockets.set(id, socket); |
| 735 | let raw; |
| 736 | try { |
| 737 | raw = JSON.parse(await __ws_upgrade( |
| 738 | id, |
| 739 | scope, |
| 740 | req.url, |
| 741 | // The iterator, not the header list, unlike every other outbound |
| 742 | // path. The handshake builder on the host side puts these into a |
| 743 | // `HeaderMap` with `insert`, which replaces, and it reads the |
| 744 | // offered subprotocols with a first-match `find`. Both would drop |
| 745 | // every repeat but one. Sending the combined form keeps |
| 746 | // `Sec-WebSocket-Protocol: a` plus `: b` meaning `a, b`, which is |
| 747 | // what the peer must see. Moving this to the header list needs the |
| 748 | // host to append instead, so it is a separate change. |
| 749 | JSON.stringify(Array.from(req.headers)), |
| 750 | )); |
| 751 | } catch (error) { |
| 752 | __sockets.delete(id); |
| 753 | throw error; |
| 754 | } |
| 755 | if (!raw.upgraded) { |
| 756 | // The server answered without upgrading. That is an ordinary response, |
| 757 | // not a connection error, and it is returned unchanged. |
| 758 | __sockets.delete(id); |
| 759 | const response = new Response(new Uint8Array(raw.body), { |
| 760 | status: raw.status, |
| 761 | headers: raw.headers, |
| 762 | }); |
| 763 | response.url = req.url; |
| 764 | return response; |
| 765 | } |
| 766 | socket.protocol = raw.protocol ?? ""; |
| 767 | const response = new Response(null, { status: 101 }); |
| 768 | response.webSocket = socket; |
| 769 | response.url = req.url; |
| 770 | return response; |
| 771 | }; |
| 772 | __celld.__makeAssetsBinding = (script) => ({ |
| 773 | async fetch(input, init) { |
| 774 | const req = input instanceof Request ? new Request(input, init) : new Request(input, init); |
| 775 | const r = JSON.parse(await __asset_fetch( |
| 776 | script, |
| 777 | req.method, |
| 778 | req.url, |
| 779 | JSON.stringify(Array.from(req.headers)), |
| 780 | )); |
| 781 | const responseBody = r.streamId !== undefined |
| 782 | ? new CelldHttpBodyStream(r.streamId) |
| 783 | : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); |
| 784 | const response = new Response( |
| 785 | responseBody, |
| 786 | { status: r.status, headers: r.headers }, |
| 787 | ); |
| 788 | response.url = req.url; |
| 789 | return response; |
| 790 | }, |
| 791 | }); |
| 792 | // An `r2_buckets` binding, served out of the fleet bucket under the |
| 793 | // reserved `r2/<bucketName>/` prefix. celld runs on blob storage rather |
| 794 | // than providing it, so a binding gets the store the node already holds |
| 795 | // credentials for; a node started without a bucket has nowhere to put a |
| 796 | // blob and every method says so. |
| 797 | // |
| 798 | // The whole `R2Bucket` surface is here: `head`, `get`, `put`, `delete`, |
| 799 | // `list`, `createMultipartUpload` and `resumeMultipartUpload`, with |
| 800 | // `httpMetadata`, `customMetadata`, `checksums`, `storageClass`, `onlyIf` |
| 801 | // and every range spelling. What celld cannot honor still fails loudly |
| 802 | // rather than pretending -- a silent gap is the failure mode the binding |
| 803 | // is written to avoid. Those are `ssecKey` (celld has no customer-key |
| 804 | // encryption), a conditional `put` of a body too big for one request, and |
| 805 | // a multipart upload resumed on a node other than the one that opened it. |
| 806 | const __r2Reject = (bucket, method, detail) => { |
| 807 | throw new Error( |
| 808 | `R2 ${method} is not implemented in celld (binding ${bucket})` + |
| 809 | (detail ? `: ${detail}` : ""), |
| 810 | ); |
| 811 | }; |
| 812 | // R2's key rules, checked here so a key the real thing refuses is refused |
| 813 | // here too rather than quietly written. |
| 814 | const __r2Key = (binding, method, key) => { |
| 815 | const text = String(key); |
| 816 | const length = new TextEncoder().encode(text).length; |
| 817 | if (length === 0 || length > 1024) { |
| 818 | throw new Error( |
| 819 | `R2 ${method} (binding ${binding}): a key is 1 to 1024 bytes, not ${length}`, |
| 820 | ); |
| 821 | } |
| 822 | return text; |
| 823 | }; |
| 824 | const __r2Hex = (value) => { |
| 825 | if (typeof value === "string") return value.trim().toLowerCase(); |
| 826 | const bytes = value instanceof ArrayBuffer |
| 827 | ? new Uint8Array(value) |
| 828 | : ArrayBuffer.isView(value) |
| 829 | ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) |
| 830 | : null; |
| 831 | if (!bytes) return null; |
| 832 | let out = ""; |
| 833 | for (const byte of bytes) out += byte.toString(16).padStart(2, "0"); |
| 834 | return out; |
| 835 | }; |
| 836 | const __r2Bytes = (hex) => { |
| 837 | const out = new Uint8Array(hex.length >> 1); |
| 838 | for (let at = 0; at < out.length; at++) { |
| 839 | out[at] = parseInt(hex.substr(at * 2, 2), 16); |
| 840 | } |
| 841 | return out.buffer; |
| 842 | }; |
| 843 | // Read a `ReadableStream` to one `Uint8Array`. Bodies drained this way |
| 844 | // are the ones the caller asked to have whole. |
| 845 | const __r2Drain = async (stream) => { |
| 846 | const reader = stream.getReader(); |
| 847 | const chunks = []; |
| 848 | let total = 0; |
| 849 | for (;;) { |
| 850 | const { done, value } = await reader.read(); |
| 851 | if (done) break; |
| 852 | chunks.push(value); |
| 853 | total += value.length; |
| 854 | } |
| 855 | const out = new Uint8Array(total); |
| 856 | let at = 0; |
| 857 | for (const chunk of chunks) { |
| 858 | out.set(chunk, at); |
| 859 | at += chunk.length; |
| 860 | } |
| 861 | return out; |
| 862 | }; |
| 863 | const __r2Ms = (value) => { |
| 864 | if (value === undefined || value === null) return undefined; |
| 865 | const ms = value instanceof Date ? value.getTime() : Number(value); |
| 866 | return Number.isFinite(ms) ? ms : undefined; |
| 867 | }; |
| 868 | // `httpMetadata` is either an `R2HTTPMetadata` or a `Headers`, and R2 |
| 869 | // takes both on the way in. |
| 870 | const __r2Http = (value) => { |
| 871 | if (value === undefined || value === null) return {}; |
| 872 | const from = (name, key) => |
| 873 | typeof value.get === "function" ? value.get(name) ?? undefined : value[key]; |
| 874 | const http = { |
| 875 | contentType: from("content-type", "contentType"), |
| 876 | contentLanguage: from("content-language", "contentLanguage"), |
| 877 | contentDisposition: from("content-disposition", "contentDisposition"), |
| 878 | contentEncoding: from("content-encoding", "contentEncoding"), |
| 879 | cacheControl: from("cache-control", "cacheControl"), |
| 880 | cacheExpiry: __r2Ms( |
| 881 | typeof value.get === "function" ? value.get("expires") : value.cacheExpiry, |
| 882 | ), |
| 883 | }; |
| 884 | for (const [name, entry] of Object.entries(http)) { |
| 885 | if (entry === undefined || entry === null) delete http[name]; |
| 886 | else if (name !== "cacheExpiry") http[name] = String(entry); |
| 887 | } |
| 888 | return http; |
| 889 | }; |
| 890 | // `onlyIf` is either an `R2Conditional` or a `Headers`; the header |
| 891 | // spelling of "only if it has not changed since" is If-Unmodified-Since, |
| 892 | // which is `uploadedBefore`. |
| 893 | const __r2OnlyIf = (value) => { |
| 894 | if (value === undefined || value === null) return undefined; |
| 895 | const only = typeof value.get === "function" |
| 896 | ? { |
| 897 | etagMatches: value.get("if-match") ?? undefined, |
| 898 | etagDoesNotMatch: value.get("if-none-match") ?? undefined, |
| 899 | uploadedAfter: __r2Ms(Date.parse(value.get("if-modified-since") ?? "")), |
| 900 | uploadedBefore: __r2Ms(Date.parse(value.get("if-unmodified-since") ?? "")), |
| 901 | } |
| 902 | : { |
| 903 | etagMatches: value.etagMatches, |
| 904 | etagDoesNotMatch: value.etagDoesNotMatch, |
| 905 | uploadedAfter: __r2Ms(value.uploadedAfter), |
| 906 | uploadedBefore: __r2Ms(value.uploadedBefore), |
| 907 | }; |
| 908 | for (const [name, entry] of Object.entries(only)) { |
| 909 | if (entry === undefined || entry === null || Number.isNaN(entry)) { |
| 910 | delete only[name]; |
| 911 | } else if (name.startsWith("etag")) only[name] = String(entry); |
| 912 | } |
| 913 | return Object.keys(only).length ? only : undefined; |
| 914 | }; |
| 915 | // A range is an `R2Range` or a `Headers` carrying a Range header. R2 |
| 916 | // takes `offset` alone, `length` alone, both, or `suffix`. |
| 917 | const __r2Range = (binding, value) => { |
| 918 | if (value === undefined || value === null) return undefined; |
| 919 | if (typeof value.get === "function") { |
| 920 | const header = value.get("range"); |
| 921 | if (!header) return undefined; |
| 922 | const parsed = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); |
| 923 | if (!parsed) { |
| 924 | __r2Reject(binding, "get(range)", `celld cannot parse ${header}`); |
| 925 | } |
| 926 | const [, first, last] = parsed; |
| 927 | if (first === "") return { suffix: Number(last) }; |
| 928 | if (last === "") return { offset: Number(first) }; |
| 929 | return { offset: Number(first), length: Number(last) - Number(first) + 1 }; |
| 930 | } |
| 931 | const range = {}; |
| 932 | if (value.suffix !== undefined && value.suffix !== null) { |
| 933 | range.suffix = Number(value.suffix); |
| 934 | } |
| 935 | if (value.offset !== undefined && value.offset !== null) { |
| 936 | range.offset = Number(value.offset); |
| 937 | } |
| 938 | if (value.length !== undefined && value.length !== null) { |
| 939 | range.length = Number(value.length); |
| 940 | } |
| 941 | for (const [name, entry] of Object.entries(range)) { |
| 942 | if (!Number.isFinite(entry) || entry < 0) { |
| 943 | __r2Reject(binding, "get(range)", `\`${name}\` must be a whole number`); |
| 944 | } |
| 945 | } |
| 946 | return Object.keys(range).length ? range : undefined; |
| 947 | }; |
| 948 | // R2 hashes an object's bytes and hands the digests back as |
| 949 | // `ArrayBuffer`s, with a `toJSON()` that spells them in hex. |
| 950 | const __r2Checksums = (hex) => { |
| 951 | const checksums = { |
| 952 | toJSON() { |
| 953 | const json = {}; |
| 954 | for (const [name, digest] of Object.entries(hex)) json[name] = digest; |
| 955 | return json; |
| 956 | }, |
| 957 | }; |
| 958 | for (const [name, digest] of Object.entries(hex)) { |
| 959 | checksums[name] = __r2Bytes(digest); |
| 960 | } |
| 961 | return checksums; |
| 962 | }; |
| 963 | // One object as R2 describes it. `object` is the host's record; `body`, |
| 964 | // when there is one, makes this an `R2ObjectBody`. |
| 965 | const __r2Object = (object, body) => { |
| 966 | const http = { ...object.http }; |
| 967 | if (http.cacheExpiry !== undefined) { |
| 968 | http.cacheExpiry = new Date(http.cacheExpiry); |
| 969 | } |
| 970 | const etag = object.etag ? String(object.etag).replace(/^"|"$/g, "") : ""; |
| 971 | const r2 = { |
| 972 | key: object.key, |
| 973 | version: object.version ?? etag, |
| 974 | size: object.size, |
| 975 | etag, |
| 976 | httpEtag: etag ? `"${etag}"` : "", |
| 977 | uploaded: new Date(object.uploaded), |
| 978 | httpMetadata: http, |
| 979 | customMetadata: object.custom ?? {}, |
| 980 | checksums: __r2Checksums(object.checksums ?? {}), |
| 981 | storageClass: object.storageClass ?? "Standard", |
| 982 | // R2 fills the response headers from the object's own metadata, which |
| 983 | // is what makes `return new Response(object.body, { headers })` serve |
| 984 | // a stored file correctly. |
| 985 | writeHttpMetadata(headers) { |
| 986 | const write = (name, value) => { |
| 987 | if (value !== undefined && value !== null) headers.set(name, value); |
| 988 | }; |
| 989 | write("content-type", http.contentType); |
| 990 | write("content-language", http.contentLanguage); |
| 991 | write("content-disposition", http.contentDisposition); |
| 992 | write("content-encoding", http.contentEncoding); |
| 993 | write("cache-control", http.cacheControl); |
| 994 | if (http.cacheExpiry !== undefined) { |
| 995 | headers.set("expires", http.cacheExpiry.toUTCString()); |
| 996 | } |
| 997 | }, |
| 998 | }; |
| 999 | if (object.range) r2.range = { ...object.range }; |
| 1000 | if (!body) return r2; |
| 1001 | const drain = () => __r2Drain(body); |
| 1002 | r2.body = body; |
| 1003 | Object.defineProperty(r2, "bodyUsed", { |
| 1004 | get: () => body.locked || body._disturbed === true, |
| 1005 | }); |
| 1006 | r2.arrayBuffer = async () => (await drain()).buffer; |
| 1007 | r2.bytes = drain; |
| 1008 | r2.text = async () => new TextDecoder().decode(await drain()); |
| 1009 | r2.json = async () => JSON.parse(new TextDecoder().decode(await drain())); |
| 1010 | r2.blob = async () => new Blob([await drain()]); |
| 1011 | return r2; |
| 1012 | }; |
| 1013 | // The write-side options every writing method shares, in the shape the |
| 1014 | // host ops read. |
| 1015 | const __r2WriteOptions = (binding, method, options) => { |
| 1016 | const o = options ?? {}; |
| 1017 | if (o.ssecKey !== undefined) { |
| 1018 | __r2Reject( |
| 1019 | binding, |
| 1020 | `${method}(ssecKey)`, |
| 1021 | "celld has no customer-key encryption", |
| 1022 | ); |
| 1023 | } |
| 1024 | const custom = {}; |
| 1025 | for (const [name, value] of Object.entries(o.customMetadata ?? {})) { |
| 1026 | custom[name] = String(value); |
| 1027 | } |
| 1028 | const verify = {}; |
| 1029 | for (const name of ["md5", "sha1", "sha256", "sha384", "sha512"]) { |
| 1030 | if (o[name] === undefined || o[name] === null) continue; |
| 1031 | const hex = __r2Hex(o[name]); |
| 1032 | if (hex === null) { |
| 1033 | __r2Reject( |
| 1034 | binding, |
| 1035 | `${method}(${name})`, |
| 1036 | "a checksum is hex or an ArrayBuffer", |
| 1037 | ); |
| 1038 | } |
| 1039 | verify[name] = hex; |
| 1040 | } |
| 1041 | const storageClass = o.storageClass === undefined || o.storageClass === null |
| 1042 | ? undefined |
| 1043 | : String(o.storageClass); |
| 1044 | if (storageClass !== undefined && |
| 1045 | !["Standard", "InfrequentAccess"].includes(storageClass) |
| 1046 | ) { |
| 1047 | __r2Reject( |
| 1048 | binding, |
| 1049 | `${method}(storageClass)`, |
| 1050 | `${storageClass} is not an R2 storage class`, |
| 1051 | ); |
| 1052 | } |
| 1053 | return { |
| 1054 | http: __r2Http(o.httpMetadata), |
| 1055 | custom, |
| 1056 | storageClass, |
| 1057 | onlyIf: __r2OnlyIf(o.onlyIf), |
| 1058 | verify, |
| 1059 | }; |
| 1060 | }; |
| 1061 | // A `put` body, as either the bytes to send in one request or the stream |
| 1062 | // to feed the host chunk by chunk. R2 takes all of these. |
| 1063 | const __r2Value = async (binding, value) => { |
| 1064 | if (value === undefined || value === null) return new Uint8Array(0); |
| 1065 | if (typeof value === "string") return new TextEncoder().encode(value); |
| 1066 | if (value instanceof Uint8Array) return value; |
| 1067 | if (ArrayBuffer.isView(value)) { |
| 1068 | return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); |
| 1069 | } |
| 1070 | if (value instanceof ArrayBuffer) return new Uint8Array(value); |
| 1071 | if (typeof Blob !== "undefined" && value instanceof Blob) { |
| 1072 | return new Uint8Array(await value.arrayBuffer()); |
| 1073 | } |
| 1074 | if (value && typeof value.getReader === "function") return value; |
| 1075 | return __r2Reject( |
| 1076 | binding, |
| 1077 | "put", |
| 1078 | "a body is a string, an ArrayBuffer, a view, a Blob, a ReadableStream, or null", |
| 1079 | ); |
| 1080 | }; |
| 1081 | // Feed a `ReadableStream` body to the host one chunk at a time. The host |
| 1082 | // writes one request when the whole body fits in a part and a multipart |
| 1083 | // upload when it does not, so a Worker can stream a body far larger than |
| 1084 | // its heap. |
| 1085 | const __r2PutStream = async (bucketName, key, stream, options) => { |
| 1086 | const id = Number(await __r2_put_begin(bucketName, key, JSON.stringify(options))); |
| 1087 | const reader = stream.getReader(); |
| 1088 | try { |
| 1089 | for (;;) { |
| 1090 | const { done, value } = await reader.read(); |
| 1091 | if (done) break; |
| 1092 | if (!value || value.length === 0) continue; |
| 1093 | await __r2_put_chunk( |
| 1094 | id, |
| 1095 | value instanceof Uint8Array |
| 1096 | ? value |
| 1097 | : new Uint8Array(value.buffer, value.byteOffset, value.byteLength), |
| 1098 | ); |
| 1099 | } |
| 1100 | } catch (error) { |
| 1101 | await __r2_put_end(id, true); |
| 1102 | throw error; |
| 1103 | } |
| 1104 | return JSON.parse(await __r2_put_end(id, false)); |
| 1105 | }; |
| 1106 | // One open multipart upload. `id` resolves to the host's upload id, so |
| 1107 | // `resumeMultipartUpload` can hand back a handle without awaiting -- as R2 |
| 1108 | // does -- and surface a bad id on the first method that uses it. |
| 1109 | const __r2Multipart = (binding, bucketName, key, id) => ({ |
| 1110 | key, |
| 1111 | get uploadId() { |
| 1112 | return String(id.value ?? ""); |
| 1113 | }, |
| 1114 | async uploadPart(partNumber, value, options) { |
| 1115 | if (options?.ssecKey !== undefined) { |
| 1116 | __r2Reject(binding, "uploadPart(ssecKey)", "celld has no customer-key encryption"); |
| 1117 | } |
| 1118 | const body = await __r2Value(binding, value); |
| 1119 | const bytes = body instanceof Uint8Array ? body : await __r2Drain(body); |
| 1120 | const r = JSON.parse(await __r2_mp_part(await id.host, partNumber | 0, bytes)); |
| 1121 | // The object store owns the part list this completion acts on, so it |
| 1122 | // never hands back a part etag to name one with. |
| 1123 | return { partNumber: r.partNumber, etag: "" }; |
| 1124 | }, |
| 1125 | async complete(parts) { |
| 1126 | const numbers = (parts ?? []).map((part) => part.partNumber | 0); |
| 1127 | return __r2Object(JSON.parse( |
| 1128 | await __r2_mp_complete(await id.host, JSON.stringify(numbers)), |
| 1129 | )); |
| 1130 | }, |
| 1131 | async abort() { |
| 1132 | await __r2_mp_abort(await id.host); |
| 1133 | }, |
| 1134 | }); |
| 1135 | // A `media` binding (Homeflare patch): Cloudflare's Media Transformations |
| 1136 | // API, `env.MEDIA.input(stream).transform(t).output(o)`, with the work done |
| 1137 | // by the node's media service (CELLD_MEDIA_URL, an ffmpeg service such as |
| 1138 | // Homeflare's homeflare-media). The binding sends the input and both option |
| 1139 | // objects in one POST to `<service>/transform`; the service validates them, |
| 1140 | // so its answers and error codes are the one source of truth. A result makes |
| 1141 | // its request once, when first read, and media(), contentType() and |
| 1142 | // response() share it. |
| 1143 | class MediaError extends Error { |
| 1144 | constructor(code, message) { |
| 1145 | super(message); |
| 1146 | this.name = "MediaError"; |
| 1147 | this.code = code; |
| 1148 | } |
| 1149 | } |
| 1150 | const __mediaBody = (binding, media) => { |
| 1151 | if (media instanceof ReadableStream) return media; |
| 1152 | if (media instanceof ArrayBuffer || ArrayBuffer.isView(media) || media instanceof Blob) return media; |
| 1153 | throw new TypeError( |
| 1154 | `${binding}.input() takes a ReadableStream of the media's bytes`); |
| 1155 | }; |
| 1156 | const __mediaResult = (binding, service, body, transform, output) => { |
| 1157 | let answer = null; |
| 1158 | const request = () => answer ??= (async () => { |
| 1159 | if (!service) { |
| 1160 | throw new MediaError(9500, |
| 1161 | `${binding}: this celld node has no media service (set CELLD_MEDIA_URL)`); |
| 1162 | } |
| 1163 | // Read into bytes first: fetch() takes a stream only from its owner, and |
| 1164 | // an R2 object's body (palm's case) belongs to the binding that made it. |
| 1165 | // Inputs are at most Cloudflare's 100 MB. |
| 1166 | const bytes = body instanceof ReadableStream |
| 1167 | ? await new Response(body).arrayBuffer() |
| 1168 | : body; |
| 1169 | let response; |
| 1170 | try { |
| 1171 | response = await fetch(`${service.replace(/\/+$/, "")}/transform`, { |
| 1172 | method: "POST", |
| 1173 | headers: { |
| 1174 | "content-type": "application/octet-stream", |
| 1175 | "x-media-transform": JSON.stringify({ transform, output }), |
| 1176 | }, |
| 1177 | body: bytes, |
| 1178 | }); |
| 1179 | } catch (error) { |
| 1180 | throw new MediaError(9502, |
| 1181 | `${binding}: the media service at ${service} can't be reached (${error?.message ?? error})`); |
| 1182 | } |
| 1183 | if (!response.ok) { |
| 1184 | let code = 9500; |
| 1185 | let message = `media service answered ${response.status}`; |
| 1186 | try { |
| 1187 | const error = await response.json(); |
| 1188 | if (Number.isInteger(error.code)) code = error.code; |
| 1189 | if (typeof error.message === "string") message = error.message; |
| 1190 | } catch { /* not JSON: keep the status */ } |
| 1191 | throw new MediaError(code, `${binding}: ${message}`); |
| 1192 | } |
| 1193 | return response; |
| 1194 | })(); |
| 1195 | return { |
| 1196 | async media() { return (await request()).body; }, |
| 1197 | async contentType() { |
| 1198 | return (await request()).headers.get("content-type") ?? "application/octet-stream"; |
| 1199 | }, |
| 1200 | async response() { |
| 1201 | const response = await request(); |
| 1202 | return new Response(response.body, { |
| 1203 | headers: { "content-type": response.headers.get("content-type") ?? "application/octet-stream" }, |
| 1204 | }); |
| 1205 | }, |
| 1206 | }; |
| 1207 | }; |
| 1208 | __celld.__makeMediaBinding = (binding, service) => ({ |
| 1209 | input(media) { |
| 1210 | const body = __mediaBody(binding, media); |
| 1211 | let used = false; |
| 1212 | const once = () => { |
| 1213 | if (used) throw new TypeError(`${binding}: an input can be transformed once`); |
| 1214 | used = true; |
| 1215 | }; |
| 1216 | return { |
| 1217 | transform(transform = {}) { |
| 1218 | return { |
| 1219 | output(output = {}) { |
| 1220 | once(); |
| 1221 | return __mediaResult(binding, service, body, transform, output); |
| 1222 | }, |
| 1223 | }; |
| 1224 | }, |
| 1225 | output(output = {}) { |
| 1226 | once(); |
| 1227 | return __mediaResult(binding, service, body, {}, output); |
| 1228 | }, |
| 1229 | }; |
| 1230 | }, |
| 1231 | }); |
| 1232 | // A `ratelimit` binding (Homeflare patch): Cloudflare's Rate Limiting API, |
| 1233 | // `await env.LIMITER.limit({ key })` -> `{ success }`. The node counts each |
| 1234 | // namespace id and key in fixed windows of the binding's period. |
| 1235 | __celld.__makeRateLimit = (binding, namespace, limit, period) => ({ |
| 1236 | async limit(options) { |
| 1237 | const key = options?.key; |
| 1238 | if (typeof key !== "string" || key === "") { |
| 1239 | throw new TypeError(`${binding}.limit() needs { key: string }`); |
| 1240 | } |
| 1241 | return { success: __ratelimit(`${namespace}\u0000${key}`, limit, period) }; |
| 1242 | }, |
| 1243 | }); |
| 1244 | __celld.__makeR2Bucket = (binding, bucketName) => ({ |
| 1245 | async head(key) { |
| 1246 | const name = __r2Key(binding, "head", key); |
| 1247 | const r = JSON.parse(await __r2_head(bucketName, name)); |
| 1248 | return r.state === "miss" ? null : __r2Object(r.object); |
| 1249 | }, |
| 1250 | async get(key, options) { |
| 1251 | const name = __r2Key(binding, "get", key); |
| 1252 | const o = options ?? {}; |
| 1253 | if (o.ssecKey !== undefined) { |
| 1254 | __r2Reject(binding, "get(ssecKey)", "celld has no customer-key encryption"); |
| 1255 | } |
| 1256 | const request = { |
| 1257 | range: __r2Range(binding, o.range), |
| 1258 | onlyIf: __r2OnlyIf(o.onlyIf), |
| 1259 | }; |
| 1260 | const r = JSON.parse(await __r2_get(bucketName, name, JSON.stringify(request))); |
| 1261 | if (r.state === "miss") return null; |
| 1262 | // A refused `onlyIf` answers the object without its body, which is how |
| 1263 | // a caller tells "not modified" from "not there". |
| 1264 | if (r.state === "unmet") return __r2Object(r.object); |
| 1265 | return __r2Object(r.object, new CelldHttpBodyStream(r.streamId)); |
| 1266 | }, |
| 1267 | async put(key, value, options) { |
| 1268 | const name = __r2Key(binding, "put", key); |
| 1269 | const write = __r2WriteOptions(binding, "put", options); |
| 1270 | const body = await __r2Value(binding, value); |
| 1271 | const r = body instanceof Uint8Array |
| 1272 | ? JSON.parse(await __r2_put(bucketName, name, body, JSON.stringify(write))) |
| 1273 | : await __r2PutStream(bucketName, name, body, write); |
| 1274 | // R2 answers a refused `onlyIf` with `null` rather than throwing. |
| 1275 | return r.stored ? __r2Object(r.object) : null; |
| 1276 | }, |
| 1277 | async delete(keys) { |
| 1278 | const list = (Array.isArray(keys) ? keys : [keys]).map((key) => |
| 1279 | __r2Key(binding, "delete", key) |
| 1280 | ); |
| 1281 | if (list.length > 1000) { |
| 1282 | throw new Error( |
| 1283 | `R2 delete (binding ${binding}) takes at most 1000 keys, not ${list.length}`, |
| 1284 | ); |
| 1285 | } |
| 1286 | if (list.length) await __r2_delete(bucketName, JSON.stringify(list)); |
| 1287 | }, |
| 1288 | async list(options) { |
| 1289 | const o = options ?? {}; |
| 1290 | const include = Array.isArray(o.include) ? o.include : []; |
| 1291 | for (const entry of include) { |
| 1292 | if (!["httpMetadata", "customMetadata"].includes(entry)) { |
| 1293 | __r2Reject(binding, "list(include)", `${entry} is not an R2 listing extra`); |
| 1294 | } |
| 1295 | } |
| 1296 | const request = { |
| 1297 | prefix: o.prefix === undefined || o.prefix === null ? "" : String(o.prefix), |
| 1298 | cursor: o.cursor === undefined || o.cursor === null ? null : String(o.cursor), |
| 1299 | startAfter: o.startAfter === undefined || o.startAfter === null |
| 1300 | ? null |
| 1301 | : String(o.startAfter), |
| 1302 | limit: o.limit === undefined || o.limit === null ? 0 : o.limit | 0, |
| 1303 | delimiter: o.delimiter === undefined || o.delimiter === null |
| 1304 | ? null |
| 1305 | : String(o.delimiter), |
| 1306 | include: include.length > 0, |
| 1307 | }; |
| 1308 | const r = JSON.parse(await __r2_list(bucketName, JSON.stringify(request))); |
| 1309 | const objects = r.objects.map((object) => { |
| 1310 | // A listing carries the extras it was asked for and nothing else, |
| 1311 | // so a caller cannot mistake an empty map for an empty object. |
| 1312 | if (!include.includes("httpMetadata")) object.http = {}; |
| 1313 | if (!include.includes("customMetadata")) object.custom = {}; |
| 1314 | return __r2Object(object); |
| 1315 | }); |
| 1316 | // R2 omits `cursor` entirely when the listing is complete, and callers |
| 1317 | // test `truncated` before reading it. |
| 1318 | const page = { objects, truncated: r.truncated, delimitedPrefixes: r.prefixes }; |
| 1319 | if (r.truncated && r.cursor) page.cursor = r.cursor; |
| 1320 | return page; |
| 1321 | }, |
| 1322 | async createMultipartUpload(key, options) { |
| 1323 | const name = __r2Key(binding, "createMultipartUpload", key); |
| 1324 | const write = __r2WriteOptions(binding, "createMultipartUpload", options); |
| 1325 | if (write.onlyIf) { |
| 1326 | __r2Reject( |
| 1327 | binding, |
| 1328 | "createMultipartUpload(onlyIf)", |
| 1329 | "a multipart completion takes no precondition", |
| 1330 | ); |
| 1331 | } |
| 1332 | // R2 takes a checksum on `put`, which sees the whole body, and not on a |
| 1333 | // multipart upload, which never does. |
| 1334 | for (const name of Object.keys(write.verify)) { |
| 1335 | __r2Reject(binding, `createMultipartUpload(${name})`, "R2 takes a checksum on `put`"); |
| 1336 | } |
| 1337 | const uploadId = await __r2_mp_begin(bucketName, name, JSON.stringify(write)); |
| 1338 | return __r2Multipart(binding, bucketName, name, { |
| 1339 | value: uploadId, |
| 1340 | host: Promise.resolve(Number(uploadId)), |
| 1341 | }); |
| 1342 | }, |
| 1343 | // R2 hands back a handle without checking it; so does this, and the |
| 1344 | // first method that uses it says whether the upload is still open. |
| 1345 | resumeMultipartUpload(key, uploadId) { |
| 1346 | const name = __r2Key(binding, "resumeMultipartUpload", key); |
| 1347 | const id = String(uploadId); |
| 1348 | const host = __r2_mp_resume(bucketName, name, id).then(Number); |
| 1349 | // A handle nobody uses must not become an unhandled rejection; the |
| 1350 | // first method that awaits `host` still sees the failure. |
| 1351 | host.catch(() => {}); |
| 1352 | return __r2Multipart(binding, bucketName, name, { value: id, host }); |
| 1353 | }, |
| 1354 | }); |
| 1355 | // A host timer op resolves once, so an interval arms a new one after every |
| 1356 | // round. `__timers` maps the id the caller holds to the op that is armed |
| 1357 | // right now: for a timeout that is the same id, and for an interval it is a |
| 1358 | // fresh id each round. Clearing therefore cancels the armed op, not the id. |
| 1359 | const __timers = new Map(); |
| 1360 | const __clearTimer = (id) => { |
| 1361 | const armed = __timers.get(id); |
| 1362 | if (armed === undefined) return; |
| 1363 | __timers.delete(id); |
| 1364 | __timer_cancel(armed); |
| 1365 | }; |
| 1366 | globalThis.setTimeout = (cb, ms, ...a) => { |
| 1367 | const id = __timer_alloc(); |
| 1368 | __timers.set(id, id); |
| 1369 | __op_timer(id, ms | 0).then(() => { |
| 1370 | if (!__timers.delete(id)) return; |
| 1371 | cb(...a); |
| 1372 | }); |
| 1373 | return id; |
| 1374 | }; |
| 1375 | globalThis.setInterval = (cb, ms, ...a) => { |
| 1376 | const id = __timer_alloc(); |
| 1377 | const delay = ms | 0; |
| 1378 | const arm = (armed) => { |
| 1379 | __timers.set(id, armed); |
| 1380 | __op_timer(armed, delay).then(() => { |
| 1381 | // Cancelling drops the entry and cancelling then re-arming replaces |
| 1382 | // it, so a round whose op is no longer the armed one is dead and |
| 1383 | // stops here. A cancelled op still resolves, which is why this test |
| 1384 | // is on identity and not on the op alone. |
| 1385 | if (__timers.get(id) !== armed) return; |
| 1386 | // Arm the next round before the callback runs. A `clearInterval` |
| 1387 | // inside the callback must end the interval, and arming after the |
| 1388 | // callback would undo it. |
| 1389 | arm(__timer_alloc()); |
| 1390 | cb(...a); |
| 1391 | }); |
| 1392 | }; |
| 1393 | arm(id); |
| 1394 | return id; |
| 1395 | }; |
| 1396 | // One id space and one cancel, because a caller can cross the two. |
| 1397 | globalThis.clearTimeout = __clearTimer; |
| 1398 | globalThis.clearInterval = __clearTimer; |
| 1399 | |
| 1400 | const __sqlCursorFinalizer = typeof FinalizationRegistry === "function" |
| 1401 | ? new FinalizationRegistry((cursorId) => __sql_cursor_close(cursorId)) |
| 1402 | : null; |
| 1403 | |
| 1404 | // A `SqlStorageCursor` over one exec's result (Cloudflare DO SQL API). |
| 1405 | class SqlCursor { |
| 1406 | // `res` is what `__sql_cursor_start` returns: V8 values throughout, with the |
| 1407 | // first row already stepped. A failing query throws out of the op, so there |
| 1408 | // is no in-band error field to test here. |
| 1409 | constructor(res) { |
| 1410 | this.columns = res.columns; |
| 1411 | this.rowsWritten = Number(res.rowsWritten || 0); |
| 1412 | this.reusedCachedQueryForTest = Boolean(res.reusedCachedQuery); |
| 1413 | this._deferredError = null; |
| 1414 | this._cursorId = Number(res.cursorId || 0); |
| 1415 | this._prefetched = res.row; |
| 1416 | this.rowsRead = this._prefetched === null ? 0 : 1; |
| 1417 | this._finalizerToken = null; |
| 1418 | if (this._cursorId && __sqlCursorFinalizer) { |
| 1419 | this._finalizerToken = {}; |
| 1420 | __sqlCursorFinalizer.register( |
| 1421 | this, this._cursorId, this._finalizerToken, |
| 1422 | ); |
| 1423 | } |
| 1424 | } |
| 1425 | _obj(r) { const o = {}; for (let i = 0; i < this.columns.length; i++) o[this.columns[i]] = r[i]; return o; } |
| 1426 | _finishNative() { |
| 1427 | if (this._finalizerToken && __sqlCursorFinalizer) |
| 1428 | __sqlCursorFinalizer.unregister(this._finalizerToken); |
| 1429 | this._finalizerToken = null; |
| 1430 | this._cursorId = 0; |
| 1431 | } |
| 1432 | _advanceNative() { |
| 1433 | if (!this._cursorId) { |
| 1434 | this._prefetched = null; |
| 1435 | return; |
| 1436 | } |
| 1437 | // The op answers with V8 values, not JSON: an array is a row, a number is |
| 1438 | // the cursor's final rowsWritten, and a failure throws. The throw is |
| 1439 | // caught and deferred, because a consumer must still receive the last good |
| 1440 | // row -- the error belongs to the call after it, not to this one. |
| 1441 | let result; |
| 1442 | try { |
| 1443 | result = __sql_cursor_next(this._cursorId); |
| 1444 | } catch (error) { |
| 1445 | this._deferredError = error; |
| 1446 | this._prefetched = null; |
| 1447 | this._finishNative(); |
| 1448 | return; |
| 1449 | } |
| 1450 | if (Array.isArray(result)) { |
| 1451 | this._prefetched = result; |
| 1452 | this.rowsRead++; |
| 1453 | return; |
| 1454 | } |
| 1455 | this.rowsWritten = Number(result || this.rowsWritten); |
| 1456 | this._prefetched = null; |
| 1457 | this._finishNative(); |
| 1458 | } |
| 1459 | _nextRaw() { |
| 1460 | if (this._deferredError) { |
| 1461 | const error = this._deferredError; |
| 1462 | this._deferredError = null; |
| 1463 | throw error; |
| 1464 | } |
| 1465 | if (this._prefetched === null) return { done: true }; |
| 1466 | const value = this._prefetched; |
| 1467 | this._advanceNative(); |
| 1468 | return { done: false, value }; |
| 1469 | } |
| 1470 | toArray() { |
| 1471 | const rows = []; |
| 1472 | while (true) { |
| 1473 | const result = this.next(); |
| 1474 | if (result.done) return rows; |
| 1475 | rows.push(result.value); |
| 1476 | if (__heap_limit_excessively_exceeded()) |
| 1477 | throw new Error( |
| 1478 | "the isolate is over its V8 heap limit, so it stopped " + |
| 1479 | "materializing a result set (see CELLD_V8_HEAP_LIMIT_MB)"); |
| 1480 | } |
| 1481 | } |
| 1482 | one() { |
| 1483 | const first = this.next(); |
| 1484 | if (first.done) |
| 1485 | throw new Error("Expected exactly one result from SQL query, but got no results"); |
| 1486 | if (!this.next().done) |
| 1487 | throw new Error("Expected exactly one result from SQL query, but got multiple results"); |
| 1488 | return first.value; |
| 1489 | } |
| 1490 | *raw() { |
| 1491 | while (true) { |
| 1492 | const result = this._nextRaw(); |
| 1493 | if (result.done) return; |
| 1494 | yield result.value; |
| 1495 | } |
| 1496 | } |
| 1497 | get columnNames() { return this.columns; } |
| 1498 | next() { |
| 1499 | const result = this._nextRaw(); |
| 1500 | return result.done ? result : { done: false, value: this._obj(result.value) }; |
| 1501 | } |
| 1502 | [Symbol.iterator]() { return this; } |
| 1503 | } |
| 1504 | class SqlStorage { |
| 1505 | // The state is what the abort guard in `exec` reads; a storage built |
| 1506 | // without one would bypass the guard silently. |
| 1507 | constructor(scope, state, storage) { |
| 1508 | if (!state) throw new TypeError("SqlStorage requires its DurableObjectState"); |
| 1509 | this._scope = scope; |
| 1510 | this._state = state; |
| 1511 | this._storage = storage; |
| 1512 | } |
| 1513 | prepare(query) { |
| 1514 | this._storage._assertTransactionActive("sql.prepare"); |
| 1515 | const storage = this; |
| 1516 | const source = String(query); |
| 1517 | return (...binds) => storage.exec(source, ...binds); |
| 1518 | } |
| 1519 | exec(query, ...binds) { |
| 1520 | this._storage._assertTransactionActive("sql.exec"); |
| 1521 | // A callback that outlived its block runs on an object that was reset, |
| 1522 | // whose replacement uses the same connection: a statement from it |
| 1523 | // would land in the replacement's state. The KV surface drops such |
| 1524 | // writes silently; SQL refuses aloud, since a cursor can carry reads. |
| 1525 | if (this._state._aborted) { |
| 1526 | throw new Error("the Durable Object was reset; this event's storage is closed"); |
| 1527 | } |
| 1528 | const jsonBinds = []; |
| 1529 | const byteBinds = []; |
| 1530 | for (let index = 0; index < binds.length; index++) { |
| 1531 | const value = binds[index]; |
| 1532 | let bytes; |
| 1533 | if (value instanceof ArrayBuffer) { |
| 1534 | bytes = new Uint8Array(value); |
| 1535 | } else if (ArrayBuffer.isView(value)) { |
| 1536 | bytes = new Uint8Array( |
| 1537 | value.buffer, value.byteOffset, value.byteLength, |
| 1538 | ); |
| 1539 | } |
| 1540 | if (bytes === undefined) { |
| 1541 | jsonBinds.push(value); |
| 1542 | } else { |
| 1543 | // Copy every buffer before JSON.stringify can call a later value's |
| 1544 | // toJSON(). That callback can resize, detach, or mutate this backing |
| 1545 | // buffer, but exec() has already accepted the bytes at this point. |
| 1546 | byteBinds.push([index, new Uint8Array(bytes)]); |
| 1547 | jsonBinds.push(null); |
| 1548 | } |
| 1549 | } |
| 1550 | const json = JSON.stringify(jsonBinds); |
| 1551 | return new SqlCursor(byteBinds.length === 0 |
| 1552 | ? __sql_cursor_start(this._scope, query, json) |
| 1553 | : __sql_cursor_start(this._scope, query, json, byteBinds)); |
| 1554 | } |
| 1555 | ingest(input) { |
| 1556 | this._storage._assertTransactionActive("sql.ingest"); |
| 1557 | const result = JSON.parse(__sql_ingest(this._scope, String(input))); |
| 1558 | if (result.error) throw new Error("SQL error: " + result.error); |
| 1559 | return result; |
| 1560 | } |
| 1561 | get databaseSize() { |
| 1562 | this._storage._assertTransactionActive("sql.databaseSize"); |
| 1563 | return __sql_database_size(this._scope); |
| 1564 | } |
| 1565 | setMaxPageCountForTest(pages) { |
| 1566 | if (typeof __sql_set_max_page_count_for_test !== "function") |
| 1567 | throw new Error("setMaxPageCountForTest is only available in tests"); |
| 1568 | __sql_set_max_page_count_for_test(this._scope, Number(pages)); |
| 1569 | } |
| 1570 | setWriteFaultForTest(enabled) { |
| 1571 | if (typeof __sql_set_write_fault_for_test !== "function") |
| 1572 | throw new Error("setWriteFaultForTest is only available in tests"); |
| 1573 | __sql_set_write_fault_for_test(!!enabled); |
| 1574 | } |
| 1575 | setCacheSizeForTest(pages) { |
| 1576 | if (typeof __sql_set_cache_size_for_test !== "function") |
| 1577 | throw new Error("setCacheSizeForTest is only available in tests"); |
| 1578 | __sql_set_cache_size_for_test(this._scope, Number(pages)); |
| 1579 | } |
| 1580 | setInterruptFaultForTest(enabled) { |
| 1581 | if (typeof __sql_set_interrupt_fault_for_test !== "function") |
| 1582 | throw new Error( |
| 1583 | "setInterruptFaultForTest is only available in tests"); |
| 1584 | __sql_set_interrupt_fault_for_test(this._scope, !!enabled); |
| 1585 | } |
| 1586 | registerNomemFunctionForTest() { |
| 1587 | if (typeof __sql_register_nomem_function_for_test !== "function") |
| 1588 | throw new Error( |
| 1589 | "registerNomemFunctionForTest is only available in tests"); |
| 1590 | __sql_register_nomem_function_for_test(this._scope); |
| 1591 | } |
| 1592 | } |
| 1593 | function __readStoredValue(scope, key, read) { |
| 1594 | try { |
| 1595 | return read(); |
| 1596 | } catch (error) { |
| 1597 | const message = String(error && error.message || error); |
| 1598 | if (!message.toLowerCase().includes("deserialize cloned data")) |
| 1599 | throw error; |
| 1600 | const contextual = new Error( |
| 1601 | "actor storage deserialization failed; actorId = " + |
| 1602 | scope + "; key = " + key + "; " + message, |
| 1603 | ); |
| 1604 | contextual.cause = error; |
| 1605 | throw contextual; |
| 1606 | } |
| 1607 | } |
| 1608 | class SyncKvListIterator { |
| 1609 | constructor(root, generation, cursor) { |
| 1610 | this._root = root; |
| 1611 | this._generation = generation; |
| 1612 | this._cursor = cursor; |
| 1613 | } |
| 1614 | [Symbol.iterator]() { return this; } |
| 1615 | next() { |
| 1616 | if (this._generation !== this._root._syncKvListGeneration) { |
| 1617 | throw new Error( |
| 1618 | "kv.list() iterator was invalidated because a new call to kv.list() was started. " + |
| 1619 | "Only one kv.list() iterator can exist at a time.", |
| 1620 | ); |
| 1621 | } |
| 1622 | const value = |
| 1623 | __storage_sync_list_next(this._cursor, __storedSentinel); |
| 1624 | if (value === null) return { done: true, value: undefined }; |
| 1625 | value[1] = __unwrapStored(value[1]); |
| 1626 | return { done: false, value }; |
| 1627 | } |
| 1628 | } |
| 1629 | class SyncKvStorage { |
| 1630 | constructor(storage) { |
| 1631 | this._storage = storage; |
| 1632 | this._root = storage._transactionRoot; |
| 1633 | } |
| 1634 | get(key) { |
| 1635 | this._storage._assertTransactionActive("kv.get"); |
| 1636 | key = String(key); |
| 1637 | return __unwrapStored(__readStoredValue( |
| 1638 | this._storage._scope, key, |
| 1639 | () => __storage_get(this._storage._scope, key, |
| 1640 | __storedSentinel), |
| 1641 | )); |
| 1642 | } |
| 1643 | put(key, value) { |
| 1644 | this._storage._assertTransactionActive("kv.put"); |
| 1645 | key = String(key); |
| 1646 | try { |
| 1647 | __storage_put(this._storage._scope, key, value); |
| 1648 | } catch (error) { |
| 1649 | __storage_put_serialized(this._storage._scope, key, |
| 1650 | __storedBytes(value, error)); |
| 1651 | } |
| 1652 | } |
| 1653 | delete(key) { |
| 1654 | this._storage._assertTransactionActive("kv.delete"); |
| 1655 | return __storage_delete(this._storage._scope, String(key)); |
| 1656 | } |
| 1657 | list(options = {}) { |
| 1658 | this._storage._assertTransactionActive("kv.list"); |
| 1659 | const generation = ++this._root._syncKvListGeneration; |
| 1660 | const cursor = __storage_sync_list_start( |
| 1661 | this._storage._scope, JSON.stringify(options), |
| 1662 | ); |
| 1663 | return new SyncKvListIterator( |
| 1664 | this._root, generation, cursor, |
| 1665 | ); |
| 1666 | } |
| 1667 | } |
| 1668 | class DurableObjectStorage { |
| 1669 | constructor( |
| 1670 | scope, |
| 1671 | state = null, |
| 1672 | transactionRoot = null, |
| 1673 | transactionDepth = 0, |
| 1674 | transactionControl = null, |
| 1675 | ) { |
| 1676 | this._scope = scope; |
| 1677 | this._state = state; |
| 1678 | this.sql = new SqlStorage(scope, state, this); |
| 1679 | this._transactionRoot = transactionRoot || this; |
| 1680 | this._transactionDepth = transactionDepth; |
| 1681 | this._transactionControl = transactionControl; |
| 1682 | if (!transactionRoot) { |
| 1683 | this._transactionSerial = 0; |
| 1684 | this._transactionTail = Promise.resolve(); |
| 1685 | this._transactionOwner = ""; |
| 1686 | this._activeTransaction = null; |
| 1687 | this._activeSyncTransaction = null; |
| 1688 | this._syncKvListGeneration = 0; |
| 1689 | } |
| 1690 | this._kv = new SyncKvStorage(this); |
| 1691 | } |
| 1692 | get kv() { return this._kv; } |
| 1693 | _transactionStatus() { |
| 1694 | let status = null; |
| 1695 | for (let control = this._transactionControl; control; control = control.parent) { |
| 1696 | if (control.rolledBack) return "rolled back"; |
| 1697 | if (control.committed) status = "committed"; |
| 1698 | } |
| 1699 | return status; |
| 1700 | } |
| 1701 | _assertTransactionActive(operation) { |
| 1702 | const status = this._transactionStatus(); |
| 1703 | // workerd's wording, which applications match on. |
| 1704 | if (status === "committed") |
| 1705 | throw new Error( |
| 1706 | "Cannot call " + operation + "() on transaction that has already committed: " + |
| 1707 | "did you move `txn` outside of the closure?", |
| 1708 | ); |
| 1709 | if (status) throw new Error("Cannot " + operation + "() on " + status + " transaction"); |
| 1710 | } |
| 1711 | _flushPendingPuts() { |
| 1712 | // An admitted put can resume after its boundary flushed and ended the |
| 1713 | // transaction. Its promise completes without flushing a later scope. |
| 1714 | if (this._transactionStatus()) return false; |
| 1715 | if (this._state && this._state._aborted) return false; |
| 1716 | __storage_flush_pending_puts(this._scope); |
| 1717 | return true; |
| 1718 | } |
| 1719 | async get(k) { |
| 1720 | this._assertTransactionActive("get"); |
| 1721 | // Transaction operations reach SQLite before their caller can roll back. |
| 1722 | if (!this._transactionControl) await Promise.resolve(); |
| 1723 | if (!this._flushPendingPuts()) return; |
| 1724 | const key = Array.isArray(k) ? JSON.stringify(k) : String(k); |
| 1725 | return __readStoredValue(this._scope, key, () => { |
| 1726 | if (Array.isArray(k)) |
| 1727 | return __unwrapStoredMap( |
| 1728 | __storage_get_many(this._scope, k, __storedSentinel)); |
| 1729 | return __unwrapStored( |
| 1730 | __storage_get(this._scope, k, __storedSentinel)); |
| 1731 | }); |
| 1732 | } |
| 1733 | async put(k, val) { |
| 1734 | this._assertTransactionActive("put"); |
| 1735 | if (typeof k === "string") { |
| 1736 | try { |
| 1737 | __storage_queue_put(this._scope, k, val); |
| 1738 | } catch (error) { |
| 1739 | __storage_queue_put_serialized(this._scope, k, |
| 1740 | __storedBytes(val, error)); |
| 1741 | } |
| 1742 | await Promise.resolve(); |
| 1743 | this._flushPendingPuts(); |
| 1744 | return; |
| 1745 | } |
| 1746 | const source = k instanceof Map ? Array.from(k) : Object.entries(k); |
| 1747 | if (source.length === 0) return; |
| 1748 | const entries = |
| 1749 | source.map(([key, value]) => [String(key), value]); |
| 1750 | try { |
| 1751 | __storage_queue_put_many(this._scope, entries); |
| 1752 | } catch (error) { |
| 1753 | // A batch with a stub entry: encode every entry first (plain |
| 1754 | // entries keep their native clone bytes, stub entries take |
| 1755 | // the stored-stub envelope), then queue -- so a genuinely |
| 1756 | // uncloneable entry still queues nothing, like the batch op, |
| 1757 | // which serializes fully before queueing. |
| 1758 | const encoded = entries.map(([key, value]) => { |
| 1759 | try { |
| 1760 | return [key, __sc_encode(value)]; |
| 1761 | } catch (error_) { |
| 1762 | return [key, __storedBytes(value, error_)]; |
| 1763 | } |
| 1764 | }); |
| 1765 | for (const [key, bytes] of encoded) |
| 1766 | __storage_queue_put_serialized(this._scope, key, bytes); |
| 1767 | } |
| 1768 | await Promise.resolve(); |
| 1769 | this._flushPendingPuts(); |
| 1770 | } |
| 1771 | async delete(k) { |
| 1772 | this._assertTransactionActive("delete"); |
| 1773 | if (!this._transactionControl) await Promise.resolve(); |
| 1774 | if (!this._flushPendingPuts()) return; |
| 1775 | if (Array.isArray(k)) { |
| 1776 | if (k.length === 0) return 0; |
| 1777 | return __storage_delete_many(this._scope, k); |
| 1778 | } |
| 1779 | return __storage_delete(this._scope, k); |
| 1780 | } |
| 1781 | async list(options = {}) { |
| 1782 | this._assertTransactionActive("list"); |
| 1783 | if (!this._transactionControl) await Promise.resolve(); |
| 1784 | if (!this._flushPendingPuts()) return new Map(); |
| 1785 | return __unwrapStoredMap(__storage_list( |
| 1786 | this._scope, JSON.stringify(options), __storedSentinel)); |
| 1787 | } |
| 1788 | async deleteAll() { |
| 1789 | this._assertTransactionActive("deleteAll"); |
| 1790 | if (!this._transactionControl) await Promise.resolve(); |
| 1791 | if (!this._flushPendingPuts()) return; |
| 1792 | __storage_delete_all(this._scope, __cell.deleteAllDeletesAlarm); |
| 1793 | } |
| 1794 | // Resolves once every write this cell committed before the call is |
| 1795 | // proven durable, by the proof the output gate requires before it releases |
| 1796 | // an egress. Workerd resolves when the pending writes have completed; on |
| 1797 | // celld the local file is a cache, so "completed" is "proven". The host op |
| 1798 | // rejects when that proof fails or times out, so an application never |
| 1799 | // treats a lost write as safe. |
| 1800 | async sync() { |
| 1801 | this._assertTransactionActive("sync"); |
| 1802 | await Promise.resolve(); |
| 1803 | const status = this._transactionStatus(); |
| 1804 | // An admitted sync can resume after transactionSync commits or rolls |
| 1805 | // back. Its boundary settled the queued puts, so prove the surviving |
| 1806 | // state without flushing a later transaction through this handle. A |
| 1807 | // new call after that boundary still fails the entry guard above. |
| 1808 | if (this._state?._aborted || (status === null && !this._flushPendingPuts())) |
| 1809 | throw new Error( |
| 1810 | "storage.sync: " + this._scope + " was aborted; the object is no " + |
| 1811 | "longer running"); |
| 1812 | await __storage_sync(this._scope); |
| 1813 | } |
| 1814 | async setAlarm(t) { |
| 1815 | this._assertTransactionActive("setAlarm"); |
| 1816 | if (!this._transactionControl) await Promise.resolve(); |
| 1817 | if (!this._flushPendingPuts()) return; |
| 1818 | if (this._state?._facetDepth > 0) |
| 1819 | throw new Error("Facets currently cannot set alarms."); |
| 1820 | __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); |
| 1821 | } |
| 1822 | async getAlarm() { |
| 1823 | this._assertTransactionActive("getAlarm"); |
| 1824 | if (!this._transactionControl) await Promise.resolve(); |
| 1825 | if (!this._flushPendingPuts()) return null; |
| 1826 | const v = __alarm_get(this._scope); |
| 1827 | return v === null ? null : v; |
| 1828 | } |
| 1829 | async deleteAlarm() { |
| 1830 | this._assertTransactionActive("deleteAlarm"); |
| 1831 | if (!this._transactionControl) await Promise.resolve(); |
| 1832 | if (!this._flushPendingPuts()) return; |
| 1833 | __alarm_delete(this._scope); |
| 1834 | } |
| 1835 | _transactionStart() { |
| 1836 | const root = this._transactionRoot; |
| 1837 | const savepoint = "cells_tx_" + (++root._transactionSerial); |
| 1838 | __storage_transaction_control( |
| 1839 | this._scope, "start", this._transactionDepth > 0, savepoint, |
| 1840 | ); |
| 1841 | return savepoint; |
| 1842 | } |
| 1843 | _transactionCommit(savepoint) { |
| 1844 | __storage_transaction_control( |
| 1845 | this._scope, "commit", this._transactionDepth > 0, savepoint, |
| 1846 | ); |
| 1847 | } |
| 1848 | _transactionRollback(savepoint, explicit = false) { |
| 1849 | __storage_transaction_control( |
| 1850 | this._scope, |
| 1851 | explicit ? "rollback_explicit" : "rollback", |
| 1852 | this._transactionDepth > 0, |
| 1853 | savepoint, |
| 1854 | ); |
| 1855 | } |
| 1856 | _transactionView(transactionControl) { |
| 1857 | return new DurableObjectStorage( |
| 1858 | this._scope, |
| 1859 | this._state, |
| 1860 | this._transactionRoot, |
| 1861 | this._transactionDepth + 1, |
| 1862 | transactionControl, |
| 1863 | ); |
| 1864 | } |
| 1865 | rollback() { |
| 1866 | const control = this._transactionControl; |
| 1867 | if (!control) |
| 1868 | throw new TypeError("rollback() must be called on a transaction"); |
| 1869 | if (control.rolledBack) return; |
| 1870 | this._assertTransactionActive("rollback"); |
| 1871 | // An asynchronous child can still own a nested savepoint. Mark this view |
| 1872 | // terminal now, but let its runner release the child before it rolls this |
| 1873 | // layer back. |
| 1874 | if (control.pending.size === 0) control.rollback(); |
| 1875 | control.rolledBack = true; |
| 1876 | } |
| 1877 | transactionSync(f) { |
| 1878 | this._assertTransactionActive("transactionSync"); |
| 1879 | const root = this._transactionRoot; |
| 1880 | if (this._transactionDepth === 0) { |
| 1881 | // A callback can call a helper that reaches the root `ctx.storage` |
| 1882 | // handle instead of the transaction view, and the helper starts its own |
| 1883 | // synchronous transaction. Workerd nests that one under the open |
| 1884 | // transaction; celld attempted a second top-level BEGIN and failed with |
| 1885 | // "cannot start a transaction within a transaction" |
| 1886 | // (denoland/celld#226). The open view takes the call instead, so it |
| 1887 | // becomes a savepoint: an inner rollback then discards only the inner |
| 1888 | // writes, and an outer rollback discards both layers. |
| 1889 | // |
| 1890 | // The synchronous transaction is preferred over an asynchronous one, |
| 1891 | // because it is the innermost open layer whenever both are open. |
| 1892 | if (root._activeSyncTransaction !== null) |
| 1893 | return root._activeSyncTransaction.transactionSync(f); |
| 1894 | const owner = String(__io_context_id()); |
| 1895 | if (owner !== "" && root._transactionOwner === owner && |
| 1896 | root._activeTransaction !== null) |
| 1897 | return root._activeTransaction.transactionSync(f); |
| 1898 | } |
| 1899 | const savepoint = this._transactionStart(); |
| 1900 | const control = this._newTransactionControl(savepoint); |
| 1901 | const view = this._transactionView(control); |
| 1902 | // No owner check guards this slot, unlike `_activeTransaction`, which an |
| 1903 | // asynchronous transaction publishes across awaits and must therefore keep |
| 1904 | // with the event that opened it. The callback below runs to its end before |
| 1905 | // any other event starts, so only that event can read the slot, and the |
| 1906 | // restore below runs at exactly the point the savepoint ends. |
| 1907 | const previousSync = root._activeSyncTransaction; |
| 1908 | root._activeSyncTransaction = view; |
| 1909 | try { |
| 1910 | // workerd hands the callback nothing: the root's own methods write |
| 1911 | // inside the transaction, and a throw rolls it back. |
| 1912 | const value = f(); |
| 1913 | if (!control.rolledBack) { |
| 1914 | this._transactionCommit(savepoint); |
| 1915 | control.committed = true; |
| 1916 | } |
| 1917 | return value; |
| 1918 | } catch (error) { |
| 1919 | if (!control.rolledBack) { |
| 1920 | try { |
| 1921 | this._transactionRollback(savepoint); |
| 1922 | control.rolledBack = true; |
| 1923 | } catch (rollbackError) { |
| 1924 | this._abortAfterFailedRollback(rollbackError, error); |
| 1925 | } |
| 1926 | } |
| 1927 | throw error; |
| 1928 | } finally { |
| 1929 | root._activeSyncTransaction = previousSync; |
| 1930 | } |
| 1931 | } |
| 1932 | _newTransactionControl(savepoint) { |
| 1933 | const control = { |
| 1934 | rolledBack: false, |
| 1935 | rollbackPerformed: false, |
| 1936 | committed: false, |
| 1937 | parent: this._transactionControl, |
| 1938 | pending: new Set(), |
| 1939 | rollback: () => { |
| 1940 | this._transactionRollback(savepoint, true); |
| 1941 | control.rollbackPerformed = true; |
| 1942 | }, |
| 1943 | }; |
| 1944 | return control; |
| 1945 | } |
| 1946 | async _drainNestedTransactions(control) { |
| 1947 | while (control.pending.size !== 0) |
| 1948 | await Promise.allSettled(Array.from(control.pending)); |
| 1949 | } |
| 1950 | async _runTransactionWith(f, savepoint, control) { |
| 1951 | const view = this._transactionView(control); |
| 1952 | const root = this._transactionRoot; |
| 1953 | const owner = String(__io_context_id()); |
| 1954 | const installsActive = owner !== "" && root._transactionOwner === owner; |
| 1955 | const previousActive = root._activeTransaction; |
| 1956 | if (installsActive) root._activeTransaction = view; |
| 1957 | try { |
| 1958 | const value = await f(view); |
| 1959 | // A helper can start a reentrant transaction through the root storage |
| 1960 | // handle and omit the returned promise. That child already owns a |
| 1961 | // savepoint, so ending this layer first would make SQLite release the |
| 1962 | // child's savepoint and let its continuation run against a false owner. |
| 1963 | await this._drainNestedTransactions(control); |
| 1964 | if (!control.rolledBack) { |
| 1965 | this._transactionCommit(savepoint); |
| 1966 | control.committed = true; |
| 1967 | } else if (!control.rollbackPerformed) { |
| 1968 | control.rollback(); |
| 1969 | } |
| 1970 | return value; |
| 1971 | } catch (error) { |
| 1972 | await this._drainNestedTransactions(control); |
| 1973 | if (!control.rollbackPerformed) { |
| 1974 | // The flag records a rollback that happened, not one that was |
| 1975 | // attempted: a rollback that fails leaves the savepoint open, and a |
| 1976 | // later transaction on the same connection would commit its writes. |
| 1977 | // Nothing can be said about the connection then, so the object is |
| 1978 | // aborted rather than left to serve from it. |
| 1979 | try { |
| 1980 | this._transactionRollback(savepoint); |
| 1981 | control.rolledBack = true; |
| 1982 | control.rollbackPerformed = true; |
| 1983 | } catch (rollbackError) { |
| 1984 | this._abortAfterFailedRollback(rollbackError, error); |
| 1985 | } |
| 1986 | } |
| 1987 | throw error; |
| 1988 | } finally { |
| 1989 | if (installsActive && root._activeTransaction === view) |
| 1990 | root._activeTransaction = previousActive; |
| 1991 | } |
| 1992 | } |
| 1993 | // `cause` is the failure that led to the rollback; the abort's error keeps |
| 1994 | // it, so a debugger can walk back to the callback's own throw. The |
| 1995 | // rollback failure is reported even when the object is already aborted, |
| 1996 | // as it is after a block's limit: the abort then changes nothing, and the |
| 1997 | // log line is the only trace the failure leaves. |
| 1998 | _abortAfterFailedRollback(rollbackError, cause) { |
| 1999 | // Inside a catch, so the log must not become the throw that leaves it: |
| 2000 | // the slot release after the caller's rethrow depends on that. |
| 2001 | try { console.error("transaction rollback failed", rollbackError); } catch {} |
| 2002 | const state = this._transactionRoot._state; |
| 2003 | if (state && !state._aborted) { |
| 2004 | state.abort( |
| 2005 | new Error( |
| 2006 | "a transaction rollback failed: " + __describeFailure(rollbackError), |
| 2007 | { cause }, |
| 2008 | ), |
| 2009 | ); |
| 2010 | } |
| 2011 | } |
| 2012 | async _runTransaction(f) { |
| 2013 | const savepoint = this._transactionStart(); |
| 2014 | return this._runTransactionWith(f, savepoint, this._newTransactionControl(savepoint)); |
| 2015 | } |
| 2016 | async transaction(f) { |
| 2017 | this._assertTransactionActive("transaction"); |
| 2018 | if (this._transactionDepth > 0) { |
| 2019 | const nested = this._runTransaction(f); |
| 2020 | const pending = this._transactionControl.pending; |
| 2021 | pending.add(nested); |
| 2022 | nested.then( |
| 2023 | () => pending.delete(nested), |
| 2024 | () => pending.delete(nested), |
| 2025 | ); |
| 2026 | return nested; |
| 2027 | } |
| 2028 | const root = this._transactionRoot; |
| 2029 | const owner = String(__io_context_id()); |
| 2030 | if (owner !== "" && root._transactionOwner === owner && |
| 2031 | root._activeTransaction !== null) |
| 2032 | return root._activeTransaction.transaction(f); |
| 2033 | // Workerd runs the callback under blockConcurrencyWhile: the input gate |
| 2034 | // shuts, so no other event starts in the object while the transaction is |
| 2035 | // open. Without it another event's reads saw uncommitted rows, its |
| 2036 | // writes joined the open transaction on the same connection, and a |
| 2037 | // rollback discarded a write celld had already acknowledged (#714). The |
| 2038 | // callback's failure is caught inside the block: a failed transaction |
| 2039 | // rolls back and rejects, and must not reset the object the way a failed |
| 2040 | // critical section does. |
| 2041 | // |
| 2042 | // The tail orders transactions one event starts concurrently, which the |
| 2043 | // gate does not separate. Its slot is taken here, in call order: taken |
| 2044 | // inside the block it would be taken in the order the gate woke the |
| 2045 | // callers, which is not theirs to keep. It is released inside the block, |
| 2046 | // when the callback has settled, and not when the block has: a second |
| 2047 | // transaction the same event starts while the first runs rides the |
| 2048 | // outer hold as a nested block, and the outer block waits for nested |
| 2049 | // ones before it releases, so a slot held until the block's end would |
| 2050 | // wait on itself. |
| 2051 | const previous = root._transactionTail; |
| 2052 | let release; |
| 2053 | root._transactionTail = new Promise((resolve) => { release = resolve; }); |
| 2054 | let control = null; |
| 2055 | let started = false; |
| 2056 | let abandoned = null; |
| 2057 | const guarded = async () => { |
| 2058 | started = true; |
| 2059 | let ownsTransaction = false; |
| 2060 | try { |
| 2061 | await previous; |
| 2062 | // The block ended while this waited for its slot, or the object was |
| 2063 | // reset under it by an enclosing block that failed: the caller has |
| 2064 | // its rejection and the gate is open again, so starting the |
| 2065 | // transaction now would run it beside whatever the object serves. |
| 2066 | if (abandoned !== null) return { error: abandoned }; |
| 2067 | if (root._state._aborted) { |
| 2068 | return { error: new Error("the Durable Object was reset before the transaction started") }; |
| 2069 | } |
| 2070 | // A callback can compose a helper which reaches the root |
| 2071 | // `ctx.storage` handle instead of the transaction view. The input |
| 2072 | // gate excludes other events, but an event which entered before the |
| 2073 | // gate closed can still be waiting for this slot. Keep the owner with |
| 2074 | // the open transaction so only the callback's event takes the |
| 2075 | // savepoint path; another event still waits on the tail. |
| 2076 | root._transactionOwner = owner; |
| 2077 | ownsTransaction = true; |
| 2078 | // The start is a host op that can fail like any other statement, and |
| 2079 | // a failure there is the transaction's to report, not the block's: |
| 2080 | // a throw that escaped here would reset the object. |
| 2081 | try { |
| 2082 | const savepoint = this._transactionStart(); |
| 2083 | control = this._newTransactionControl(savepoint); |
| 2084 | return { value: await this._runTransactionWith(f, savepoint, control) }; |
| 2085 | } catch (error) { |
| 2086 | return { error }; |
| 2087 | } |
| 2088 | } finally { |
| 2089 | if (ownsTransaction && root._transactionOwner === owner) { |
| 2090 | root._activeTransaction = null; |
| 2091 | root._transactionOwner = ""; |
| 2092 | } |
| 2093 | release(); |
| 2094 | } |
| 2095 | }; |
| 2096 | let outcome; |
| 2097 | try { |
| 2098 | outcome = await root._state.blockConcurrencyWhile(guarded); |
| 2099 | } catch (error) { |
| 2100 | // The block itself failed: its limit ended the callback while it still |
| 2101 | // ran, or the block ahead of it failed and this one never started. A |
| 2102 | // transaction the callback still holds would otherwise stay open on |
| 2103 | // the connection the object's replacement uses, and the callback's |
| 2104 | // late commit would carry the replacement's writes with it. Roll it |
| 2105 | // back now, unless the callback's continuation committed in the same |
| 2106 | // tick the limit won; the callback's own commit is skipped from here |
| 2107 | // on. The slot stays with the callback until it settles: the callback |
| 2108 | // still runs on the connection, and a transaction started beside it |
| 2109 | // would interleave with its remaining statements. A routed child must |
| 2110 | // release its savepoint before this layer rolls back, so a live child |
| 2111 | // leaves the rollback for `_runTransactionWith`. A block that failed |
| 2112 | // before the callback started holds nothing, so its slot is released |
| 2113 | // here or nothing ever would. |
| 2114 | abandoned = error; |
| 2115 | if (control && !control.rolledBack && !control.committed) { |
| 2116 | try { |
| 2117 | if (control.pending.size === 0) control.rollback(); |
| 2118 | control.rolledBack = true; |
| 2119 | } catch (rollbackError) { |
| 2120 | this._abortAfterFailedRollback(rollbackError, error); |
| 2121 | } |
| 2122 | } |
| 2123 | if (!started) release(); |
| 2124 | throw error; |
| 2125 | } |
| 2126 | if ("error" in outcome) throw outcome.error; |
| 2127 | return outcome.value; |
| 2128 | } |
| 2129 | } |
| 2130 | class DurableObjectId { |
| 2131 | constructor(className, value, name = undefined) { |
| 2132 | Object.defineProperties(this, { |
| 2133 | _className: { value: className }, |
| 2134 | _value: { value }, |
| 2135 | }); |
| 2136 | this.name = name; |
| 2137 | this.jurisdiction = undefined; |
| 2138 | } |
| 2139 | toString() { return this._value; } |
| 2140 | equals(other) { |
| 2141 | return other instanceof DurableObjectId && other._value === this._value; |
| 2142 | } |
| 2143 | _scope() { return this._className + ":" + this._value; } |
| 2144 | } |
| 2145 | globalThis.DurableObjectRoutingError = class DurableObjectRoutingError |
| 2146 | extends Error { |
| 2147 | constructor(detail = {}) { |
| 2148 | super("The Durable Object owner is currently unreachable"); |
| 2149 | this.name = "DurableObjectRoutingError"; |
| 2150 | this.code = "owner_unreachable"; |
| 2151 | this.retryable = true; |
| 2152 | if (typeof detail.scope === "string") this.scope = detail.scope; |
| 2153 | if (typeof detail.owner === "string") this.owner = detail.owner; |
| 2154 | } |
| 2155 | }; |
| 2156 | const __durableObjectRoutingError = (error) => { |
| 2157 | const marker = "__CELLD_DO_ROUTING_ERROR__:"; |
| 2158 | const message = String(error && error.message || error); |
| 2159 | const offset = message.indexOf(marker); |
| 2160 | if (offset < 0) return null; |
| 2161 | try { |
| 2162 | return new DurableObjectRoutingError( |
| 2163 | JSON.parse(message.slice(offset + marker.length)), |
| 2164 | ); |
| 2165 | } catch { |
| 2166 | return new DurableObjectRoutingError(); |
| 2167 | } |
| 2168 | }; |
| 2169 | // A cell's input gate as the isolate sees it, for the one delivery |
| 2170 | // point that is inside the isolate rather than in front of it: an |
| 2171 | // RPC stub op. `events` records every block that has asked for the |
| 2172 | // gate, so no window exists in which a block has started and the |
| 2173 | // isolate still thinks the cell is open. `holder` names the block |
| 2174 | // actually running; another event can still be queued. |
| 2175 | // |
| 2176 | // A stub minted while a block runs carries that block's token and |
| 2177 | // re-enters it instead of queueing behind it. That is Workerd's |
| 2178 | // `IoContext::makeReentryCallback`, and without it a callback the |
| 2179 | // block itself sent out could never come back. |
| 2180 | const __cellBlocks = new Map(); |
| 2181 | const __blockEnter = (scope, event, owner) => { |
| 2182 | let settleReady; |
| 2183 | let rejectReady; |
| 2184 | const ready = new Promise((resolve, reject) => { |
| 2185 | settleReady = resolve; |
| 2186 | rejectReady = reject; |
| 2187 | }); |
| 2188 | const record = { |
| 2189 | owner, |
| 2190 | reaction: String(__io_context_id()), |
| 2191 | actorEvent: __currentActorEvent(), |
| 2192 | retired: false, |
| 2193 | ready, |
| 2194 | settleReady, |
| 2195 | rejectReady, |
| 2196 | }; |
| 2197 | const block = __cellBlocks.get(scope); |
| 2198 | if (block !== undefined) { |
| 2199 | block.events.set(event, record); |
| 2200 | return { block, record }; |
| 2201 | } |
| 2202 | const fresh = { |
| 2203 | holder: null, |
| 2204 | events: new Map([[event, record]]), |
| 2205 | }; |
| 2206 | __cellBlocks.set(scope, fresh); |
| 2207 | return { block: fresh, record }; |
| 2208 | }; |
| 2209 | const __blockLeave = (scope, block, event) => { |
| 2210 | if (!block.events.delete(event)) return; |
| 2211 | if (block.holder === event) block.holder = null; |
| 2212 | if (block.events.size === 0 && __cellBlocks.get(scope) === block) |
| 2213 | __cellBlocks.delete(scope); |
| 2214 | }; |
| 2215 | const __durableClassMeta = new WeakMap(); |
| 2216 | let __nextFacetOwner = 1; |
| 2217 | // Takes encoded props, not the caller's options bag: an options bag reaching |
| 2218 | // here is a bag nothing validated, and reading one key out of it is how every |
| 2219 | // other key came to be dropped in silence. The loader stub validates the bag |
| 2220 | // and encodes its value before it creates the class. |
| 2221 | const __makeDurableObjectClass = (loadPromise, name, propsSc) => { |
| 2222 | const value = {}; |
| 2223 | __durableClassMeta.set(value, { |
| 2224 | loadPromise, |
| 2225 | name: name === null || name === undefined ? "default" : String(name), |
| 2226 | propsSc, |
| 2227 | }); |
| 2228 | return value; |
| 2229 | }; |
| 2230 | // Loopback classes are callable; a specialized class is only a handle. Capture |
| 2231 | // props now, so later mutation of the caller's options cannot change startup. |
| 2232 | const __makeLoopbackDurableObjectClass = (name) => { |
| 2233 | const loadPromise = Promise.resolve({ id: 0 }); |
| 2234 | const specialize = function(options) { |
| 2235 | if (arguments.length === 0) |
| 2236 | throw new TypeError("DurableObjectClass requires an options argument."); |
| 2237 | if (options !== undefined && options !== null && |
| 2238 | typeof options !== "object" && typeof options !== "function") |
| 2239 | throw new TypeError("DurableObjectClass options must be an object."); |
| 2240 | const props = options?.props; |
| 2241 | if (props !== undefined && |
| 2242 | (props === null || (typeof props !== "object" && typeof props !== "function"))) |
| 2243 | throw new TypeError("DurableObjectClass props must be an object."); |
| 2244 | return __makeDurableObjectClass( |
| 2245 | loadPromise, name, __rpcOut(props === undefined ? {} : props, false)); |
| 2246 | }; |
| 2247 | __durableClassMeta.set(specialize, { |
| 2248 | loadPromise, name, propsSc: __rpcOut({}, false), |
| 2249 | }); |
| 2250 | return specialize; |
| 2251 | }; |
| 2252 | class DurableObjectFacets { |
| 2253 | constructor(state) { |
| 2254 | this._state = state; |
| 2255 | this._owner = String(__nextFacetOwner++); |
| 2256 | this._next = 1; |
| 2257 | this._running = new Map(); |
| 2258 | this._barriers = new Map(); |
| 2259 | } |
| 2260 | _validName(name) { |
| 2261 | name = String(name); |
| 2262 | if (new TextEncoder().encode(name).length > 256) |
| 2263 | throw new TypeError("Facet name is too long (max 256 characters)."); |
| 2264 | return name; |
| 2265 | } |
| 2266 | get(name, getStartupOptions) { |
| 2267 | name = this._validName(name); |
| 2268 | if (this._state._facetDepth >= 3) |
| 2269 | throw new Error( |
| 2270 | "Facet nesting depth limit exceeded. The maximum depth including the root Durable Object is 4."); |
| 2271 | if (typeof getStartupOptions !== "function") |
| 2272 | throw new TypeError("The facet startup callback must be a function."); |
| 2273 | let record = this._running.get(name); |
| 2274 | if (record !== undefined) return record.stub; |
| 2275 | // Each run gets a distinct host scope. An aborted request can still have |
| 2276 | // a pending continuation, so reusing its scope would let that continuation |
| 2277 | // enter the replacement instance after the abort barrier opens. |
| 2278 | record = { |
| 2279 | aborted: false, |
| 2280 | error: undefined, |
| 2281 | owner: this._owner + ":" + this._next++, |
| 2282 | started: null, |
| 2283 | stub: null, |
| 2284 | }; |
| 2285 | const barrier = this._barriers.get(name); |
| 2286 | const start = () => record.started ??= Promise.resolve(barrier) |
| 2287 | .then(getStartupOptions) |
| 2288 | .then(async (options) => { |
| 2289 | const meta = __durableClassMeta.get(options?.class); |
| 2290 | if (meta === undefined) |
| 2291 | throw new TypeError( |
| 2292 | "FacetStartupOptions.class must be a DurableObjectClass."); |
| 2293 | const { id: loader } = await meta.loadPromise; |
| 2294 | const id = options.id === undefined ? this._state.id : options.id; |
| 2295 | // Keep the ID kind and name in one clone. A string round-trip erases |
| 2296 | // named IDs and turns a literal string ID into a DurableObjectId. |
| 2297 | const idSc = __sc_encode(id instanceof DurableObjectId |
| 2298 | ? [id._className, id.toString(), id.name] : String(id)); |
| 2299 | // Keep the load alive after the startup callback and class are gone. |
| 2300 | return [loader, meta.name, idSc, meta.propsSc, meta]; |
| 2301 | }); |
| 2302 | const invoke = async (operation) => { |
| 2303 | if (record.aborted) throw record.error; |
| 2304 | return operation(await start()); |
| 2305 | }; |
| 2306 | const target = {}; |
| 2307 | // Methods share the loaded-worker RPC transport. A facet stub is not |
| 2308 | // awaitable, and a property is a single callable pipeline node. |
| 2309 | const session = { |
| 2310 | get: () => Promise.reject(new Error( |
| 2311 | "Awaitable properties on facets are not supported yet.")), |
| 2312 | call: (path, args) => invoke(async ([loader, className, id, propsSc]) => { |
| 2313 | if (path.length !== 1) |
| 2314 | throw new Error( |
| 2315 | "Pipelined property paths on facets are not supported yet."); |
| 2316 | return __rpcDes(await __facet_rpc( |
| 2317 | loader, className, this._state._scope, record.owner, name, id, |
| 2318 | propsSc, path[0], __rpcOut(args, false))); |
| 2319 | }), |
| 2320 | }; |
| 2321 | // Arrow closures retain the manager because `target.fetch`'s method |
| 2322 | // receiver is the target object, not the DurableObjectFacets instance. |
| 2323 | const manager = this; |
| 2324 | target.fetch = async function(input, init) { |
| 2325 | return invoke(async ([loader, className, id, propsSc]) => { |
| 2326 | const req = new Request(input, init); |
| 2327 | const headers = JSON.stringify(req.headers.__celldHeaderList); |
| 2328 | const { body, streamId } = await __subrequestBody(req); |
| 2329 | const response = JSON.parse(await __facet_fetch( |
| 2330 | loader, className, manager._state._scope, record.owner, name, id, |
| 2331 | propsSc, req.url, req.method, body, headers, streamId)); |
| 2332 | const responseBody = response.streamId !== undefined |
| 2333 | ? new CelldHttpBodyStream(response.streamId) |
| 2334 | : response.body !== undefined ? response.body |
| 2335 | : Uint8Array.from(response.bodyBytes || []); |
| 2336 | // The facet's socket lives in the facet's isolate. The target lets |
| 2337 | // the root return the upgrade, or accept the client end that the |
| 2338 | // wrapper binds to the facet's socket. |
| 2339 | return __wrapServiceResponse(new Response(responseBody, { |
| 2340 | status: response.status, |
| 2341 | headers: response.headers, |
| 2342 | __wsTarget: response.wsTarget, |
| 2343 | }), req.url); |
| 2344 | }); |
| 2345 | }; |
| 2346 | record.stub = new Proxy(target, { |
| 2347 | get(base, prop) { |
| 2348 | if (prop === "then") return undefined; |
| 2349 | if (Reflect.has(base, prop)) return Reflect.get(base, prop); |
| 2350 | if (typeof prop !== "string") return undefined; |
| 2351 | return __makeNode(session, [prop], null); |
| 2352 | }, |
| 2353 | }); |
| 2354 | this._running.set(name, record); |
| 2355 | return record.stub; |
| 2356 | } |
| 2357 | _abort(name, reason) { |
| 2358 | name = this._validName(name); |
| 2359 | const record = this._running.get(name); |
| 2360 | if (record === undefined) return Promise.resolve(); |
| 2361 | record.aborted = true; |
| 2362 | record.error = reason; |
| 2363 | this._running.delete(name); |
| 2364 | const barrier = record.started === null ? Promise.resolve() : record.started |
| 2365 | .then(([loader, className]) => |
| 2366 | __facet_abort( |
| 2367 | loader, className, this._state._scope, record.owner, name), () => {}); |
| 2368 | this._barriers.set(name, barrier); |
| 2369 | const clear = () => { |
| 2370 | if (this._barriers.get(name) === barrier) this._barriers.delete(name); |
| 2371 | }; |
| 2372 | barrier.then(clear, clear); |
| 2373 | return barrier; |
| 2374 | } |
| 2375 | abort(name, reason) { |
| 2376 | this._abort(name, reason); |
| 2377 | } |
| 2378 | delete(name) { |
| 2379 | name = this._validName(name); |
| 2380 | const barrier = this._abort(name, new Error("Facet was deleted.")).then(() => |
| 2381 | __facet_delete(this._state._scope, name)); |
| 2382 | this._barriers.set(name, barrier); |
| 2383 | const clear = () => { |
| 2384 | if (this._barriers.get(name) === barrier) this._barriers.delete(name); |
| 2385 | }; |
| 2386 | // Keep a failed delete as the name's barrier. Clearing it would let the |
| 2387 | // next get reload the image which the failed operation did not delete. |
| 2388 | barrier.then(clear, () => {}); |
| 2389 | } |
| 2390 | _release() { |
| 2391 | // The host closes these facets during give-back. Queuing _abort here |
| 2392 | // leaves an undriven op whose promise retains the manager, its root, |
| 2393 | // and the loaded classes after the root has stopped. |
| 2394 | const reason = new Error("The parent Durable Object was released."); |
| 2395 | for (const record of this._running.values()) { |
| 2396 | record.aborted = true; |
| 2397 | record.error = reason; |
| 2398 | } |
| 2399 | this._running.clear(); |
| 2400 | this._barriers.clear(); |
| 2401 | } |
| 2402 | } |
| 2403 | // The reason a failed critical section gives its waiters. It must not throw: |
| 2404 | // it runs where a throw would skip the gate's release, and a value with no |
| 2405 | // string form, such as `Object.create(null)`, is a legal thing to throw. |
| 2406 | function __describeFailure(error) { |
| 2407 | try { |
| 2408 | return String((error && error.message) || error); |
| 2409 | } catch { |
| 2410 | return "critical section failed"; |
| 2411 | } |
| 2412 | } |
| 2413 | // ---- Containers ----------------------------------------------------------- |
| 2414 | // `ctx.container` for a class named in the deployment's `containers`. The |
| 2415 | // surface and every message follow workerd's api/container.c++; the host |
| 2416 | // ops perform the effects against the node's container engine, and the |
| 2417 | // scope names the cell the way the storage ops do. |
| 2418 | const __containerEnvList = (env, what) => { |
| 2419 | const list = []; |
| 2420 | if (env === undefined || env === null) return list; |
| 2421 | for (const [name, value] of Object.entries(env)) { |
| 2422 | const text = String(value); |
| 2423 | if (name.includes("=")) |
| 2424 | throw new Error(`Environment variable names cannot contain '=': ${name}`); |
| 2425 | if (name.includes("\0")) |
| 2426 | throw new Error(`Environment variable names cannot contain '\\0': ${name}`); |
| 2427 | if (text.includes("\0")) |
| 2428 | throw new Error(`Environment variable values cannot contain '\\0': ${name}`); |
| 2429 | list.push([name, text]); |
| 2430 | } |
| 2431 | return list; |
| 2432 | }; |
| 2433 | const __execOutputMode = (mode, kind) => { |
| 2434 | const value = mode === undefined ? "pipe" : String(mode); |
| 2435 | if (value === "pipe" || value === "ignore" || |
| 2436 | (kind === "stderr" && value === "combined")) return value; |
| 2437 | throw new TypeError(`Invalid ${kind} option: ${value}`); |
| 2438 | }; |
| 2439 | const __validSignal = (signo) => Number.isInteger(signo) && signo > 0 && signo <= 64; |
| 2440 | const __execStream = (id, which) => new ReadableStream({ |
| 2441 | type: "bytes", |
| 2442 | async pull(controller) { |
| 2443 | const chunk = await __container_exec_read(id, which); |
| 2444 | if (chunk.byteLength === 0) controller.close(); |
| 2445 | else controller.enqueue(new Uint8Array(chunk)); |
| 2446 | }, |
| 2447 | }); |
| 2448 | class ContainerExecOutput { |
| 2449 | constructor(stdout, stderr, exitCode) { |
| 2450 | this.stdout = stdout; |
| 2451 | this.stderr = stderr; |
| 2452 | this.exitCode = exitCode; |
| 2453 | } |
| 2454 | } |
| 2455 | class ContainerExecProcess { |
| 2456 | constructor(id, pid, stdinMode, stdoutMode, stderrMode) { |
| 2457 | this._id = id; |
| 2458 | this.pid = pid; |
| 2459 | this._outputCalled = false; |
| 2460 | this._exitCode = null; |
| 2461 | this.stdout = stdoutMode === "pipe" ? __execStream(id, 1) : null; |
| 2462 | this.stderr = stderrMode === "pipe" ? __execStream(id, 2) : null; |
| 2463 | this.stdin = stdinMode === "pipe" |
| 2464 | ? new WritableStream({ |
| 2465 | write: (chunk) => __container_exec_write(id, __bytesOf(chunk)), |
| 2466 | close: () => __container_exec_close(id), |
| 2467 | abort: () => __container_exec_close(id), |
| 2468 | }) |
| 2469 | : null; |
| 2470 | } |
| 2471 | get exitCode() { |
| 2472 | if (this._exitCode === null) { |
| 2473 | this._exitCode = __container_exec_wait(this._id).then(Number); |
| 2474 | } |
| 2475 | return this._exitCode; |
| 2476 | } |
| 2477 | async output() { |
| 2478 | if (this._outputCalled) throw new TypeError("output() can only be called once."); |
| 2479 | this._outputCalled = true; |
| 2480 | for (const [stream, name] of [[this.stdout, "stdout"], [this.stderr, "stderr"]]) { |
| 2481 | if (stream && stream.locked) |
| 2482 | throw new TypeError(`Cannot call output() after ${name} has started being consumed.`); |
| 2483 | } |
| 2484 | const all = (stream) => stream |
| 2485 | ? new Response(stream).arrayBuffer() |
| 2486 | : Promise.resolve(new ArrayBuffer(0)); |
| 2487 | const [stdout, stderr] = await Promise.all([all(this.stdout), all(this.stderr)]); |
| 2488 | const exitCode = await this.exitCode; |
| 2489 | // Nothing else can read the process now, so the host can forget it. |
| 2490 | __container_exec_drop(this._id); |
| 2491 | return new ContainerExecOutput(stdout, stderr, exitCode); |
| 2492 | } |
| 2493 | kill(signal = 15) { |
| 2494 | if (!__validSignal(signal)) throw new RangeError("Invalid signal number."); |
| 2495 | __container_exec_kill(this._id, signal).catch(() => {}); |
| 2496 | } |
| 2497 | } |
| 2498 | const __bytesOf = (chunk) => { |
| 2499 | if (chunk instanceof Uint8Array) return chunk; |
| 2500 | if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk); |
| 2501 | if (ArrayBuffer.isView(chunk)) |
| 2502 | return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); |
| 2503 | throw new TypeError("stdin accepts bytes"); |
| 2504 | }; |
| 2505 | // The Fetcher `getTcpPort()` returns: `fetch()` speaks HTTP to the port over |
| 2506 | // the node's route to the container, and `connect()` is the raw socket. |
| 2507 | class ContainerPort { |
| 2508 | constructor(scope, port) { |
| 2509 | this._scope = scope; |
| 2510 | this._port = port; |
| 2511 | } |
| 2512 | async fetch(input, init) { |
| 2513 | const request = new Request(input, init); |
| 2514 | const url = new URL(request.url); |
| 2515 | if (url.protocol === "https:") |
| 2516 | throw new Error( |
| 2517 | "Connecting to a container using HTTPS is not currently supported; use HTTP " + |
| 2518 | "instead. TLS is unnecessary anyway, as the connection is already secure by default.", |
| 2519 | ); |
| 2520 | if (url.protocol !== "http:") throw new TypeError(`Fetch API cannot load: ${url}`); |
| 2521 | const authority = url.host; |
| 2522 | url.host = __container_address(this._scope, this._port); |
| 2523 | const forwarded = new Request(url.toString(), request); |
| 2524 | forwarded.headers.set("host", authority); |
| 2525 | try { |
| 2526 | return await fetch(forwarded); |
| 2527 | } catch (error) { |
| 2528 | // A refused or reset connection is the port not listening yet, which |
| 2529 | // the `@cloudflare/containers` start loop recognizes by this phrase |
| 2530 | // and retries; any other failure keeps its own message. |
| 2531 | const message = error?.message ?? String(error); |
| 2532 | if (/error sending request|connection|connect/i.test(message)) { |
| 2533 | throw new Error( |
| 2534 | `The container is not listening on port ${this._port}: ${message}`, |
| 2535 | ); |
| 2536 | } |
| 2537 | throw error; |
| 2538 | } |
| 2539 | } |
| 2540 | connect(address, options) { |
| 2541 | if (options?.secureTransport === "on") |
| 2542 | throw new Error( |
| 2543 | "Connencting to a container using TLS is not currently supported. It is " + |
| 2544 | "unnecessary anyway, as the connection is already secure by default.", |
| 2545 | ); |
| 2546 | return __celld.__cfSockets.connect( |
| 2547 | __container_address(this._scope, this._port), options); |
| 2548 | } |
| 2549 | } |
| 2550 | class Container { |
| 2551 | constructor(scope) { |
| 2552 | this._scope = scope; |
| 2553 | this._destroyReason = undefined; |
| 2554 | } |
| 2555 | // The host's answer, not a JavaScript flag: a monitor() promise can be |
| 2556 | // dropped with its event, so the flag it would maintain could go stale. |
| 2557 | get running() { return __container_running(this._scope); } |
| 2558 | start(options) { |
| 2559 | if (this.running) |
| 2560 | throw new Error("start() cannot be called on a container that is already running."); |
| 2561 | const o = options ?? {}; |
| 2562 | const params = { enableInternet: !!o.enableInternet, labels: [] }; |
| 2563 | if (o.entrypoint !== undefined) params.entrypoint = Array.from(o.entrypoint, String); |
| 2564 | params.env = __containerEnvList(o.env); |
| 2565 | if (o.labels !== undefined) { |
| 2566 | for (const [name, value] of Object.entries(o.labels)) { |
| 2567 | if (name.length === 0) throw new Error("Label names cannot be empty"); |
| 2568 | for (const text of [name, String(value)]) { |
| 2569 | for (let i = 0; i < text.length; i++) { |
| 2570 | if (text.charCodeAt(i) < 0x20) |
| 2571 | throw new Error(`Label names cannot contain control characters (index ${i})`); |
| 2572 | } |
| 2573 | } |
| 2574 | params.labels.push([name, String(value)]); |
| 2575 | } |
| 2576 | } |
| 2577 | if (o.hardTimeout !== undefined && !(o.hardTimeout > 0)) |
| 2578 | throw new RangeError("Hard timeout must be greater than 0"); |
| 2579 | // Fire and forget, as on Cloudflare: a start that fails reports |
| 2580 | // through monitor(). The host marks the run as running at once. |
| 2581 | this._destroyReason = undefined; |
| 2582 | __container_start(this._scope, JSON.stringify(params)).catch(() => {}); |
| 2583 | } |
| 2584 | async monitor() { |
| 2585 | if (!this.running) |
| 2586 | throw new Error("monitor() cannot be called on a container that is not running."); |
| 2587 | let raw; |
| 2588 | try { |
| 2589 | raw = await __container_monitor(this._scope); |
| 2590 | } catch (error) { |
| 2591 | this._destroyReason = undefined; |
| 2592 | throw error; |
| 2593 | } |
| 2594 | const exitCode = Number(raw); |
| 2595 | if (this._destroyReason !== undefined) { |
| 2596 | const reason = this._destroyReason; |
| 2597 | this._destroyReason = undefined; |
| 2598 | throw reason; |
| 2599 | } |
| 2600 | if (exitCode !== 0) { |
| 2601 | const error = new Error(`Container exited with unexpected exit code: ${exitCode}`); |
| 2602 | error.exitCode = exitCode; |
| 2603 | throw error; |
| 2604 | } |
| 2605 | } |
| 2606 | async destroy(error) { |
| 2607 | if (!this.running) return; |
| 2608 | if (this._destroyReason === undefined) this._destroyReason = error; |
| 2609 | await __container_destroy(this._scope); |
| 2610 | } |
| 2611 | signal(signo) { |
| 2612 | if (!__validSignal(signo)) throw new RangeError("Invalid signal number."); |
| 2613 | if (!this.running) |
| 2614 | throw new Error("signal() cannot be called on a container that is not running."); |
| 2615 | __container_signal(this._scope, signo).catch(() => {}); |
| 2616 | } |
| 2617 | getTcpPort(port) { |
| 2618 | if (!(Number.isInteger(port) && port > 0 && port < 65536)) |
| 2619 | throw new TypeError(`Invalid port number: ${port}`); |
| 2620 | return new ContainerPort(this._scope, port); |
| 2621 | } |
| 2622 | setInactivityTimeout(durationMs) { |
| 2623 | if (!(durationMs > 0)) |
| 2624 | throw new Error(`setInactivityTimeout() requires durationMs > 0, got ${durationMs}`); |
| 2625 | return __container_inactivity(this._scope, durationMs); |
| 2626 | } |
| 2627 | async exec(cmd, options) { |
| 2628 | if (!this.running) |
| 2629 | throw new Error("exec() cannot be called on a container that is not running."); |
| 2630 | if (!Array.isArray(cmd) || cmd.length === 0) |
| 2631 | throw new TypeError("exec() requires a non-empty command array."); |
| 2632 | const o = options ?? {}; |
| 2633 | const stdoutMode = __execOutputMode(o.stdout, "stdout"); |
| 2634 | const stderrMode = __execOutputMode(o.stderr, "stderr"); |
| 2635 | const combined = stderrMode === "combined"; |
| 2636 | if (combined && stdoutMode !== "pipe") |
| 2637 | throw new TypeError('stderr: "combined" requires stdout to be "pipe".'); |
| 2638 | if (o.cwd !== undefined && String(o.cwd).includes("\0")) |
| 2639 | throw new TypeError("cwd cannot contain '\\0' characters."); |
| 2640 | if (o.user !== undefined && String(o.user).includes("\0")) |
| 2641 | throw new TypeError("user cannot contain '\\0' characters."); |
| 2642 | let stdinMode = "none"; |
| 2643 | if (o.stdin !== undefined) { |
| 2644 | if (o.stdin === "pipe") stdinMode = "pipe"; |
| 2645 | else if (o.stdin instanceof ReadableStream) stdinMode = "stream"; |
| 2646 | else throw new TypeError('stdin must be a ReadableStream or the string "pipe".'); |
| 2647 | } |
| 2648 | const params = { |
| 2649 | cmd: Array.from(cmd, String), |
| 2650 | env: __containerEnvList(o.env), |
| 2651 | combined, |
| 2652 | }; |
| 2653 | if (o.cwd !== undefined) params.cwd = String(o.cwd); |
| 2654 | if (o.user !== undefined) params.user = String(o.user); |
| 2655 | const { id, pid } = JSON.parse( |
| 2656 | await __container_exec(this._scope, JSON.stringify(params)), |
| 2657 | ); |
| 2658 | if (stdinMode === "stream") { |
| 2659 | // Pump the caller's stream to the process; the pump is pending work |
| 2660 | // of the event, like a subrequest body. |
| 2661 | (async () => { |
| 2662 | const reader = o.stdin.getReader(); |
| 2663 | try { |
| 2664 | for (;;) { |
| 2665 | const { value, done } = await reader.read(); |
| 2666 | if (done) break; |
| 2667 | await __container_exec_write(id, __bytesOf(value)); |
| 2668 | } |
| 2669 | } finally { |
| 2670 | await __container_exec_close(id); |
| 2671 | } |
| 2672 | })().catch(() => {}); |
| 2673 | } else if (stdinMode === "none") { |
| 2674 | __container_exec_close(id).catch(() => {}); |
| 2675 | } |
| 2676 | return new ContainerExecProcess(id, pid, stdinMode, stdoutMode, stderrMode); |
| 2677 | } |
| 2678 | inspect() { |
| 2679 | return Promise.reject(new Error("inspect() is not implemented in celld")); |
| 2680 | } |
| 2681 | snapshotDirectory() { |
| 2682 | return Promise.reject(new Error("snapshotDirectory() is not implemented in celld")); |
| 2683 | } |
| 2684 | snapshotContainer() { |
| 2685 | return Promise.reject(new Error("snapshotContainer() is not implemented in celld")); |
| 2686 | } |
| 2687 | interceptOutboundHttp() { |
| 2688 | return Promise.reject(new Error("interceptOutboundHttp() is not implemented in celld")); |
| 2689 | } |
| 2690 | interceptOutboundHttps() { |
| 2691 | return Promise.reject(new Error("interceptOutboundHttps() is not implemented in celld")); |
| 2692 | } |
| 2693 | interceptAllOutboundHttp() { |
| 2694 | return Promise.reject(new Error("interceptAllOutboundHttp() is not implemented in celld")); |
| 2695 | } |
| 2696 | interceptOutboundTcp() { |
| 2697 | return Promise.reject(new Error("interceptOutboundTcp() is not implemented in celld")); |
| 2698 | } |
| 2699 | } |
| 2700 | class DurableObjectState { |
| 2701 | constructor(scope) { |
| 2702 | this._scope = scope; |
| 2703 | this._aborted = false; |
| 2704 | this.storage = new DurableObjectStorage(scope, this); |
| 2705 | this.facets = new DurableObjectFacets(this); |
| 2706 | this._gate = Promise.resolve(); |
| 2707 | this._blockDepth = 0; |
| 2708 | const facet = __cell.facetConfigs[scope]; |
| 2709 | this._facetDepth = facet?.depth ?? 0; |
| 2710 | const separator = scope.indexOf(":"); |
| 2711 | const className = separator < 0 ? scope : scope.slice(0, separator); |
| 2712 | this.id = facet === undefined |
| 2713 | ? new DurableObjectId( |
| 2714 | className, separator < 0 ? scope : scope.slice(separator + 1), |
| 2715 | __cell.idNames[scope]) |
| 2716 | : typeof facet.id === "string" ? facet.id : new DurableObjectId(...facet.id); |
| 2717 | this.props = facet?.props; |
| 2718 | // A class outside `containers` has no `ctx.container`, which is what |
| 2719 | // the `@cloudflare/containers` constructor checks. |
| 2720 | if (__cell.containers[className]) this.container = new Container(scope); |
| 2721 | } |
| 2722 | // Workerd's DurableObjectState.exports (actor-state.h): the same |
| 2723 | // loopback surface as ctx.exports on stateless entrypoints. |
| 2724 | get exports() { return __ctxExports(); } |
| 2725 | blockConcurrencyWhile(f) { |
| 2726 | // The native context binds the gate and its operations to one driver. |
| 2727 | // Its async continuations keep that driver even inside a foreign turn. |
| 2728 | return __with_input_gate_context(() => this._blockConcurrencyWhile(f)); |
| 2729 | } |
| 2730 | _blockConcurrencyWhile(f) { |
| 2731 | if (typeof f !== "function") |
| 2732 | throw new TypeError("blockConcurrencyWhile() requires a function"); |
| 2733 | if (this._blockDepth >= 64) |
| 2734 | throw new Error( |
| 2735 | "blockConcurrencyWhile() calls are nested too deeply.", |
| 2736 | ); |
| 2737 | if (this._blockDepth > 0) { |
| 2738 | // A stale reaction can run while an unrelated live block makes this |
| 2739 | // actor's depth nonzero. It cannot ride that hold when either half of |
| 2740 | // its retained [origin, driver] pair has already retired. |
| 2741 | if (__io_context_id() === "" || __io_context_id(true) === "") { |
| 2742 | return Promise.reject(new Error( |
| 2743 | "the cell event ended before it could acquire an input gate", |
| 2744 | )); |
| 2745 | } |
| 2746 | // A nested block rides the outer hold. One the outer body starts and |
| 2747 | // does not await would outlive that hold, and a `transaction()` |
| 2748 | // started that way is the shape that mattered: the outer block |
| 2749 | // returned, the gate opened, and another event wrote into the still |
| 2750 | // open transaction (#714). The outer block drains these before it |
| 2751 | // releases, so the hold lasts as long as any block under it. A nested |
| 2752 | // block that fails resets the object as any block does, and the outer |
| 2753 | // release must carry that failure, or the waiters would be admitted to |
| 2754 | // an object that no longer exists: the drain records it. |
| 2755 | const nested = this._runConcurrencyBlock(f); |
| 2756 | (this._nestedBlocks ||= []).push(nested.then(() => null, __describeFailure)); |
| 2757 | return nested; |
| 2758 | } |
| 2759 | // The host owns the gate (celld_logic::gate::InputGate). It replaces a |
| 2760 | // promise chain that could only order blocks against each other; the |
| 2761 | // gate sits at the delivery points, so nothing else is delivered to this |
| 2762 | // cell at all while the block runs. |
| 2763 | // |
| 2764 | // The acquire waits. It used to be synchronous, and had to be: a cell's |
| 2765 | // events came off one channel, so yielding even one microtask reopened a |
| 2766 | // window in which this cell delivered an event that then waited on a |
| 2767 | // gate nothing would release. Events are independent tasks now, so two |
| 2768 | // can reach a block together and the second has to queue -- and nothing |
| 2769 | // nests, so waiting cannot deadlock on an event suspended beneath it. |
| 2770 | // Asked for synchronously, awaited asynchronously, and the split is the |
| 2771 | // whole point. The op shuts the gate in this very call, so no event can |
| 2772 | // be delivered to this cell from here on -- that immediacy is what makes |
| 2773 | // `failCriticalSection()` reject a `ping()` issued right after it. |
| 2774 | // Waiting for the *ticket* is separate: events are independent tasks |
| 2775 | // now, so two of them can reach a block together and the second has to |
| 2776 | // queue behind the first. Calling this inside the async body instead |
| 2777 | // costs one microtask, and an event delivered in that window walks |
| 2778 | // straight into the critical section. |
| 2779 | const [eventText, owner, acquired] = __gate_acquire(this._scope); |
| 2780 | // An empty owner is an immediate refusal. Return its already-rejected |
| 2781 | // promise before recording the block, because no driver exists to settle |
| 2782 | // native work or to repair a readiness gate installed for stale work. |
| 2783 | if (owner === "") return acquired; |
| 2784 | const event = Number(eventText); |
| 2785 | const { block, record } = __blockEnter(this._scope, event, owner); |
| 2786 | const next = (async () => { |
| 2787 | try { |
| 2788 | await acquired; |
| 2789 | // A shutdown can retire the promise reaction while another event |
| 2790 | // owns this queued acquisition. The owner still has to consume its |
| 2791 | // ticket, but the retired callback must not run. |
| 2792 | if (record.retired) { |
| 2793 | __gate_release(this._scope, event, owner, null); |
| 2794 | return; |
| 2795 | } |
| 2796 | block.holder = event; |
| 2797 | // A critical section that fails resets the actor, so whatever queued |
| 2798 | // behind its gate must be refused rather than handed to the reset |
| 2799 | // one -- it was sent to a cell whose state no longer exists. The |
| 2800 | // failure rides with the release for that: waiters are woken with it |
| 2801 | // instead of merely woken. |
| 2802 | let failure = null; |
| 2803 | try { |
| 2804 | return await this._runConcurrencyBlock(f); |
| 2805 | } catch (error) { |
| 2806 | failure = __describeFailure(error); |
| 2807 | throw error; |
| 2808 | } finally { |
| 2809 | // Nested blocks are drained only after a body that returned: a |
| 2810 | // body that failed has reset the object, its waiters are refused |
| 2811 | // whatever the nested blocks do, and waiting for them would only |
| 2812 | // delay the refusal and a transaction's rollback behind it. Each |
| 2813 | // nested block has its own limit, so a drain is bounded by the |
| 2814 | // last one started, as workerd's nested critical sections are. |
| 2815 | while (failure === null && this._nestedBlocks && this._nestedBlocks.length > 0) { |
| 2816 | for (const nestedFailure of await Promise.all(this._nestedBlocks.splice(0))) { |
| 2817 | if (nestedFailure !== null && failure === null) failure = nestedFailure; |
| 2818 | } |
| 2819 | } |
| 2820 | this._nestedBlocks = undefined; |
| 2821 | __gate_release(this._scope, event, owner, failure); |
| 2822 | } |
| 2823 | } finally { |
| 2824 | // Also on a rejected `acquired`: the block ahead failed, this one |
| 2825 | // never ran, and the cell must not stay shut on its behalf. |
| 2826 | __blockLeave(this._scope, block, event); |
| 2827 | } |
| 2828 | })(); |
| 2829 | // `_ready()` awaits this. The host gate stops *other* events, but a |
| 2830 | // block taken in the constructor runs inside the very event that is |
| 2831 | // being delivered, so nothing external can hold that event back -- the |
| 2832 | // promise does. Concurrent blocks within one event go through |
| 2833 | // `_blockDepth` above and never reach here. |
| 2834 | this._gate = Promise.all([this._gate, record.ready]).then(() => undefined); |
| 2835 | // `_ready()` observes the original promise. This extra handler prevents |
| 2836 | // a constructor-time rejection from becoming unhandled before an event |
| 2837 | // reaches `_ready()`. |
| 2838 | this._gate.catch(() => {}); |
| 2839 | next.then(record.settleReady, record.rejectReady); |
| 2840 | return next; |
| 2841 | } |
| 2842 | _runConcurrencyBlock(f) { |
| 2843 | this._blockDepth++; |
| 2844 | let result; |
| 2845 | try { |
| 2846 | result = f(); |
| 2847 | } catch (error) { |
| 2848 | this._blockDepth--; |
| 2849 | this._resetAfterConcurrencyFailure(error); |
| 2850 | throw error; |
| 2851 | } |
| 2852 | const timerId = __timer_alloc(); |
| 2853 | let settled = false; |
| 2854 | const timeout = __op_timer( |
| 2855 | timerId, |
| 2856 | 30_000, |
| 2857 | ).then(() => { |
| 2858 | if (!settled) { |
| 2859 | throw new Error( |
| 2860 | "A call to blockConcurrencyWhile() in a Durable Object waited for " + |
| 2861 | "too long. The call was canceled and the Durable Object was reset.", |
| 2862 | ); |
| 2863 | } |
| 2864 | }); |
| 2865 | return Promise.race([Promise.resolve(result), timeout]).then( |
| 2866 | (value) => { |
| 2867 | settled = true; |
| 2868 | __timer_cancel(timerId); |
| 2869 | this._blockDepth--; |
| 2870 | return value; |
| 2871 | }, |
| 2872 | (error) => { |
| 2873 | settled = true; |
| 2874 | __timer_cancel(timerId); |
| 2875 | this._blockDepth--; |
| 2876 | this._resetAfterConcurrencyFailure(error); |
| 2877 | throw error; |
| 2878 | }, |
| 2879 | ); |
| 2880 | } |
| 2881 | _resetAfterConcurrencyFailure(error) { |
| 2882 | if (this._aborted) return; |
| 2883 | this._aborted = true; |
| 2884 | __storage_cancel_pending_puts(this._scope); |
| 2885 | const instance = __cell.instances[this._scope]; |
| 2886 | if (instance && instance.__celldState === this) |
| 2887 | delete __cell.instances[this._scope]; |
| 2888 | // Under a stub-mediated caller (this scope is not the current |
| 2889 | // event) the failure breaks the actor, as Workerd joins it |
| 2890 | // into the on-abort promise; a direct event keeps reset-only |
| 2891 | // semantics -- its caller sees the rejection itself. |
| 2892 | if (__currentActorScope() !== this._scope) |
| 2893 | __actorBreak(this._scope, error); |
| 2894 | } |
| 2895 | abort(reason) { |
| 2896 | if (this._aborted) return; |
| 2897 | this._aborted = true; |
| 2898 | __storage_cancel_pending_puts(this._scope); |
| 2899 | const instance = __cell.instances[this._scope]; |
| 2900 | if (instance && instance.__celldState === this) |
| 2901 | delete __cell.instances[this._scope]; |
| 2902 | const message = reason instanceof Error |
| 2903 | ? reason.message |
| 2904 | : String(reason); |
| 2905 | // Direct host-dispatched event on this actor: the uncatchable |
| 2906 | // terminate_execution path. Under a same-isolate stub caller, |
| 2907 | // termination would unwind the caller too, so break in JS. |
| 2908 | if (__currentActorScope() === this._scope) { |
| 2909 | __actor_abort(this._scope, message); |
| 2910 | return; |
| 2911 | } |
| 2912 | __actorBreak(this._scope, |
| 2913 | reason instanceof Error ? reason : new Error(message)); |
| 2914 | } |
| 2915 | _ready() { return this._gate; } |
| 2916 | getWebSockets(tag) { |
| 2917 | return JSON.parse(__ws_list(this._scope, tag)).map((row) => __socketFromRow(row)); |
| 2918 | } |
| 2919 | getTags(ws) { |
| 2920 | if (!(ws instanceof WebSocket) || !ws._hibernatable) { |
| 2921 | throw new Error( |
| 2922 | "you must call 'acceptWebSocket()' before attempting to access " + |
| 2923 | "the tags of a WebSocket."); |
| 2924 | } |
| 2925 | return Array.from(ws._tags); |
| 2926 | } |
| 2927 | acceptWebSocket(ws, tags = []) { |
| 2928 | if (__heap_over_admission_share()) |
| 2929 | throw new Error( |
| 2930 | "the isolate is near its V8 heap limit, so it refused a " + |
| 2931 | "WebSocket (see CELLD_V8_HEAP_LIMIT_MB)"); |
| 2932 | ws._target = { id: ws._id, scope: this._scope }; |
| 2933 | if (ws._peer) ws._peer._target = ws._target; |
| 2934 | ws._hibernatable = true; |
| 2935 | if (ws._peer) ws._peer._hibernatable = true; |
| 2936 | ws._tags = Array.from(tags, String); |
| 2937 | __ws_accept(ws._id, this._scope, JSON.stringify(ws._tags)); |
| 2938 | __sockets.set(ws._id, ws); |
| 2939 | } |
| 2940 | _socket(id) { |
| 2941 | return __sockets.get(Number(id)) || |
| 2942 | this.getWebSockets().find((ws) => ws._id === id) || |
| 2943 | __wsStub(id); |
| 2944 | } |
| 2945 | // Workerd actor-state.c++ setWebSocketAutoResponse: no pair unsets, and |
| 2946 | // each side is capped at 2048 UTF-8 bytes. The pair itself lives in the |
| 2947 | // shell -- a matched message is answered without waking this cell. |
| 2948 | setWebSocketAutoResponse(pair) { |
| 2949 | if (pair === undefined || pair === null) { |
| 2950 | __ws_auto_response_set(this._scope, null, null); |
| 2951 | return; |
| 2952 | } |
| 2953 | if (!(pair instanceof WebSocketRequestResponsePair)) |
| 2954 | throw new TypeError( |
| 2955 | "Failed to execute 'setWebSocketAutoResponse' on " + |
| 2956 | "'DurableObjectState': parameter 1 is not of type " + |
| 2957 | "'WebSocketRequestResponsePair'.", |
| 2958 | ); |
| 2959 | const max = 2048; |
| 2960 | const bytes = (s) => new TextEncoder().encode(s).length; |
| 2961 | const requestSize = bytes(pair.request); |
| 2962 | if (requestSize > max) |
| 2963 | throw new RangeError( |
| 2964 | `Request cannot be larger than ${max} bytes. ` + |
| 2965 | `A request of size ${requestSize} was provided.`, |
| 2966 | ); |
| 2967 | const responseSize = bytes(pair.response); |
| 2968 | if (responseSize > max) |
| 2969 | throw new RangeError( |
| 2970 | `Response cannot be larger than ${max} bytes. ` + |
| 2971 | `A response of size ${responseSize} was provided.`, |
| 2972 | ); |
| 2973 | __ws_auto_response_set(this._scope, pair.request, pair.response); |
| 2974 | } |
| 2975 | getWebSocketAutoResponse() { |
| 2976 | const pair = JSON.parse(__ws_auto_response_get(this._scope)); |
| 2977 | if (pair === null) return null; |
| 2978 | return new WebSocketRequestResponsePair(pair[0], pair[1]); |
| 2979 | } |
| 2980 | getWebSocketAutoResponseTimestamp(ws) { |
| 2981 | const ms = __ws_auto_response_ts(ws._id); |
| 2982 | return ms === null ? null : new Date(ms); |
| 2983 | } |
| 2984 | waitUntil(promise) { |
| 2985 | __registerWaitUntil(promise); |
| 2986 | } |
| 2987 | } |
| 2988 | function _instance(scope) { |
| 2989 | let inst = __cell.instances[scope]; |
| 2990 | if (!inst) { |
| 2991 | const className = scope.split(":")[0]; |
| 2992 | const cls = __cell.classes[className]; |
| 2993 | if (!cls) throw new Error("no DO class " + className); |
| 2994 | const state = new DurableObjectState(scope); |
| 2995 | inst = new cls(state, __cell.env); |
| 2996 | Object.defineProperty(inst, "__celldState", { value: state }); |
| 2997 | // Workerd worker-rpc.c++ getTargetInfo(): RPC needs `extends |
| 2998 | // DurableObject` unless the js_rpc compat flag is on. Decided |
| 2999 | // once here; dispatch reads a boolean. |
| 3000 | state._rpcOk = __cell.compat.jsRpc || |
| 3001 | __cell.doExports[className] === true; |
| 3002 | __cell.instances[scope] = inst; |
| 3003 | } |
| 3004 | return inst; |
| 3005 | } |
| 3006 | async function _readyInstance(scope) { |
| 3007 | const inst = _instance(scope); |
| 3008 | await inst.__celldState._ready(); |
| 3009 | return inst; |
| 3010 | } |
| 3011 | const __actorEventStack = []; |
| 3012 | const __currentActorEvent = () => { |
| 3013 | const context = String(__io_context_id()); |
| 3014 | if (context === "") return undefined; |
| 3015 | for (let index = __actorEventStack.length - 1; index >= 0; index--) { |
| 3016 | const event = __actorEventStack[index]; |
| 3017 | if (event.context === context) return event; |
| 3018 | } |
| 3019 | return undefined; |
| 3020 | }; |
| 3021 | const __currentActorScope = () => __currentActorEvent()?.scope ?? ""; |
| 3022 | const __beginActorEvent = (scope) => { |
| 3023 | __rpcSignalRefresh(); |
| 3024 | const event = { scope, context: String(__io_context_id()) }; |
| 3025 | __actorEventStack.push(event); |
| 3026 | return event; |
| 3027 | }; |
| 3028 | const __endActorEvent = (event) => { |
| 3029 | const index = __actorEventStack.lastIndexOf(event); |
| 3030 | if (index >= 0) __actorEventStack.splice(index, 1); |
| 3031 | }; |
| 3032 | const __endActorEventsForContext = (context) => { |
| 3033 | for (let index = __actorEventStack.length - 1; index >= 0; index--) { |
| 3034 | if (__actorEventStack[index].context === context) |
| 3035 | __actorEventStack.splice(index, 1); |
| 3036 | } |
| 3037 | }; |
| 3038 | const __incomingRequestSignals = new Map(); |
| 3039 | const __abortSignal = (signal, reason) => { |
| 3040 | if (signal.aborted) return; |
| 3041 | signal.aborted = true; |
| 3042 | signal.reason = reason; |
| 3043 | signal.dispatchEvent(new Event("abort")); |
| 3044 | }; |
| 3045 | const __abortIncomingRequest = __celld.__abortIncomingRequest = (requestId) => { |
| 3046 | const signal = __incomingRequestSignals.get(String(requestId)); |
| 3047 | if (signal && !signal.aborted) { |
| 3048 | __abortSignal(signal, new Error("The client has disconnected")); |
| 3049 | return true; |
| 3050 | } |
| 3051 | return false; |
| 3052 | }; |
| 3053 | __celld.__registerIncomingRequest = (requestId, request) => { |
| 3054 | __incomingRequestSignals.set(String(requestId), request.signal); |
| 3055 | }; |
| 3056 | __celld.__finishIncomingRequest = (requestId) => { |
| 3057 | __incomingRequestSignals.delete(String(requestId)); |
| 3058 | }; |
| 3059 | __celld.__retireInputGateContext = (context) => { |
| 3060 | for (const [scope, block] of __cellBlocks) { |
| 3061 | const retired = [...block.events].filter(([, record]) => |
| 3062 | record.owner === context || record.reaction === context |
| 3063 | ); |
| 3064 | if (retired.length === 0) continue; |
| 3065 | const holder = retired.find(([event]) => block.holder === event); |
| 3066 | if (holder === undefined) { |
| 3067 | // A queued callback has not changed the actor. Remove only that |
| 3068 | // callback, and let an unrelated holder continue with the same state. |
| 3069 | for (const [event, record] of retired) { |
| 3070 | record.retired = true; |
| 3071 | record.settleReady(); |
| 3072 | block.events.delete(event); |
| 3073 | if (record.actorEvent !== undefined) |
| 3074 | __endActorEvent(record.actorEvent); |
| 3075 | } |
| 3076 | if (block.events.size === 0 && __cellBlocks.get(scope) === block) |
| 3077 | __cellBlocks.delete(scope); |
| 3078 | continue; |
| 3079 | } |
| 3080 | // A running callback changed this actor and cannot reach its own |
| 3081 | // `finally`. Reset the actor, and release the host gate when the context |
| 3082 | // that started the callback differs from the turn that owns its work. |
| 3083 | const [holderEvent, holderRecord] = holder; |
| 3084 | __gate_release( |
| 3085 | scope, |
| 3086 | holderEvent, |
| 3087 | holderRecord.owner, |
| 3088 | "the cell's critical section ended without releasing", |
| 3089 | ); |
| 3090 | const instance = __cell.instances[scope]; |
| 3091 | if (instance !== undefined) instance.__celldState._aborted = true; |
| 3092 | __storage_cancel_pending_puts(scope); |
| 3093 | if (instance !== undefined && __cell.instances[scope] === instance) |
| 3094 | delete __cell.instances[scope]; |
| 3095 | for (const record of block.events.values()) { |
| 3096 | record.retired = true; |
| 3097 | record.settleReady(); |
| 3098 | if (record.actorEvent !== undefined) |
| 3099 | __endActorEvent(record.actorEvent); |
| 3100 | } |
| 3101 | // The old actor cannot run any block `finally`. A later event creates an |
| 3102 | // instance whose ready promise contains none of this actor's work. |
| 3103 | if (__cellBlocks.get(scope) === block) __cellBlocks.delete(scope); |
| 3104 | } |
| 3105 | __endActorEventsForContext(context); |
| 3106 | }; |
| 3107 | // Race a pending dispatch against the caller's abort signal: on abort, |
| 3108 | // run `abandon` (which reaches the target's side) and reject with the |
| 3109 | // caller's reason. The dispatch keeps its settle handlers, so a late |
| 3110 | // settlement after abandonment cannot trip the unhandled-rejection |
| 3111 | // signal. |
| 3112 | const __raceCallerAbort = (dispatch, signal, abandon) => |
| 3113 | new Promise((resolve, reject) => { |
| 3114 | let settled = false; |
| 3115 | const onAbort = () => { |
| 3116 | if (settled) return; |
| 3117 | settled = true; |
| 3118 | abandon(); |
| 3119 | reject(signal.reason); |
| 3120 | }; |
| 3121 | signal.addEventListener("abort", onAbort, { once: true }); |
| 3122 | dispatch.then( |
| 3123 | (value) => { |
| 3124 | if (settled) return; |
| 3125 | settled = true; |
| 3126 | signal.removeEventListener("abort", onAbort); |
| 3127 | resolve(value); |
| 3128 | }, |
| 3129 | (error) => { |
| 3130 | if (settled) return; |
| 3131 | settled = true; |
| 3132 | signal.removeEventListener("abort", onAbort); |
| 3133 | reject(error); |
| 3134 | }, |
| 3135 | ); |
| 3136 | }); |
| 3137 | const __awaitCancellableDoCall = (operation, signal) => { |
| 3138 | if (signal.aborted) { |
| 3139 | __do_call_cancel(operation.__celldCancelId); |
| 3140 | return Promise.reject(signal.reason); |
| 3141 | } |
| 3142 | return __raceCallerAbort(operation, signal, |
| 3143 | () => __do_call_cancel(operation.__celldCancelId)); |
| 3144 | }; |
| 3145 | // Workerd semantics: a Response crossing a service binding is a fresh |
| 3146 | // fetch-shaped Response -- immutable headers, default reason phrase, |
| 3147 | // the request URL, and a real body stream -- never the callee's own |
| 3148 | // mutable object. |
| 3149 | const __STATUS_TEXT = { |
| 3150 | 100: "Continue", 101: "Switching Protocols", 102: "Processing", |
| 3151 | 103: "Early Hints", 200: "OK", 201: "Created", 202: "Accepted", |
| 3152 | 203: "Non-Authoritative Information", 204: "No Content", |
| 3153 | 205: "Reset Content", 206: "Partial Content", 207: "Multi-Status", |
| 3154 | 208: "Already Reported", 226: "IM Used", 300: "Multiple Choices", |
| 3155 | 301: "Moved Permanently", 302: "Found", 303: "See Other", |
| 3156 | 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", |
| 3157 | 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", |
| 3158 | 402: "Payment Required", 403: "Forbidden", 404: "Not Found", |
| 3159 | 405: "Method Not Allowed", 406: "Not Acceptable", |
| 3160 | 407: "Proxy Authentication Required", 408: "Request Timeout", |
| 3161 | 409: "Conflict", 410: "Gone", 411: "Length Required", |
| 3162 | 412: "Precondition Failed", 413: "Payload Too Large", |
| 3163 | 414: "URI Too Long", 415: "Unsupported Media Type", |
| 3164 | 416: "Range Not Satisfiable", 417: "Expectation Failed", |
| 3165 | 418: "I'm a teapot", 421: "Misdirected Request", |
| 3166 | 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", |
| 3167 | 425: "Too Early", 426: "Upgrade Required", |
| 3168 | 428: "Precondition Required", 429: "Too Many Requests", |
| 3169 | 431: "Request Header Fields Too Large", |
| 3170 | 451: "Unavailable For Legal Reasons", 500: "Internal Server Error", |
| 3171 | 501: "Not Implemented", 502: "Bad Gateway", |
| 3172 | 503: "Service Unavailable", 504: "Gateway Timeout", |
| 3173 | 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", |
| 3174 | 507: "Insufficient Storage", 508: "Loop Detected", |
| 3175 | 510: "Not Extended", 511: "Network Authentication Required", |
| 3176 | }; |
| 3177 | const __ERROR_RESPONSE_MESSAGE = |
| 3178 | "Return value from serve handler must not be an error " + |
| 3179 | "response (like Response.error())"; |
| 3180 | const __wrapServiceResponse = (res, url) => { |
| 3181 | // Response.error() represents a Fetch network error, not an HTTP response. |
| 3182 | // Letting status 0 cross this seam turns it into an ordinary response and |
| 3183 | // makes callers continue after the target explicitly reported failure. |
| 3184 | if (res.type === "error" || res.status === 0) { |
| 3185 | throw new TypeError(__ERROR_RESPONSE_MESSAGE); |
| 3186 | } |
| 3187 | // A 101 that crossed isolates carries a target rather than a socket: the |
| 3188 | // pair's other end is in the isolate that answered, and the two cannot be |
| 3189 | // linked the way the loopback below links them. Give the caller a client |
| 3190 | // end the host can join to that target, on the same terms as a Durable |
| 3191 | // Object subrequest -- nothing binds until `accept()`, so a response |
| 3192 | // passed straight back out keeps the direct route to the real client. |
| 3193 | const bound = !res.webSocket && res._wsTarget && res.status === 101 |
| 3194 | ? new WebSocket(undefined, [], res._wsTarget) |
| 3195 | : undefined; |
| 3196 | const wrapped = new Response( |
| 3197 | // Buffered bodies re-stream (an empty buffer still yields a |
| 3198 | // stream, as over real HTTP); a streaming body passes through. |
| 3199 | res._bodyBytes !== null ? res._bodyBytes : res.body, |
| 3200 | { |
| 3201 | status: res.status, |
| 3202 | statusText: |
| 3203 | res.statusText || __STATUS_TEXT[res.status] || "", |
| 3204 | headers: res.headers, |
| 3205 | webSocket: res.webSocket || bound, |
| 3206 | __wsTarget: res._wsTarget, |
| 3207 | }, |
| 3208 | ); |
| 3209 | // The constructor copies headers, so mark the copy. |
| 3210 | Object.defineProperty(wrapped.headers, "_immutable", { value: true }); |
| 3211 | wrapped.url = url; |
| 3212 | // An upgraded pair whose both ends live in this isolate: link them |
| 3213 | // directly -- the host connection seam only reaches external |
| 3214 | // clients. Frames the handler queued before linking flush first. |
| 3215 | const client = wrapped.webSocket; |
| 3216 | if (wrapped.status === 101 && client && client._peer) { |
| 3217 | const server = client._peer; |
| 3218 | client._loopback = server; |
| 3219 | server._loopback = client; |
| 3220 | for (const frame of server._pending.splice(0)) { |
| 3221 | // "send-binary" joined this queue with outbound sockets; without a case |
| 3222 | // of its own it fell through to the close branch and tore the pair down |
| 3223 | // instead of delivering the frame. |
| 3224 | if (frame[0] === "send") |
| 3225 | queueMicrotask(() => client._dispatchMessage(frame[1])); |
| 3226 | else if (frame[0] === "send-binary") |
| 3227 | queueMicrotask(() => { |
| 3228 | const data = frame[1]; |
| 3229 | client._dispatchMessage( |
| 3230 | data instanceof ArrayBuffer ? data : data.buffer.slice( |
| 3231 | data.byteOffset, |
| 3232 | data.byteOffset + data.byteLength, |
| 3233 | ), |
| 3234 | ); |
| 3235 | }); |
| 3236 | else |
| 3237 | queueMicrotask( |
| 3238 | () => client._dispatchClose(frame[1], frame[2], true)); |
| 3239 | } |
| 3240 | } |
| 3241 | return wrapped; |
| 3242 | }; |
| 3243 | const __SERVICE_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); |
| 3244 | const __REQUEST_BODY_HEADERS = [ |
| 3245 | "content-encoding", "content-language", "content-length", |
| 3246 | "content-location", "content-type", "transfer-encoding", |
| 3247 | ]; |
| 3248 | const __CROSS_ORIGIN_SENSITIVE_HEADERS = [ |
| 3249 | "authorization", "cookie", "proxy-authorization", |
| 3250 | ]; |
| 3251 | // A service target only produces the first response. Fetch redirect handling |
| 3252 | // belongs to the caller, because the Location leaves through the caller's |
| 3253 | // ambient outbound policy rather than gaining the target service's authority. |
| 3254 | // Capture the replayable request state before dispatch: a same-isolate target |
| 3255 | // receives the Request itself and can consume or mutate it before it redirects. |
| 3256 | const __serviceRedirectState = (req) => ({ |
| 3257 | method: req.method, |
| 3258 | headers: req.headers.__celldHeaderList, |
| 3259 | body: req.body === null ? undefined |
| 3260 | : req._bodyBytes === null ? null : req._bodyBytes.slice(), |
| 3261 | signal: req._signalForSubrequests, |
| 3262 | }); |
| 3263 | const __finishServiceFetch = async (res, req, replay) => { |
| 3264 | const response = __wrapServiceResponse(res, req.url); |
| 3265 | if (!__SERVICE_REDIRECT_STATUSES.has(response.status)) return response; |
| 3266 | const location = response.headers.get("location"); |
| 3267 | if (location === null) return response; |
| 3268 | if (req.redirect === "manual") return response; |
| 3269 | |
| 3270 | // Nobody can consume the redirect response after this branch. Cancelling it |
| 3271 | // releases a cross-isolate body stream instead of waiting for its idle TTL. |
| 3272 | if (response.body !== null) { |
| 3273 | try { await response.body.cancel(); } catch { /* the redirect still wins */ } |
| 3274 | } |
| 3275 | if (req.redirect === "error") |
| 3276 | throw new TypeError("A redirect was returned for a request with redirect mode error."); |
| 3277 | |
| 3278 | const url = new URL(location, req.url).href; |
| 3279 | let method = replay.method; |
| 3280 | let body = replay.body; |
| 3281 | const headers = new Headers(replay.headers); |
| 3282 | if ((response.status === 301 || response.status === 302) && method === "POST" || |
| 3283 | response.status === 303 && method !== "GET" && method !== "HEAD") { |
| 3284 | method = "GET"; |
| 3285 | body = undefined; |
| 3286 | for (const name of __REQUEST_BODY_HEADERS) headers.delete(name); |
| 3287 | } else if (body === null) { |
| 3288 | // A transferred or live JavaScript stream has no replay copy. Fetch treats |
| 3289 | // the redirect as a network error instead of sending an empty replacement. |
| 3290 | throw new TypeError("Cannot follow a redirect with a non-replayable request body."); |
| 3291 | } |
| 3292 | // The ambient fetch starts a new native request, so its HTTP client cannot |
| 3293 | // know that these credentials came from another origin and remove them. Do |
| 3294 | // that at the service-to-network boundary before they can leak to Location. |
| 3295 | if (new URL(req.url).origin !== new URL(url).origin) { |
| 3296 | for (const name of __CROSS_ORIGIN_SENSITIVE_HEADERS) headers.delete(name); |
| 3297 | } |
| 3298 | const init = { method, headers, redirect: "follow" }; |
| 3299 | if (body !== undefined) init.body = body; |
| 3300 | if (replay.signal !== null) init.signal = replay.signal; |
| 3301 | const followed = await globalThis.fetch(url, init); |
| 3302 | followed.redirected = true; |
| 3303 | if (followed.url === "") followed.url = url; |
| 3304 | return followed; |
| 3305 | }; |
| 3306 | // `[[services]]` binding: a Fetcher pointed at another Worker in this |
| 3307 | // process. No identity to resolve, so it goes straight to __svc_call. |
| 3308 | // Worker Loader (Code Mode): spawn a fresh isolate from supplied code and |
| 3309 | // invoke its default or named entrypoint through the cross-isolate request and |
| 3310 | // RPC paths. |
| 3311 | // A Fetcher can cross into a loaded isolate only as this host-minted route. |
| 3312 | // Reading properties from a Proxy is not a trustworthy brand check, so the |
| 3313 | // metadata lives in a side table that application objects cannot forge. |
| 3314 | const __outboundMeta = new WeakMap(); |
| 3315 | const __loaderServiceMarker = "__celld$loaderSvc"; |
| 3316 | __celld.__makeLoader = () => { |
| 3317 | // A name weakly caches a shared load; `load()` is anonymous. Keep the load |
| 3318 | // promise itself on every derived capability, including a running facet, |
| 3319 | // so collection cannot evict a Worker while that capability still uses it. |
| 3320 | const byName = new Map(); |
| 3321 | const loaderOptions = (method, options, supportsLimits) => { |
| 3322 | if (options === null || options === undefined) return undefined; |
| 3323 | if (typeof options !== "object") |
| 3324 | throw new TypeError(method + "() options must be an object."); |
| 3325 | const extra = Object.keys(options).filter( |
| 3326 | (key) => key !== "props" && !(supportsLimits && key === "limits")); |
| 3327 | if (extra.length !== 0) |
| 3328 | throw new TypeError( |
| 3329 | method + '() does not support the option "' + extra.join('", "') + |
| 3330 | '".'); |
| 3331 | return options; |
| 3332 | }; |
| 3333 | // `props` cross to the loaded isolate by structured clone, on the same |
| 3334 | // transport that already carries the call's arguments (`__rpcOut` below). |
| 3335 | // JSON is the obvious alternative and it is wrong: JSON.stringify turns a |
| 3336 | // Map, a Set, a Date, a typed array, and a RegExp into a plain object or a |
| 3337 | // string and reports no error, so the callee reads a mangled value that the |
| 3338 | // same call's arguments would have carried intact. Encoding here, once per |
| 3339 | // loader API call, also rejects an unclonable value at that call rather than |
| 3340 | // at the first operation. |
| 3341 | const loaderPropsSc = (method, options) => { |
| 3342 | const props = loaderOptions(method, options, false)?.props; |
| 3343 | if (props === undefined) return undefined; |
| 3344 | // `lift` false: the props cross an isolate boundary, so a stub inside them |
| 3345 | // is a DataCloneError, exactly as a stub inside an argument of the same |
| 3346 | // call is. |
| 3347 | return __rpcOut(props, false); |
| 3348 | }; |
| 3349 | const loaderEntrypointOptions = (options) => { |
| 3350 | options = loaderOptions("getEntrypoint", options, true); |
| 3351 | const props = options?.props; |
| 3352 | return { |
| 3353 | propsSc: props === undefined ? undefined : __rpcOut(props, false), |
| 3354 | limitsJson: JSON.stringify(options?.limits ?? null), |
| 3355 | }; |
| 3356 | }; |
| 3357 | const makeEntrypoint = (loadPromise, entrypoint, propsSc, limitsJson) => { |
| 3358 | const target = { |
| 3359 | async fetch(input, init) { |
| 3360 | const { id, tails } = await loadPromise; |
| 3361 | const req = new Request(input, init); |
| 3362 | // The caller's signal, never the incoming request's own, as for a |
| 3363 | // service binding. |
| 3364 | const signal = req._signalForSubrequests; |
| 3365 | if (signal?.aborted) throw signal.reason; |
| 3366 | // The verbatim header list; see the note on the outbound `fetch`. |
| 3367 | // The loaded worker rebuilds a `Headers` from these pairs, so a |
| 3368 | // repeat and its casing survive the isolate boundary. |
| 3369 | const headers = JSON.stringify(req.headers.__celldHeaderList); |
| 3370 | const { body, streamId } = await __subrequestBody(req); |
| 3371 | const loaded = __loader_fetch( |
| 3372 | id, req.url, req.method, body, headers, streamId, entrypoint, |
| 3373 | propsSc === undefined ? new Uint8Array() : propsSc, |
| 3374 | limitsJson, tails.length !== 0, signal != null); |
| 3375 | const dispatch = tails.length === 0 ? loaded : loaded[0]; |
| 3376 | const response = signal |
| 3377 | ? __awaitCancellableDoCall(dispatch, signal) |
| 3378 | : dispatch; |
| 3379 | if (tails.length !== 0) { |
| 3380 | const delivery = loaded[1] |
| 3381 | .then((report) => JSON.parse(report)) |
| 3382 | .then((events) => Promise.allSettled( |
| 3383 | tails.map((tail) => tail.tail(events)))) |
| 3384 | .then((results) => { |
| 3385 | for (const result of results) { |
| 3386 | if (result.status === "rejected") |
| 3387 | console.error("Tail Worker failed:", result.reason); |
| 3388 | } |
| 3389 | }) |
| 3390 | .catch((error) => console.error("Tail delivery failed:", error)); |
| 3391 | // The loaded fetch answers before its report because the child can |
| 3392 | // still have waitUntil work. Keep this chain on the loader event so |
| 3393 | // its IoContext cannot retire and abort the report operation. |
| 3394 | __registerWaitUntil(delivery); |
| 3395 | } |
| 3396 | const r = JSON.parse(await response); |
| 3397 | const responseBody = r.streamId !== undefined |
| 3398 | ? new CelldHttpBodyStream(r.streamId) |
| 3399 | : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); |
| 3400 | return __wrapServiceResponse( |
| 3401 | new Response(responseBody, { status: r.status, headers: r.headers }), |
| 3402 | req.url); |
| 3403 | }, |
| 3404 | }; |
| 3405 | // Both the default and named entrypoints expose RPC: property access is a |
| 3406 | // callable pipeline node dispatched via __loader_rpc to that entrypoint in |
| 3407 | // the loaded worker (default -> the "default" export, which |
| 3408 | // register_entrypoints registers like any other). fetch stays on the |
| 3409 | // target. Only single-method calls are supported for now. |
| 3410 | const session = { |
| 3411 | get: () => Promise.reject(new Error( |
| 3412 | "Awaitable properties on loaded workers are not supported yet.")), |
| 3413 | call: (path, args) => (async () => { |
| 3414 | if (path.length !== 1) |
| 3415 | throw new Error( |
| 3416 | "Pipelined property paths on loaded workers are not supported " + |
| 3417 | "yet."); |
| 3418 | const { id } = await loadPromise; |
| 3419 | return __rpcDes( |
| 3420 | await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false), |
| 3421 | propsSc, limitsJson)); |
| 3422 | })(), |
| 3423 | }; |
| 3424 | return new Proxy(target, { |
| 3425 | get: (base, prop) => { |
| 3426 | if (prop === "then") return undefined; |
| 3427 | if (Reflect.has(base, prop)) return Reflect.get(base, prop); |
| 3428 | if (typeof prop !== "string") return undefined; |
| 3429 | return __makeNode(session, [prop], null); |
| 3430 | }, |
| 3431 | }); |
| 3432 | }; |
| 3433 | // The load promise is the shared lifetime, retained by stubs, entrypoints, |
| 3434 | // classes, and running facets. Finalizing only the original stub can evict |
| 3435 | // a Worker that one of its derived capabilities still uses. |
| 3436 | const finalizer = new FinalizationRegistry(({ id, name, ref }) => { |
| 3437 | if (ref !== undefined && byName.get(name) === ref) byName.delete(name); |
| 3438 | if (id !== undefined) __loader_drop(id); |
| 3439 | }); |
| 3440 | const track = (loadPromise, name, ref) => { |
| 3441 | // Register before settlement, so failed loads also release their names. |
| 3442 | const held = { id: undefined, name, ref }; |
| 3443 | finalizer.register(loadPromise, held, loadPromise); |
| 3444 | loadPromise.then(({ id }) => { held.id = id; }, () => {}); |
| 3445 | return loadPromise; |
| 3446 | }; |
| 3447 | const makeStub = (loadPromise, name, ref) => { |
| 3448 | const drop = () => { |
| 3449 | if (ref !== undefined && byName.get(name) === ref) byName.delete(name); |
| 3450 | finalizer.unregister(loadPromise); |
| 3451 | loadPromise.then(({ id }) => __loader_drop(id), () => {}); |
| 3452 | }; |
| 3453 | const stub = { |
| 3454 | getEntrypoint(name = null, options = {}) { |
| 3455 | const { propsSc, limitsJson } = loaderEntrypointOptions(options); |
| 3456 | return makeEntrypoint( |
| 3457 | loadPromise, name === null ? "default" : String(name), |
| 3458 | propsSc, limitsJson); |
| 3459 | }, |
| 3460 | getDurableObjectClass(name = null, options = {}) { |
| 3461 | return __makeDurableObjectClass( |
| 3462 | loadPromise, name, loaderPropsSc("getDurableObjectClass", options)); |
| 3463 | }, |
| 3464 | dispose: drop, |
| 3465 | }; |
| 3466 | if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; |
| 3467 | return stub; |
| 3468 | }; |
| 3469 | // JSON.stringify silently drops binary values, so each non-string module -- |
| 3470 | // an explicit module shape such as `{ wasm: bytes }` -- is normalized |
| 3471 | // first. JavaScript modules become plain strings, and wasm moves into a |
| 3472 | // side-band `[name, Uint8Array]` list so multi-MB blobs never take a |
| 3473 | // base64/JSON round-trip. |
| 3474 | const toBytes = (v) => v instanceof ArrayBuffer ? new Uint8Array(v) |
| 3475 | : ArrayBuffer.isView(v) |
| 3476 | ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : null; |
| 3477 | const moduleKinds = [ |
| 3478 | "js", "cjs", "py", "text", "data", "json", "wasm", |
| 3479 | ]; |
| 3480 | const encodeLoaderEnv = (value) => { |
| 3481 | if (value === undefined || value === null) |
| 3482 | return { env: undefined, envRoutes: [] }; |
| 3483 | const envRoutes = []; |
| 3484 | const seen = new Map(); |
| 3485 | const project = (v) => { |
| 3486 | if (v === null || |
| 3487 | (typeof v !== "object" && typeof v !== "function")) return v; |
| 3488 | const cached = seen.get(v); |
| 3489 | if (cached !== undefined) return cached; |
| 3490 | const route = __outboundMeta.get(v); |
| 3491 | if (route !== undefined) { |
| 3492 | const marker = { [__loaderServiceMarker]: envRoutes.length }; |
| 3493 | seen.set(v, marker); |
| 3494 | envRoutes.push([ |
| 3495 | route.script, |
| 3496 | route.entrypoint, |
| 3497 | route.propsSc ?? (route.props === undefined |
| 3498 | ? new Uint8Array() : __rpcOut(route.props, false)), |
| 3499 | ]); |
| 3500 | return marker; |
| 3501 | } |
| 3502 | if (Object.prototype.hasOwnProperty.call(v, __loaderServiceMarker)) |
| 3503 | throw new DOMException( |
| 3504 | `Worker Loader env contains the reserved key ` + |
| 3505 | `${JSON.stringify(__loaderServiceMarker)}.`, |
| 3506 | "DataCloneError"); |
| 3507 | if (typeof v === "function" || v instanceof __cf.RpcTarget || |
| 3508 | __stubMeta.has(v) || __doStubMeta.has(v)) |
| 3509 | throw new DOMException( |
| 3510 | "Worker Loader env supports only Service Binding capabilities.", |
| 3511 | "DataCloneError"); |
| 3512 | if (v instanceof Map) { |
| 3513 | const out = new Map(); |
| 3514 | seen.set(v, out); |
| 3515 | for (const [key, item] of v) out.set(project(key), project(item)); |
| 3516 | return out; |
| 3517 | } |
| 3518 | if (v instanceof Set) { |
| 3519 | const out = new Set(); |
| 3520 | seen.set(v, out); |
| 3521 | for (const item of v) out.add(project(item)); |
| 3522 | return out; |
| 3523 | } |
| 3524 | const proto = Object.getPrototypeOf(v); |
| 3525 | if (!Array.isArray(v) && proto !== Object.prototype && proto !== null) |
| 3526 | return v; |
| 3527 | const out = Array.isArray(v) ? [] : {}; |
| 3528 | seen.set(v, out); |
| 3529 | for (const key of Object.keys(v)) out[key] = project(v[key]); |
| 3530 | return out; |
| 3531 | }; |
| 3532 | return { env: __sc_encode(project(value)), envRoutes }; |
| 3533 | }; |
| 3534 | const encodeModules = (c) => { |
| 3535 | if (c === null || typeof c !== "object" || c.modules === null |
| 3536 | || typeof c.modules !== "object") |
| 3537 | return { config: c, wasm: [], outbound: undefined, tails: [] }; |
| 3538 | // workerd requires the date, and names the missing value as it does. |
| 3539 | if (typeof c.compatibilityDate !== "string") |
| 3540 | throw new Error(`Invalid compatibility date: ${c.compatibilityDate}`); |
| 3541 | const modules = {}; |
| 3542 | const wasm = []; |
| 3543 | for (const [name, value] of Object.entries(c.modules)) { |
| 3544 | const wrapped = value !== null && typeof value === "object" ? value : {}; |
| 3545 | const explicitKinds = moduleKinds.filter((kind) => |
| 3546 | Object.prototype.hasOwnProperty.call(wrapped, kind) |
| 3547 | ); |
| 3548 | // An object is a module shape with one kind, as in workerd; bare bytes |
| 3549 | // are not a module. |
| 3550 | if (value !== null && typeof value === "object" && |
| 3551 | !(value instanceof WebAssembly.Module) && explicitKinds.length !== 1) |
| 3552 | throw new TypeError( |
| 3553 | "Each module must contain exactly one of 'js', 'cjs', 'text', " + |
| 3554 | `'data', 'json', 'py', or 'wasm'. Module '${name}' contained ` + |
| 3555 | `${explicitKinds.length} properties.`); |
| 3556 | const kind = explicitKinds[0]; |
| 3557 | if (kind === "js") { |
| 3558 | const source = wrapped[kind]; |
| 3559 | if (typeof source !== "string") |
| 3560 | throw new TypeError( |
| 3561 | `Worker Loader module ${JSON.stringify(name)} field ` + |
| 3562 | `${JSON.stringify(kind)} must be a string.`); |
| 3563 | modules[name] = source; |
| 3564 | continue; |
| 3565 | } |
| 3566 | const bytes = kind === "wasm" ? toBytes(wrapped.wasm) : null; |
| 3567 | if (bytes !== null) wasm.push([name, bytes]); |
| 3568 | else modules[name] = value; |
| 3569 | } |
| 3570 | let outbound; |
| 3571 | let outboundProps; |
| 3572 | if (Object.prototype.hasOwnProperty.call(c, "globalOutbound")) { |
| 3573 | if (c.globalOutbound === undefined) { |
| 3574 | outbound = undefined; |
| 3575 | } else if (c.globalOutbound === null) { |
| 3576 | outbound = null; |
| 3577 | } else { |
| 3578 | const meta = __outboundMeta.get(c.globalOutbound); |
| 3579 | if (meta === undefined) |
| 3580 | throw new TypeError("globalOutbound must be a Fetcher or null."); |
| 3581 | // JSON carries only the host-minted route. Props use V8 structured |
| 3582 | // clone bytes, so their types and the cross-isolate clone boundary |
| 3583 | // match the other parameterized ctx.exports transports. |
| 3584 | outboundProps = meta.propsSc ?? (meta.props === undefined |
| 3585 | ? new Uint8Array() |
| 3586 | : __rpcOut(meta.props, false)); |
| 3587 | outbound = JSON.stringify({ |
| 3588 | script: meta.script, |
| 3589 | entrypoint: meta.entrypoint, |
| 3590 | }); |
| 3591 | } |
| 3592 | } |
| 3593 | const { env, envRoutes } = encodeLoaderEnv(c.env); |
| 3594 | let tails = []; |
| 3595 | if (Object.prototype.hasOwnProperty.call(c, "tails")) { |
| 3596 | if (!Array.isArray(c.tails)) |
| 3597 | throw new TypeError("tails must be an array of Fetchers."); |
| 3598 | tails = c.tails.map((tail) => { |
| 3599 | if (!__outboundMeta.has(tail)) |
| 3600 | throw new TypeError("tails must be an array of Fetchers."); |
| 3601 | return tail; |
| 3602 | }); |
| 3603 | } |
| 3604 | const { |
| 3605 | globalOutbound: _globalOutbound, |
| 3606 | env: _env, |
| 3607 | tails: _tails, |
| 3608 | ...rest |
| 3609 | } = c; |
| 3610 | return { |
| 3611 | config: { ...rest, modules }, wasm, outbound, outboundProps, |
| 3612 | env, envRoutes, tails, |
| 3613 | }; |
| 3614 | }; |
| 3615 | // getCode is deferred into a microtask so a throw (or async getCode) |
| 3616 | // surfaces as a rejection when the worker is first used, not at get()/load(). |
| 3617 | const loadFrom = (getCode) => |
| 3618 | Promise.resolve().then(getCode) |
| 3619 | .then((c) => { |
| 3620 | const { |
| 3621 | config, wasm, outbound, outboundProps, env, envRoutes, tails, |
| 3622 | } = encodeModules(c); |
| 3623 | const id = __loader_load( |
| 3624 | JSON.stringify(config), wasm, outbound, outboundProps, env, |
| 3625 | envRoutes, tails.length !== 0); |
| 3626 | return { id, tails }; |
| 3627 | }); |
| 3628 | return { |
| 3629 | load(code) { return makeStub(track(loadFrom(() => code))); }, |
| 3630 | get(name, getCode) { |
| 3631 | let ref = byName.get(name); |
| 3632 | let loadPromise = ref?.deref(); |
| 3633 | if (loadPromise === undefined) { |
| 3634 | loadPromise = loadFrom(getCode); |
| 3635 | ref = new WeakRef(loadPromise); |
| 3636 | byName.set(name, ref); |
| 3637 | track(loadPromise, name, ref); |
| 3638 | } |
| 3639 | return makeStub(loadPromise, name, ref); |
| 3640 | }, |
| 3641 | }; |
| 3642 | }; |
| 3643 | |
| 3644 | const __makeServiceBinding = __celld.__makeServiceBinding = |
| 3645 | (script, entrypoint = null, propsSc = undefined) => { |
| 3646 | const target = { |
| 3647 | async fetch(input, init) { |
| 3648 | const req = new Request(input, init); |
| 3649 | const signal = req._signalForSubrequests; |
| 3650 | if (signal?.aborted) throw signal.reason; |
| 3651 | // A stream body advertises its length the way the HTTP layer |
| 3652 | // would: known length -> Content-Length, unknown -> chunked. |
| 3653 | if (req._bodyBytes === null && |
| 3654 | !req.headers.has("content-length") && |
| 3655 | !req.headers.has("transfer-encoding")) { |
| 3656 | const length = req.body._expectedLength; |
| 3657 | if (length === undefined) |
| 3658 | req.headers.set("transfer-encoding", "chunked"); |
| 3659 | else req.headers.set("content-length", String(length)); |
| 3660 | } |
| 3661 | const redirectState = __serviceRedirectState(req); |
| 3662 | // Fast path: the target is this same script, so its handler lives in |
| 3663 | // this isolate. Skip the op + pool-thread hop and call it directly, |
| 3664 | // inside its own event so the target's waitUntil does not attach to |
| 3665 | // the caller's. Cross-script targets still need their own isolate. |
| 3666 | if (script === __cell.script && entrypoint !== null && |
| 3667 | propsSc === undefined) { |
| 3668 | // Mirror __dispatchTo: the target sees a fresh incoming signal, |
| 3669 | // aborted with "The client has disconnected" when the caller |
| 3670 | // abandons the call or cancels the response body; the caller's |
| 3671 | // own signal races the dispatch so an abandoned call rejects |
| 3672 | // immediately instead of pinning on a hung target. |
| 3673 | const requestController = new AbortController(); |
| 3674 | const dispatch = __dispatchEntrypointFetch( |
| 3675 | entrypoint, |
| 3676 | new Request(req, { |
| 3677 | signal: requestController.signal, |
| 3678 | __celldIncomingSignal: true, |
| 3679 | })); |
| 3680 | const response = signal |
| 3681 | ? await __raceCallerAbort(dispatch, signal, () => |
| 3682 | requestController.abort( |
| 3683 | new Error("The client has disconnected"))) |
| 3684 | : await dispatch; |
| 3685 | __attachResponseRequestCancellation( |
| 3686 | response, requestController, true); |
| 3687 | return __finishServiceFetch(response, req, redirectState); |
| 3688 | } |
| 3689 | if (script === __cell.script && entrypoint === null && |
| 3690 | typeof __cell.selfFetch === "function") { |
| 3691 | if (__cell.svcDepth >= 8) |
| 3692 | throw new Error( |
| 3693 | "Service binding recursion limit exceeded (8)"); |
| 3694 | __cell.svcDepth = (__cell.svcDepth || 0) + 1; |
| 3695 | const ctx = __beginEvent(); |
| 3696 | try { |
| 3697 | return __finishServiceFetch( |
| 3698 | await __ctxRun(undefined, |
| 3699 | () => __cell.selfFetch(req, __cell.env, ctx)), |
| 3700 | req, redirectState); |
| 3701 | } finally { |
| 3702 | __cell.svcDepth--; |
| 3703 | __endEvent(); |
| 3704 | } |
| 3705 | } |
| 3706 | // The verbatim header list; see the note on the outbound `fetch`. The |
| 3707 | // target isolate rebuilds a `Headers` from these pairs, so a repeat and |
| 3708 | // its casing survive the crossing. |
| 3709 | const headers = JSON.stringify(req.headers.__celldHeaderList); |
| 3710 | // Cross-isolate calls carry exact bytes. A host-backed stream transfers |
| 3711 | // its one source to the target, and another stream uses the byte fallback. |
| 3712 | const { body, streamId } = await __subrequestBody(req); |
| 3713 | const r = JSON.parse(await (signal |
| 3714 | ? __awaitCancellableDoCall( |
| 3715 | __svc_call_cancellable( |
| 3716 | script, req.url, req.method, body, headers, streamId, entrypoint, |
| 3717 | propsSc), |
| 3718 | signal) |
| 3719 | : __svc_call( |
| 3720 | script, req.url, req.method, body, headers, streamId, entrypoint, |
| 3721 | propsSc))); |
| 3722 | const responseBody = r.streamId !== undefined |
| 3723 | ? new CelldHttpBodyStream(r.streamId) |
| 3724 | : r.body !== undefined |
| 3725 | ? r.body |
| 3726 | : Uint8Array.from(r.bodyBytes || []); |
| 3727 | return __finishServiceFetch( |
| 3728 | new Response(responseBody, { |
| 3729 | status: r.status, headers: r.headers, __wsTarget: r.wsTarget, |
| 3730 | }), |
| 3731 | req, redirectState); |
| 3732 | }, |
| 3733 | // Workerd's test-visible Fetcher.scheduled(): invoke the target's |
| 3734 | // scheduled handler and report the outcome. |
| 3735 | async scheduled(options = {}) { |
| 3736 | if (script !== __cell.script || entrypoint !== null || |
| 3737 | typeof __cell.selfScheduled !== "function") |
| 3738 | throw new Error( |
| 3739 | "scheduled() is only implemented for same-script service " + |
| 3740 | "bindings whose target has a scheduled handler"); |
| 3741 | let noRetry = false; |
| 3742 | const ctrl = { |
| 3743 | scheduledTime: options.scheduledTime === undefined |
| 3744 | ? Date.now() : Number(options.scheduledTime), |
| 3745 | cron: options.cron === undefined ? "" : String(options.cron), |
| 3746 | noRetry() { noRetry = true; }, |
| 3747 | }; |
| 3748 | const ctx = __beginEvent(); |
| 3749 | try { |
| 3750 | await __cell.selfScheduled(ctrl, __cell.env, ctx); |
| 3751 | return { outcome: "ok", noRetry }; |
| 3752 | } finally { |
| 3753 | const drain = __endEvent(); |
| 3754 | // scheduled() reports the event outcome, so it cannot return while the |
| 3755 | // work that defines that event is still pending. Fetch replies differ: |
| 3756 | // a streamed response can depend on waitUntil work and must return first. |
| 3757 | if (drain !== null) await drain; |
| 3758 | } |
| 3759 | }, |
| 3760 | }; |
| 3761 | // An omitted entrypoint selects the module's default export, which may be a |
| 3762 | // WorkerEntrypoint or an object handler. `entrypoint = "Name"` selects that |
| 3763 | // named class. Any property other than a reserved Fetcher method is an |
| 3764 | // awaitable/callable pipeline node: awaiting |
| 3765 | // resolves the property remotely (a property-GET wire op), calling |
| 3766 | // invokes it, and deeper access extends the path, resolved on the |
| 3767 | // receiver side in one op. Same-script dispatch stays in this |
| 3768 | // isolate, so stub-able values may cross. A property path rooted |
| 3769 | // directly at the binding is context-free (ctx null): awaiting it |
| 3770 | // starts a fresh session, as in Workerd. |
| 3771 | const rpcEntrypoint = entrypoint === null ? "default" : entrypoint; |
| 3772 | const session = __entrypointSession( |
| 3773 | rpcEntrypoint, script === __cell.script, script, undefined, propsSc); |
| 3774 | const binding = new Proxy(target, { |
| 3775 | getPrototypeOf: () => __cf.ServiceStub.prototype, |
| 3776 | get: (base, prop) => { |
| 3777 | if (prop === "then") return undefined; // a stub is not a thenable |
| 3778 | if (Reflect.has(base, prop)) return Reflect.get(base, prop); |
| 3779 | if (typeof prop !== "string") return undefined; |
| 3780 | // Workerd's test hook: the named method as a callable handle, |
| 3781 | // resolved -- and refused -- on the receiver side. |
| 3782 | if (prop === "getRpcMethodForTestOnly") |
| 3783 | return (name) => __makeNode(session, [String(name)], null); |
| 3784 | return __makeNode(session, [prop], null); |
| 3785 | }}); |
| 3786 | __outboundMeta.set(binding, { script, entrypoint, propsSc }); |
| 3787 | return binding; |
| 3788 | }; |
| 3789 | |
| 3790 | __celld.__installLoaderEnv = (bytes, routes) => { |
| 3791 | const env = __sc_decode(bytes); |
| 3792 | const seen = new Set(); |
| 3793 | const revive = (v) => { |
| 3794 | if (v === null || typeof v !== "object") return v; |
| 3795 | const routeIndex = Object.prototype.hasOwnProperty.call( |
| 3796 | v, __loaderServiceMarker) ? v[__loaderServiceMarker] : undefined; |
| 3797 | if (Number.isSafeInteger(routeIndex) && routeIndex >= 0) { |
| 3798 | // Rust supplies flat [script, entrypoint, props] triples, and the marker |
| 3799 | // stores the triple index rather than an offset into that array. |
| 3800 | const routeOffset = routeIndex * 3; |
| 3801 | if (!Number.isSafeInteger(routeOffset) || routeOffset + 2 >= routes.length) |
| 3802 | throw new DOMException( |
| 3803 | "Worker Loader env contains an invalid capability.", |
| 3804 | "DataCloneError"); |
| 3805 | return __makeServiceBinding( |
| 3806 | routes[routeOffset], routes[routeOffset + 1], routes[routeOffset + 2]); |
| 3807 | } |
| 3808 | if (seen.has(v)) return v; |
| 3809 | seen.add(v); |
| 3810 | if (v instanceof Map) { |
| 3811 | const entries = [...v]; |
| 3812 | v.clear(); |
| 3813 | for (const [key, item] of entries) v.set(revive(key), revive(item)); |
| 3814 | return v; |
| 3815 | } |
| 3816 | if (v instanceof Set) { |
| 3817 | const items = [...v]; |
| 3818 | v.clear(); |
| 3819 | for (const item of items) v.add(revive(item)); |
| 3820 | return v; |
| 3821 | } |
| 3822 | if (Array.isArray(v) || Object.getPrototypeOf(v) === Object.prototype || |
| 3823 | Object.getPrototypeOf(v) === null) |
| 3824 | for (const key of Object.keys(v)) v[key] = revive(v[key]); |
| 3825 | return v; |
| 3826 | }; |
| 3827 | Object.assign(__cell.env, revive(env)); |
| 3828 | }; |
| 3829 | // RPC marshalling: V8 structured clone (Workerd js-rpc semantics), so |
| 3830 | // undefined, Date, Map, Set, BigInt, typed arrays, and cycles survive. |
| 3831 | // A value V8 cannot clone throws DataCloneError, as in Workerd. |
| 3832 | // |
| 3833 | // The envelope's first byte tags the payload. 0xff (the clone version |
| 3834 | // header) = plain clone, decoded as-is. 0x01 = clone of a lifted tree in |
| 3835 | // which RpcTarget instances, functions, and Durable Object stubs were |
| 3836 | // replaced by stub markers; the lift runs only after a plain clone |
| 3837 | // already threw. A projection walk happens first because V8 silently erases |
| 3838 | // custom and null prototypes. 0x02 = a lifted tree carrying only by-value |
| 3839 | // host types (Blob/File, Headers, |
| 3840 | // Request/Response) and no capabilities -- decoded like 0x01, but a |
| 3841 | // reply so tagged does not root its callee context. 0x00 = clone of |
| 3842 | // [error, ownProps] -- a callee exception crossing as a real Error. |
| 3843 | const __dataCloneError = (error) => new DOMException( |
| 3844 | String(error && error.message || error), "DataCloneError"); |
| 3845 | const __rpcUnsupportedType = (value) => new DOMException( |
| 3846 | 'Could not serialize object of type "' + |
| 3847 | (__util_constructor_name(value) || "Object") + |
| 3848 | '". This type does not support serialization.', |
| 3849 | "DataCloneError"); |
| 3850 | // V8 clones a user-class instance and a null-prototype object as plain data, |
| 3851 | // but Workerd refuses both over RPC. Project the value graph before V8 can |
| 3852 | // erase that distinction. The projection also snapshots enumerable getters, |
| 3853 | // so validation and serialization cannot invoke one getter twice. Native |
| 3854 | // clone types and RPC host types keep their own serializers. |
| 3855 | const __rpcProject = (value) => { |
| 3856 | const seen = new Map(); |
| 3857 | const originals = new WeakMap(); |
| 3858 | const set = (target, key, value) => Object.defineProperty(target, key, { |
| 3859 | value, enumerable: true, configurable: true, writable: true, |
| 3860 | }); |
| 3861 | const project = (v) => { |
| 3862 | if (v === null || (typeof v !== "object" && typeof v !== "function")) |
| 3863 | return v; |
| 3864 | const cached = seen.get(v); |
| 3865 | if (cached !== undefined) return cached; |
| 3866 | if (typeof v === "function" || v instanceof __cf.RpcTarget || |
| 3867 | __stubMeta.has(v) || __svcMeta.has(v) || __doStubMeta.has(v) || |
| 3868 | v instanceof Headers || v instanceof Blob || v instanceof Request || |
| 3869 | v instanceof Response || v instanceof ReadableStream || |
| 3870 | v instanceof WritableStream || v instanceof AbortSignal || |
| 3871 | v instanceof Date || v instanceof RegExp || v instanceof Error || |
| 3872 | v instanceof ArrayBuffer || ArrayBuffer.isView(v) || |
| 3873 | (typeof SharedArrayBuffer !== "undefined" && |
| 3874 | v instanceof SharedArrayBuffer) || |
| 3875 | (typeof CryptoKey !== "undefined" && v instanceof CryptoKey) || |
| 3876 | (typeof WebAssembly !== "undefined" && |
| 3877 | v instanceof WebAssembly.Module) || |
| 3878 | __util_proxy_details(v) !== undefined) return v; |
| 3879 | if (v instanceof Map) { |
| 3880 | const out = new Map(); |
| 3881 | seen.set(v, out); |
| 3882 | for (const [key, entry] of v) { |
| 3883 | out.set(project(key), project(entry)); |
| 3884 | } |
| 3885 | return out; |
| 3886 | } |
| 3887 | if (v instanceof Set) { |
| 3888 | const out = new Set(); |
| 3889 | seen.set(v, out); |
| 3890 | for (const entry of v) out.add(project(entry)); |
| 3891 | return out; |
| 3892 | } |
| 3893 | if (Array.isArray(v)) { |
| 3894 | const out = new Array(v.length); |
| 3895 | seen.set(v, out); |
| 3896 | originals.set(out, v); |
| 3897 | for (const key of Object.keys(v)) set(out, key, project(v[key])); |
| 3898 | return out; |
| 3899 | } |
| 3900 | if (Object.getPrototypeOf(v) !== Object.prototype) |
| 3901 | throw __rpcUnsupportedType(v); |
| 3902 | const out = {}; |
| 3903 | seen.set(v, out); |
| 3904 | originals.set(out, v); |
| 3905 | for (const key of Object.keys(v)) set(out, key, project(v[key])); |
| 3906 | return out; |
| 3907 | }; |
| 3908 | return { tree: project(value), originals }; |
| 3909 | }; |
| 3910 | const __tagged = (tag, sc) => { |
| 3911 | const out = new Uint8Array(sc.length + 1); |
| 3912 | out[0] = tag; |
| 3913 | out.set(sc, 1); |
| 3914 | return out; |
| 3915 | }; |
| 3916 | // ---- request-context confinement ------------------------------- |
| 3917 | // Workerd ties I/O objects to the IoContext of the event that made |
| 3918 | // them. Cells' equivalent: each dispatched event enters an |
| 3919 | // async-context frame (the same CPED the ALS rides, so it survives |
| 3920 | // awaits) carrying a context id. Stubs remember their owning |
| 3921 | // context and refuse to serialize elsewhere; pipeline nodes refuse |
| 3922 | // foreign awaits and calls -- each with Workerd's exact error. |
| 3923 | let __nextCtxId = 1; |
| 3924 | const __ctxKey = Symbol("celld.ctx"); |
| 3925 | const __ctxNow = () => { |
| 3926 | const frame = __als_get(); |
| 3927 | return frame === undefined ? undefined : frame.get(__ctxKey); |
| 3928 | }; |
| 3929 | // Run `fn` under context `id` (undefined = a fresh one). An async |
| 3930 | // fn started inside keeps the frame across its awaits. The prior |
| 3931 | // frame is cloned so user AsyncLocalStorage stores still flow into |
| 3932 | // same-isolate callees, as they did before contexts existed. |
| 3933 | const __ctxRun = (id, fn) => { |
| 3934 | const prior = __als_get(); |
| 3935 | const frame = new Map(prior); |
| 3936 | frame.set(__ctxKey, id ?? __nextCtxId++); |
| 3937 | __als_set(frame); |
| 3938 | try { |
| 3939 | return fn(); |
| 3940 | } finally { |
| 3941 | __als_set(prior); |
| 3942 | } |
| 3943 | }; |
| 3944 | const __ctxError = (kind) => new Error( |
| 3945 | "Cannot perform I/O on behalf of a different request. I/O " + |
| 3946 | "objects (such as streams, request/response bodies, and others) " + |
| 3947 | "created in the context of one request handler cannot be " + |
| 3948 | "accessed from a different request's handler. This is a " + |
| 3949 | "limitation of Cloudflare Workers which allows us to improve " + |
| 3950 | "overall performance. (I/O type: " + kind + ")"); |
| 3951 | // ---- abortable request contexts -------------------------------- |
| 3952 | // Workerd's ctx.abort(reason) on an entrypoint aborts the request's |
| 3953 | // IoContext: the in-flight call rejects with the reason, and stubs |
| 3954 | // the context holds are disposed (their disposal callbacks fire). |
| 3955 | // State is allocated only when a context first holds a stub handle |
| 3956 | // or aborts, so plain-data dispatch pays nothing; call paths gate |
| 3957 | // every abort lookup on `__abortedCtxs.size` (one field read). |
| 3958 | // Aborted ids stay recorded: a stub rooted in a dead context must |
| 3959 | // keep rejecting with the reason. |
| 3960 | const __abortedCtxs = new Map(); |
| 3961 | // An actor-flavored abort reason: in-flight ops reject with the |
| 3962 | // wrapped reason, later ops with Workerd's post-abort message |
| 3963 | // (upstream TODO(bug): should propagate the reason, but doesn't). |
| 3964 | class __ActorAbort { constructor(reason) { this.reason = reason; } } |
| 3965 | const __postAbortError = (aborted) => aborted instanceof __ActorAbort |
| 3966 | ? new Error("The execution context which hosts this callback " + |
| 3967 | "is no longer running.") |
| 3968 | : aborted; |
| 3969 | // ctx id -> Set of live stub handles (metas) the context holds. |
| 3970 | const __ctxStubs = new Map(); |
| 3971 | // ctx id -> Set of reject callbacks for stub ops in flight against |
| 3972 | // that context. A hung callee never settles, so a context abort |
| 3973 | // must reject its pending callers directly. |
| 3974 | const __ctxPendingOps = new Map(); |
| 3975 | const __opTrack = (ctx, reject) => { |
| 3976 | let set = __ctxPendingOps.get(ctx); |
| 3977 | if (set === undefined) __ctxPendingOps.set(ctx, set = new Set()); |
| 3978 | set.add(reject); |
| 3979 | return () => { |
| 3980 | set.delete(reject); |
| 3981 | if (set.size === 0) __ctxPendingOps.delete(ctx); |
| 3982 | }; |
| 3983 | }; |
| 3984 | const __ctxRegister = (meta) => { |
| 3985 | if (meta.ctx === undefined) return; |
| 3986 | let set = __ctxStubs.get(meta.ctx); |
| 3987 | if (set === undefined) __ctxStubs.set(meta.ctx, set = new Set()); |
| 3988 | set.add(meta); |
| 3989 | }; |
| 3990 | const __ctxUnregister = (meta) => { |
| 3991 | const set = __ctxStubs.get(meta.ctx); |
| 3992 | if (set === undefined) return; |
| 3993 | set.delete(meta); |
| 3994 | if (set.size === 0) __ctxStubs.delete(meta.ctx); |
| 3995 | }; |
| 3996 | // Tear down a context: dispose every handle it still holds, so a |
| 3997 | // dup() leaked into it reaches the sender's disposal callback. |
| 3998 | const __ctxEnd = (id) => { |
| 3999 | const set = __ctxStubs.get(id); |
| 4000 | if (set === undefined) return; |
| 4001 | __ctxStubs.delete(id); |
| 4002 | for (const meta of set) __disposeStub(meta); |
| 4003 | }; |
| 4004 | const __ctxAbort = (id, reason) => { |
| 4005 | if (id === undefined || __abortedCtxs.has(id)) return; |
| 4006 | const stored = reason === undefined |
| 4007 | ? new Error("The execution context has been aborted.") |
| 4008 | : reason; |
| 4009 | __abortedCtxs.set(id, stored); |
| 4010 | __ctxEnd(id); |
| 4011 | const pending = __ctxPendingOps.get(id); |
| 4012 | if (pending === undefined) return; |
| 4013 | __ctxPendingOps.delete(id); |
| 4014 | const live = |
| 4015 | stored instanceof __ActorAbort ? stored.reason : stored; |
| 4016 | for (const reject of pending) reject(live); |
| 4017 | }; |
| 4018 | // The entrypoint ctx.abort. Instances are cached across calls, so |
| 4019 | // the construction-time ctx cannot pin a request id (Workerd |
| 4020 | // constructs per request); the current frame's id at abort() time |
| 4021 | // is the request being served, which matches Workerd observably. |
| 4022 | const __ctxAbortCurrent = |
| 4023 | (reason) => __ctxAbort(__ctxNow(), reason); |
| 4024 | // ---- same-process RPC stubs ------------------------------------ |
| 4025 | // A stub entry owns a local target; `refs` counts live handles |
| 4026 | // across dup()s. When the last handle is disposed the target's own |
| 4027 | // Symbol.dispose runs (async, matching Workerd's disposal callback). |
| 4028 | // Stubs cross same-isolate transports only (same-script entrypoint |
| 4029 | // RPC and same-process routed dispatch); a marker revived elsewhere fails |
| 4030 | // loudly on use instead of aliasing an unrelated local entry. |
| 4031 | // `ctx` records the owning request context: the entry's for |
| 4032 | // running its target, the handle's for the serialize-elsewhere |
| 4033 | // check. |
| 4034 | const __stubEntries = new Map(); |
| 4035 | const __stubMeta = new WeakMap(); |
| 4036 | // Keep the Durable Object brand outside the user-visible object. Reading a |
| 4037 | // string property here would invoke an inherited getter before validation can |
| 4038 | // reject its unsupported prototype. |
| 4039 | const __doStubMeta = new WeakMap(); |
| 4040 | let __nextStubId = 1; |
| 4041 | const __stubIsolate = Math.random().toString(36).slice(2); |
| 4042 | const __newEntry = (target) => { |
| 4043 | // `scope` records the actor event that minted the entry (top of |
| 4044 | // the event stack at lift time), so an actor breakage can find |
| 4045 | // and abort the contexts hosting its exported stubs, and an op on |
| 4046 | // the stub can queue on that cell's input gate. `section` is the |
| 4047 | // critical section running at lift time, if any -- an op on this |
| 4048 | // stub re-enters it rather than queueing behind it. |
| 4049 | const scope = __currentActorScope() || undefined; |
| 4050 | const entry = { |
| 4051 | id: __nextStubId++, target, refs: 1, ctx: __ctxNow(), scope, |
| 4052 | section: __cellBlocks.get(scope)?.holder ?? null, |
| 4053 | }; |
| 4054 | __stubEntries.set(entry.id, entry); |
| 4055 | return entry; |
| 4056 | }; |
| 4057 | // Actors broken in JS: scope -> reason. Workerd's DO ctx.abort |
| 4058 | // rejects in-flight and future calls; when the abort fires under a |
| 4059 | // same-isolate stub caller, terminate_execution would unwind that |
| 4060 | // caller too (the routed dispatch re-enters the isolate), so the |
| 4061 | // breakage is recorded here instead: contexts hosting the actor's |
| 4062 | // exported stubs abort (in-flight ops reject with the reason, |
| 4063 | // later ops with the post-abort message) and RPC dispatch to the |
| 4064 | // scope rejects with the reason. Direct host-dispatched DO events |
| 4065 | // keep the uncatchable terminate_execution path. |
| 4066 | const __brokenActors = new Map(); |
| 4067 | const __actorBreak = (scope, reason) => { |
| 4068 | if (__brokenActors.has(scope)) return; |
| 4069 | __brokenActors.set(scope, reason); |
| 4070 | for (const entry of __stubEntries.values()) |
| 4071 | if (entry.scope === scope) |
| 4072 | __ctxAbort(entry.ctx, new __ActorAbort(reason)); |
| 4073 | }; |
| 4074 | // Everything this isolate holds for one cell scope that belongs to the |
| 4075 | // cell's residency rather than to the isolate, so a fresh instance |
| 4076 | // inherits none of it. `adopt_cell` calls this on both edges: the |
| 4077 | // give-back frees it, the take-in guarantees that no epoch spans. |
| 4078 | // Storage is not here -- `stop_cell` closes it host-side -- and sockets |
| 4079 | // live in the host registry, so a hibernated cell keeps them. |
| 4080 | const __cellRelease = (scope) => { |
| 4081 | __cell.instances[scope]?.ctx?.facets?._release(); |
| 4082 | delete __cell.instances[scope]; |
| 4083 | delete __cell.idNames[scope]; |
| 4084 | delete __cell.facetConfigs[scope]; |
| 4085 | __brokenActors.delete(scope); |
| 4086 | // An abandoned block can never run `__blockLeave`. A normal eviction |
| 4087 | // cannot abandon a block because its event keeps the cell in flight. A |
| 4088 | // stop that waits for nobody can, so the release drops every block record |
| 4089 | // together with the other state for this residency. |
| 4090 | __cellBlocks.delete(scope); |
| 4091 | // An entry holds `target`, which can be an object the released |
| 4092 | // instance owns. Dropping it ends that reachability; `released` is |
| 4093 | // what an already-revived handle reads, since it holds its entry |
| 4094 | // directly and never looks in this map again. |
| 4095 | for (const entry of __stubEntries.values()) { |
| 4096 | if (entry.scope !== scope) continue; |
| 4097 | entry.released = true; |
| 4098 | __stubEntries.delete(entry.id); |
| 4099 | // Break in-flight ops as an abort would, but not through |
| 4100 | // `__actorBreak`: that records the scope broken for the life of the |
| 4101 | // isolate, which is the state this function drops. |
| 4102 | __ctxAbort(entry.ctx, new __ActorAbort(__releasedStubError())); |
| 4103 | } |
| 4104 | }; |
| 4105 | const __releasedStubError = () => new Error( |
| 4106 | "The Durable Object that returned this RPC stub no longer runs on " + |
| 4107 | "this node."); |
| 4108 | const __disposeStub = (meta) => { |
| 4109 | if (meta.disposed) return; |
| 4110 | meta.disposed = true; |
| 4111 | __ctxUnregister(meta); |
| 4112 | const entry = meta.entry; |
| 4113 | if (--entry.refs > 0) return; |
| 4114 | __stubEntries.delete(entry.id); |
| 4115 | const disposer = entry.target?.[Symbol.dispose]; |
| 4116 | if (typeof disposer === "function") |
| 4117 | Promise.resolve().then(() => disposer.call(entry.target)); |
| 4118 | }; |
| 4119 | const __stubDisposedError = () => |
| 4120 | new Error("RPC stub used after being disposed."); |
| 4121 | // Shared brand value for RpcTarget instances; see the RpcTarget |
| 4122 | // constructor. |
| 4123 | const __rpcNoClone = () => {}; |
| 4124 | // Workerd method-visibility rules by target kind: an RpcTarget |
| 4125 | // exposes inherited methods/accessors (never own instance state, |
| 4126 | // never Object.prototype); a plain object or function exposes own |
| 4127 | // properties only. Property reads go through normal [[Get]] so |
| 4128 | // Proxy handlers participate, as in Workerd. |
| 4129 | const __rpcNoSuchMethod = (prop) => new TypeError( |
| 4130 | 'The RPC receiver does not implement the method "' + prop + '".'); |
| 4131 | // Bind through the intrinsic because a callable proxy can implement `.bind` |
| 4132 | // as a remote property. Reading that property can turn a valid named RPC |
| 4133 | // method into a non-function. Keep this rule shared by every RPC binding site. |
| 4134 | const __rpcBindMethod = (value, receiver) => |
| 4135 | Reflect.apply(Function.prototype.bind, value, [receiver]); |
| 4136 | const __stubResolve = (target, prop) => { |
| 4137 | if (target instanceof __cf.RpcTarget) { |
| 4138 | if (Object.hasOwn(target, prop) || !(prop in target) || |
| 4139 | prop in Object.prototype) throw __rpcNoSuchMethod(prop); |
| 4140 | } else if (!Object.hasOwn(target, prop)) { |
| 4141 | throw __rpcNoSuchMethod(prop); |
| 4142 | } |
| 4143 | const value = target[prop]; |
| 4144 | // Keep celld's own stubs and pipeline nodes unwrapped because the wrapper |
| 4145 | // would lose their metadata. |
| 4146 | return typeof value === "function" && !__stubMeta.has(value) && |
| 4147 | !(value instanceof __cf.RpcPromise) && |
| 4148 | !(value instanceof __cf.RpcProperty) |
| 4149 | ? __rpcBindMethod(value, target) : value; |
| 4150 | }; |
| 4151 | // ---- streams over RPC ------------------------------------------ |
| 4152 | // A live stream crosses as a handle in the caps table: the sender |
| 4153 | // locks the origin (reader/writer acquired at lift) behind a |
| 4154 | // bridge entry, and the receiver's endpoint is an ordinary |
| 4155 | // ReadableStream/WritableStream whose pulls and writes are stub |
| 4156 | // ops against the bridge -- one bounded reverse call per chunk, |
| 4157 | // the clone being the one wire copy. Backpressure is the op in |
| 4158 | // flight: hwm 0 pulls only on demand, and the writable carries |
| 4159 | // one chunk per op. EOF, close, and errors cross as op results; |
| 4160 | // teardown (param disposal, context end, context abort) runs the |
| 4161 | // bridge disposer, which cancels or aborts an unfinished origin |
| 4162 | // with Workerd's generic disconnect errors -- reasons do not |
| 4163 | // propagate, matching Workerd's own TODOs (and its verbatim |
| 4164 | // "endeded" typo). |
| 4165 | const __wsDisconnect = () => new Error( |
| 4166 | "WritableStream received over RPC was disconnected because " + |
| 4167 | "the remote execution context has endeded."); |
| 4168 | const __rsDisconnect = () => new Error( |
| 4169 | "ReadableStream received over RPC disconnected prematurely."); |
| 4170 | // Receiver wrapper stream -> its handle meta, for forwarding. |
| 4171 | const __rpcStreamMeta = new WeakMap(); |
| 4172 | const __readableBridge = (reader) => { |
| 4173 | const bridge = { |
| 4174 | done: false, |
| 4175 | async read() { |
| 4176 | let result; |
| 4177 | try { |
| 4178 | result = await reader.read(); |
| 4179 | } catch (error) { |
| 4180 | bridge.done = true; |
| 4181 | throw error; |
| 4182 | } |
| 4183 | if (result.done) bridge.done = true; |
| 4184 | return result; |
| 4185 | }, |
| 4186 | cancel() { |
| 4187 | if (bridge.done) return; |
| 4188 | bridge.done = true; |
| 4189 | reader.cancel(__rsDisconnect()).catch(() => {}); |
| 4190 | }, |
| 4191 | [Symbol.dispose]() { bridge.cancel(); }, |
| 4192 | }; |
| 4193 | return bridge; |
| 4194 | }; |
| 4195 | const __writableBridge = (writer) => { |
| 4196 | const bridge = { |
| 4197 | done: false, |
| 4198 | write: (chunk) => writer.write(chunk), |
| 4199 | close() { |
| 4200 | bridge.done = true; |
| 4201 | return writer.close(); |
| 4202 | }, |
| 4203 | abort() { |
| 4204 | bridge.done = true; |
| 4205 | return writer.abort(__wsDisconnect()); |
| 4206 | }, |
| 4207 | [Symbol.dispose]() { |
| 4208 | if (!bridge.done) bridge.abort().catch(() => {}); |
| 4209 | }, |
| 4210 | }; |
| 4211 | return bridge; |
| 4212 | }; |
| 4213 | const __liftStream = (v) => { |
| 4214 | const readable = v instanceof ReadableStream; |
| 4215 | const key = readable ? "__celld$rs" : "__celld$ws"; |
| 4216 | const meta = __rpcStreamMeta.get(v); |
| 4217 | if (meta !== undefined && !meta.disposed && !v.locked) { |
| 4218 | // Re-serializing a received, untouched stream forwards the |
| 4219 | // original handle: the reference moves (like a stub) and |
| 4220 | // the local wrapper is dead -- a round trip stays one hop. |
| 4221 | meta.disposed = true; |
| 4222 | __ctxUnregister(meta); |
| 4223 | return { [key]: meta.entry.id, t: __stubIsolate }; |
| 4224 | } |
| 4225 | if (v.locked) |
| 4226 | throw new TypeError(readable |
| 4227 | ? "The ReadableStream has been locked to a reader." |
| 4228 | : "The WritableStream has been locked to a writer."); |
| 4229 | const bridge = readable |
| 4230 | ? __readableBridge(v.getReader()) |
| 4231 | : __writableBridge(v.getWriter()); |
| 4232 | return { [key]: __newEntry(bridge).id, t: __stubIsolate }; |
| 4233 | }; |
| 4234 | // A signal is not a snapshot on the RPC wire. The marker carries a |
| 4235 | // process-wide identity, and the host forwards the source's single state |
| 4236 | // transition to every receiving isolate. A received signal keeps that |
| 4237 | // identity when an RPC forwards it again, so a chain does not add relays. |
| 4238 | const __rpcSignalMeta = new WeakMap(); |
| 4239 | const __rpcSignalReceivers = new Map(); |
| 4240 | const __rpcSignalSourceFinalizer = new FinalizationRegistry( |
| 4241 | (id) => __rpc_signal_release(id)); |
| 4242 | const __rpcSignalReceiverFinalizer = new FinalizationRegistry( |
| 4243 | ({ id, subscription }) => |
| 4244 | __rpc_signal_unsubscribe(id, subscription)); |
| 4245 | const __rpcSignalReasonOut = (reason) => { |
| 4246 | if (reason instanceof DOMException) |
| 4247 | return __sc_encode({ d: true, n: reason.name, m: reason.message }); |
| 4248 | try { |
| 4249 | return __sc_encode({ v: reason }); |
| 4250 | } catch { |
| 4251 | return __sc_encode({ v: new Error(String(reason)) }); |
| 4252 | } |
| 4253 | }; |
| 4254 | const __rpcSignalReasonIn = (bytes) => { |
| 4255 | const reason = __sc_decode(bytes); |
| 4256 | return reason.d |
| 4257 | ? new DOMException(reason.m, reason.n) |
| 4258 | : reason.v; |
| 4259 | }; |
| 4260 | const __rpcSignalSubscribe = (receiver) => { |
| 4261 | const signal = receiver.signal.deref(); |
| 4262 | if (signal === undefined) return false; |
| 4263 | const pending = __rpc_signal_wait(receiver.id); |
| 4264 | receiver.subscription = pending.__celldRpcSignalSubscription; |
| 4265 | pending.then((reason) => { |
| 4266 | const target = receiver.signal.deref(); |
| 4267 | if (target !== undefined && reason.byteLength !== 0) |
| 4268 | __abortSignal(target, __rpcSignalReasonIn(reason)); |
| 4269 | }); |
| 4270 | // A wait belongs to the request that installed it. A retained signal needs |
| 4271 | // a fresh wait in each later request, and its finalizer must unsubscribe the |
| 4272 | // newest one rather than the dead request's subscription. |
| 4273 | __rpcSignalReceiverFinalizer.unregister(receiver); |
| 4274 | __rpcSignalReceiverFinalizer.register(signal, receiver, receiver); |
| 4275 | return true; |
| 4276 | }; |
| 4277 | const __liftSignal = (signal) => { |
| 4278 | let meta = __rpcSignalMeta.get(signal); |
| 4279 | if (meta === undefined) { |
| 4280 | const id = __rpc_signal_new(); |
| 4281 | meta = { id }; |
| 4282 | __rpcSignalMeta.set(signal, meta); |
| 4283 | __rpcSignalSourceFinalizer.register(signal, id); |
| 4284 | if (signal.aborted) { |
| 4285 | __rpc_signal_abort(id, __rpcSignalReasonOut(signal.reason)); |
| 4286 | } else { |
| 4287 | signal.addEventListener("abort", (event) => { |
| 4288 | __rpc_signal_abort(id, |
| 4289 | __rpcSignalReasonOut(event.target.reason)); |
| 4290 | }, { once: true }); |
| 4291 | } |
| 4292 | } |
| 4293 | const marker = { "__celld$sig": meta.id, a: signal.aborted }; |
| 4294 | if (signal.aborted) marker.r = __rpcSignalReasonOut(signal.reason); |
| 4295 | return marker; |
| 4296 | }; |
| 4297 | const __rpcSignalRefresh = () => { |
| 4298 | for (const [id, receivers] of __rpcSignalReceivers) { |
| 4299 | const state = __rpc_signal_poll(id); |
| 4300 | const live = new Set(); |
| 4301 | for (const receiver of receivers) { |
| 4302 | const signal = receiver.signal.deref(); |
| 4303 | if (signal === undefined) continue; |
| 4304 | if (state instanceof Uint8Array) |
| 4305 | __abortSignal(signal, __rpcSignalReasonIn(state)); |
| 4306 | else if (state !== null && __rpcSignalSubscribe(receiver)) |
| 4307 | live.add(receiver); |
| 4308 | } |
| 4309 | if (live.size === 0 || state === null || state instanceof Uint8Array) |
| 4310 | __rpcSignalReceivers.delete(id); |
| 4311 | else |
| 4312 | __rpcSignalReceivers.set(id, live); |
| 4313 | } |
| 4314 | }; |
| 4315 | // Replace stub-able values with wire markers. Runs only after a |
| 4316 | // plain clone failed, so plain-data serialization never pays for |
| 4317 | // it. Passing an existing stub transfers its reference: the |
| 4318 | // sender's handle is disposed (dup() first to keep one) and the |
| 4319 | // receiver adopts it. Returns null when nothing was liftable. |
| 4320 | const __stubLift = (value, allowCapabilities = true, originals) => { |
| 4321 | let lifted = false; |
| 4322 | // Capabilities (stubs, disposers) root the callee context; |
| 4323 | // by-value host types do not -- they pick the 0x02 envelope. |
| 4324 | let caps = false; |
| 4325 | const seen = new Map(); |
| 4326 | const ctx = __ctxNow(); |
| 4327 | // A buffered body crosses as its bytes; a live-stream body |
| 4328 | // crosses as a stream handle (a capability, so the reply |
| 4329 | // roots its callee context and the pulls keep working). |
| 4330 | const liftBody = (v) => { |
| 4331 | if (v._bodyBytes !== null) return v._bodyBytes; |
| 4332 | caps = true; |
| 4333 | return __liftStream(v.body); |
| 4334 | }; |
| 4335 | const lift = (v) => { |
| 4336 | if (v === null || |
| 4337 | (typeof v !== "object" && typeof v !== "function")) return v; |
| 4338 | const cached = seen.get(v); |
| 4339 | if (cached !== undefined) return cached; |
| 4340 | const meta = __stubMeta.get(v); |
| 4341 | if (meta) { |
| 4342 | if (!allowCapabilities) return v; |
| 4343 | lifted = true; |
| 4344 | caps = true; |
| 4345 | if (meta.disposed) throw __stubDisposedError(); |
| 4346 | // A stub belongs to the request that received it; another |
| 4347 | // request cannot serialize it (Workerd's IoContext rule). |
| 4348 | if (meta.ctx !== ctx) throw __ctxError("Client"); |
| 4349 | meta.disposed = true; // the ref moves to the receiver |
| 4350 | __ctxUnregister(meta); |
| 4351 | const marker = { "__celld$stub": meta.entry.id, |
| 4352 | t: __stubIsolate, c: meta.callable }; |
| 4353 | seen.set(v, marker); |
| 4354 | return marker; |
| 4355 | } |
| 4356 | const svc = __svcMeta.get(v); |
| 4357 | if (svc !== undefined) { |
| 4358 | if (!allowCapabilities) return v; |
| 4359 | // A loopback service stub (ctx.exports): name + props cross |
| 4360 | // as plain data and revive as a fresh loopback stub. Props |
| 4361 | // are lifted too -- they may nest further stubs (Workerd's |
| 4362 | // nested channel tokens). |
| 4363 | lifted = true; |
| 4364 | caps = true; |
| 4365 | const marker = { "__celld$svc": svc.name, t: __stubIsolate }; |
| 4366 | seen.set(v, marker); |
| 4367 | if (svc.props !== undefined) marker.p = lift(svc.props); |
| 4368 | return marker; |
| 4369 | } |
| 4370 | // Workerd refuses to serialize its promise/property handles. |
| 4371 | if (v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty) |
| 4372 | throw new DOMException( |
| 4373 | 'Could not serialize object of type "' + |
| 4374 | (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + |
| 4375 | '". This type does not support serialization.', |
| 4376 | "DataCloneError"); |
| 4377 | if (typeof v === "function" || v instanceof __cf.RpcTarget) { |
| 4378 | if (!allowCapabilities) return v; |
| 4379 | lifted = true; |
| 4380 | caps = true; |
| 4381 | const marker = { "__celld$stub": __newEntry(v).id, |
| 4382 | t: __stubIsolate, |
| 4383 | c: typeof v === "function" }; |
| 4384 | seen.set(v, marker); |
| 4385 | return marker; |
| 4386 | } |
| 4387 | const doId = __doStubMeta.get(v); |
| 4388 | if (doId !== undefined) { |
| 4389 | if (!allowCapabilities) return v; |
| 4390 | lifted = true; |
| 4391 | caps = true; |
| 4392 | const marker = { "__celld$do": doId._className, |
| 4393 | v: doId._value, n: v.name ?? null }; |
| 4394 | seen.set(v, marker); |
| 4395 | return marker; |
| 4396 | } |
| 4397 | // HTTP host types cross by value, as in Workerd's RPC |
| 4398 | // serialization: entry lists for Headers, the buffered bytes |
| 4399 | // for bodies (the marker aliases the live buffer; the clone |
| 4400 | // is the one wire copy), and no signal -- the receiver mints |
| 4401 | // a fresh one. A live stream body cannot cross yet. |
| 4402 | let marker; |
| 4403 | if (v instanceof Headers) { |
| 4404 | if (!allowCapabilities) return v; |
| 4405 | marker = { "__celld$hdr": [...v] }; |
| 4406 | } else if (v instanceof Blob) { |
| 4407 | if (!allowCapabilities) return v; |
| 4408 | marker = { "__celld$blob": v._bytes, y: v.type }; |
| 4409 | if (v instanceof File) { |
| 4410 | marker.n = v.name; |
| 4411 | marker.m = v.lastModified; |
| 4412 | } |
| 4413 | } else if (v instanceof Request) { |
| 4414 | if (!allowCapabilities) return v; |
| 4415 | marker = { "__celld$req": v.url, m: v.method, |
| 4416 | h: [...v.headers], r: v.redirect, c: v.cf, |
| 4417 | b: liftBody(v) }; |
| 4418 | } else if (v instanceof Response) { |
| 4419 | if (!allowCapabilities) return v; |
| 4420 | marker = { "__celld$res": v.status, |
| 4421 | t: v.statusText || |
| 4422 | __STATUS_TEXT[v.status] || "", |
| 4423 | h: [...v.headers], c: v.cf, |
| 4424 | e: v.type === "error", |
| 4425 | b: v.body === null ? null : liftBody(v) }; |
| 4426 | } else if (v instanceof ReadableStream || |
| 4427 | v instanceof WritableStream) { |
| 4428 | if (!allowCapabilities) return v; |
| 4429 | caps = true; |
| 4430 | marker = __liftStream(v); |
| 4431 | } else if (v instanceof AbortSignal) { |
| 4432 | marker = __liftSignal(v); |
| 4433 | } |
| 4434 | if (marker !== undefined) { |
| 4435 | lifted = true; |
| 4436 | seen.set(v, marker); |
| 4437 | return marker; |
| 4438 | } |
| 4439 | const proto = Object.getPrototypeOf(v); |
| 4440 | if (!Array.isArray(v) && |
| 4441 | proto !== Object.prototype && proto !== null) { |
| 4442 | // A Proxy emulating neither a plain object nor an RpcTarget |
| 4443 | // is Workerd's canonical proxy serialization error. |
| 4444 | if (__util_proxy_details(v) !== undefined) |
| 4445 | throw new DOMException( |
| 4446 | "Proxy could not be serialized because it is not a " + |
| 4447 | "valid RPC receiver type. The Proxy must emulate either " + |
| 4448 | "a plain object or an RpcTarget, as indicated by the " + |
| 4449 | "Proxy's prototype chain.", "DataCloneError"); |
| 4450 | return v; // host/other: leave to the clone |
| 4451 | } |
| 4452 | const out = Array.isArray(v) ? [] : {}; |
| 4453 | seen.set(v, out); |
| 4454 | for (const key of Object.keys(v)) out[key] = lift(v[key]); |
| 4455 | const disposerSource = originals?.get(v) ?? v; |
| 4456 | const disposer = disposerSource[Symbol.dispose]; |
| 4457 | if (allowCapabilities && !Array.isArray(v) && |
| 4458 | typeof disposer === "function") { |
| 4459 | lifted = true; |
| 4460 | caps = true; |
| 4461 | out["__celld$disp"] = |
| 4462 | __newEntry(__rpcBindMethod(disposer, disposerSource)).id; |
| 4463 | } |
| 4464 | return out; |
| 4465 | }; |
| 4466 | const tree = lift(value); |
| 4467 | return lifted ? { tree, caps } : null; |
| 4468 | }; |
| 4469 | // Revive host-type markers into real instances, adopting the wire |
| 4470 | // bytes directly -- no copy beyond the clone's own. |
| 4471 | const __reviveBlob = (marker, bytes) => { |
| 4472 | const blob = marker.n !== undefined |
| 4473 | ? new File([], marker.n, |
| 4474 | { type: marker.y, lastModified: marker.m }) |
| 4475 | : new Blob([], { type: marker.y }); |
| 4476 | blob._bytes = bytes; |
| 4477 | blob.size = bytes.byteLength; |
| 4478 | return blob; |
| 4479 | }; |
| 4480 | const __adoptBody = (target, bytes) => { |
| 4481 | target._bodyBytes = bytes; |
| 4482 | target._body = undefined; // decoded lazily on the first text()/json() |
| 4483 | const body = target.body; |
| 4484 | if (body !== null) { |
| 4485 | body._st.bytes = bytes; |
| 4486 | body.__celldBodyBytes = bytes; |
| 4487 | body._expectedLength = bytes.byteLength; |
| 4488 | } |
| 4489 | }; |
| 4490 | // A non-bytes `b` is a live-stream body marker: revive it and |
| 4491 | // let the constructor adopt it as a streaming body. |
| 4492 | const __reviveRequest = (marker, url, revive) => { |
| 4493 | if (!(marker.b instanceof Uint8Array)) |
| 4494 | return new Request(url, { method: marker.m, |
| 4495 | headers: marker.h, redirect: marker.r, cf: marker.c, |
| 4496 | body: revive(marker.b) }); |
| 4497 | const req = new Request(url, { method: marker.m, |
| 4498 | headers: marker.h, redirect: marker.r, cf: marker.c }); |
| 4499 | __adoptBody(req, marker.b); |
| 4500 | return req; |
| 4501 | }; |
| 4502 | const __reviveResponse = (marker, revive) => { |
| 4503 | const bytes = marker.b instanceof Uint8Array; |
| 4504 | const res = new Response( |
| 4505 | marker.b === null ? null : bytes ? "" : revive(marker.b), { |
| 4506 | status: marker["__celld$res"], statusText: marker.t, |
| 4507 | headers: marker.h, cf: marker.c }); |
| 4508 | if (bytes) __adoptBody(res, marker.b); |
| 4509 | if (marker.e) res.type = "error"; |
| 4510 | return res; |
| 4511 | }; |
| 4512 | // Wire a received stream handle to a local endpoint built with |
| 4513 | // the ordinary constructors -- nothing new threads through the |
| 4514 | // stream hot paths. Read errors surface as Workerd's generic |
| 4515 | // premature-disconnect; write errors propagate (Workerd sends |
| 4516 | // real errors back through the write loop). |
| 4517 | const __foreignStreamOp = () => Promise.reject(new Error( |
| 4518 | "RPC streams cannot cross isolate boundaries yet.")); |
| 4519 | const __reviveStream = (marker, id, readable, handles) => { |
| 4520 | const entry = marker.t === __stubIsolate |
| 4521 | ? __stubEntries.get(id) : undefined; |
| 4522 | if (entry === undefined) |
| 4523 | return readable |
| 4524 | ? new ReadableStream({ pull: __foreignStreamOp }) |
| 4525 | : new WritableStream({ write: __foreignStreamOp, |
| 4526 | close: __foreignStreamOp, abort: __foreignStreamOp }); |
| 4527 | const meta = { entry, disposed: false, ctx: __ctxNow() }; |
| 4528 | __ctxRegister(meta); |
| 4529 | handles.push(meta); |
| 4530 | const stream = readable |
| 4531 | ? new ReadableStream({ |
| 4532 | async pull(controller) { |
| 4533 | let result; |
| 4534 | try { |
| 4535 | result = await __stubOp(meta, ["read"], []); |
| 4536 | } catch { |
| 4537 | throw __rsDisconnect(); |
| 4538 | } |
| 4539 | if (result.done) controller.close(); |
| 4540 | else controller.enqueue(result.value); |
| 4541 | }, |
| 4542 | cancel: () => |
| 4543 | __stubOp(meta, ["cancel"], []).catch(() => {}), |
| 4544 | }, { highWaterMark: 0 }) |
| 4545 | : new WritableStream({ |
| 4546 | write: (chunk) => __stubOp(meta, ["write"], [chunk]), |
| 4547 | close: () => __stubOp(meta, ["close"], []), |
| 4548 | abort: () => |
| 4549 | __stubOp(meta, ["abort"], []).catch(() => {}), |
| 4550 | }); |
| 4551 | __rpcStreamMeta.set(stream, meta); |
| 4552 | return stream; |
| 4553 | }; |
| 4554 | const __reviveSignal = (marker, id) => { |
| 4555 | const controller = new AbortController(); |
| 4556 | const signal = controller.signal; |
| 4557 | __rpcSignalMeta.set(signal, { id }); |
| 4558 | if (marker.a) { |
| 4559 | controller.abort(__rpcSignalReasonIn(marker.r)); |
| 4560 | return controller.signal; |
| 4561 | } |
| 4562 | let receivers = __rpcSignalReceivers.get(id); |
| 4563 | if (receivers === undefined) { |
| 4564 | receivers = new Set(); |
| 4565 | __rpcSignalReceivers.set(id, receivers); |
| 4566 | } |
| 4567 | const receiver = { id, signal: new WeakRef(signal), subscription: null }; |
| 4568 | receivers.add(receiver); |
| 4569 | __rpcSignalSubscribe(receiver); |
| 4570 | return signal; |
| 4571 | }; |
| 4572 | // The inverse: markers become live handles. `handles` collects the |
| 4573 | // revived stubs (for call-end param disposal or result-tree |
| 4574 | // disposal); `disposers` collects remote Symbol.dispose entries. |
| 4575 | const __stubRevive = (value) => { |
| 4576 | const handles = []; |
| 4577 | const disposers = []; |
| 4578 | const seen = new Set(); |
| 4579 | const revive = (v) => { |
| 4580 | if (v === null || typeof v !== "object") return v; |
| 4581 | const stubId = v["__celld$stub"]; |
| 4582 | if (stubId !== undefined) { |
| 4583 | const entry = v.t === __stubIsolate |
| 4584 | ? __stubEntries.get(stubId) : undefined; |
| 4585 | const stub = entry === undefined |
| 4586 | ? __foreignStub() |
| 4587 | : __makeStub(entry, v.c); |
| 4588 | const meta = __stubMeta.get(stub); |
| 4589 | if (meta) handles.push(meta); |
| 4590 | return stub; |
| 4591 | } |
| 4592 | const svcName = v["__celld$svc"]; |
| 4593 | if (svcName !== undefined) |
| 4594 | return v.t === __stubIsolate |
| 4595 | ? __entrypointStub(svcName, revive(v.p)) |
| 4596 | : __foreignStub(); |
| 4597 | const doClass = v["__celld$do"]; |
| 4598 | if (doClass !== undefined) { |
| 4599 | const namespace = __cell.makeNamespace(doClass); |
| 4600 | return namespace.get( |
| 4601 | new DurableObjectId(doClass, v.v, v.n ?? undefined)); |
| 4602 | } |
| 4603 | const hdr = v["__celld$hdr"]; |
| 4604 | if (hdr !== undefined) return new Headers(hdr); |
| 4605 | const blobBytes = v["__celld$blob"]; |
| 4606 | if (blobBytes !== undefined) return __reviveBlob(v, blobBytes); |
| 4607 | const reqUrl = v["__celld$req"]; |
| 4608 | if (reqUrl !== undefined) |
| 4609 | return __reviveRequest(v, reqUrl, revive); |
| 4610 | if (v["__celld$res"] !== undefined) |
| 4611 | return __reviveResponse(v, revive); |
| 4612 | const rsId = v["__celld$rs"]; |
| 4613 | if (rsId !== undefined) |
| 4614 | return __reviveStream(v, rsId, true, handles); |
| 4615 | const wsId = v["__celld$ws"]; |
| 4616 | if (wsId !== undefined) |
| 4617 | return __reviveStream(v, wsId, false, handles); |
| 4618 | const sigId = v["__celld$sig"]; |
| 4619 | if (sigId !== undefined) return __reviveSignal(v, sigId); |
| 4620 | if (seen.has(v)) return v; |
| 4621 | seen.add(v); |
| 4622 | if (Array.isArray(v)) { |
| 4623 | for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); |
| 4624 | return v; |
| 4625 | } |
| 4626 | const proto = Object.getPrototypeOf(v); |
| 4627 | if (proto !== Object.prototype && proto !== null) return v; |
| 4628 | for (const key of Object.keys(v)) { |
| 4629 | if (key === "__celld$disp") { |
| 4630 | const entry = __stubEntries.get(v[key]); |
| 4631 | if (entry) disposers.push(entry); |
| 4632 | delete v[key]; |
| 4633 | continue; |
| 4634 | } |
| 4635 | v[key] = revive(v[key]); |
| 4636 | } |
| 4637 | return v; |
| 4638 | }; |
| 4639 | return { value: revive(value), handles, disposers }; |
| 4640 | }; |
| 4641 | // A marker that crossed an isolate boundary: fail on use, loudly. |
| 4642 | const __foreignStub = () => new Proxy(function () {}, { |
| 4643 | get: (_b, prop) => { |
| 4644 | if (prop === "then" || typeof prop !== "string") return undefined; |
| 4645 | return () => Promise.reject(new Error( |
| 4646 | "RPC stubs cannot cross isolate boundaries yet.")); |
| 4647 | }, |
| 4648 | apply: () => Promise.reject(new Error( |
| 4649 | "RPC stubs cannot cross isolate boundaries yet.")), |
| 4650 | }); |
| 4651 | // Workerd's entrypoint method-visibility rules (worker-rpc.c++): |
| 4652 | // reserved lifecycle names are refused outright; only prototype |
| 4653 | // methods and accessors are visible -- never own instance state |
| 4654 | // (env/ctx live there) and never Object.prototype. |
| 4655 | const __entrypointReserved = new Set([ |
| 4656 | "constructor", "fetch", "connect", "alarm", "scheduled", |
| 4657 | "webSocketMessage", "webSocketClose", "webSocketError", "dup", |
| 4658 | ]); |
| 4659 | const __entrypointResolve = (inst, prop) => { |
| 4660 | if (__entrypointReserved.has(prop)) |
| 4661 | throw new TypeError("'" + prop + |
| 4662 | "' is a reserved method and cannot be called over RPC."); |
| 4663 | if (Object.hasOwn(inst, prop) || !(prop in inst) || |
| 4664 | prop in Object.prototype) |
| 4665 | throw __rpcNoSuchMethod(prop); |
| 4666 | const value = inst[prop]; |
| 4667 | return typeof value === "function" && !__stubMeta.has(value) && |
| 4668 | !(value instanceof __cf.RpcPromise) && |
| 4669 | !(value instanceof __cf.RpcProperty) |
| 4670 | ? __rpcBindMethod(value, inst) : value; |
| 4671 | }; |
| 4672 | // A pipeline hop may continue only through plain data, functions, |
| 4673 | // RpcTargets, and stubs -- never through an RPC promise/property |
| 4674 | // handle or a class instance (Workerd's receiver rules). |
| 4675 | const __walkable = (v) => |
| 4676 | v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty |
| 4677 | ? false |
| 4678 | : typeof v === "function" || v instanceof __cf.RpcTarget || |
| 4679 | (typeof v === "object" && v !== null && |
| 4680 | (Object.getPrototypeOf(v) === Object.prototype || |
| 4681 | Array.isArray(v))); |
| 4682 | // Receiver-side pipeline walk: resolve `path` from `root`, then |
| 4683 | // GET the final member (`args` null) or CALL it. Errors name the |
| 4684 | // path walked so far, as Workerd's do. A stub mid-walk continues |
| 4685 | // against its own target, in the stub's owning context. |
| 4686 | const __rpcWalk = async (root, path, args, entrypointRoot) => { |
| 4687 | let value = root; |
| 4688 | for (let i = 0; i < path.length; i++) { |
| 4689 | const meta = __stubMeta.get(value); |
| 4690 | if (meta) { |
| 4691 | if (meta.disposed) throw __stubDisposedError(); |
| 4692 | const rest = path.slice(i); |
| 4693 | return await __ctxRun(meta.entry.ctx, |
| 4694 | () => __rpcWalk(meta.entry.target, rest, args, false)); |
| 4695 | } |
| 4696 | if (i > 0 && !__walkable(value)) |
| 4697 | throw __rpcNoSuchMethod(path[i - 1]); |
| 4698 | const prop = path[i]; |
| 4699 | const next = entrypointRoot && i === 0 |
| 4700 | ? __entrypointResolve(value, prop) |
| 4701 | : __stubResolve(value, prop); |
| 4702 | if (i === path.length - 1) { |
| 4703 | if (args === null) return next; |
| 4704 | if (typeof next !== "function") |
| 4705 | throw new TypeError( |
| 4706 | '"' + path.join(".") + '" is not a function.'); |
| 4707 | return next(...args); |
| 4708 | } |
| 4709 | if (next instanceof __cf.RpcPromise || |
| 4710 | next instanceof __cf.RpcProperty) |
| 4711 | throw __rpcNoSuchMethod(prop); |
| 4712 | value = next; |
| 4713 | } |
| 4714 | // An empty path applies the root itself (a callable stub). |
| 4715 | if (args === null) return value; |
| 4716 | if (typeof value !== "function") |
| 4717 | throw new TypeError("The RPC stub is not callable."); |
| 4718 | return value(...args); |
| 4719 | }; |
| 4720 | // One stub-mediated op: clone through the RPC envelope both ways, |
| 4721 | // so nested stubs, errors, and uncloneables behave exactly as a |
| 4722 | // dispatched call. Args serialize in the caller's context (its |
| 4723 | // stubs must be its own to transfer); the decode, the walk, and |
| 4724 | // the reply serialization run in the stub's owning context, so |
| 4725 | // stubs minted by the target belong to the target's context. |
| 4726 | // Params received by the target are disposed when the op ends |
| 4727 | // (Workerd's param-disposal rule). |
| 4728 | const __stubOp = (meta, path, args) => { |
| 4729 | if (meta.disposed) return Promise.reject(__stubDisposedError()); |
| 4730 | const entry = meta.entry; |
| 4731 | // The cell that minted this stub left residency, so `entry.target` |
| 4732 | // belongs to an instance this node released. The stub fails here |
| 4733 | // rather than calling into it. |
| 4734 | if (entry.released) return Promise.reject(__releasedStubError()); |
| 4735 | // A stub rooted in an aborted context is broken: reject with the |
| 4736 | // abort reason, before and after the dispatch (the target may |
| 4737 | // abort its own context mid-call). Gated on one field read. |
| 4738 | if (__abortedCtxs.size !== 0) { |
| 4739 | const aborted = __abortedCtxs.get(entry.ctx); |
| 4740 | if (aborted !== undefined) |
| 4741 | return Promise.reject(__postAbortError(aborted)); |
| 4742 | } |
| 4743 | const argsSc = args === null ? null : __rpcOut(args, true); |
| 4744 | const dispatch = (async () => { |
| 4745 | // Workerd delivers RPC asynchronously: the callee must not run |
| 4746 | // before the caller's synchronous code. A call made just after |
| 4747 | // a not-yet-delivered ctx.abort counts as in flight (rejects |
| 4748 | // with the reason, not the post-abort message). Bodies queue |
| 4749 | // in call order, so e-order holds. |
| 4750 | await null; |
| 4751 | // The cell that minted this stub gates it like any other event. |
| 4752 | // The op is dispatched inside the isolate and never becomes a |
| 4753 | // drive, so it is the one delivery point that has to ask here |
| 4754 | // rather than in Rust. A stub carrying the running critical |
| 4755 | // section re-enters it; everything else queues, and a section |
| 4756 | // that failed refuses what queued. |
| 4757 | const cell = entry.scope; |
| 4758 | if (cell !== undefined) { |
| 4759 | const block = __cellBlocks.get(cell); |
| 4760 | if (block !== undefined && (entry.section === null || |
| 4761 | entry.section !== block.holder)) |
| 4762 | await __gate_wait(cell); |
| 4763 | } |
| 4764 | const reply = await __ctxRun(entry.ctx, |
| 4765 | () => __rpcRun(async () => { |
| 4766 | const decoded = |
| 4767 | argsSc === null ? null : __rpcDesArgs(argsSc); |
| 4768 | try { |
| 4769 | return await __rpcWalk(entry.target, path, |
| 4770 | decoded === null ? null : decoded.args, false); |
| 4771 | } finally { |
| 4772 | if (decoded !== null) |
| 4773 | for (const handle of decoded.received) |
| 4774 | __disposeStub(handle); |
| 4775 | } |
| 4776 | }, true)); |
| 4777 | if (__abortedCtxs.size !== 0) { |
| 4778 | const aborted = __abortedCtxs.get(entry.ctx); |
| 4779 | if (aborted !== undefined) |
| 4780 | throw aborted instanceof __ActorAbort |
| 4781 | ? aborted.reason : aborted; |
| 4782 | } |
| 4783 | return __rpcDes(reply); |
| 4784 | })(); |
| 4785 | if (entry.ctx === undefined) return dispatch; |
| 4786 | // Race the op against its hosting context's abort: a hung callee |
| 4787 | // never settles, so the settlement check above cannot reach it. |
| 4788 | // A late settlement lands on an already-settled promise (no-op). |
| 4789 | return new Promise((resolve, reject) => { |
| 4790 | const untrack = __opTrack(entry.ctx, reject); |
| 4791 | dispatch.then( |
| 4792 | (value) => { untrack(); resolve(value); }, |
| 4793 | (error) => { untrack(); reject(error); }); |
| 4794 | }); |
| 4795 | }; |
| 4796 | // Resolve a path against a local, already-revived value. A hop |
| 4797 | // landing on a same-isolate stub delegates the rest of the path |
| 4798 | // to the stub's target; everything else is a plain [[Get]] so |
| 4799 | // Durable Object stubs and Proxies participate. |
| 4800 | const __walkLocal = (parent, path, args) => { |
| 4801 | for (let i = 0; i < path.length; i++) { |
| 4802 | const meta = __stubMeta.get(parent); |
| 4803 | if (meta) return __stubOp(meta, path.slice(i), args); |
| 4804 | const prop = path[i]; |
| 4805 | const member = parent == null ? undefined : parent[prop]; |
| 4806 | if (i < path.length - 1) { |
| 4807 | parent = member; |
| 4808 | continue; |
| 4809 | } |
| 4810 | if (args === null) return member; |
| 4811 | if (typeof member !== "function") { |
| 4812 | if (member === undefined) throw __rpcNoSuchMethod(prop); |
| 4813 | throw new TypeError('"' + prop + '" is not a function.'); |
| 4814 | } |
| 4815 | // [[Call]] directly: `.apply` on a stub proxy would be a |
| 4816 | // remote property access, not an invocation. |
| 4817 | return Reflect.apply(member, parent, args); |
| 4818 | } |
| 4819 | if (args === null) return parent; |
| 4820 | const meta = __stubMeta.get(parent); |
| 4821 | if (meta) return __stubOp(meta, [], args); |
| 4822 | if (typeof parent !== "function") |
| 4823 | throw new TypeError("The RPC value is not callable."); |
| 4824 | return parent(...args); |
| 4825 | }; |
| 4826 | // A session is one place pipeline ops resolve: the local value a |
| 4827 | // call returned, a same-isolate stub's target, or a named |
| 4828 | // entrypoint (whose paths resolve receiver-side in one op). |
| 4829 | const __valueSession = (promise) => ({ |
| 4830 | root: () => promise, |
| 4831 | get: (path) => promise.then((v) => __walkLocal(v, path, null)), |
| 4832 | call: (path, args) => |
| 4833 | promise.then((v) => __walkLocal(v, path, args)), |
| 4834 | }); |
| 4835 | const __stubSession = (meta) => ({ |
| 4836 | get: (path) => __stubOp(meta, path, null), |
| 4837 | call: (path, args) => __stubOp(meta, path, args), |
| 4838 | }); |
| 4839 | const __entrypointSession = (name, local, script, makeInst, propsSc) => ({ |
| 4840 | get: (path) => local |
| 4841 | ? (async () => __rpcDes( |
| 4842 | await __entrypointOp(name, path, null, true, makeInst)))() |
| 4843 | : (async () => __rpcDes( |
| 4844 | await __svc_rpc( |
| 4845 | script, name, JSON.stringify(path), null, propsSc)))(), |
| 4846 | call: (path, args) => (async () => { |
| 4847 | const argsSc = __rpcOut(args, local); |
| 4848 | if (local) |
| 4849 | return __rpcDes(await __entrypointOp( |
| 4850 | name, path, argsSc, true, makeInst)); |
| 4851 | return __rpcDes( |
| 4852 | await __svc_rpc( |
| 4853 | script, name, JSON.stringify(path), argsSc, propsSc)); |
| 4854 | })(), |
| 4855 | }); |
| 4856 | // Workerd's JsRpcPromise/JsRpcProperty: awaitable, callable, and |
| 4857 | // property access extends a path resolved at the far end, so |
| 4858 | // intermediates obey Workerd's receiver rules. `ctx` is the node's |
| 4859 | // owning request context -- null marks a context-free node (a |
| 4860 | // property path rooted directly at a service binding, which |
| 4861 | // starts a fresh session per await); a foreign context awaiting a |
| 4862 | // property or calling through the node gets Workerd's |
| 4863 | // cross-context error. Depth is capped like Workerd's |
| 4864 | // MAX_PROPERTY_DEPTH. |
| 4865 | const __makeNode = (session, path, ctx) => { |
| 4866 | let promise; |
| 4867 | const value = () => promise ??= (() => { |
| 4868 | if (path.length === 0) return session.root(); |
| 4869 | if (ctx !== null && ctx !== __ctxNow()) |
| 4870 | return Promise.reject(__ctxError("Pipeline")); |
| 4871 | return session.get(path); |
| 4872 | })(); |
| 4873 | const brand = |
| 4874 | path.length === 0 ? __cf.RpcPromise : __cf.RpcProperty; |
| 4875 | return new Proxy(function () {}, { |
| 4876 | getPrototypeOf: () => brand.prototype, |
| 4877 | get: (_b, p) => { |
| 4878 | if (p === "then") |
| 4879 | return (onOk, onErr) => value().then(onOk, onErr); |
| 4880 | if (p === "catch") return (onErr) => value().catch(onErr); |
| 4881 | if (p === "finally") |
| 4882 | return (onDone) => value().finally(onDone); |
| 4883 | if (typeof p !== "string") return undefined; |
| 4884 | if (path.length >= 5120) |
| 4885 | throw new TypeError( |
| 4886 | "RPC pipelined property chain is too deep."); |
| 4887 | return __makeNode(session, [...path, p], ctx); |
| 4888 | }, |
| 4889 | apply: (_b, _this, args) => { |
| 4890 | let call; |
| 4891 | if (ctx !== null && ctx !== __ctxNow()) { |
| 4892 | call = Promise.reject(__ctxError("JsRpcPromise")); |
| 4893 | call.catch(() => {}); |
| 4894 | } else { |
| 4895 | // Eager, so concurrent calls keep e-order. |
| 4896 | call = session.call(path, args); |
| 4897 | } |
| 4898 | return __makeNode( |
| 4899 | __valueSession(call), [], ctx ?? __ctxNow()); |
| 4900 | }, |
| 4901 | }); |
| 4902 | }; |
| 4903 | const __makeStub = (entry, callable) => { |
| 4904 | const meta = |
| 4905 | { entry, callable, disposed: false, ctx: __ctxNow() }; |
| 4906 | __ctxRegister(meta); |
| 4907 | const stub = new Proxy(function () {}, { |
| 4908 | getPrototypeOf: () => __cf.RpcStub.prototype, |
| 4909 | get: (_b, prop) => { |
| 4910 | if (prop === "then") return undefined; |
| 4911 | if (prop === Symbol.dispose) return () => __disposeStub(meta); |
| 4912 | if (prop === "dup") return () => { |
| 4913 | if (meta.disposed) throw __stubDisposedError(); |
| 4914 | entry.refs++; |
| 4915 | return __makeStub(entry, callable); |
| 4916 | }; |
| 4917 | if (typeof prop !== "string") return undefined; |
| 4918 | return __makeNode(__stubSession(meta), [prop], __ctxNow()); |
| 4919 | }, |
| 4920 | apply: (_b, _this, args) => __makeNode( |
| 4921 | __valueSession(__stubOp(meta, [], args)), [], __ctxNow()), |
| 4922 | }); |
| 4923 | __stubMeta.set(stub, meta); |
| 4924 | return stub; |
| 4925 | }; |
| 4926 | // A loopback service stub for one of this worker's own |
| 4927 | // entrypoints -- the ctx.exports surface. Calling the stub itself |
| 4928 | // returns a new stub carrying per-instance props, delivered to |
| 4929 | // the class constructor as ctx.props (Workerd's |
| 4930 | // ctx.exports.Name({ props })). |
| 4931 | const __svcMeta = new WeakMap(); |
| 4932 | const __entrypointStub = (name, props) => { |
| 4933 | let inst; |
| 4934 | const makeInst = props === undefined ? undefined : () => { |
| 4935 | if (inst !== undefined) return inst; |
| 4936 | const cls = __cell.entrypoints[name]; |
| 4937 | if (typeof cls !== "function") |
| 4938 | throw new TypeError( |
| 4939 | "The entrypoint " + name + " cannot carry props."); |
| 4940 | // Construction gets its own event, like a top-level invocation, and hands |
| 4941 | // that event's drain to the enclosing one. This runs inside the event of |
| 4942 | // the first method call on the stub, so a ctx.waitUntil() call in the |
| 4943 | // constructor drains before that call replies. |
| 4944 | inst = __constructEntrypoint(cls, props); |
| 4945 | return inst; |
| 4946 | }; |
| 4947 | const session = __entrypointSession(name, true, null, makeInst); |
| 4948 | const stub = new Proxy(function () {}, { |
| 4949 | getPrototypeOf: () => __cf.ServiceStub.prototype, |
| 4950 | get: (_b, prop) => { |
| 4951 | if (prop === "then") return undefined; |
| 4952 | if (typeof prop !== "string") return undefined; |
| 4953 | if (prop === "getRpcMethodForTestOnly") |
| 4954 | return (n) => __makeNode(session, [String(n)], null); |
| 4955 | // A Fetcher's fetch() is an HTTP request, as a service binding's is. |
| 4956 | if (prop === "fetch") |
| 4957 | return (input, init) => __makeServiceBinding( |
| 4958 | __cell.script, name === "default" ? null : name, |
| 4959 | props === undefined ? undefined : __rpcOut(props, false), |
| 4960 | ).fetch(input, init); |
| 4961 | return __makeNode(session, [prop], null); |
| 4962 | }, |
| 4963 | apply: (_b, _this, args) => |
| 4964 | __entrypointStub(name, args[0]?.props), |
| 4965 | }); |
| 4966 | __svcMeta.set(stub, { name, props }); |
| 4967 | __outboundMeta.set(stub, { |
| 4968 | script: __cell.script, |
| 4969 | entrypoint: name, |
| 4970 | props, |
| 4971 | }); |
| 4972 | return stub; |
| 4973 | }; |
| 4974 | // ---- stored stubs ---------------------------------------------- |
| 4975 | // Durable Object storage accepts only stubs with durable identity: |
| 4976 | // loopback service stubs (entrypoint name + props re-mint a fresh |
| 4977 | // stub on read) and Durable Object stubs (HMAC'd id + class revive |
| 4978 | // in any isolate). A transient handle -- a received RPC stub, a |
| 4979 | // function, an RpcTarget -- dies with its isolate; persisting its |
| 4980 | // entry id would revive garbage after a restart, so it is refused. |
| 4981 | // A stub-bearing row is written as 0x01 + clone(marker tree), off |
| 4982 | // the plain-clone fast path (the lift runs only after the plain |
| 4983 | // clone already threw, exactly like the RPC envelope). Reads hand |
| 4984 | // tagged rows to JS as [sentinel, tree]; the sentinel never leaves |
| 4985 | // this script and no user value can decode to it, so revival |
| 4986 | // cannot be spoofed by data shaped like a marker. |
| 4987 | const __storedSentinel = {}; |
| 4988 | const __storedLift = (value) => { |
| 4989 | let lifted = false; |
| 4990 | const seen = new Map(); |
| 4991 | const lift = (v) => { |
| 4992 | if (v === null || |
| 4993 | (typeof v !== "object" && typeof v !== "function")) return v; |
| 4994 | const cached = seen.get(v); |
| 4995 | if (cached !== undefined) return cached; |
| 4996 | // Ordering mirrors __stubLift: identify proxies by their |
| 4997 | // side tables and brands before touching any property -- a |
| 4998 | // stub or pipeline proxy answers every property read with a |
| 4999 | // fresh RpcProperty node. |
| 5000 | if (__stubMeta.has(v) || v instanceof __cf.RpcTarget) |
| 5001 | throw new DOMException( |
| 5002 | "Durable Object storage can only store stubs with " + |
| 5003 | "durable identity: service stubs from ctx.exports and " + |
| 5004 | "Durable Object stubs. This value is a transient RPC " + |
| 5005 | "handle that would not survive a restart.", |
| 5006 | "DataCloneError"); |
| 5007 | const svc = __svcMeta.get(v); |
| 5008 | if (svc !== undefined) { |
| 5009 | lifted = true; |
| 5010 | const marker = { "__celld$svc": svc.name }; |
| 5011 | seen.set(v, marker); |
| 5012 | if (svc.props !== undefined) marker.p = lift(svc.props); |
| 5013 | return marker; |
| 5014 | } |
| 5015 | if (v instanceof __cf.RpcPromise || |
| 5016 | v instanceof __cf.RpcProperty) |
| 5017 | throw new DOMException( |
| 5018 | 'Could not serialize object of type "' + |
| 5019 | (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + |
| 5020 | '". This type does not support serialization.', |
| 5021 | "DataCloneError"); |
| 5022 | if (typeof v === "function") return v; // leave to the clone |
| 5023 | const doId = __doStubMeta.get(v); |
| 5024 | if (doId !== undefined) { |
| 5025 | lifted = true; |
| 5026 | const marker = { "__celld$do": doId._className, |
| 5027 | v: doId._value, n: v.name ?? null }; |
| 5028 | seen.set(v, marker); |
| 5029 | return marker; |
| 5030 | } |
| 5031 | if (Array.isArray(v)) { |
| 5032 | const out = []; |
| 5033 | seen.set(v, out); |
| 5034 | for (let i = 0; i < v.length; i++) out[i] = lift(v[i]); |
| 5035 | return out; |
| 5036 | } |
| 5037 | const proto = Object.getPrototypeOf(v); |
| 5038 | if (proto !== Object.prototype && proto !== null) |
| 5039 | return v; // host/other: leave to the clone |
| 5040 | const out = {}; |
| 5041 | seen.set(v, out); |
| 5042 | for (const key of Object.keys(v)) out[key] = lift(v[key]); |
| 5043 | return out; |
| 5044 | }; |
| 5045 | const tree = lift(value); |
| 5046 | return lifted ? tree : null; |
| 5047 | }; |
| 5048 | // Encode one stub-bearing value for storage. Rethrows the original |
| 5049 | // clone error when nothing was liftable, so plain uncloneables |
| 5050 | // fail exactly as they always did. |
| 5051 | const __storedBytes = (value, error) => { |
| 5052 | const tree = __storedLift(value); |
| 5053 | if (tree === null) throw error; |
| 5054 | return __tagged(1, __sc_encode(tree)); |
| 5055 | }; |
| 5056 | const __storedRevive = (value) => { |
| 5057 | const seen = new Set(); |
| 5058 | const revive = (v) => { |
| 5059 | if (v === null || typeof v !== "object") return v; |
| 5060 | const svcName = v["__celld$svc"]; |
| 5061 | if (svcName !== undefined) |
| 5062 | return __entrypointStub(svcName, revive(v.p)); |
| 5063 | const doClass = v["__celld$do"]; |
| 5064 | if (doClass !== undefined) |
| 5065 | return __cell.makeNamespace(doClass).get( |
| 5066 | new DurableObjectId(doClass, v.v, v.n ?? undefined)); |
| 5067 | if (seen.has(v)) return v; |
| 5068 | seen.add(v); |
| 5069 | if (Array.isArray(v)) { |
| 5070 | for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); |
| 5071 | return v; |
| 5072 | } |
| 5073 | const proto = Object.getPrototypeOf(v); |
| 5074 | if (proto !== Object.prototype && proto !== null) return v; |
| 5075 | for (const key of Object.keys(v)) v[key] = revive(v[key]); |
| 5076 | return v; |
| 5077 | }; |
| 5078 | return revive(value); |
| 5079 | }; |
| 5080 | const __unwrapStored = (v) => |
| 5081 | Array.isArray(v) && v[0] === __storedSentinel |
| 5082 | ? __storedRevive(v[1]) : v; |
| 5083 | // A map result is wrapped as a whole only when it holds at least |
| 5084 | // one tagged row, so the per-entry walk never runs on plain data. |
| 5085 | const __unwrapStoredMap = (v) => { |
| 5086 | if (!Array.isArray(v) || v[0] !== __storedSentinel) return v; |
| 5087 | const map = v[1]; |
| 5088 | for (const [key, value] of map) |
| 5089 | map.set(key, __unwrapStored(value)); |
| 5090 | return map; |
| 5091 | }; |
| 5092 | // ctx.exports, as workerd's server builds it: a loopback stub for |
| 5093 | // `default` and each other entrypoint, a namespace for each exported |
| 5094 | // Durable Object class with storage, and a class, for facets, for |
| 5095 | // each other exported one. Built once, on first access -- ctx |
| 5096 | // construction itself only carries the getter. |
| 5097 | let __ctxExportsCache; |
| 5098 | const __ctxExports = () => __ctxExportsCache ??= (() => { |
| 5099 | const out = {}; |
| 5100 | for (const name of Object.keys(__cell.entrypoints)) |
| 5101 | out[name] = __entrypointStub(name, undefined); |
| 5102 | for (const name of Object.keys(__cell.objectEntrypoints)) |
| 5103 | out[name] = __entrypointStub(name, undefined); |
| 5104 | // Loader 0 is the script's own isolate: a facet of such a class runs |
| 5105 | // beside the object that holds it. |
| 5106 | for (const name of Object.keys(__cell.doExports)) { |
| 5107 | if (__runtimeClasses.has(name)) continue; |
| 5108 | out[name] = Object.hasOwn(__cell.namespaceKeys, name) |
| 5109 | ? __cell.makeNamespace(name) |
| 5110 | : __makeLoopbackDurableObjectClass(name); |
| 5111 | } |
| 5112 | return out; |
| 5113 | })(); |
| 5114 | // ---- RPC envelope ---------------------------------------------- |
| 5115 | // Serialize one payload. `lift` marks a same-isolate transport, |
| 5116 | // where stub-able values may cross as markers; elsewhere they stay |
| 5117 | // a DataCloneError, exactly as before stubs existed. |
| 5118 | const __rpcOut = (value, lift) => { |
| 5119 | const projected = __rpcProject(value); |
| 5120 | try { |
| 5121 | return __sc_encode(projected.tree); |
| 5122 | } catch (error) { |
| 5123 | // A cross-isolate call lifts only a live signal. A same-isolate call can |
| 5124 | // also transfer the existing host values and JS capability handles. |
| 5125 | const lifted = __stubLift(projected.tree, lift, projected.originals); |
| 5126 | if (lifted === null) throw __dataCloneError(error); |
| 5127 | try { |
| 5128 | return __tagged( |
| 5129 | lifted.caps ? 1 : 2, __sc_encode(lifted.tree)); |
| 5130 | } catch (error_) { |
| 5131 | throw __dataCloneError(error_); |
| 5132 | } |
| 5133 | } |
| 5134 | }; |
| 5135 | // A callee exception as tagged bytes: the Error crosses by value |
| 5136 | // (V8 serializes Error natively), custom own properties beside it. |
| 5137 | const __rpcErrOut = (error) => { |
| 5138 | // `name` rides in the props: V8 only round-trips the standard |
| 5139 | // Error subclass names, and e.g. DataCloneError must survive. |
| 5140 | const props = error instanceof Error |
| 5141 | ? { ...error, name: error.name } : {}; |
| 5142 | let sc; |
| 5143 | try { |
| 5144 | sc = __sc_encode([error, props]); |
| 5145 | } catch { |
| 5146 | const error_ = new Error(String(error?.message ?? error)); |
| 5147 | sc = __sc_encode([error_, { name: String(error?.name ?? "Error") }]); |
| 5148 | } |
| 5149 | return __tagged(0, sc); |
| 5150 | }; |
| 5151 | // The callee half of one RPC: run `body`, answer tagged bytes. |
| 5152 | const __rpcRun = async (body, lift) => { |
| 5153 | try { |
| 5154 | return __rpcOut(await body(), lift); |
| 5155 | } catch (error) { |
| 5156 | return __rpcErrOut(error); |
| 5157 | } |
| 5158 | }; |
| 5159 | const __rpcDesArgs = (bytes) => { |
| 5160 | if (bytes[0] === 0xff) |
| 5161 | return { args: __sc_decode(bytes), received: [] }; |
| 5162 | const revived = __stubRevive(__sc_decode(bytes.subarray(1))); |
| 5163 | return { args: revived.value, received: revived.handles }; |
| 5164 | }; |
| 5165 | // The caller half: decode a reply, rebuilding stubs and rethrowing |
| 5166 | // callee exceptions as real Errors with the callee's own |
| 5167 | // properties, `.remote`, and a local (caller-side) stack. |
| 5168 | const __rpcDes = (bytes) => { |
| 5169 | if (bytes[0] === 0xff) return __sc_decode(bytes); |
| 5170 | if (bytes[0] === 1 || bytes[0] === 2) { |
| 5171 | const { value, handles, disposers } = |
| 5172 | __stubRevive(__sc_decode(bytes.subarray(1))); |
| 5173 | if (value !== null && typeof value === "object" && |
| 5174 | !__stubMeta.has(value) && |
| 5175 | (handles.length > 0 || disposers.length > 0)) { |
| 5176 | Object.defineProperty(value, Symbol.dispose, { |
| 5177 | configurable: true, |
| 5178 | value: () => { |
| 5179 | for (const handle of handles) __disposeStub(handle); |
| 5180 | for (const entry of disposers) { |
| 5181 | __stubEntries.delete(entry.id); |
| 5182 | Promise.resolve().then(() => entry.target()); |
| 5183 | } |
| 5184 | }, |
| 5185 | }); |
| 5186 | } |
| 5187 | return value; |
| 5188 | } |
| 5189 | const [error, props] = __sc_decode(bytes.subarray(1)); |
| 5190 | if (error instanceof Error) { |
| 5191 | Object.assign(error, props); |
| 5192 | error.remote = true; |
| 5193 | const local = new Error().stack; |
| 5194 | error.stack = error.name + ": " + error.message + |
| 5195 | local.slice(local.indexOf("\n")); |
| 5196 | } |
| 5197 | throw error; |
| 5198 | }; |
| 5199 | // Deprecated Fetcher `get()`/`put()`/`delete()` HTTP helpers, kept by |
| 5200 | // the fetcher_has_get_put_delete compat flag (Workerd http.c++): |
| 5201 | // shortcuts for fetch() with the corresponding method. |
| 5202 | const __fetcherStatus = (res, method) => { |
| 5203 | if (res.status >= 200 && res.status < 300) return; |
| 5204 | throw new Error("HTTP " + method + " request failed: " + res.status + |
| 5205 | " " + (res.statusText || __STATUS_TEXT[res.status] || "")); |
| 5206 | }; |
| 5207 | const __fetcherHelper = (fetch, prop) => { |
| 5208 | if (prop === "get") return async (url, type) => { |
| 5209 | const res = await fetch(url, { method: "GET" }); |
| 5210 | if (res.status === 404 || res.status === 410) return null; |
| 5211 | __fetcherStatus(res, "GET"); |
| 5212 | if (type === "stream") |
| 5213 | return res.body ?? new ReadableStream({ start(c) { c.close(); } }); |
| 5214 | if (type === "arrayBuffer") return res.arrayBuffer(); |
| 5215 | if (type === "json") return res.json(); |
| 5216 | return res.text(); |
| 5217 | }; |
| 5218 | if (prop === "put") return async (url, body, options) => { |
| 5219 | const { expiration, expirationTtl } = options ?? {}; |
| 5220 | if (expiration !== undefined || expirationTtl !== undefined) { |
| 5221 | const url_ = new URL(url); |
| 5222 | if (expiration !== undefined) |
| 5223 | url_.searchParams.append("expiration", expiration); |
| 5224 | if (expirationTtl !== undefined) |
| 5225 | url_.searchParams.append("expiration_ttl", expirationTtl); |
| 5226 | url = url_.toString(); |
| 5227 | } |
| 5228 | __fetcherStatus(await fetch(url, { method: "PUT", body }), "PUT"); |
| 5229 | }; |
| 5230 | return async (url) => { |
| 5231 | __fetcherStatus(await fetch(url, { method: "DELETE" }), "DELETE"); |
| 5232 | }; |
| 5233 | }; |
| 5234 | function makeNamespace(className) { |
| 5235 | const namespaceKey = __cell.namespaceKeys[className]; |
| 5236 | if (typeof namespaceKey !== "string") |
| 5237 | throw new Error("no Durable Object namespace key for " + className); |
| 5238 | return new DurableObjectNamespace(className, namespaceKey); |
| 5239 | } |
| 5240 | // A named class: SDKs sniff bindings by constructor name (workers-rs |
| 5241 | // EnvBinding requires `constructor.name === "DurableObjectNamespace"`). |
| 5242 | class DurableObjectNamespace { |
| 5243 | constructor(className, namespaceKey) { |
| 5244 | Object.defineProperty(this, "_className", { value: className }); |
| 5245 | Object.defineProperty(this, "_namespaceKey", { value: namespaceKey }); |
| 5246 | } |
| 5247 | idFromName(name) { |
| 5248 | name = String(name); |
| 5249 | return new DurableObjectId( |
| 5250 | this._className, __do_id(this._namespaceKey, "name", name), name, |
| 5251 | ); |
| 5252 | } |
| 5253 | idFromString(value) { |
| 5254 | return new DurableObjectId( |
| 5255 | this._className, __do_id(this._namespaceKey, "validate", String(value)), |
| 5256 | ); |
| 5257 | } |
| 5258 | newUniqueId(options = {}) { |
| 5259 | const jurisdiction = options == null ? undefined : options.jurisdiction; |
| 5260 | if (jurisdiction != null) |
| 5261 | throw new Error("Jurisdiction restrictions are not implemented"); |
| 5262 | return new DurableObjectId( |
| 5263 | this._className, __do_id(this._namespaceKey, "unique", ""), |
| 5264 | ); |
| 5265 | } |
| 5266 | jurisdiction(value) { |
| 5267 | if (value == null) return this; |
| 5268 | throw new Error("Jurisdiction restrictions are not implemented"); |
| 5269 | } |
| 5270 | getByName(name, options) { |
| 5271 | return this.get(this.idFromName(name), options); |
| 5272 | } |
| 5273 | get(id) { |
| 5274 | const className = this._className; |
| 5275 | if (!(id instanceof DurableObjectId) || id._className !== className) |
| 5276 | throw new TypeError("Durable Object ID is not valid for this namespace"); |
| 5277 | const scope = id._scope(); |
| 5278 | // Emulate production: the actor recovers its name only when it is |
| 5279 | // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is |
| 5280 | // undefined. The full name still seeds the routing hash, so |
| 5281 | // dispatch is unchanged. Short names skip the byte count (< 256 |
| 5282 | // chars is always <= 1020 bytes) to keep the hot path alloc-free. |
| 5283 | const nm = id.name; |
| 5284 | const dispatchName = nm === undefined ? undefined |
| 5285 | : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024 |
| 5286 | ? nm : undefined; |
| 5287 | if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName; |
| 5288 | // Fetch and native RPC use the same host routing/activation seam. |
| 5289 | // Never expose `.then`: a DO stub is not itself a promise. |
| 5290 | const target = { id, name: dispatchName }; |
| 5291 | const abortMarker = "__CELLD_ACTOR_ABORT__:"; |
| 5292 | const processExitMarker = "__CELLD_PROCESS_EXIT__:"; |
| 5293 | let brokenReason = null; |
| 5294 | const invoke = async (operation) => { |
| 5295 | if (brokenReason !== null) throw new Error(brokenReason); |
| 5296 | try { |
| 5297 | return await operation(); |
| 5298 | } catch (error) { |
| 5299 | const routingError = __durableObjectRoutingError(error); |
| 5300 | if (routingError !== null) throw routingError; |
| 5301 | const message = String(error && error.message || error); |
| 5302 | const marker = [abortMarker, processExitMarker] |
| 5303 | .find((candidate) => message.includes(candidate)); |
| 5304 | if (!marker) throw error; |
| 5305 | brokenReason = message.slice(message.indexOf(marker) + marker.length); |
| 5306 | throw new Error(brokenReason); |
| 5307 | } |
| 5308 | }; |
| 5309 | const doFetch = async (input, init) => { |
| 5310 | const req = new Request(input, init); |
| 5311 | const signal = req._signalForSubrequests; |
| 5312 | if (signal?.aborted) throw signal.reason; |
| 5313 | // A body already backed by a host stream forwards to the cell as its |
| 5314 | // stream id, so a proxied upload to a cell on this node costs a chunk |
| 5315 | // rather than the whole body (#156). The host keeps it a stream for a |
| 5316 | // local cell and collects it only to sign a cross-node frame. A held |
| 5317 | // body -- or a stream with no host id -- crosses as its bytes. |
| 5318 | const bodyStreamId = |
| 5319 | req._bodyBytes === null && req.body && req.body.__celldStreamId !== undefined |
| 5320 | ? req.body.__celldStreamId |
| 5321 | : undefined; |
| 5322 | const body_ = bodyStreamId !== undefined |
| 5323 | ? new Uint8Array() |
| 5324 | : req._bodyBytes === null |
| 5325 | ? await req._consume() |
| 5326 | : req._bodyBytes; |
| 5327 | if (bodyStreamId !== undefined) { |
| 5328 | // The cell reads this upload through the same host stream id, so the |
| 5329 | // Worker's wrapper must not also read it: lock it (a late read throws |
| 5330 | // instead of racing the cell over one host stream) and mark it used, |
| 5331 | // which is what awaiting the old _consume() did and what workerd |
| 5332 | // reports as request.bodyUsed after the forward. |
| 5333 | req.bodyUsed = true; |
| 5334 | req.body.getReader(); |
| 5335 | } |
| 5336 | // Forward the request's headers to the cell as JSON. When they were |
| 5337 | // never materialized -- a Worker that only routes to a cell reads |
| 5338 | // none -- pass the raw header string straight through, so the whole |
| 5339 | // dispatch never builds a Headers object on either side. |
| 5340 | // |
| 5341 | // Both branches now carry the same shape. The raw string is the |
| 5342 | // wire list the host handed in, so the materialized branch must send |
| 5343 | // the header list too, not the iterator; see the note on the |
| 5344 | // outbound `fetch`. Reading `.headers` on a forwarded request used |
| 5345 | // to change what the cell received. |
| 5346 | const headersJson = req._headersJson !== undefined |
| 5347 | ? req._headersJson |
| 5348 | : JSON.stringify(req.headers.__celldHeaderList); |
| 5349 | const r = JSON.parse(await invoke(() => { |
| 5350 | if (!signal) return __do_call( |
| 5351 | scope, dispatchName ?? null, req.url, req.method, body_, |
| 5352 | headersJson, bodyStreamId, |
| 5353 | ); |
| 5354 | return __awaitCancellableDoCall( |
| 5355 | __do_call_cancellable( |
| 5356 | scope, dispatchName ?? null, req.url, req.method, body_, |
| 5357 | headersJson, bodyStreamId, |
| 5358 | ), |
| 5359 | signal, |
| 5360 | ); |
| 5361 | })); |
| 5362 | const body = r.streamId !== undefined |
| 5363 | ? new CelldHttpBodyStream(r.streamId) |
| 5364 | : r.body !== undefined |
| 5365 | ? r.body |
| 5366 | : Uint8Array.from(r.bodyBytes || []); |
| 5367 | // An upgrade the cell answered with. The pair straddles two isolates, |
| 5368 | // so the client end cannot be the peer object itself -- it is a new |
| 5369 | // socket the host joins to the cell's on `accept()`. A caller that |
| 5370 | // returns this response instead of accepting keeps the direct route |
| 5371 | // `__wsTarget` already describes, and binds nothing. |
| 5372 | return new Response(body, { |
| 5373 | status: r.status, |
| 5374 | headers: r.headers, |
| 5375 | __wsTarget: r.wsTarget, |
| 5376 | webSocket: r.status === 101 && r.wsTarget |
| 5377 | ? new WebSocket(undefined, [], r.wsTarget) |
| 5378 | : undefined, |
| 5379 | }); |
| 5380 | }; |
| 5381 | const stub = new Proxy(target, { get: (_target, prop) => { |
| 5382 | if (prop === "then") return undefined; |
| 5383 | if (Reflect.has(_target, prop)) return Reflect.get(_target, prop); |
| 5384 | if (prop === "fetch") return doFetch; |
| 5385 | if (typeof prop !== "string") return undefined; |
| 5386 | if (__cell.compat.fetcherGetPutDelete && |
| 5387 | (prop === "get" || prop === "put" || prop === "delete")) |
| 5388 | return __fetcherHelper(doFetch, prop); |
| 5389 | // Every cell RPC goes out through the host, whichever node owns the |
| 5390 | // target. Same-process dispatch re-enters this isolate, where the |
| 5391 | // abort and exit markers revive; bytes that land elsewhere revive as |
| 5392 | // loud foreign stubs. |
| 5393 | return async (...args) => invoke( |
| 5394 | async () => __rpcDes(await __rpc_call( |
| 5395 | scope, dispatchName ?? null, prop, __rpcOut(args, true), |
| 5396 | )), |
| 5397 | ); |
| 5398 | }}); |
| 5399 | __doStubMeta.set(stub, id); |
| 5400 | return stub; |
| 5401 | } |
| 5402 | } |
| 5403 | const __attachResponseRequestCancellation = ( |
| 5404 | response, |
| 5405 | requestController, |
| 5406 | wrapBody, |
| 5407 | ) => { |
| 5408 | if (!(response instanceof Response) || |
| 5409 | response._bodyBytes !== null || |
| 5410 | response.body === null) { |
| 5411 | return; |
| 5412 | } |
| 5413 | const requestControllers = Array.isArray( |
| 5414 | response.__celldRequestControllers, |
| 5415 | ) |
| 5416 | ? response.__celldRequestControllers |
| 5417 | : [requestController]; |
| 5418 | if (requestControllers !== response.__celldRequestControllers) { |
| 5419 | Object.defineProperty(response, "__celldRequestControllers", { |
| 5420 | value: requestControllers, |
| 5421 | }); |
| 5422 | } else { |
| 5423 | requestControllers.push(requestController); |
| 5424 | } |
| 5425 | if (!wrapBody || response.__celldCancellationWrapped) return; |
| 5426 | const reader = response.body.getReader(); |
| 5427 | response.body = new ReadableStream({ |
| 5428 | async pull(controller) { |
| 5429 | const result = await reader.read(); |
| 5430 | if (result.done) controller.close(); |
| 5431 | else controller.enqueue(result.value); |
| 5432 | }, |
| 5433 | async cancel() { |
| 5434 | const reason = new Error("The client has disconnected"); |
| 5435 | for (const controller of requestControllers) { |
| 5436 | if (!controller.signal.aborted) controller.abort(reason); |
| 5437 | } |
| 5438 | try { |
| 5439 | await reader.cancel(reason); |
| 5440 | } catch {} |
| 5441 | }, |
| 5442 | }, { highWaterMark: 0 }); |
| 5443 | Object.defineProperty(response, "__celldCancellationWrapped", { |
| 5444 | value: true, |
| 5445 | }); |
| 5446 | }; |
| 5447 | // called on the owner node by the /__do/<scope> endpoint: run one object. |
| 5448 | // Returns the Response; Rust's read_response unwraps it (don't double-wrap). |
| 5449 | // A top-level (non-actor) request whose signal can be aborted by id, so a |
| 5450 | // disconnected HTTP or service-binding caller reaches the target's |
| 5451 | // `request.signal`. |
| 5452 | // A large body, or a body of unknown length, arrives as a stream id and |
| 5453 | // not as bytes. The handler then pulls the body off the socket as it |
| 5454 | // reads, so the whole body is never resident. `request.body` is a stream |
| 5455 | // in both cases. |
| 5456 | __celld.__makeIncomingRequest = ( |
| 5457 | url, method, body, headersJson, streamId, |
| 5458 | ) => __makeRequest( |
| 5459 | url, method, |
| 5460 | streamId === undefined ? body : new CelldHttpBodyStream(streamId), |
| 5461 | headersJson, undefined, true); |
| 5462 | const __dispatchTo = __celld.__dispatchTo = async ( |
| 5463 | scope, url, method, body, headersJson, requestId = null, bodyStreamId = null, |
| 5464 | ) => { |
| 5465 | // A routed body that must not be collected crosses as a host stream id; the |
| 5466 | // handler here reads it in parts. A held body arrives as its bytes. |
| 5467 | if (bodyStreamId !== null) body = new CelldHttpBodyStream(bodyStreamId); |
| 5468 | // Request already allocates a default controller for an absent signal. |
| 5469 | // Retain that same allocation so a streamed response can report reader |
| 5470 | // cancellation after the handler has returned. |
| 5471 | const requestController = new AbortController(); |
| 5472 | if (requestId !== null) |
| 5473 | __incomingRequestSignals.set( |
| 5474 | String(requestId), requestController.signal); |
| 5475 | const actorEvent = __beginActorEvent(scope); |
| 5476 | try { |
| 5477 | const dispatch = (async () => { |
| 5478 | const inst = await _readyInstance(scope); |
| 5479 | return await __ctxRun(undefined, () => inst.fetch( |
| 5480 | __makeRequest( |
| 5481 | url, |
| 5482 | method, |
| 5483 | body, |
| 5484 | headersJson, |
| 5485 | requestController.signal, |
| 5486 | true, |
| 5487 | ))); |
| 5488 | })(); |
| 5489 | // The caller's abandonment reaches the target through |
| 5490 | // __do_call_cancel/__abortIncomingRequest, which aborts the fresh incoming |
| 5491 | // signal made above; the host dispatcher passes no caller signal here. |
| 5492 | const response = await dispatch; |
| 5493 | // Not wrapped: the host holds this response and gates it, and the caller |
| 5494 | // that would cancel the body reaches it through the routed channel's own |
| 5495 | // controller rather than this one. |
| 5496 | __attachResponseRequestCancellation(response, requestController, false); |
| 5497 | if (response instanceof Response && response.status === 101 && |
| 5498 | response.webSocket && !response.webSocket._target) { |
| 5499 | const socket = response.webSocket._peer; |
| 5500 | const target = { id: response.webSocket._id, scope }; |
| 5501 | response.webSocket._target = target; |
| 5502 | if (socket) { |
| 5503 | socket._target = target; |
| 5504 | if (!socket._hibernatable) |
| 5505 | __ws_accept_regular(socket._id, scope); |
| 5506 | __sockets.set(socket._id, socket); |
| 5507 | socket._flushPending(); |
| 5508 | } |
| 5509 | } |
| 5510 | return response; |
| 5511 | } finally { |
| 5512 | if (requestId !== null) |
| 5513 | __incomingRequestSignals.delete(String(requestId)); |
| 5514 | __endActorEvent(actorEvent); |
| 5515 | } |
| 5516 | }; |
| 5517 | const __rpcTargetMethod = async (scope, method) => { |
| 5518 | const inst = await _readyInstance(scope); |
| 5519 | if (!inst.__celldState._rpcOk) |
| 5520 | throw new TypeError( |
| 5521 | "The receiving Durable Object does not support RPC, because " + |
| 5522 | "its class was not declared with `extends DurableObject`. In " + |
| 5523 | "order to enable RPC, make sure your class extends the " + |
| 5524 | "special class `DurableObject`, which can be imported from " + |
| 5525 | "the module \"cloudflare:workers\"."); |
| 5526 | const fn = inst[method]; |
| 5527 | if (typeof fn !== "function") |
| 5528 | throw new TypeError(method + " is not a function"); |
| 5529 | return [inst, fn]; |
| 5530 | }; |
| 5531 | // The byte path always lifts stub-able values into the reply: the |
| 5532 | // markers carry the isolate token, so they revive only back in this |
| 5533 | // isolate (same-process routed dispatch re-enters it) and fail loudly |
| 5534 | // on use anywhere else. Callee exceptions cross in |
| 5535 | // the error envelope on every flavor. |
| 5536 | __celld.__dispatchRpc = async (scope, method, args) => { |
| 5537 | const actorEvent = __beginActorEvent(scope); |
| 5538 | try { |
| 5539 | // A string is the legacy JSON flavor; bytes are V8 structured clone. |
| 5540 | // Answer in kind. |
| 5541 | if (typeof args === "string") { |
| 5542 | const [inst, fn] = await __rpcTargetMethod(scope, method); |
| 5543 | const result = await fn.apply(inst, JSON.parse(args)); |
| 5544 | return JSON.stringify(result) ?? "null"; |
| 5545 | } |
| 5546 | return await __ctxRun(undefined, () => (async () => { |
| 5547 | const decoded = __rpcDesArgs(args); |
| 5548 | try { |
| 5549 | return await __rpcRun(async () => { |
| 5550 | // A broken actor (JS-flavored ctx.abort) rejects every |
| 5551 | // later call with the reason. One gated field read. |
| 5552 | if (__brokenActors.size !== 0) { |
| 5553 | const broken = __brokenActors.get(scope); |
| 5554 | if (broken !== undefined) throw broken; |
| 5555 | } |
| 5556 | const [inst, fn] = await __rpcTargetMethod(scope, method); |
| 5557 | return fn.apply(inst, decoded.args); |
| 5558 | }, true); |
| 5559 | } finally { |
| 5560 | for (const handle of decoded.received) __disposeStub(handle); |
| 5561 | } |
| 5562 | })()); |
| 5563 | } finally { |
| 5564 | __endActorEvent(actorEvent); |
| 5565 | } |
| 5566 | }; |
| 5567 | const __entrypointClass = (name) => { |
| 5568 | const cls = __cell.entrypoints[name]; |
| 5569 | if (typeof cls !== "function") { |
| 5570 | // Workerd getExportedHandler(): distinguish a Durable Object class |
| 5571 | // misused as a stateless entrypoint from a name that resolves to |
| 5572 | // nothing. Error path only; both lookups are O(1). |
| 5573 | if (__cell.classes[name] !== undefined || __cell.doExports[name]) |
| 5574 | throw new TypeError( |
| 5575 | `The entrypoint name ${name} refers to a Durable Object ` + |
| 5576 | "class, but the incoming request is trying to invoke it as " + |
| 5577 | "a stateless worker."); |
| 5578 | throw new TypeError( |
| 5579 | `The entrypoint name ${name} was not found in this worker. ` + |
| 5580 | "Ensure the worker exports an entrypoint with that name."); |
| 5581 | } |
| 5582 | return cls; |
| 5583 | }; |
| 5584 | // End the construction event immediately: ctx.waitUntil registers into |
| 5585 | // whichever event is current at call time, so leaving this event on the |
| 5586 | // stack would swallow every later registration in the isolate. The drain that |
| 5587 | // the event yields moves to the enclosing event, because a ctx.waitUntil() |
| 5588 | // call inside a constructor is otherwise fire-and-forget: the RPC reply can |
| 5589 | // answer and the request context can tear down before that work runs. |
| 5590 | // __wait_until drops the drain when no event encloses this one, which is the |
| 5591 | // isolate-startup case and matches the older behavior. |
| 5592 | const __constructEntrypoint = (cls, props) => { |
| 5593 | const ctx = __beginEvent(props); |
| 5594 | try { |
| 5595 | return new cls(ctx, __cell.env); |
| 5596 | } finally { |
| 5597 | const drain = __endEvent(); |
| 5598 | if (drain !== null) __wait_until(drain); |
| 5599 | } |
| 5600 | }; |
| 5601 | // A stateless Worker invocation owns one class instance and its constructor |
| 5602 | // context. Reusing either across invocations leaks class fields and request |
| 5603 | // authority, while constructing more than once inside one invocation splits |
| 5604 | // work that Cloudflare delivers to one receiver. |
| 5605 | const __newEntrypointInstance = (name, props) => |
| 5606 | __constructEntrypoint(__entrypointClass(name), props); |
| 5607 | // `env.NAME.fetch()` where NAME is bound with `entrypoint = "..."` goes |
| 5608 | // to that class's fetch, not the module's default export. A plain |
| 5609 | // object export (Workerd's non-class entrypoint) dispatches its |
| 5610 | // handler functions as fn(arg, env, ctx). |
| 5611 | // A missing fetch reports workerd's own text, the same one the loader |
| 5612 | // installs for a Worker with no default export, so the two paths agree. |
| 5613 | const __noHandler = (name, method) => |
| 5614 | method === "fetch" && name === "default" |
| 5615 | ? new Error("Handler does not export a fetch() function.") |
| 5616 | : new TypeError( |
| 5617 | `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); |
| 5618 | |
| 5619 | const __dispatchEntrypointMethod = async (name, method, arg, props) => { |
| 5620 | const handler = __cell.objectEntrypoints[name]; |
| 5621 | if (handler !== undefined) { |
| 5622 | if (typeof handler[method] !== "function") |
| 5623 | throw __noHandler(name, method); |
| 5624 | const ctx = __beginEvent(props); |
| 5625 | try { |
| 5626 | return await __ctxRun(undefined, |
| 5627 | () => handler[method](arg, __cell.env, ctx)); |
| 5628 | } finally { |
| 5629 | __endEvent(); |
| 5630 | } |
| 5631 | } |
| 5632 | // A class entrypoint's methods get env and ctx from its constructor, |
| 5633 | // not as arguments. |
| 5634 | const inst = __newEntrypointInstance(name, props); |
| 5635 | if (typeof inst[method] !== "function") |
| 5636 | throw __noHandler(name, method); |
| 5637 | return await __ctxRun(undefined, () => inst[method](arg)); |
| 5638 | }; |
| 5639 | // Invoke a handler inside the event frame that the host already opened. A |
| 5640 | // Queue dispatch uses this form because its host driver must receive and keep |
| 5641 | // driving the handler's waitUntil aggregate after the settlement is returned. |
| 5642 | const __dispatchEntrypointMethodInCurrentEvent = async (name, method, arg) => { |
| 5643 | const handler = __cell.objectEntrypoints[name]; |
| 5644 | if (handler !== undefined) { |
| 5645 | if (typeof handler[method] !== "function") |
| 5646 | throw __noHandler(name, method); |
| 5647 | return await __ctxRun(undefined, |
| 5648 | () => handler[method](arg, __cell.env, __entrypointContext())); |
| 5649 | } |
| 5650 | const inst = __newEntrypointInstance(name, undefined); |
| 5651 | if (typeof inst[method] !== "function") |
| 5652 | throw __noHandler(name, method); |
| 5653 | return await __ctxRun(undefined, () => inst[method](arg)); |
| 5654 | }; |
| 5655 | const __dispatchEntrypointFetch = __celld.__dispatchEntrypointFetch = |
| 5656 | (name, request, propsSc = null) => |
| 5657 | __dispatchEntrypointMethod( |
| 5658 | name, "fetch", request, |
| 5659 | propsSc === null || propsSc.length === 0 |
| 5660 | ? undefined : __sc_decode(propsSc)); |
| 5661 | __celld.__dispatchEntrypointScheduled = (name, ctrl) => |
| 5662 | __dispatchEntrypointMethod(name, "scheduled", ctrl); |
| 5663 | // A queue batch owns mutable settlement state only while its handler runs. |
| 5664 | // Keeping a batch alive after dispatch must not keep authority to settle its |
| 5665 | // lease, because that lease can have expired and been handed out again. |
| 5666 | __celld.__dispatchEntrypointQueue = async (name, incoming) => { |
| 5667 | let active = true; |
| 5668 | let ackAll = false; |
| 5669 | const explicitAcks = new Set(); |
| 5670 | const retries = new Map(); |
| 5671 | const retryBatch = { retry: false, delaySeconds: undefined }; |
| 5672 | const checkActive = () => { |
| 5673 | if (!active) |
| 5674 | throw new Error("Queue event methods cannot be called after the handler returns."); |
| 5675 | }; |
| 5676 | const retryDelay = (options) => { |
| 5677 | const value = options?.delaySeconds; |
| 5678 | if (value === undefined) return undefined; |
| 5679 | if (!Number.isInteger(value) || value < -0x8000_0000 || value > 0x7fff_ffff) |
| 5680 | throw new TypeError("delaySeconds must be a 32-bit integer"); |
| 5681 | return value; |
| 5682 | }; |
| 5683 | const decode = (message) => { |
| 5684 | switch (message.contentType) { |
| 5685 | case "text": return new TextDecoder().decode(message.body); |
| 5686 | case "bytes": return message.body; |
| 5687 | case "json": return JSON.parse(new TextDecoder().decode(message.body)); |
| 5688 | case "v8": return __sc_decode(message.body); |
| 5689 | default: throw new TypeError(`Unknown queue content type: ${message.contentType}`); |
| 5690 | } |
| 5691 | }; |
| 5692 | const messages = incoming.messages.map((message) => ({ |
| 5693 | id: message.id, |
| 5694 | timestamp: new Date(message.timestamp), |
| 5695 | body: decode(message), |
| 5696 | attempts: message.attempts, |
| 5697 | ack() { |
| 5698 | checkActive(); |
| 5699 | if (ackAll || retryBatch.retry || retries.has(message.id)) return; |
| 5700 | explicitAcks.add(message.id); |
| 5701 | }, |
| 5702 | retry(options) { |
| 5703 | checkActive(); |
| 5704 | if (ackAll || explicitAcks.has(message.id)) return; |
| 5705 | const delaySeconds = retryDelay(options); |
| 5706 | if (delaySeconds !== undefined || !retries.has(message.id)) |
| 5707 | retries.set(message.id, delaySeconds); |
| 5708 | }, |
| 5709 | })); |
| 5710 | const oldest = incoming.metrics.oldestMessageTimestamp; |
| 5711 | const batch = { |
| 5712 | queue: incoming.queue, |
| 5713 | messages, |
| 5714 | metadata: { |
| 5715 | metrics: { |
| 5716 | backlogCount: incoming.metrics.backlogCount, |
| 5717 | backlogBytes: incoming.metrics.backlogBytes, |
| 5718 | oldestMessageTimestamp: oldest === undefined ? undefined : new Date(oldest), |
| 5719 | }, |
| 5720 | }, |
| 5721 | ackAll() { |
| 5722 | checkActive(); |
| 5723 | if (!retryBatch.retry) ackAll = true; |
| 5724 | }, |
| 5725 | retryAll(options) { |
| 5726 | checkActive(); |
| 5727 | if (ackAll) return; |
| 5728 | retryBatch.retry = true; |
| 5729 | const delaySeconds = retryDelay(options); |
| 5730 | if (delaySeconds !== undefined) retryBatch.delaySeconds = delaySeconds; |
| 5731 | }, |
| 5732 | }; |
| 5733 | let outcome = "ok"; |
| 5734 | let errorText; |
| 5735 | try { |
| 5736 | await __dispatchEntrypointMethodInCurrentEvent(name, "queue", batch); |
| 5737 | } catch (error) { |
| 5738 | // A handler exception retries the batch but keeps explicit acks that the |
| 5739 | // handler made before it threw. The caller needs both facts together. |
| 5740 | outcome = "exception"; |
| 5741 | try { |
| 5742 | errorText = String(error); |
| 5743 | } catch { |
| 5744 | errorText = "queue handler rejected"; |
| 5745 | } |
| 5746 | } finally { |
| 5747 | active = false; |
| 5748 | } |
| 5749 | return { |
| 5750 | outcome, |
| 5751 | error: errorText, |
| 5752 | ackAll, |
| 5753 | retryBatch, |
| 5754 | explicitAcks: [...explicitAcks], |
| 5755 | retryMessages: [...retries].map(([msgId, delaySeconds]) => ({ |
| 5756 | msgId, |
| 5757 | delaySeconds, |
| 5758 | })), |
| 5759 | }; |
| 5760 | }; |
| 5761 | // Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class |
| 5762 | // handler method is called as fn(arg, env, ctx), the client must send |
| 5763 | // exactly one argument, and the handler must not declare more than |
| 5764 | // (arg, env, ctx). The messages are Workerd's, verbatim. |
| 5765 | const __callObjectEntrypoint = (handler, method, args, props) => { |
| 5766 | const fn = handler[method]; |
| 5767 | if (typeof fn !== "function") |
| 5768 | throw new TypeError( |
| 5769 | 'The RPC receiver does not implement the method "' + method + |
| 5770 | '".'); |
| 5771 | if (fn.length > 3) |
| 5772 | throw new TypeError( |
| 5773 | 'Cannot call handler function "' + method + '" over RPC ' + |
| 5774 | "because it has the wrong number of arguments. A simple " + |
| 5775 | "function handler can only be called over RPC if it has " + |
| 5776 | "exactly the arguments (arg, env, ctx), where only the first " + |
| 5777 | "argument comes from the client. To support multi-argument " + |
| 5778 | "RPC functions, use class-based syntax (extending " + |
| 5779 | "WorkerEntrypoint) instead."); |
| 5780 | if (args.length !== 1) |
| 5781 | throw new TypeError( |
| 5782 | 'Attempted to call RPC function "' + method + '" with the ' + |
| 5783 | "wrong number of arguments. When calling a top-level handler " + |
| 5784 | "function that is not declared as part of a class, you must " + |
| 5785 | "always send exactly one argument. In order to support " + |
| 5786 | "variable numbers of arguments, the server must use " + |
| 5787 | "class-based syntax (extending WorkerEntrypoint) instead."); |
| 5788 | return fn.call(handler, args[0], __cell.env, __entrypointContext(props)); |
| 5789 | }; |
| 5790 | let __nextPendingEventId = 1; |
| 5791 | const __pendingEvents = new Map(); |
| 5792 | const __pendingEventError = () => new Error( |
| 5793 | "The Workers runtime canceled this request because it detected that " + |
| 5794 | "your Worker's code had hung and would never generate a response. " + |
| 5795 | "Refer to: https://developers.cloudflare.com/workers/observability/errors/"); |
| 5796 | // The host calls this only when the request has no native operation that can |
| 5797 | // resume JavaScript. Reject the entrypoint call itself, so its caller can |
| 5798 | // catch the cancellation and continue the enclosing event. |
| 5799 | __celld.__cancelPendingEvents = (ids) => { |
| 5800 | for (const id of ids) __pendingEvents.get(id)?.(__pendingEventError()); |
| 5801 | }; |
| 5802 | // One entrypoint op (a call, or a property GET when argsSc is |
| 5803 | // null), inside a fresh request context -- the callee owns stubs |
| 5804 | // revived from its params, and stubs it mints belong to it. |
| 5805 | // `props` is the caller's per-stub props (Workerd's |
| 5806 | // getEntrypoint(name, { props })); undefined leaves the entrypoint's |
| 5807 | // default empty props. |
| 5808 | const __entrypointOp = (name, path, argsSc, local, makeInst, props) => { |
| 5809 | const id = __nextCtxId++; |
| 5810 | return __ctxRun(id, () => { |
| 5811 | const pendingId = __nextPendingEventId++; |
| 5812 | let cancel; |
| 5813 | const cancellation = new Promise((_, reject) => { cancel = reject; }); |
| 5814 | __pendingEvents.set(pendingId, cancel); |
| 5815 | __pending_event_begin(pendingId); |
| 5816 | const running = (async () => { |
| 5817 | const decoded = argsSc === null ? null : __rpcDesArgs(argsSc); |
| 5818 | let drain = null; |
| 5819 | try { |
| 5820 | const reply = await __rpcRun(async () => { |
| 5821 | // The handler's synchronous part runs inside its own event so |
| 5822 | // ctx.waitUntil and the imported waitUntil have a target. The |
| 5823 | // event pops before the first await -- the event stack is |
| 5824 | // strictly LIFO and an event held across an await would be |
| 5825 | // popped by whichever event settles next -- and its registered |
| 5826 | // work drains before a plain reply (below). |
| 5827 | __beginEvent(); |
| 5828 | let result; |
| 5829 | try { |
| 5830 | const handler = __cell.objectEntrypoints[name]; |
| 5831 | if (handler !== undefined && makeInst === undefined) { |
| 5832 | // Simple-handler entrypoints expose single-method calls |
| 5833 | // only; property GETs and deeper paths are refused. |
| 5834 | if (argsSc === null || path.length !== 1) |
| 5835 | throw __rpcNoSuchMethod(path[0]); |
| 5836 | result = __callObjectEntrypoint( |
| 5837 | handler, path[0], decoded.args, props); |
| 5838 | } else { |
| 5839 | // A loopback stub with props retains one instance for that RPC |
| 5840 | // session. Each ordinary top-level operation constructs once here, |
| 5841 | // so neither its fields nor its constructor context reach the next |
| 5842 | // invocation. |
| 5843 | const inst = makeInst !== undefined ? makeInst() |
| 5844 | : __newEntrypointInstance(name, props); |
| 5845 | result = __rpcWalk(inst, path, |
| 5846 | decoded === null ? null : decoded.args, true); |
| 5847 | } |
| 5848 | } finally { |
| 5849 | drain = __endEvent(); |
| 5850 | } |
| 5851 | return await result; |
| 5852 | }, local); |
| 5853 | // Registered work drains before a plain reply. A |
| 5854 | // capability-bearing reply (tag 1) must not wait: a returned |
| 5855 | // stream's chunks may be produced by that very work, which |
| 5856 | // cannot finish until the caller pulls (returnReadableStream's |
| 5857 | // waitUntil writer would deadlock behind its own reply). |
| 5858 | if (reply[0] !== 1 && drain !== null) await drain; |
| 5859 | // ctx.abort() during the call supersedes its result; the raw |
| 5860 | // reason rejects the caller (same isolate -- identity holds). |
| 5861 | if (__abortedCtxs.size !== 0) { |
| 5862 | const reason = __abortedCtxs.get(id); |
| 5863 | if (reason !== undefined) throw reason; |
| 5864 | } |
| 5865 | // A reply that exports no stubs (tag 0xff plain, tag 0 error) |
| 5866 | // leaves nothing rooting this context: tear it down now, so a |
| 5867 | // dup() the callee leaked reaches its disposal callback |
| 5868 | // promptly (Workerd tears the IoContext down at call end |
| 5869 | // unless returned capabilities hold it open). |
| 5870 | if (reply[0] !== 1) __ctxEnd(id); |
| 5871 | return reply; |
| 5872 | } finally { |
| 5873 | if (decoded !== null) |
| 5874 | for (const handle of decoded.received) __disposeStub(handle); |
| 5875 | } |
| 5876 | })(); |
| 5877 | return Promise.race([running, cancellation]).finally(() => { |
| 5878 | __pendingEvents.delete(pendingId); |
| 5879 | __pending_event_end(pendingId); |
| 5880 | }); |
| 5881 | }); |
| 5882 | }; |
| 5883 | // Cross-isolate service callers pass a complete property path. Older host |
| 5884 | // callers can still pass one method name, which becomes a one-part path. |
| 5885 | // `propsSc` carries getEntrypoint(name, {props}) as structured-clone bytes, |
| 5886 | // the same encoding as `argsSc`. It is empty when the caller sent no props, |
| 5887 | // which no encoded value can be, so an empty buffer is an unambiguous absent. |
| 5888 | __celld.__dispatchEntrypointRpc = |
| 5889 | (name, path, argsSc, local = false, propsSc = null) => __entrypointOp( |
| 5890 | name, typeof path === "string" ? [path] : path, argsSc, local, |
| 5891 | undefined, |
| 5892 | propsSc === null || propsSc.length === 0 |
| 5893 | ? undefined : __sc_decode(propsSc)); |
| 5894 | // WebSocket: the host holds the socket; these deliver events into the DO. |
| 5895 | // `ws` is a lightweight stub whose send/close route back to the host task |
| 5896 | // by wsId -- so the isolate can be hibernated between messages. |
| 5897 | const __wsStub = __celld.__wsStub = (wsId) => ({ |
| 5898 | _hibernatable: true, |
| 5899 | send: (data) => { |
| 5900 | if (data instanceof ArrayBuffer) |
| 5901 | __ws_send_binary(wsId, new Uint8Array(data)); |
| 5902 | else if (ArrayBuffer.isView(data)) |
| 5903 | __ws_send_binary(wsId, |
| 5904 | new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); |
| 5905 | else |
| 5906 | __ws_send(wsId, String(data)); |
| 5907 | }, |
| 5908 | close: (code = 1000, reason = "") => __ws_close(wsId, code, reason), |
| 5909 | }); |
| 5910 | __celld.__wsOpen = async (scope, wsId, protocol) => { |
| 5911 | const actorEvent = __beginActorEvent(scope); |
| 5912 | try { |
| 5913 | const inst = await _readyInstance(scope); |
| 5914 | const socket = inst.__celldState._socket(wsId); |
| 5915 | if (socket.readyState !== WebSocket.READY_STATE_CONNECTING) return; |
| 5916 | socket.protocol = protocol; |
| 5917 | socket.readyState = WebSocket.READY_STATE_OPEN; |
| 5918 | socket.dispatchEvent(new Event("open")); |
| 5919 | } finally { |
| 5920 | __endActorEvent(actorEvent); |
| 5921 | } |
| 5922 | }; |
| 5923 | __celld.__wsMessage = async (scope, wsId, msg) => { |
| 5924 | const actorEvent = __beginActorEvent(scope); |
| 5925 | try { |
| 5926 | const inst = await _readyInstance(scope); |
| 5927 | const socket = inst.__celldState._socket(wsId); |
| 5928 | if (!socket._hibernatable && typeof socket._dispatchMessage === "function") |
| 5929 | socket._dispatchMessage(msg); |
| 5930 | else if (typeof inst.webSocketMessage === "function") |
| 5931 | await inst.webSocketMessage(socket, msg); |
| 5932 | } finally { |
| 5933 | __endActorEvent(actorEvent); |
| 5934 | } |
| 5935 | }; |
| 5936 | __celld.__wsBinary = async (scope, wsId, data) => { |
| 5937 | const actorEvent = __beginActorEvent(scope); |
| 5938 | try { |
| 5939 | const inst = await _readyInstance(scope); |
| 5940 | const socket = inst.__celldState._socket(wsId); |
| 5941 | const bytes = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); |
| 5942 | if (!socket._hibernatable && typeof socket._dispatchMessage === "function") |
| 5943 | socket._dispatchMessage(bytes); |
| 5944 | else if (typeof inst.webSocketMessage === "function") |
| 5945 | await inst.webSocketMessage(socket, bytes); |
| 5946 | } finally { |
| 5947 | __endActorEvent(actorEvent); |
| 5948 | } |
| 5949 | }; |
| 5950 | __celld.__wsClosed = async (scope, wsId, code, reason, wasClean) => { |
| 5951 | const actorEvent = __beginActorEvent(scope); |
| 5952 | try { |
| 5953 | const inst = await _readyInstance(scope); |
| 5954 | const socket = inst.__celldState._socket(wsId); |
| 5955 | if (!socket._hibernatable && typeof socket._dispatchClose === "function") |
| 5956 | socket._dispatchClose(code, reason, wasClean); |
| 5957 | else if (!wasClean && typeof inst.webSocketError === "function") |
| 5958 | // A hibernatable socket reports an abnormal closure through |
| 5959 | // webSocketError, which celld listed as a handler name and never |
| 5960 | // called. |
| 5961 | await inst.webSocketError( |
| 5962 | socket, |
| 5963 | new Error(reason ? `WebSocket closed abnormally: ${reason}` : "WebSocket closed abnormally"), |
| 5964 | ); |
| 5965 | else if (typeof inst.webSocketClose === "function") |
| 5966 | await inst.webSocketClose(socket, code, reason, wasClean); |
| 5967 | } finally { |
| 5968 | __endActorEvent(actorEvent); |
| 5969 | } |
| 5970 | }; |
| 5971 | // called by celld's scheduler when an alarm is due. Returns a promise. |
| 5972 | __celld.__fireAlarm = async (scope, scheduledTime, retryCount) => { |
| 5973 | const actorEvent = __beginActorEvent(scope); |
| 5974 | try { |
| 5975 | const inst = await _readyInstance(scope); |
| 5976 | if (typeof inst.alarm !== "function") return; |
| 5977 | await inst.alarm({ scheduledTime, retryCount, isRetry: retryCount > 0 }); |
| 5978 | } finally { |
| 5979 | __endActorEvent(actorEvent); |
| 5980 | } |
| 5981 | }; |
| 5982 | // The reserved cron cell. It is not a user class: celld registers it under |
| 5983 | // `.cron` for every deployment that declares `triggers.crons`, and one cell |
| 5984 | // per script carries that script's whole schedule. Ownership CAS on that one |
| 5985 | // name is what makes a cron trigger fire once per fleet rather than once per |
| 5986 | // node -- the same arbiter an alarm already relies on, with nothing added. |
| 5987 | // |
| 5988 | // The schedule itself is never stored here. `__cell.crons` comes from the |
| 5989 | // deployment the cell is running under, so changing a cron expression takes |
| 5990 | // effect on the next activation and needs no migration of an armed alarm. |
| 5991 | class CelldCronSchedule { |
| 5992 | constructor(state) { |
| 5993 | this._state = state; |
| 5994 | // Failures within one occurrence. Held in memory on purpose: losing the |
| 5995 | // count to an eviction only makes the next retry sooner, and every retry |
| 5996 | // is capped at the next occurrence anyway, so it need not be durable. |
| 5997 | this._retry = 0; |
| 5998 | // What a pending retry owes: the occurrence, the expressions of it that |
| 5999 | // failed, and the deadline the retry was armed for. A retry deadline is a |
| 6000 | // backoff instant and not an occurrence, so nothing about it can be |
| 6001 | // recovered from the deadline itself -- without this record the wake |
| 6002 | // matches no expression, runs nothing, and drops the failed tick in |
| 6003 | // silence. Held in memory beside `_retry` and for the same reason: an |
| 6004 | // eviction costs the retry, never the next occurrence. |
| 6005 | this._owed = null; |
| 6006 | } |
| 6007 | // celld calls this once per node after a deployment loads, because a cron |
| 6008 | // cell has no client to wake it. Arming is idempotent -- the same schedule |
| 6009 | // and the same clock give the same answer -- so it does not matter which |
| 6010 | // node wins the cell. |
| 6011 | async fetch() { |
| 6012 | // A pending retry is a deadline this cell already owes, and re-arming |
| 6013 | // would move it to the next occurrence and lose the tick it owes with it. |
| 6014 | if (this._owed !== null) return new Response(null, { status: 204 }); |
| 6015 | const armed = await this._state.storage.getAlarm(); |
| 6016 | // An alarm already due is a tick that is late, not one that is wrong. |
| 6017 | // Leaving it alone is what makes a fleet that was down fire the missed |
| 6018 | // occurrence once, instead of skipping it by re-arming into the future. |
| 6019 | if (armed === null || armed > Date.now()) await this._arm(null, [], false); |
| 6020 | return new Response(null, { status: 204 }); |
| 6021 | } |
| 6022 | async alarm(info) { |
| 6023 | const crons = __cell.crons || []; |
| 6024 | // A retry wake carries the backoff instant as its deadline, so what to run |
| 6025 | // and what time to report both come from the record the failure left. Only |
| 6026 | // a deadline that is not a retry is an occurrence to match against. |
| 6027 | const owed = this._owed !== null && this._owed.armedFor === info.scheduledTime |
| 6028 | ? this._owed |
| 6029 | : null; |
| 6030 | const occurrence = owed === null ? info.scheduledTime : owed.at; |
| 6031 | // One deadline can belong to several expressions, and each is its own |
| 6032 | // invocation with its own controller.cron, as on Cloudflare. A retry |
| 6033 | // repeats only the expressions that failed, because the ones that |
| 6034 | // succeeded already ran for this occurrence. |
| 6035 | const due = owed === null |
| 6036 | ? __cron_plan(crons, info.scheduledTime, Date.now(), 0, false).matching |
| 6037 | : owed.indices; |
| 6038 | const failed = []; |
| 6039 | for (const index of due) { |
| 6040 | let noRetry = false; |
| 6041 | const controller = { |
| 6042 | // The occurrence, never the instant this attempt started, so a late |
| 6043 | // run and a retry both report the minute they were scheduled for. |
| 6044 | scheduledTime: occurrence, |
| 6045 | cron: crons[index], |
| 6046 | noRetry() { noRetry = true; }, |
| 6047 | }; |
| 6048 | const ctx = __beginEvent(); |
| 6049 | try { |
| 6050 | if (typeof __cell.selfScheduled !== "function") |
| 6051 | throw new Error( |
| 6052 | "a cron trigger needs the Worker to export a `scheduled` handler"); |
| 6053 | await __cell.selfScheduled(controller, __cell.env, ctx); |
| 6054 | } catch (error) { |
| 6055 | // Swallowed on purpose: this handler owns the re-arm below, so |
| 6056 | // throwing would hand the deadline to the generic alarm retry and |
| 6057 | // lose the next occurrence with it. |
| 6058 | console.error( |
| 6059 | `scheduled handler for cron ${JSON.stringify(crons[index])} failed:`, |
| 6060 | error); |
| 6061 | if (!noRetry) failed.push(index); |
| 6062 | } finally { |
| 6063 | const drain = __endEvent(); |
| 6064 | // The alarm turn is the only host owner for this scheduled event. |
| 6065 | // Dropping its drain lets the actor turn end with waitUntil work still |
| 6066 | // pending, so an I/O promise can remain unresolved forever. |
| 6067 | if (drain !== null) await drain; |
| 6068 | } |
| 6069 | } |
| 6070 | await this._arm(occurrence, failed, owed !== null); |
| 6071 | } |
| 6072 | // `occurrence` is the tick just handled, or null when the cell is only |
| 6073 | // arming, `failed` holds the expressions of it still owed, and `retried` |
| 6074 | // says the deadline just handled was a backoff rather than an occurrence. |
| 6075 | async _arm(occurrence, failed, retried) { |
| 6076 | const crons = __cell.crons || []; |
| 6077 | // The count is failures within one occurrence, so a fresh occurrence |
| 6078 | // starts at one however the last one ended. Carrying it across would |
| 6079 | // spend `alarm_retry`'s ceiling once and leave every later occurrence |
| 6080 | // with no retry at all, which is a budget for the schedule and not for |
| 6081 | // the tick. |
| 6082 | this._retry = failed.length ? (retried ? this._retry + 1 : 1) : 0; |
| 6083 | // A negative first argument means "arming only, nothing fired". |
| 6084 | const plan = __cron_plan(crons, -1, Date.now(), this._retry, failed.length > 0); |
| 6085 | // The next occurrence beats the backoff whenever it is sooner, and it then |
| 6086 | // cancels the retry rather than queueing behind it, so the record the |
| 6087 | // retry needed goes when the retry does. |
| 6088 | this._owed = plan.armIsRetry |
| 6089 | ? { at: occurrence, indices: failed, armedFor: plan.armAt } |
| 6090 | : null; |
| 6091 | // No expression matches again and nothing is owed: the deployment dropped |
| 6092 | // its crons, so the cell retires rather than waking forever. |
| 6093 | if (plan.armAt === null) await this._state.storage.deleteAlarm(); |
| 6094 | else await this._state.storage.setAlarm(plan.armAt); |
| 6095 | } |
| 6096 | } |
| 6097 | const __cell = __celld.__cell = { |
| 6098 | entrypoints: {}, |
| 6099 | objectEntrypoints: {}, |
| 6100 | doExports: {}, |
| 6101 | classes: { ".cron": CelldCronSchedule }, |
| 6102 | crons: [], |
| 6103 | workflows: {}, |
| 6104 | containers: {}, |
| 6105 | instances: {}, |
| 6106 | facetConfigs: {}, |
| 6107 | env: {}, |
| 6108 | idNames: {}, |
| 6109 | namespaceKeys: {}, |
| 6110 | node: "", |
| 6111 | deleteAllDeletesAlarm: false, |
| 6112 | compat: { jsRpc: false, fetcherGetPutDelete: false, queueJsonMessages: false }, |
| 6113 | makeNamespace, |
| 6114 | release: __cellRelease, |
| 6115 | }; |
| 6116 | // A class the runtime supplies. RPC on a stub needs `extends DurableObject` |
| 6117 | // or the js_rpc flag; the class is the runtime's own, so grant it here rather |
| 6118 | // than make every user set a flag. It is not the application's export, so it |
| 6119 | // stays out of ctx.exports. |
| 6120 | const __runtimeClasses = new Set(); |
| 6121 | const __runtimeClass = (name, cls) => { |
| 6122 | __cell.classes[name] = cls; |
| 6123 | __cell.doExports[name] = true; |
| 6124 | __runtimeClasses.add(name); |
| 6125 | }; |
| 6126 | // ---- KV ------------------------------------------------------------------ |
| 6127 | // The namespace cell and the binding's client are `services/kv.js`, which the |
| 6128 | // workerd engine runs too; this is the host they run against here. |
| 6129 | const { |
| 6130 | KvNamespaceCell: __KvNamespaceCell, |
| 6131 | KvNamespace: __KvNamespace, |
| 6132 | cellSweepBatch: __cellSweepBatch, |
| 6133 | } = kvService({ |
| 6134 | // RPC on a runtime class is granted by `__runtimeClass` below. |
| 6135 | DurableObject: class { |
| 6136 | constructor(ctx) { |
| 6137 | this.ctx = ctx; |
| 6138 | } |
| 6139 | }, |
| 6140 | limits: () => __cell.kvLimits, |
| 6141 | // One op for the whole large-value path, following `__d1_run`. |
| 6142 | blob: async (_cell, request, value) => { |
| 6143 | const reply = await __kv_blob(JSON.stringify(request), value); |
| 6144 | return reply instanceof Uint8Array |
| 6145 | ? { found: true, value: reply } |
| 6146 | : JSON.parse(reply); |
| 6147 | }, |
| 6148 | // The raw base64 ops accept typed views for this internal wire form; the |
| 6149 | // public atob() and btoa() wrappers keep their standard string-only |
| 6150 | // behaviour. |
| 6151 | btoa: (bytes) => $$btoa(bytes), |
| 6152 | atob: (text) => $$atob(text, true), |
| 6153 | }); |
| 6154 | |
| 6155 | __runtimeClass("__KvNamespace", __KvNamespaceCell); |
| 6156 | |
| 6157 | const __makeKvNamespace = __celld.__makeKvNamespace = (id, cellName) => |
| 6158 | new __KvNamespace(() => __cell.makeNamespace("__KvNamespace"), cellName); |
| 6159 | |
| 6160 | // ---- Queues -------------------------------------------------------------- |
| 6161 | // A Queue is one runtime-supplied Durable Object. The producer binding writes |
| 6162 | // bytes and a content tag through RPC, and the cell owns the durable order, |
| 6163 | // deadlines, leases, and alarms. `celld_logic::queue` owns every transition |
| 6164 | // that can invalidate a lease or choose a deadline; this code supplies SQL and |
| 6165 | // the Cloudflare-compatible presentation. |
| 6166 | |
| 6167 | const __QUEUE_MESSAGES = "__queue_messages"; |
| 6168 | const __QUEUE_META = "__queue_meta"; |
| 6169 | const __QUEUE_STATS = "__queue_stats"; |
| 6170 | const __QUEUE_TRANSFER_RECEIPTS = "__queue_transfer_receipts"; |
| 6171 | const __queueEncoder = new TextEncoder(); |
| 6172 | |
| 6173 | // Independent send() calls share the same economics as sendBatch() without |
| 6174 | // changing the public promise boundary. The first call opens a four-millisecond |
| 6175 | // owner-local group by default; later cell events append their already-copied |
| 6176 | // entries, and park on their own promise. One event commits the bounded group, |
| 6177 | // and every response still trails that commit through the ordinary output |
| 6178 | // gate. The three caps bound heap retention and keep the persisted transaction |
| 6179 | // inside the public sendBatch limits. |
| 6180 | const __QUEUE_PRODUCER_GROUP_CALLS = 64; |
| 6181 | const __QUEUE_PRODUCER_GROUP_MESSAGES = 100; |
| 6182 | const __QUEUE_PRODUCER_GROUP_BYTES = 256_000; |
| 6183 | |
| 6184 | const __queueError = (message) => new Error("QUEUE_ERROR: " + String(message)); |
| 6185 | // A Queue message id is a UUIDv7 (RFC 9562): 48 bits of enqueue time, a |
| 6186 | // 12-bit sequence inside that millisecond, and 62 random bits. It keeps the |
| 6187 | // UUID shape a consumer can parse, and it sorts in enqueue order, so the |
| 6188 | // UNIQUE index on `id` appends. A random v4 id made every grouped send |
| 6189 | // transaction dirty one index leaf per message (about 1.6 WAL frames per |
| 6190 | // 64-byte message) and turned every passive checkpoint into a random write |
| 6191 | // across the whole backlog, which is what made a deep Queue's checkpoint |
| 6192 | // cost grow with its backlog. The sequence never moves backwards inside one |
| 6193 | // process, so a clock step only widens the gap between consecutive ids. |
| 6194 | let __queueIdMs = 0; |
| 6195 | let __queueIdSeq = 0; |
| 6196 | function __queueMessageId(now) { |
| 6197 | if (now > __queueIdMs) { |
| 6198 | __queueIdMs = now; |
| 6199 | __queueIdSeq = 0; |
| 6200 | } else { |
| 6201 | __queueIdSeq += 1; |
| 6202 | if (__queueIdSeq > 0xfff) { |
| 6203 | __queueIdMs += 1; |
| 6204 | __queueIdSeq = 0; |
| 6205 | } |
| 6206 | } |
| 6207 | const bytes = new Uint8Array(16); |
| 6208 | crypto.getRandomValues(bytes); |
| 6209 | const ms = __queueIdMs; |
| 6210 | bytes[0] = Math.floor(ms / 0x10000000000) & 0xff; |
| 6211 | bytes[1] = Math.floor(ms / 0x100000000) & 0xff; |
| 6212 | bytes[2] = (ms >>> 24) & 0xff; |
| 6213 | bytes[3] = (ms >>> 16) & 0xff; |
| 6214 | bytes[4] = (ms >>> 8) & 0xff; |
| 6215 | bytes[5] = ms & 0xff; |
| 6216 | bytes[6] = 0x70 | (__queueIdSeq >> 8); |
| 6217 | bytes[7] = __queueIdSeq & 0xff; |
| 6218 | bytes[8] = (bytes[8] & 0x3f) | 0x80; |
| 6219 | let hex = ""; |
| 6220 | for (let i = 0; i < 16; i++) hex += bytes[i].toString(16).padStart(2, "0"); |
| 6221 | return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${ |
| 6222 | hex.slice(16, 20) |
| 6223 | }-${hex.slice(20)}`; |
| 6224 | } |
| 6225 | const __queueLimits = () => __cell.queueLimits; |
| 6226 | const __queuePolicy = (request) => |
| 6227 | JSON.parse(__queue_policy(JSON.stringify(request))); |
| 6228 | |
| 6229 | const __queueDelay = (value, fallback = 0) => { |
| 6230 | if (value === undefined || value === null) return fallback; |
| 6231 | const seconds = Number(value); |
| 6232 | if (!Number.isInteger(seconds) || seconds < 0 || |
| 6233 | seconds > __queueLimits().maxDelaySeconds) { |
| 6234 | throw __queueError( |
| 6235 | `delaySeconds must be an integer from 0 to ${__queueLimits().maxDelaySeconds}`, |
| 6236 | ); |
| 6237 | } |
| 6238 | return seconds; |
| 6239 | }; |
| 6240 | |
| 6241 | const __queueBytes = (value) => { |
| 6242 | if (value instanceof ArrayBuffer) { |
| 6243 | return new Uint8Array(value.slice(0)); |
| 6244 | } |
| 6245 | if (ArrayBuffer.isView(value)) { |
| 6246 | return new Uint8Array( |
| 6247 | value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), |
| 6248 | ); |
| 6249 | } |
| 6250 | throw __queueError("a bytes message must be an ArrayBuffer or a typed array"); |
| 6251 | }; |
| 6252 | |
| 6253 | // Encode before entering the cell. The copy makes `sendBatch()` immune to a |
| 6254 | // caller resizing or reusing a backing buffer while the durable write awaits. |
| 6255 | const __queueEncode = (body, requestedType) => { |
| 6256 | const contentType = requestedType ?? |
| 6257 | (__cell.compat.queueJsonMessages ? "json" : "v8"); |
| 6258 | let bytes; |
| 6259 | switch (contentType) { |
| 6260 | case "text": |
| 6261 | bytes = __queueEncoder.encode(String(body)); |
| 6262 | break; |
| 6263 | case "bytes": |
| 6264 | bytes = __queueBytes(body); |
| 6265 | break; |
| 6266 | case "json": { |
| 6267 | let json; |
| 6268 | try { |
| 6269 | json = JSON.stringify(body); |
| 6270 | } catch (error) { |
| 6271 | throw __queueError("the JSON message body cannot be serialized", error); |
| 6272 | } |
| 6273 | if (json === undefined) { |
| 6274 | throw __queueError("the JSON message body cannot be undefined"); |
| 6275 | } |
| 6276 | bytes = __queueEncoder.encode(json); |
| 6277 | break; |
| 6278 | } |
| 6279 | case "v8": |
| 6280 | try { |
| 6281 | bytes = __sc_encode(body); |
| 6282 | } catch (error) { |
| 6283 | throw __queueError("the message body cannot be cloned", error); |
| 6284 | } |
| 6285 | break; |
| 6286 | default: |
| 6287 | throw __queueError( |
| 6288 | `contentType must be "text", "bytes", "json", or "v8", got ${JSON.stringify(contentType)}`, |
| 6289 | ); |
| 6290 | } |
| 6291 | if (bytes.byteLength > __queueLimits().maxMessageBytes) { |
| 6292 | throw __queueError( |
| 6293 | `a message is at most ${__queueLimits().maxMessageBytes} bytes, got ${bytes.byteLength}`, |
| 6294 | ); |
| 6295 | } |
| 6296 | return { body: bytes, contentType, size: bytes.byteLength }; |
| 6297 | }; |
| 6298 | |
| 6299 | // A lease-scoped read must seek, not walk the backlog. The plan is the only |
| 6300 | // evidence that says which, and it is cheap to ask for, so a gated test seam |
| 6301 | // reads it from the shipped query rather than from a copy that can drift. |
| 6302 | const __queueReportLeaseLookupPlan = (sql, query, leaseId) => { |
| 6303 | if (typeof __test_queue_lease_lookup_plan !== "function") return; |
| 6304 | const plan = sql.exec(`EXPLAIN QUERY PLAN ${query}`, leaseId) |
| 6305 | .toArray() |
| 6306 | .map((row) => row.detail) |
| 6307 | .join("; "); |
| 6308 | __test_queue_lease_lookup_plan(plan); |
| 6309 | }; |
| 6310 | |
| 6311 | const __queueMetricsView = (metrics) => ({ |
| 6312 | backlogCount: metrics.backlogCount, |
| 6313 | backlogBytes: metrics.backlogBytes, |
| 6314 | oldestMessageTimestamp: metrics.oldestMessageTimestamp === null || |
| 6315 | metrics.oldestMessageTimestamp === undefined |
| 6316 | ? undefined |
| 6317 | : new Date(metrics.oldestMessageTimestamp), |
| 6318 | }); |
| 6319 | |
| 6320 | class __QueueCell { |
| 6321 | constructor(ctx) { |
| 6322 | this.ctx = ctx; |
| 6323 | this.queue = ctx.id.name; |
| 6324 | this._ready = false; |
| 6325 | this._producerGroup = null; |
| 6326 | } |
| 6327 | |
| 6328 | _open() { |
| 6329 | if (this._ready) return this.ctx.storage.sql; |
| 6330 | const sql = this.ctx.storage.sql; |
| 6331 | sql.exec( |
| 6332 | `CREATE TABLE IF NOT EXISTS ${__QUEUE_MESSAGES} ( |
| 6333 | seq INTEGER PRIMARY KEY AUTOINCREMENT, |
| 6334 | id TEXT NOT NULL UNIQUE, |
| 6335 | body BLOB NOT NULL, |
| 6336 | content_type TEXT NOT NULL, |
| 6337 | size INTEGER NOT NULL, |
| 6338 | enqueued_at INTEGER NOT NULL, |
| 6339 | visible_at INTEGER NOT NULL, |
| 6340 | attempts INTEGER NOT NULL DEFAULT 0, |
| 6341 | lease_id TEXT, |
| 6342 | lease_generation INTEGER NOT NULL DEFAULT 0, |
| 6343 | leased_until INTEGER, |
| 6344 | purge_on_settle INTEGER NOT NULL DEFAULT 0, |
| 6345 | dlq_target TEXT, |
| 6346 | dlq_transfer_id TEXT, |
| 6347 | transfer_kind TEXT, |
| 6348 | dead_letter_source TEXT, |
| 6349 | CHECK ((dlq_target IS NULL AND transfer_kind IS NULL) |
| 6350 | OR (dlq_target IS NOT NULL |
| 6351 | AND transfer_kind IN ('dead-letter', 'redrive'))) |
| 6352 | )`, |
| 6353 | ); |
| 6354 | sql.exec( |
| 6355 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_visible |
| 6356 | ON ${__QUEUE_MESSAGES} (visible_at, seq)`, |
| 6357 | ); |
| 6358 | // Rearming is on every producer acknowledgement and settlement. Each |
| 6359 | // scheduling lookup must therefore stop at one deadline or one batch; |
| 6360 | // an aggregate over the backlog makes a large Queue quadratic to fill. |
| 6361 | sql.exec( |
| 6362 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_ready |
| 6363 | ON ${__QUEUE_MESSAGES} (visible_at, seq) |
| 6364 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6365 | AND lease_id IS NULL`, |
| 6366 | ); |
| 6367 | sql.exec( |
| 6368 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_enqueued |
| 6369 | ON ${__QUEUE_MESSAGES} (enqueued_at, seq)`, |
| 6370 | ); |
| 6371 | sql.exec( |
| 6372 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_retained |
| 6373 | ON ${__QUEUE_MESSAGES} (enqueued_at, seq) |
| 6374 | WHERE purge_on_settle = 0 AND dlq_target IS NULL`, |
| 6375 | ); |
| 6376 | sql.exec( |
| 6377 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease |
| 6378 | ON ${__QUEUE_MESSAGES} (leased_until, seq) |
| 6379 | WHERE lease_id IS NOT NULL`, |
| 6380 | ); |
| 6381 | sql.exec( |
| 6382 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_moving |
| 6383 | ON ${__QUEUE_MESSAGES} (seq) |
| 6384 | WHERE dlq_target IS NOT NULL`, |
| 6385 | ); |
| 6386 | // Dispatch and settlement both select a whole batch by its lease. Without |
| 6387 | // this index SQLite answers them by walking every row: the dispatch |
| 6388 | // readback scans `_visible` and the settlement scan walks the table, so |
| 6389 | // each delivered batch costs two passes over the backlog. The `_lease` |
| 6390 | // index cannot serve them because it is keyed on `leased_until`. |
| 6391 | // The partial predicate keeps only leased rows, which `max_concurrency` |
| 6392 | // times `max_batch_size` bounds, and an inserted message has a null |
| 6393 | // `lease_id`, so `send` pays nothing for it. |
| 6394 | sql.exec( |
| 6395 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease_batch |
| 6396 | ON ${__QUEUE_MESSAGES} (lease_id, visible_at, seq) |
| 6397 | WHERE lease_id IS NOT NULL`, |
| 6398 | ); |
| 6399 | // The live-row index catches an impossible duplicate while a received |
| 6400 | // message remains queued. The receipt below is the durable deduplication |
| 6401 | // record after a consumer or purge removes that message. |
| 6402 | sql.exec( |
| 6403 | `CREATE UNIQUE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_dlq_transfer |
| 6404 | ON ${__QUEUE_MESSAGES} (dlq_transfer_id) |
| 6405 | WHERE dlq_transfer_id IS NOT NULL AND dlq_target IS NULL`, |
| 6406 | ); |
| 6407 | sql.exec( |
| 6408 | `CREATE TABLE IF NOT EXISTS ${__QUEUE_META} ( |
| 6409 | name TEXT PRIMARY KEY, |
| 6410 | value TEXT NOT NULL |
| 6411 | ) WITHOUT ROWID`, |
| 6412 | ); |
| 6413 | // The producer result and operator metrics are on hot paths. SQLite |
| 6414 | // triggers keep the three values in the same transaction as every row |
| 6415 | // transition, so a caller cannot observe a new message with old totals. |
| 6416 | sql.exec( |
| 6417 | `CREATE TABLE IF NOT EXISTS ${__QUEUE_STATS} ( |
| 6418 | id INTEGER PRIMARY KEY CHECK (id = 1), |
| 6419 | stored_count INTEGER NOT NULL, |
| 6420 | backlog_count INTEGER NOT NULL, |
| 6421 | backlog_bytes INTEGER NOT NULL, |
| 6422 | oldest_message_timestamp INTEGER |
| 6423 | )`, |
| 6424 | ); |
| 6425 | sql.exec( |
| 6426 | `INSERT INTO ${__QUEUE_STATS} |
| 6427 | (id, stored_count, backlog_count, backlog_bytes, |
| 6428 | oldest_message_timestamp) |
| 6429 | SELECT 1, |
| 6430 | COUNT(*), |
| 6431 | COALESCE(SUM(purge_on_settle = 0), 0), |
| 6432 | COALESCE(SUM(CASE WHEN purge_on_settle = 0 THEN size ELSE 0 END), 0), |
| 6433 | MIN(CASE WHEN purge_on_settle = 0 THEN enqueued_at END) |
| 6434 | FROM ${__QUEUE_MESSAGES} |
| 6435 | WHERE true |
| 6436 | ON CONFLICT(id) DO NOTHING`, |
| 6437 | ); |
| 6438 | sql.exec( |
| 6439 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_insert |
| 6440 | AFTER INSERT ON ${__QUEUE_MESSAGES} |
| 6441 | BEGIN |
| 6442 | UPDATE ${__QUEUE_STATS} |
| 6443 | SET stored_count = stored_count + 1 |
| 6444 | WHERE id = 1; |
| 6445 | END`, |
| 6446 | ); |
| 6447 | sql.exec( |
| 6448 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_delete |
| 6449 | AFTER DELETE ON ${__QUEUE_MESSAGES} |
| 6450 | BEGIN |
| 6451 | UPDATE ${__QUEUE_STATS} |
| 6452 | SET stored_count = stored_count - 1 |
| 6453 | WHERE id = 1; |
| 6454 | END`, |
| 6455 | ); |
| 6456 | sql.exec( |
| 6457 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_insert |
| 6458 | AFTER INSERT ON ${__QUEUE_MESSAGES} |
| 6459 | WHEN new.purge_on_settle = 0 |
| 6460 | BEGIN |
| 6461 | UPDATE ${__QUEUE_STATS} |
| 6462 | SET backlog_count = backlog_count + 1, |
| 6463 | backlog_bytes = backlog_bytes + new.size, |
| 6464 | oldest_message_timestamp = CASE |
| 6465 | WHEN oldest_message_timestamp IS NULL |
| 6466 | OR new.enqueued_at < oldest_message_timestamp |
| 6467 | THEN new.enqueued_at ELSE oldest_message_timestamp END |
| 6468 | WHERE id = 1; |
| 6469 | END`, |
| 6470 | ); |
| 6471 | sql.exec( |
| 6472 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_delete |
| 6473 | AFTER DELETE ON ${__QUEUE_MESSAGES} |
| 6474 | WHEN old.purge_on_settle = 0 |
| 6475 | BEGIN |
| 6476 | UPDATE ${__QUEUE_STATS} |
| 6477 | SET backlog_count = backlog_count - 1, |
| 6478 | backlog_bytes = backlog_bytes - old.size, |
| 6479 | oldest_message_timestamp = CASE |
| 6480 | WHEN backlog_count <= 1 THEN NULL |
| 6481 | WHEN oldest_message_timestamp = old.enqueued_at |
| 6482 | THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} |
| 6483 | WHERE purge_on_settle = 0) |
| 6484 | ELSE oldest_message_timestamp END |
| 6485 | WHERE id = 1; |
| 6486 | END`, |
| 6487 | ); |
| 6488 | sql.exec( |
| 6489 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_exclude |
| 6490 | AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} |
| 6491 | WHEN old.purge_on_settle = 0 AND new.purge_on_settle != 0 |
| 6492 | BEGIN |
| 6493 | UPDATE ${__QUEUE_STATS} |
| 6494 | SET backlog_count = backlog_count - 1, |
| 6495 | backlog_bytes = backlog_bytes - old.size, |
| 6496 | oldest_message_timestamp = CASE |
| 6497 | WHEN backlog_count <= 1 THEN NULL |
| 6498 | WHEN oldest_message_timestamp = old.enqueued_at |
| 6499 | THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} |
| 6500 | WHERE purge_on_settle = 0) |
| 6501 | ELSE oldest_message_timestamp END |
| 6502 | WHERE id = 1; |
| 6503 | END`, |
| 6504 | ); |
| 6505 | sql.exec( |
| 6506 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_include |
| 6507 | AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} |
| 6508 | WHEN old.purge_on_settle != 0 AND new.purge_on_settle = 0 |
| 6509 | BEGIN |
| 6510 | UPDATE ${__QUEUE_STATS} |
| 6511 | SET backlog_count = backlog_count + 1, |
| 6512 | backlog_bytes = backlog_bytes + new.size, |
| 6513 | oldest_message_timestamp = CASE |
| 6514 | WHEN oldest_message_timestamp IS NULL |
| 6515 | OR new.enqueued_at < oldest_message_timestamp |
| 6516 | THEN new.enqueued_at ELSE oldest_message_timestamp END |
| 6517 | WHERE id = 1; |
| 6518 | END`, |
| 6519 | ); |
| 6520 | sql.exec( |
| 6521 | `CREATE TABLE IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS} ( |
| 6522 | transfer_id TEXT PRIMARY KEY, |
| 6523 | message_id TEXT NOT NULL, |
| 6524 | dead_letter_source TEXT, |
| 6525 | expires_at INTEGER NOT NULL |
| 6526 | ) WITHOUT ROWID`, |
| 6527 | ); |
| 6528 | sql.exec( |
| 6529 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS}_expires |
| 6530 | ON ${__QUEUE_TRANSFER_RECEIPTS} (expires_at, transfer_id)`, |
| 6531 | ); |
| 6532 | this._ready = true; |
| 6533 | return sql; |
| 6534 | } |
| 6535 | |
| 6536 | _meta(name) { |
| 6537 | return this._open().exec( |
| 6538 | `SELECT value FROM ${__QUEUE_META} WHERE name = ?`, name, |
| 6539 | ).toArray()[0]?.value; |
| 6540 | } |
| 6541 | |
| 6542 | _setMeta(name, value) { |
| 6543 | if (value === null || value === undefined) { |
| 6544 | this._open().exec(`DELETE FROM ${__QUEUE_META} WHERE name = ?`, name); |
| 6545 | return; |
| 6546 | } |
| 6547 | this._open().exec( |
| 6548 | `INSERT INTO ${__QUEUE_META} (name, value) VALUES (?, ?) |
| 6549 | ON CONFLICT(name) DO UPDATE SET value = excluded.value`, |
| 6550 | name, |
| 6551 | String(value), |
| 6552 | ); |
| 6553 | } |
| 6554 | |
| 6555 | _paused() { |
| 6556 | return this._meta("paused") === "1"; |
| 6557 | } |
| 6558 | |
| 6559 | _metrics(now = Date.now(), waitingOnly = false) { |
| 6560 | const expiresBefore = now - __queueLimits().retentionMs; |
| 6561 | const sql = this._open(); |
| 6562 | const stats = sql.exec( |
| 6563 | `SELECT backlog_count, backlog_bytes, oldest_message_timestamp |
| 6564 | FROM ${__QUEUE_STATS} WHERE id = 1`, |
| 6565 | ).toArray()[0]; |
| 6566 | // Retention is a clock transition, not a row transition. Until the |
| 6567 | // bounded sweep catches up, use the exact query only at that boundary; |
| 6568 | // the normal hot path remains one materialized row at every depth. |
| 6569 | if (stats.oldest_message_timestamp !== null && |
| 6570 | stats.oldest_message_timestamp <= expiresBefore) { |
| 6571 | const row = sql.exec( |
| 6572 | `SELECT COUNT(*) AS backlog_count, |
| 6573 | COALESCE(SUM(size), 0) AS backlog_bytes, |
| 6574 | MIN(enqueued_at) AS oldest_message_timestamp |
| 6575 | FROM ${__QUEUE_MESSAGES} |
| 6576 | WHERE purge_on_settle = 0 AND enqueued_at > ? |
| 6577 | AND (? = 0 OR (lease_id IS NULL AND dlq_target IS NULL |
| 6578 | AND visible_at <= ?))`, |
| 6579 | expiresBefore, |
| 6580 | waitingOnly ? 1 : 0, |
| 6581 | now, |
| 6582 | ).toArray()[0]; |
| 6583 | return { |
| 6584 | backlogCount: row.backlog_count, |
| 6585 | backlogBytes: row.backlog_bytes, |
| 6586 | oldestMessageTimestamp: row.oldest_message_timestamp ?? null, |
| 6587 | }; |
| 6588 | } |
| 6589 | if (!waitingOnly) { |
| 6590 | if (typeof __test_queue_metrics_materialized === "function") { |
| 6591 | __test_queue_metrics_materialized(); |
| 6592 | } |
| 6593 | return { |
| 6594 | backlogCount: stats.backlog_count, |
| 6595 | backlogBytes: stats.backlog_bytes, |
| 6596 | oldestMessageTimestamp: stats.oldest_message_timestamp ?? null, |
| 6597 | }; |
| 6598 | } |
| 6599 | const blocked = sql.exec( |
| 6600 | `SELECT COALESCE(SUM(blocked_count), 0) AS blocked_count, |
| 6601 | COALESCE(SUM(blocked_bytes), 0) AS blocked_bytes |
| 6602 | FROM ( |
| 6603 | SELECT COUNT(*) AS blocked_count, |
| 6604 | COALESCE(SUM(size), 0) AS blocked_bytes |
| 6605 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease |
| 6606 | WHERE purge_on_settle = 0 AND lease_id IS NOT NULL |
| 6607 | UNION ALL |
| 6608 | SELECT COUNT(*) AS blocked_count, |
| 6609 | COALESCE(SUM(size), 0) AS blocked_bytes |
| 6610 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving |
| 6611 | WHERE purge_on_settle = 0 AND dlq_target IS NOT NULL |
| 6612 | UNION ALL |
| 6613 | SELECT COUNT(*) AS blocked_count, |
| 6614 | COALESCE(SUM(size), 0) AS blocked_bytes |
| 6615 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready |
| 6616 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6617 | AND lease_id IS NULL AND visible_at > ? |
| 6618 | )`, |
| 6619 | now, |
| 6620 | ).toArray()[0]; |
| 6621 | const unleasedOldest = sql.exec( |
| 6622 | `SELECT enqueued_at |
| 6623 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained |
| 6624 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6625 | AND lease_id IS NULL AND visible_at <= ? |
| 6626 | ORDER BY enqueued_at, seq |
| 6627 | LIMIT 1`, |
| 6628 | now, |
| 6629 | ).toArray()[0]?.enqueued_at ?? null; |
| 6630 | return { |
| 6631 | backlogCount: stats.backlog_count - blocked.blocked_count, |
| 6632 | backlogBytes: stats.backlog_bytes - blocked.blocked_bytes, |
| 6633 | oldestMessageTimestamp: unleasedOldest, |
| 6634 | }; |
| 6635 | } |
| 6636 | |
| 6637 | async _rearm(now = Date.now(), waitForWake = false) { |
| 6638 | const sql = this._open(); |
| 6639 | const consumer = __cell.queueConsumers?.[this.queue]; |
| 6640 | const paused = this._paused(); |
| 6641 | const active = sql.exec( |
| 6642 | `SELECT COUNT(DISTINCT lease_id) AS count |
| 6643 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease |
| 6644 | WHERE lease_id IS NOT NULL AND leased_until > ?`, |
| 6645 | now, |
| 6646 | ).toArray()[0].count; |
| 6647 | const concurrency = consumer |
| 6648 | ? consumer.maxConcurrency ?? __queueLimits().maxConcurrency |
| 6649 | : 0; |
| 6650 | const hasCapacity = !paused && consumer !== undefined && __queuePolicy({ |
| 6651 | op: "capacity", |
| 6652 | active, |
| 6653 | maximum: concurrency, |
| 6654 | }); |
| 6655 | // We need only enough ready rows to distinguish a partial batch from a |
| 6656 | // full one. The two indexed arms cover a new row and an expired lease, |
| 6657 | // and the outer LIMIT keeps the work independent of backlog depth. |
| 6658 | let ready = []; |
| 6659 | if (hasCapacity) { |
| 6660 | const visibleReady = sql.exec( |
| 6661 | `SELECT visible_at AS ready_at, seq |
| 6662 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready |
| 6663 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6664 | AND lease_id IS NULL AND visible_at <= ? |
| 6665 | ORDER BY visible_at, seq |
| 6666 | LIMIT ?`, |
| 6667 | now, |
| 6668 | consumer.maxBatchSize, |
| 6669 | ).toArray(); |
| 6670 | const expiredReady = sql.exec( |
| 6671 | `SELECT leased_until AS ready_at, seq |
| 6672 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease |
| 6673 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6674 | AND lease_id IS NOT NULL AND leased_until <= ? |
| 6675 | ORDER BY leased_until, seq |
| 6676 | LIMIT ?`, |
| 6677 | now, |
| 6678 | consumer.maxBatchSize, |
| 6679 | ).toArray(); |
| 6680 | ready = [...visibleReady, ...expiredReady] |
| 6681 | .sort((left, right) => left.ready_at - right.ready_at || left.seq - right.seq) |
| 6682 | .slice(0, consumer.maxBatchSize); |
| 6683 | } |
| 6684 | if (typeof __test_queue_rearm_bounded === "function") { |
| 6685 | __test_queue_rearm_bounded( |
| 6686 | ready.length <= (consumer?.maxBatchSize ?? 0), |
| 6687 | ready.length > 0, |
| 6688 | ); |
| 6689 | } |
| 6690 | const earliestVisible = hasCapacity |
| 6691 | ? sql.exec( |
| 6692 | `SELECT visible_at |
| 6693 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready |
| 6694 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6695 | AND lease_id IS NULL AND visible_at > ? |
| 6696 | ORDER BY visible_at, seq |
| 6697 | LIMIT 1`, |
| 6698 | now, |
| 6699 | ).toArray()[0]?.visible_at ?? null |
| 6700 | : null; |
| 6701 | const earliestLeaseExpiry = paused |
| 6702 | ? null |
| 6703 | : sql.exec( |
| 6704 | `SELECT leased_until |
| 6705 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease |
| 6706 | WHERE lease_id IS NOT NULL |
| 6707 | ORDER BY leased_until |
| 6708 | LIMIT 1`, |
| 6709 | ).toArray()[0]?.leased_until ?? null; |
| 6710 | const nextSweep = sql.exec( |
| 6711 | `SELECT enqueued_at + ? AS next_sweep |
| 6712 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained |
| 6713 | WHERE dlq_target IS NULL AND purge_on_settle = 0 |
| 6714 | ORDER BY enqueued_at, seq |
| 6715 | LIMIT 1`, |
| 6716 | __queueLimits().retentionMs, |
| 6717 | ).toArray()[0]?.next_sweep ?? null; |
| 6718 | const dlqPending = sql.exec( |
| 6719 | `SELECT 1 AS pending |
| 6720 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving |
| 6721 | WHERE dlq_target IS NOT NULL |
| 6722 | LIMIT 1`, |
| 6723 | ).toArray().length !== 0; |
| 6724 | const receiptSweep = sql.exec( |
| 6725 | `SELECT expires_at AS next_sweep |
| 6726 | FROM ${__QUEUE_TRANSFER_RECEIPTS} |
| 6727 | ORDER BY expires_at, transfer_id |
| 6728 | LIMIT 1`, |
| 6729 | ).toArray()[0]?.next_sweep ?? null; |
| 6730 | // A queue without an attached consumer only wakes to reclaim retention. |
| 6731 | // Consumer attachment will nudge the cell when the fleet catalog gains a |
| 6732 | // registration; spinning on an already-visible row cannot make progress. |
| 6733 | let batchDeadline = null; |
| 6734 | if (ready.length > 0) { |
| 6735 | batchDeadline = ready.length >= consumer.maxBatchSize |
| 6736 | ? now |
| 6737 | : ready[0].ready_at + consumer.maxBatchTimeoutMs; |
| 6738 | } |
| 6739 | if (dlqPending) { |
| 6740 | batchDeadline = batchDeadline === null ? now : Math.min(batchDeadline, now); |
| 6741 | } |
| 6742 | const sweepDeadlines = [nextSweep, receiptSweep] |
| 6743 | .filter((deadline) => deadline !== null && deadline !== undefined); |
| 6744 | const armAt = __queuePolicy({ |
| 6745 | op: "rearm", |
| 6746 | now, |
| 6747 | batchDeadline, |
| 6748 | earliestVisible, |
| 6749 | // A live handler can settle after delivery pauses. Do not reclaim its |
| 6750 | // lease while paused; resume re-arms the expired deadline immediately |
| 6751 | // and only then can a new generation replace it. |
| 6752 | earliestLeaseExpiry, |
| 6753 | nextSweep: sweepDeadlines.length === 0 ? null : Math.min(...sweepDeadlines), |
| 6754 | }); |
| 6755 | if (armAt !== null && !Number.isFinite(armAt)) { |
| 6756 | throw __queueError("the Queue sweep deadline is invalid"); |
| 6757 | } |
| 6758 | if (armAt === null) await this.ctx.storage.deleteAlarm(); |
| 6759 | else if (waitForWake) { |
| 6760 | await __queue_alarm_set_wait(this.ctx.storage._scope, armAt); |
| 6761 | } else await this.ctx.storage.setAlarm(armAt); |
| 6762 | } |
| 6763 | |
| 6764 | _newProducerGroup() { |
| 6765 | const group = { |
| 6766 | calls: [], |
| 6767 | entries: [], |
| 6768 | bytes: 0, |
| 6769 | flushing: false, |
| 6770 | timer: null, |
| 6771 | }; |
| 6772 | this._producerGroup = group; |
| 6773 | group.timer = setTimeout(() => { |
| 6774 | void this._flushProducerGroup(group); |
| 6775 | }, __queueLimits().producerGroupMs); |
| 6776 | return group; |
| 6777 | } |
| 6778 | |
| 6779 | async _flushProducerGroup(group) { |
| 6780 | if (group.flushing) return; |
| 6781 | group.flushing = true; |
| 6782 | if (this._producerGroup === group) this._producerGroup = null; |
| 6783 | if (group.timer !== null) { |
| 6784 | clearTimeout(group.timer); |
| 6785 | group.timer = null; |
| 6786 | } |
| 6787 | |
| 6788 | const now = Date.now(); |
| 6789 | try { |
| 6790 | const sql = this._open(); |
| 6791 | this.ctx.storage.transactionSync(() => { |
| 6792 | for (const entry of group.entries) { |
| 6793 | sql.exec( |
| 6794 | `INSERT INTO ${__QUEUE_MESSAGES} |
| 6795 | (id, body, content_type, size, enqueued_at, visible_at) |
| 6796 | VALUES (?, ?, ?, ?, ?, ?)`, |
| 6797 | __queueMessageId(now), |
| 6798 | entry.body, |
| 6799 | entry.contentType, |
| 6800 | entry.size, |
| 6801 | now, |
| 6802 | now + entry.delaySeconds * 1000, |
| 6803 | ); |
| 6804 | } |
| 6805 | }); |
| 6806 | await this._rearm(now, true); |
| 6807 | const metrics = this._metrics(now); |
| 6808 | if (typeof __test_queue_producer_group === "function") { |
| 6809 | __test_queue_producer_group(group.calls.length, group.entries.length); |
| 6810 | } |
| 6811 | for (const call of group.calls) call.resolve(metrics); |
| 6812 | } catch (error) { |
| 6813 | for (const call of group.calls) call.reject(error); |
| 6814 | } |
| 6815 | } |
| 6816 | |
| 6817 | __queueSend({ entries }) { |
| 6818 | const bytes = entries.reduce((total, entry) => total + entry.size, 0); |
| 6819 | return new Promise((resolve, reject) => { |
| 6820 | let group = this._producerGroup; |
| 6821 | if (group !== null && |
| 6822 | (group.calls.length + 1 > __QUEUE_PRODUCER_GROUP_CALLS || |
| 6823 | group.entries.length + entries.length > __QUEUE_PRODUCER_GROUP_MESSAGES || |
| 6824 | group.bytes + bytes > __QUEUE_PRODUCER_GROUP_BYTES)) { |
| 6825 | void this._flushProducerGroup(group); |
| 6826 | group = null; |
| 6827 | } |
| 6828 | if (group === null) group = this._newProducerGroup(); |
| 6829 | group.calls.push({ resolve, reject }); |
| 6830 | group.entries.push(...entries); |
| 6831 | group.bytes += bytes; |
| 6832 | if (group.calls.length === __QUEUE_PRODUCER_GROUP_CALLS || |
| 6833 | group.entries.length === __QUEUE_PRODUCER_GROUP_MESSAGES || |
| 6834 | group.bytes === __QUEUE_PRODUCER_GROUP_BYTES) { |
| 6835 | void this._flushProducerGroup(group); |
| 6836 | } |
| 6837 | }); |
| 6838 | } |
| 6839 | |
| 6840 | __queueMetrics() { |
| 6841 | return this._metrics(); |
| 6842 | } |
| 6843 | |
| 6844 | // Retention decides visibility through `_metrics` immediately, while this |
| 6845 | // bounded sweep only reclaims space. A live lease is marked instead of |
| 6846 | // deleted, so its handler can finish but settlement or expiry removes it |
| 6847 | // without a redelivery. |
| 6848 | _sweep(now) { |
| 6849 | const sql = this._open(); |
| 6850 | const cutoff = now - __queueLimits().retentionMs; |
| 6851 | const messages = __cellSweepBatch( |
| 6852 | this.ctx.storage, |
| 6853 | (limit) => sql.exec( |
| 6854 | `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} |
| 6855 | WHERE enqueued_at <= ? |
| 6856 | AND (purge_on_settle = 0 |
| 6857 | OR lease_id IS NULL OR leased_until <= ?) |
| 6858 | ORDER BY enqueued_at, seq |
| 6859 | LIMIT ?`, |
| 6860 | cutoff, |
| 6861 | now, |
| 6862 | limit, |
| 6863 | ).toArray(), |
| 6864 | (row) => { |
| 6865 | if (row.lease_id !== null && row.leased_until > now) { |
| 6866 | sql.exec( |
| 6867 | `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 WHERE seq = ?`, |
| 6868 | row.seq, |
| 6869 | ); |
| 6870 | } else { |
| 6871 | sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); |
| 6872 | } |
| 6873 | }, |
| 6874 | __queueLimits().sweepBatchRows, |
| 6875 | ); |
| 6876 | const remaining = __queueLimits().sweepBatchRows - messages; |
| 6877 | if (remaining === 0) return messages; |
| 6878 | const receipts = __cellSweepBatch( |
| 6879 | this.ctx.storage, |
| 6880 | (limit) => sql.exec( |
| 6881 | `SELECT transfer_id FROM ${__QUEUE_TRANSFER_RECEIPTS} |
| 6882 | WHERE expires_at <= ? |
| 6883 | ORDER BY expires_at, transfer_id |
| 6884 | LIMIT ?`, |
| 6885 | now, |
| 6886 | limit, |
| 6887 | ).toArray(), |
| 6888 | (row) => { |
| 6889 | sql.exec( |
| 6890 | `DELETE FROM ${__QUEUE_TRANSFER_RECEIPTS} WHERE transfer_id = ?`, |
| 6891 | row.transfer_id, |
| 6892 | ); |
| 6893 | }, |
| 6894 | remaining, |
| 6895 | ); |
| 6896 | return messages + receipts; |
| 6897 | } |
| 6898 | |
| 6899 | _candidateRows(now, limit) { |
| 6900 | return this._open().exec( |
| 6901 | `SELECT seq, id, body, content_type, size, enqueued_at, visible_at, |
| 6902 | attempts, lease_id, lease_generation, leased_until, |
| 6903 | purge_on_settle |
| 6904 | FROM ${__QUEUE_MESSAGES} |
| 6905 | WHERE dlq_target IS NULL AND ((purge_on_settle = 1 |
| 6906 | AND (lease_id IS NULL OR leased_until <= ?)) |
| 6907 | OR (purge_on_settle = 0 AND visible_at <= ? |
| 6908 | AND (lease_id IS NULL OR leased_until <= ?))) |
| 6909 | ORDER BY visible_at, seq |
| 6910 | LIMIT ?`, |
| 6911 | now, |
| 6912 | now, |
| 6913 | now, |
| 6914 | limit, |
| 6915 | ).toArray(); |
| 6916 | } |
| 6917 | |
| 6918 | async _leaseBatch(now, consumer) { |
| 6919 | const sql = this._open(); |
| 6920 | const active = sql.exec( |
| 6921 | `SELECT COUNT(DISTINCT lease_id) AS count |
| 6922 | FROM ${__QUEUE_MESSAGES} |
| 6923 | WHERE lease_id IS NOT NULL AND leased_until > ?`, |
| 6924 | now, |
| 6925 | ).toArray()[0].count; |
| 6926 | const concurrency = consumer.maxConcurrency ?? __queueLimits().maxConcurrency; |
| 6927 | if (!__queuePolicy({ op: "capacity", active, maximum: concurrency })) return null; |
| 6928 | |
| 6929 | // Read extra rows so expired purge markers cannot hide a deliverable |
| 6930 | // batch. Policy chooses at most `maxBatchSize` rows and returns every |
| 6931 | // purge deletion that precedes them in this bounded scan. |
| 6932 | const rows = this._candidateRows(now, consumer.maxBatchSize + 256); |
| 6933 | const deliverable = rows.filter((row) => row.purge_on_settle === 0); |
| 6934 | if (deliverable.length === 0) { |
| 6935 | if (rows.length > 0) { |
| 6936 | this.ctx.storage.transactionSync(() => { |
| 6937 | for (const row of rows) { |
| 6938 | sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); |
| 6939 | } |
| 6940 | }); |
| 6941 | } |
| 6942 | return null; |
| 6943 | } |
| 6944 | const readySince = Math.min(...deliverable.map((row) => |
| 6945 | row.lease_id === null ? row.visible_at : row.leased_until |
| 6946 | )); |
| 6947 | if (deliverable.length < consumer.maxBatchSize && |
| 6948 | readySince + consumer.maxBatchTimeoutMs > now) { |
| 6949 | return null; |
| 6950 | } |
| 6951 | |
| 6952 | const plan = __queuePolicy({ |
| 6953 | op: "batch", |
| 6954 | now, |
| 6955 | maxBatchSize: consumer.maxBatchSize, |
| 6956 | rows: rows.map((row) => ({ |
| 6957 | seq: row.seq, |
| 6958 | visibleAt: row.visible_at, |
| 6959 | leaseGeneration: String(row.lease_generation), |
| 6960 | leasedUntil: row.leased_until, |
| 6961 | purgeOnSettle: row.purge_on_settle !== 0, |
| 6962 | })), |
| 6963 | }); |
| 6964 | if (plan.leases.length === 0 && plan.deletePurged.length === 0) return null; |
| 6965 | const rowBySeq = new Map(rows.map((row) => [row.seq, row])); |
| 6966 | const reclaimed = plan.leases.filter((lease) => lease.reclaimed); |
| 6967 | const expiryPolicy = __queuePolicy({ |
| 6968 | op: "expiry", |
| 6969 | now, |
| 6970 | entries: reclaimed.map((lease) => { |
| 6971 | const row = rowBySeq.get(lease.seq); |
| 6972 | return { |
| 6973 | priorFailures: row.attempts, |
| 6974 | maxRetries: consumer.maxRetries, |
| 6975 | configuredSeconds: consumer.retryDelaySeconds ?? null, |
| 6976 | purgeOnSettle: row.purge_on_settle !== 0, |
| 6977 | }; |
| 6978 | }), |
| 6979 | }); |
| 6980 | const expiryBySeq = new Map( |
| 6981 | reclaimed.map((lease, index) => [lease.seq, expiryPolicy[index]]), |
| 6982 | ); |
| 6983 | const installs = plan.leases.filter((lease) => { |
| 6984 | const expiry = expiryBySeq.get(lease.seq); |
| 6985 | return expiry === undefined || |
| 6986 | (expiry.action.kind === "retry" && expiry.action.at <= now); |
| 6987 | }); |
| 6988 | const exhaustedTransfers = new Map( |
| 6989 | reclaimed |
| 6990 | .filter((lease) => |
| 6991 | expiryBySeq.get(lease.seq).action.kind === "exhausted" && |
| 6992 | consumer.deadLetterQueue !== undefined |
| 6993 | ) |
| 6994 | .map((lease) => [lease.seq, crypto.randomUUID()]), |
| 6995 | ); |
| 6996 | const leaseId = crypto.randomUUID(); |
| 6997 | const leasedUntil = Math.min( |
| 6998 | Number.MAX_SAFE_INTEGER, |
| 6999 | now + __cell.queueLeaseDurationMs, |
| 7000 | ); |
| 7001 | this.ctx.storage.transactionSync(() => { |
| 7002 | for (const seq of plan.deletePurged) { |
| 7003 | sql.exec( |
| 7004 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7005 | WHERE seq = ? AND purge_on_settle = 1 |
| 7006 | AND (lease_id IS NULL OR leased_until <= ?)`, |
| 7007 | seq, |
| 7008 | now, |
| 7009 | ); |
| 7010 | } |
| 7011 | for (const lease of reclaimed) { |
| 7012 | const expiry = expiryBySeq.get(lease.seq); |
| 7013 | if (expiry.action.kind === "delete-purged") { |
| 7014 | sql.exec( |
| 7015 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7016 | WHERE seq = ? AND leased_until <= ?`, |
| 7017 | lease.seq, |
| 7018 | now, |
| 7019 | ); |
| 7020 | } else if (expiry.action.kind === "exhausted") { |
| 7021 | if (consumer.deadLetterQueue === undefined) { |
| 7022 | sql.exec( |
| 7023 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7024 | WHERE seq = ? AND leased_until <= ?`, |
| 7025 | lease.seq, |
| 7026 | now, |
| 7027 | ); |
| 7028 | } else { |
| 7029 | sql.exec( |
| 7030 | `UPDATE ${__QUEUE_MESSAGES} |
| 7031 | SET attempts = ?, lease_id = NULL, leased_until = NULL, |
| 7032 | dlq_target = ?, dlq_transfer_id = ?, |
| 7033 | transfer_kind = 'dead-letter' |
| 7034 | WHERE seq = ? AND leased_until <= ?`, |
| 7035 | expiry.attempt, |
| 7036 | consumer.deadLetterQueue, |
| 7037 | exhaustedTransfers.get(lease.seq), |
| 7038 | lease.seq, |
| 7039 | now, |
| 7040 | ); |
| 7041 | } |
| 7042 | } else if (expiry.action.at > now) { |
| 7043 | sql.exec( |
| 7044 | `UPDATE ${__QUEUE_MESSAGES} |
| 7045 | SET attempts = ?, visible_at = ?, lease_id = NULL, |
| 7046 | leased_until = NULL |
| 7047 | WHERE seq = ? AND leased_until <= ?`, |
| 7048 | expiry.attempt, |
| 7049 | expiry.action.at, |
| 7050 | lease.seq, |
| 7051 | now, |
| 7052 | ); |
| 7053 | } |
| 7054 | } |
| 7055 | for (const lease of installs) { |
| 7056 | const generation = Number(lease.generation); |
| 7057 | if (!Number.isSafeInteger(generation)) { |
| 7058 | throw __queueError(`message ${lease.seq} exhausted its safe lease generation`); |
| 7059 | } |
| 7060 | sql.exec( |
| 7061 | `UPDATE ${__QUEUE_MESSAGES} |
| 7062 | SET lease_id = ?, lease_generation = ?, leased_until = ?, |
| 7063 | attempts = attempts + ? |
| 7064 | WHERE seq = ? AND lease_generation = ? |
| 7065 | AND (lease_id IS NULL OR leased_until <= ?)`, |
| 7066 | leaseId, |
| 7067 | generation, |
| 7068 | leasedUntil, |
| 7069 | lease.reclaimed ? 1 : 0, |
| 7070 | lease.seq, |
| 7071 | generation - 1, |
| 7072 | now, |
| 7073 | ); |
| 7074 | } |
| 7075 | }); |
| 7076 | if (installs.length === 0) return null; |
| 7077 | const leasedQuery = |
| 7078 | `SELECT seq, id, body, content_type, enqueued_at, attempts, |
| 7079 | lease_generation |
| 7080 | FROM ${__QUEUE_MESSAGES} |
| 7081 | WHERE lease_id = ? |
| 7082 | ORDER BY visible_at, seq`; |
| 7083 | __queueReportLeaseLookupPlan(sql, leasedQuery, leaseId); |
| 7084 | const leased = sql.exec(leasedQuery, leaseId).toArray(); |
| 7085 | if (leased.length !== installs.length) { |
| 7086 | throw __queueError("the Queue lease transaction changed fewer rows than its plan"); |
| 7087 | } |
| 7088 | return { |
| 7089 | leaseId, |
| 7090 | leases: leased.map((row) => ({ |
| 7091 | message_id: row.id, |
| 7092 | seq: row.seq, |
| 7093 | generation: row.lease_generation, |
| 7094 | })), |
| 7095 | messages: leased.map((row) => ({ |
| 7096 | id: row.id, |
| 7097 | timestampMs: row.enqueued_at, |
| 7098 | // SQLite answers a BLOB as an ArrayBuffer. The raw base64 op accepts |
| 7099 | // typed views, so normalize here; otherwise it encodes the text |
| 7100 | // "[object ArrayBuffer]" and every consumer decoder sees corrupt data. |
| 7101 | bodyBase64: $$btoa( |
| 7102 | row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), |
| 7103 | ), |
| 7104 | contentType: row.content_type, |
| 7105 | attempts: row.attempts + 1, |
| 7106 | })), |
| 7107 | // Miniflare removes every dispatched batch from its backlog before it |
| 7108 | // invokes the consumer. Exclude every lease here for the same contract; |
| 7109 | // the operator aggregate still includes durable in-flight messages. |
| 7110 | metrics: this._metrics(now, true), |
| 7111 | }; |
| 7112 | } |
| 7113 | |
| 7114 | // The target deduplicates the stable transfer identity. The source can |
| 7115 | // therefore repeat this call after a stop between the target commit and the |
| 7116 | // source delete without creating a second message. |
| 7117 | async __queueDlqAcceptBatch({ transfers }) { |
| 7118 | if (!Array.isArray(transfers) || transfers.length === 0 || |
| 7119 | transfers.length > __queueLimits().maxBatchMessages) { |
| 7120 | throw __queueError("a Queue transfer batch has an invalid size"); |
| 7121 | } |
| 7122 | for (const transfer of transfers) { |
| 7123 | if (transfer.deadLetterSource !== null && |
| 7124 | typeof transfer.deadLetterSource !== "string") { |
| 7125 | throw __queueError("a Queue transfer has an invalid dead-letter source"); |
| 7126 | } |
| 7127 | } |
| 7128 | const now = Date.now(); |
| 7129 | const sql = this._open(); |
| 7130 | this.ctx.storage.transactionSync(() => { |
| 7131 | for (const { transferId, entry, deadLetterSource } of transfers) { |
| 7132 | const accepted = sql.exec( |
| 7133 | `SELECT message_id, dead_letter_source |
| 7134 | FROM ${__QUEUE_TRANSFER_RECEIPTS} |
| 7135 | WHERE transfer_id = ?`, |
| 7136 | transferId, |
| 7137 | ).toArray()[0]; |
| 7138 | if (accepted !== undefined && (accepted.message_id !== entry.id || |
| 7139 | accepted.dead_letter_source !== deadLetterSource)) { |
| 7140 | throw __queueError("a DLQ transfer collided with another message identity"); |
| 7141 | } |
| 7142 | if (accepted !== undefined) continue; |
| 7143 | sql.exec( |
| 7144 | `INSERT INTO ${__QUEUE_TRANSFER_RECEIPTS} |
| 7145 | (transfer_id, message_id, dead_letter_source, expires_at) |
| 7146 | VALUES (?, ?, ?, ?)`, |
| 7147 | transferId, |
| 7148 | entry.id, |
| 7149 | deadLetterSource, |
| 7150 | now + __queueLimits().retentionMs, |
| 7151 | ); |
| 7152 | sql.exec( |
| 7153 | `INSERT INTO ${__QUEUE_MESSAGES} |
| 7154 | (id, body, content_type, size, enqueued_at, visible_at, |
| 7155 | attempts, dlq_transfer_id, dead_letter_source) |
| 7156 | VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)`, |
| 7157 | entry.id, |
| 7158 | entry.body, |
| 7159 | entry.contentType, |
| 7160 | entry.size, |
| 7161 | now, |
| 7162 | now, |
| 7163 | transferId, |
| 7164 | deadLetterSource, |
| 7165 | ); |
| 7166 | } |
| 7167 | }); |
| 7168 | await this._rearm(now); |
| 7169 | return this._metrics(now); |
| 7170 | } |
| 7171 | |
| 7172 | async _driveDlq(limit = 100) { |
| 7173 | const now = Date.now(); |
| 7174 | const pending = this._open().exec( |
| 7175 | `SELECT seq, id, body, content_type, size, dlq_target, dlq_transfer_id, |
| 7176 | transfer_kind |
| 7177 | FROM ${__QUEUE_MESSAGES} |
| 7178 | WHERE dlq_target IS NOT NULL |
| 7179 | AND enqueued_at > ? |
| 7180 | ORDER BY seq |
| 7181 | LIMIT ?`, |
| 7182 | now - __queueLimits().retentionMs, |
| 7183 | limit, |
| 7184 | ).toArray(); |
| 7185 | const groups = new Map(); |
| 7186 | for (const row of pending) { |
| 7187 | let group = groups.get(row.dlq_target); |
| 7188 | if (group === undefined) groups.set(row.dlq_target, group = []); |
| 7189 | group.push(row); |
| 7190 | } |
| 7191 | for (const [targetName, rows] of groups) { |
| 7192 | const target = __cell.makeNamespace("__Queue").getByName(targetName); |
| 7193 | await target.__queueDlqAcceptBatch({ |
| 7194 | transfers: rows.map((row) => ({ |
| 7195 | transferId: row.dlq_transfer_id, |
| 7196 | // A dead-letter transfer records where redrive returns the message. |
| 7197 | // A redrive returns it to ordinary queue state, so the source marker |
| 7198 | // must not follow it and make a later redrive bounce it backwards. |
| 7199 | deadLetterSource: row.transfer_kind === "dead-letter" ? this.queue : null, |
| 7200 | entry: { |
| 7201 | id: row.id, |
| 7202 | body: row.body, |
| 7203 | contentType: row.content_type, |
| 7204 | size: row.size, |
| 7205 | }, |
| 7206 | })), |
| 7207 | }); |
| 7208 | if (typeof __test_queue_dlq_accepted === "function") { |
| 7209 | __test_queue_dlq_accepted(); |
| 7210 | } |
| 7211 | // The target committed every receipt before this reply. Delete the |
| 7212 | // corresponding source marks together; a stop before this transaction |
| 7213 | // leaves the whole group replayable through those stable receipts. |
| 7214 | this.ctx.storage.transactionSync(() => { |
| 7215 | for (const row of rows) { |
| 7216 | this._open().exec( |
| 7217 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7218 | WHERE seq = ? AND dlq_target = ? AND dlq_transfer_id = ? |
| 7219 | AND transfer_kind = ?`, |
| 7220 | row.seq, |
| 7221 | row.dlq_target, |
| 7222 | row.dlq_transfer_id, |
| 7223 | row.transfer_kind, |
| 7224 | ); |
| 7225 | } |
| 7226 | }); |
| 7227 | } |
| 7228 | return pending.length; |
| 7229 | } |
| 7230 | |
| 7231 | async alarm() { |
| 7232 | const now = Date.now(); |
| 7233 | try { |
| 7234 | await this._driveDlq(); |
| 7235 | } catch (error) { |
| 7236 | // The durable source mark is the retry record. An alarm stays armed at |
| 7237 | // `now`, and the target's transfer identity makes a replay idempotent. |
| 7238 | console.error("Queue DLQ transfer failed:", error); |
| 7239 | } |
| 7240 | const swept = this._sweep(now); |
| 7241 | const consumer = this._paused() |
| 7242 | ? undefined |
| 7243 | : __cell.queueConsumers?.[this.queue]; |
| 7244 | // Install every lease that the configured concurrency admits before the |
| 7245 | // first consumer can settle. One lease per alarm serialized full batches |
| 7246 | // because the next alarm depended on a later scheduler turn, so a queue |
| 7247 | // with maxConcurrency > 1 still used only one handler under backlog. |
| 7248 | // `_leaseBatch` counts the durable lease IDs on every iteration, which |
| 7249 | // makes the configured concurrency the structural bound for this loop. |
| 7250 | const batches = []; |
| 7251 | if (consumer !== undefined) { |
| 7252 | while (true) { |
| 7253 | const batch = await this._leaseBatch(now, consumer); |
| 7254 | if (batch === null) break; |
| 7255 | batches.push(batch); |
| 7256 | } |
| 7257 | } |
| 7258 | try { |
| 7259 | // `_leaseBatch` can exhaust an expired lease and create a new durable |
| 7260 | // DLQ mark. Drive that mark in the same wake; the first call above is |
| 7261 | // for a mark recovered from an earlier stopped process. |
| 7262 | await this._driveDlq(); |
| 7263 | } catch (error) { |
| 7264 | console.error("Queue DLQ transfer failed:", error); |
| 7265 | } |
| 7266 | await this._rearm(now); |
| 7267 | if (swept >= __queueLimits().sweepBatchRows && batches.length === 0) { |
| 7268 | await this.ctx.storage.setAlarm(now + 1); |
| 7269 | return; |
| 7270 | } |
| 7271 | for (const batch of batches) { |
| 7272 | // This await covers only the output-gated handoff to the host. The |
| 7273 | // consumer runs after this alarm returns, and settlement comes back as |
| 7274 | // an independent cell event. All admitted leases are durable before the |
| 7275 | // first handoff, so a fast settlement cannot make this turn exceed the |
| 7276 | // configured concurrency. |
| 7277 | await __queue_dispatch( |
| 7278 | consumer.script, |
| 7279 | this.queue, |
| 7280 | JSON.stringify(batch), |
| 7281 | ); |
| 7282 | } |
| 7283 | } |
| 7284 | |
| 7285 | _matchingLease(body) { |
| 7286 | if (typeof body.leaseId !== "string" || !Array.isArray(body.leases)) return null; |
| 7287 | const matchQuery = |
| 7288 | `SELECT seq, id, attempts, lease_generation, purge_on_settle |
| 7289 | FROM ${__QUEUE_MESSAGES} |
| 7290 | WHERE lease_id = ? |
| 7291 | ORDER BY seq`; |
| 7292 | __queueReportLeaseLookupPlan(this._open(), matchQuery, body.leaseId); |
| 7293 | const rows = this._open().exec(matchQuery, body.leaseId).toArray(); |
| 7294 | for (const lease of body.leases) { |
| 7295 | if (typeof lease?.message_id !== "string" || |
| 7296 | !Number.isSafeInteger(lease.seq) || |
| 7297 | !Number.isSafeInteger(lease.generation)) return null; |
| 7298 | } |
| 7299 | const matches = __queuePolicy({ |
| 7300 | op: "settlement", |
| 7301 | current: rows.map((row) => ({ |
| 7302 | seq: String(row.seq), |
| 7303 | messageId: row.id, |
| 7304 | generation: String(row.lease_generation), |
| 7305 | })), |
| 7306 | submitted: body.leases.map((lease) => ({ |
| 7307 | seq: String(lease.seq), |
| 7308 | messageId: lease.message_id, |
| 7309 | generation: String(lease.generation), |
| 7310 | })), |
| 7311 | }); |
| 7312 | return matches ? rows : null; |
| 7313 | } |
| 7314 | |
| 7315 | async _settle(body) { |
| 7316 | const rows = this._matchingLease(body); |
| 7317 | if (rows === null) return false; |
| 7318 | const consumer = __cell.queueConsumers?.[this.queue]; |
| 7319 | if (consumer === undefined) return false; |
| 7320 | const explicitAcks = new Set(body.explicitAcks ?? []); |
| 7321 | const retryMessages = new Map( |
| 7322 | (body.retryMessages ?? []).map((retry) => [retry.msgId, retry.delaySeconds]), |
| 7323 | ); |
| 7324 | const retryBatch = body.retryBatch?.retry === true; |
| 7325 | const batchDelay = body.retryBatch?.delaySeconds; |
| 7326 | const exception = body.outcome === "exception"; |
| 7327 | // An explicit ack-all survives a later handler exception, so it must |
| 7328 | // override every batch-level and message-level retry signal. |
| 7329 | const ackAll = body.ackAll === true; |
| 7330 | const decisions = rows.map((row) => { |
| 7331 | const retry = !ackAll && !explicitAcks.has(row.id) && ( |
| 7332 | retryMessages.has(row.id) || retryBatch || exception |
| 7333 | ); |
| 7334 | return { row, retry }; |
| 7335 | }); |
| 7336 | const retrying = decisions.filter((decision) => |
| 7337 | decision.retry && decision.row.purge_on_settle === 0 |
| 7338 | ); |
| 7339 | const retryPolicy = __queuePolicy({ |
| 7340 | op: "retries", |
| 7341 | now: Date.now(), |
| 7342 | entries: retrying.map(({ row }) => ({ |
| 7343 | attempt: row.attempts + 1, |
| 7344 | maxRetries: consumer.maxRetries, |
| 7345 | explicitSeconds: retryMessages.has(row.id) |
| 7346 | ? retryMessages.get(row.id) |
| 7347 | : retryBatch ? batchDelay : null, |
| 7348 | configuredSeconds: consumer.retryDelaySeconds ?? null, |
| 7349 | })), |
| 7350 | }); |
| 7351 | const retryById = new Map( |
| 7352 | retrying.map(({ row }, index) => [row.id, retryPolicy[index]]), |
| 7353 | ); |
| 7354 | const dlqTransferById = new Map( |
| 7355 | retrying |
| 7356 | .filter(({ row }) => |
| 7357 | retryById.get(row.id).exhausted && consumer.deadLetterQueue !== undefined |
| 7358 | ) |
| 7359 | .map(({ row }) => [row.id, crypto.randomUUID()]), |
| 7360 | ); |
| 7361 | const sql = this._open(); |
| 7362 | this.ctx.storage.transactionSync(() => { |
| 7363 | for (const { row, retry } of decisions) { |
| 7364 | const policy = retryById.get(row.id); |
| 7365 | if (row.purge_on_settle !== 0 || !retry || |
| 7366 | (policy.exhausted && consumer.deadLetterQueue === undefined)) { |
| 7367 | sql.exec( |
| 7368 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7369 | WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, |
| 7370 | row.seq, |
| 7371 | body.leaseId, |
| 7372 | row.lease_generation, |
| 7373 | ); |
| 7374 | continue; |
| 7375 | } |
| 7376 | if (policy.exhausted) { |
| 7377 | sql.exec( |
| 7378 | `UPDATE ${__QUEUE_MESSAGES} |
| 7379 | SET attempts = attempts + 1, lease_id = NULL, |
| 7380 | leased_until = NULL, dlq_target = ?, dlq_transfer_id = ?, |
| 7381 | transfer_kind = 'dead-letter' |
| 7382 | WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, |
| 7383 | consumer.deadLetterQueue, |
| 7384 | dlqTransferById.get(row.id), |
| 7385 | row.seq, |
| 7386 | body.leaseId, |
| 7387 | row.lease_generation, |
| 7388 | ); |
| 7389 | continue; |
| 7390 | } |
| 7391 | sql.exec( |
| 7392 | `UPDATE ${__QUEUE_MESSAGES} |
| 7393 | SET attempts = attempts + 1, visible_at = ?, |
| 7394 | lease_id = NULL, leased_until = NULL |
| 7395 | WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, |
| 7396 | policy.at, |
| 7397 | row.seq, |
| 7398 | body.leaseId, |
| 7399 | row.lease_generation, |
| 7400 | ); |
| 7401 | } |
| 7402 | }); |
| 7403 | try { |
| 7404 | await this._driveDlq(); |
| 7405 | } catch (error) { |
| 7406 | // Settlement is durable once the source mark commits. A failed transfer |
| 7407 | // is alarm work now, not a reason to put the message back in delivery. |
| 7408 | console.error("Queue DLQ transfer deferred:", error); |
| 7409 | } |
| 7410 | await this._rearm(); |
| 7411 | return true; |
| 7412 | } |
| 7413 | |
| 7414 | async _purge() { |
| 7415 | const now = Date.now(); |
| 7416 | const sql = this._open(); |
| 7417 | let deleted = 0; |
| 7418 | let leased = 0; |
| 7419 | this.ctx.storage.transactionSync(() => { |
| 7420 | let after = 0; |
| 7421 | while (true) { |
| 7422 | // Purge is necessarily proportional to the stored backlog, but its |
| 7423 | // policy envelope stays bounded instead of materializing the Queue in |
| 7424 | // V8 or Rust. One SQLite transaction keeps the visibility change |
| 7425 | // atomic across all chunks. |
| 7426 | const rows = sql.exec( |
| 7427 | `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} |
| 7428 | WHERE seq > ? |
| 7429 | ORDER BY seq |
| 7430 | LIMIT 256`, |
| 7431 | after, |
| 7432 | ).toArray(); |
| 7433 | if (rows.length === 0) break; |
| 7434 | after = rows[rows.length - 1].seq; |
| 7435 | const plan = __queuePolicy({ |
| 7436 | op: "purge", |
| 7437 | now, |
| 7438 | rows: rows.map((row) => ({ |
| 7439 | seq: String(row.seq), |
| 7440 | leaseIdPresent: row.lease_id !== null, |
| 7441 | leasedUntil: row.leased_until, |
| 7442 | })), |
| 7443 | }); |
| 7444 | for (const seq of plan.delete) { |
| 7445 | sql.exec( |
| 7446 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7447 | WHERE seq = ? |
| 7448 | AND (lease_id IS NULL OR leased_until IS NULL OR leased_until <= ?)`, |
| 7449 | Number(seq), |
| 7450 | now, |
| 7451 | ); |
| 7452 | deleted += 1; |
| 7453 | } |
| 7454 | for (const seq of plan.markForSettle) { |
| 7455 | sql.exec( |
| 7456 | `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 |
| 7457 | WHERE seq = ? AND lease_id IS NOT NULL AND leased_until > ?`, |
| 7458 | Number(seq), |
| 7459 | now, |
| 7460 | ); |
| 7461 | leased += 1; |
| 7462 | } |
| 7463 | } |
| 7464 | }); |
| 7465 | await this._rearm(now); |
| 7466 | return { deleted, leased, metrics: this._metrics(now) }; |
| 7467 | } |
| 7468 | |
| 7469 | async _setPaused(paused) { |
| 7470 | this._setMeta("paused", paused ? "1" : null); |
| 7471 | await this._rearm(); |
| 7472 | return { paused, ...this._metrics() }; |
| 7473 | } |
| 7474 | |
| 7475 | _operatorLimit(value, fallback) { |
| 7476 | const limit = value ?? fallback; |
| 7477 | if (!Number.isInteger(limit) || limit < 1 || limit > 100) { |
| 7478 | throw __queueError("limit must be an integer from 1 through 100"); |
| 7479 | } |
| 7480 | return limit; |
| 7481 | } |
| 7482 | |
| 7483 | _peek(limit) { |
| 7484 | const now = Date.now(); |
| 7485 | const cutoff = now - __queueLimits().retentionMs; |
| 7486 | const rows = this._open().exec( |
| 7487 | `SELECT id, body, content_type, size, enqueued_at, visible_at, attempts, |
| 7488 | lease_id, leased_until, purge_on_settle, dlq_target, |
| 7489 | dead_letter_source |
| 7490 | FROM ${__QUEUE_MESSAGES} |
| 7491 | WHERE enqueued_at > ? |
| 7492 | ORDER BY visible_at, seq |
| 7493 | LIMIT ?`, |
| 7494 | cutoff, |
| 7495 | limit, |
| 7496 | ).toArray(); |
| 7497 | return { |
| 7498 | messages: rows.map((row) => ({ |
| 7499 | id: row.id, |
| 7500 | bodyBase64: $$btoa( |
| 7501 | row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), |
| 7502 | ), |
| 7503 | contentType: row.content_type, |
| 7504 | size: row.size, |
| 7505 | enqueuedAt: row.enqueued_at, |
| 7506 | visibleAt: row.visible_at, |
| 7507 | attempts: row.attempts, |
| 7508 | state: row.dlq_target !== null |
| 7509 | ? "moving" |
| 7510 | : row.purge_on_settle !== 0 |
| 7511 | ? "purging" |
| 7512 | : row.lease_id !== null && row.leased_until > now |
| 7513 | ? "leased" |
| 7514 | : row.visible_at <= now |
| 7515 | ? "visible" |
| 7516 | : "delayed", |
| 7517 | leasedUntil: row.lease_id !== null && row.leased_until > now |
| 7518 | ? row.leased_until |
| 7519 | : null, |
| 7520 | transferTarget: row.dlq_target, |
| 7521 | deadLetterSource: row.dead_letter_source, |
| 7522 | })), |
| 7523 | }; |
| 7524 | } |
| 7525 | |
| 7526 | async _redrive(limit) { |
| 7527 | // Finish an interrupted move before selecting more work. A transfer mark |
| 7528 | // is durable, so selecting it a second time would invent another identity |
| 7529 | // where replaying the existing identity is sufficient. |
| 7530 | await this._driveDlq(100); |
| 7531 | const now = Date.now(); |
| 7532 | const cutoff = now - __queueLimits().retentionMs; |
| 7533 | const candidates = this._open().exec( |
| 7534 | `SELECT seq, dead_letter_source |
| 7535 | FROM ${__QUEUE_MESSAGES} |
| 7536 | WHERE dead_letter_source IS NOT NULL |
| 7537 | AND dlq_target IS NULL |
| 7538 | AND purge_on_settle = 0 |
| 7539 | AND enqueued_at > ? |
| 7540 | AND (lease_id IS NULL OR leased_until <= ?) |
| 7541 | ORDER BY visible_at, seq |
| 7542 | LIMIT ?`, |
| 7543 | cutoff, |
| 7544 | now, |
| 7545 | limit, |
| 7546 | ).toArray(); |
| 7547 | const transfers = candidates.map((row) => ({ |
| 7548 | ...row, |
| 7549 | transferId: crypto.randomUUID(), |
| 7550 | })); |
| 7551 | this.ctx.storage.transactionSync(() => { |
| 7552 | for (const transfer of transfers) { |
| 7553 | this._open().exec( |
| 7554 | `UPDATE ${__QUEUE_MESSAGES} |
| 7555 | SET dlq_target = ?, dlq_transfer_id = ?, transfer_kind = 'redrive', |
| 7556 | lease_id = NULL, leased_until = NULL |
| 7557 | WHERE seq = ? AND dead_letter_source = ? AND dlq_target IS NULL |
| 7558 | AND purge_on_settle = 0 |
| 7559 | AND (lease_id IS NULL OR leased_until <= ?)`, |
| 7560 | transfer.dead_letter_source, |
| 7561 | transfer.transferId, |
| 7562 | transfer.seq, |
| 7563 | transfer.dead_letter_source, |
| 7564 | now, |
| 7565 | ); |
| 7566 | } |
| 7567 | }); |
| 7568 | // Arm before the cross-cell call. If the process stops after the durable |
| 7569 | // mark, the alarm replays the same transfer identity. |
| 7570 | await this._rearm(now); |
| 7571 | await this._driveDlq(100); |
| 7572 | await this._rearm(); |
| 7573 | return { redriven: transfers.length, metrics: this._metrics() }; |
| 7574 | } |
| 7575 | |
| 7576 | async fetch(request) { |
| 7577 | const path = new URL(request.url).pathname; |
| 7578 | if (request.method !== "POST") { |
| 7579 | return new Response("Queue route not found", { status: 404 }); |
| 7580 | } |
| 7581 | let body; |
| 7582 | try { |
| 7583 | body = await request.json(); |
| 7584 | } catch { |
| 7585 | return new Response("invalid Queue request", { status: 400 }); |
| 7586 | } |
| 7587 | try { |
| 7588 | if (path === "/__qSettle") { |
| 7589 | return await this._settle(body) |
| 7590 | ? new Response(null, { status: 204 }) |
| 7591 | : new Response("stale Queue settlement", { status: 409 }); |
| 7592 | } |
| 7593 | if (body.op === "info") { |
| 7594 | const metrics = this._metrics(); |
| 7595 | const stored = this._open().exec( |
| 7596 | `SELECT stored_count FROM ${__QUEUE_STATS} WHERE id = 1`, |
| 7597 | ).toArray()[0].stored_count; |
| 7598 | return Response.json({ result: { ...metrics, stored, paused: this._paused() } }); |
| 7599 | } |
| 7600 | if (body.op === "purge") { |
| 7601 | return Response.json({ result: await this._purge() }); |
| 7602 | } |
| 7603 | if (body.op === "pause") { |
| 7604 | return Response.json({ result: await this._setPaused(true) }); |
| 7605 | } |
| 7606 | if (body.op === "resume") { |
| 7607 | return Response.json({ result: await this._setPaused(false) }); |
| 7608 | } |
| 7609 | if (body.op === "peek") { |
| 7610 | return Response.json({ |
| 7611 | result: this._peek(this._operatorLimit(body.limit, 10)), |
| 7612 | }); |
| 7613 | } |
| 7614 | if (body.op === "redrive") { |
| 7615 | return Response.json({ |
| 7616 | result: await this._redrive(this._operatorLimit(body.limit, 100)), |
| 7617 | }); |
| 7618 | } |
| 7619 | return Response.json( |
| 7620 | { error: `QUEUE_ERROR: unknown operation ${JSON.stringify(body.op)}` }, |
| 7621 | { status: 400 }, |
| 7622 | ); |
| 7623 | } catch (error) { |
| 7624 | return Response.json( |
| 7625 | { error: String(error?.message ?? error) }, |
| 7626 | { status: 400 }, |
| 7627 | ); |
| 7628 | } |
| 7629 | } |
| 7630 | } |
| 7631 | |
| 7632 | __runtimeClass("__Queue", __QueueCell); |
| 7633 | |
| 7634 | class Queue { |
| 7635 | constructor(queue, cellName, deliveryDelay) { |
| 7636 | Object.defineProperties(this, { |
| 7637 | _queue: { value: queue }, |
| 7638 | _cellName: { value: cellName }, |
| 7639 | _deliveryDelay: { value: deliveryDelay }, |
| 7640 | }); |
| 7641 | } |
| 7642 | |
| 7643 | get _stub() { |
| 7644 | return __cell.makeNamespace("__Queue").getByName(this._cellName); |
| 7645 | } |
| 7646 | |
| 7647 | async _send(entries) { |
| 7648 | const metrics = await this._stub.__queueSend({ entries }); |
| 7649 | return { metadata: { metrics: __queueMetricsView(metrics) } }; |
| 7650 | } |
| 7651 | |
| 7652 | send(body, options = {}) { |
| 7653 | const encoded = __queueEncode(body, options.contentType); |
| 7654 | return this._send([{ |
| 7655 | ...encoded, |
| 7656 | delaySeconds: __queueDelay(options.delaySeconds, this._deliveryDelay), |
| 7657 | }]); |
| 7658 | } |
| 7659 | |
| 7660 | sendBatch(messages, options = {}) { |
| 7661 | if (messages === null || messages === undefined || |
| 7662 | typeof messages[Symbol.iterator] !== "function") { |
| 7663 | throw __queueError("sendBatch() needs an iterable of messages"); |
| 7664 | } |
| 7665 | const entries = []; |
| 7666 | let bytes = 0; |
| 7667 | const batchDelay = __queueDelay(options.delaySeconds, this._deliveryDelay); |
| 7668 | for (const message of messages) { |
| 7669 | if (entries.length >= __queueLimits().maxBatchMessages) { |
| 7670 | throw __queueError( |
| 7671 | `a batch has at most ${__queueLimits().maxBatchMessages} messages`, |
| 7672 | ); |
| 7673 | } |
| 7674 | if (message === null || typeof message !== "object" || !("body" in message)) { |
| 7675 | throw __queueError("each batch entry needs a body"); |
| 7676 | } |
| 7677 | const encoded = __queueEncode(message.body, message.contentType); |
| 7678 | bytes += encoded.size; |
| 7679 | if (bytes > __queueLimits().maxBatchBytes) { |
| 7680 | throw __queueError( |
| 7681 | `a batch is at most ${__queueLimits().maxBatchBytes} bytes, got ${bytes}`, |
| 7682 | ); |
| 7683 | } |
| 7684 | entries.push({ |
| 7685 | ...encoded, |
| 7686 | delaySeconds: __queueDelay(message.delaySeconds, batchDelay), |
| 7687 | }); |
| 7688 | } |
| 7689 | if (entries.length === 0) { |
| 7690 | throw __queueError("sendBatch() needs at least one message"); |
| 7691 | } |
| 7692 | return this._send(entries); |
| 7693 | } |
| 7694 | |
| 7695 | async metrics() { |
| 7696 | return __queueMetricsView(await this._stub.__queueMetrics()); |
| 7697 | } |
| 7698 | } |
| 7699 | |
| 7700 | __celld.__makeQueue = (queue, cellName, deliveryDelay) => |
| 7701 | new Queue(queue, cellName, deliveryDelay); |
| 7702 | |
| 7703 | // ---- D1 ----------------------------------------------------------------- |
| 7704 | // A D1 database is a cell of a runtime-supplied Durable Object class, so it |
| 7705 | // inherits ownership, fencing, LTX replication, RPO=0 acknowledgement and |
| 7706 | // pressure shedding from the cell it already is. This half is the server; |
| 7707 | // `__makeD1Database` below is the client the binding hands to a Worker. |
| 7708 | // |
| 7709 | // Everything SQL goes through the one `__d1_run` op. The engine owns the |
| 7710 | // statement walk, the row and byte caps, and the meta snapshot, all inside |
| 7711 | // one execution -- the previous shape assembled these from the general |
| 7712 | // SqlStorage ops, and every seam between them was a contract only convention |
| 7713 | // enforced. |
| 7714 | |
| 7715 | // The error families applications match on. A message that already carries |
| 7716 | // one must pass through unwrapped: wrapping again would bury the family the |
| 7717 | // application is matching under a second D1_ERROR prefix. |
| 7718 | const __d1IsFamilyError = (message) => |
| 7719 | /^D1_([A-Z]+_)*(ERROR|NOTFOUND): /.test(String(message)); |
| 7720 | |
| 7721 | const __d1Error = (message, cause) => { |
| 7722 | const error = new Error("D1_ERROR: " + String(message)); |
| 7723 | error.cause = cause !== undefined ? cause : new Error(String(message)); |
| 7724 | return error; |
| 7725 | }; |
| 7726 | |
| 7727 | // A typed refusal from the engine: `{family, message}` becomes the Error the |
| 7728 | // application sees, with `.cause` carrying the bare message as upstream does. |
| 7729 | const __d1Failure = (failure) => { |
| 7730 | const error = new Error(failure.family + ": " + failure.message); |
| 7731 | error.cause = new Error(failure.message); |
| 7732 | return error; |
| 7733 | }; |
| 7734 | |
| 7735 | const __d1Run = (scope, request) => { |
| 7736 | const response = JSON.parse(__d1_run(scope, JSON.stringify(request))); |
| 7737 | if (response.error) throw __d1Failure(response.error); |
| 7738 | return response.ok; |
| 7739 | }; |
| 7740 | |
| 7741 | class __D1DatabaseCell { |
| 7742 | constructor(ctx) { |
| 7743 | this.ctx = ctx; |
| 7744 | } |
| 7745 | // Takes an array so that `batch()` can ride this same method, and the |
| 7746 | // same turn, when it lands. |
| 7747 | __d1Query(statements) { |
| 7748 | const scope = this.ctx.storage.sql._scope; |
| 7749 | return statements.map((statement) => |
| 7750 | __d1Run(scope, { |
| 7751 | mode: "prepared", |
| 7752 | sql: String(statement.sql), |
| 7753 | params: statement.params || [], |
| 7754 | first: !!statement.first, |
| 7755 | }) |
| 7756 | ); |
| 7757 | } |
| 7758 | __d1Batch(statements) { |
| 7759 | return __d1Run(this.ctx.storage.sql._scope, { |
| 7760 | mode: "batch", |
| 7761 | statements: statements.map((statement) => ({ |
| 7762 | sql: String(statement.sql), |
| 7763 | params: statement.params || [], |
| 7764 | })), |
| 7765 | }); |
| 7766 | } |
| 7767 | // The CLI's way in. `celld d1` signs each request with the fleet secret |
| 7768 | // and sends it to a live node's `/runtime/<scope>` route, which verifies the |
| 7769 | // signature and then forwards to the owner over the same dispatch `/do/` |
| 7770 | // uses -- so the CLI needs no ownership logic and the database is reached |
| 7771 | // the way a Worker reaches it. The unauthenticated `/do/` route refuses a |
| 7772 | // D1 scope outright: this cell answers arbitrary SQL, and its scope is an |
| 7773 | // HMAC over names that sit in the project's config, so the scope itself |
| 7774 | // is no secret. |
| 7775 | async fetch(request) { |
| 7776 | let body; |
| 7777 | try { |
| 7778 | body = await request.json(); |
| 7779 | } catch { |
| 7780 | return Response.json({ error: "D1_ERROR: invalid request body" }, { status: 400 }); |
| 7781 | } |
| 7782 | try { |
| 7783 | let result; |
| 7784 | if (body.migrate !== undefined) { |
| 7785 | result = this.__d1Migrate( |
| 7786 | String(body.migrate.name), |
| 7787 | String(body.migrate.sql), |
| 7788 | String(body.migrate.table || "d1_migrations"), |
| 7789 | ); |
| 7790 | } else if (body.exec !== undefined) { |
| 7791 | // The CLI asks for rows; the Worker binding's exec() never does. |
| 7792 | result = __d1Run(this.ctx.storage.sql._scope, { |
| 7793 | mode: "exec", |
| 7794 | sql: String(body.exec.sql), |
| 7795 | rows: !!body.exec.rows, |
| 7796 | }); |
| 7797 | } else { |
| 7798 | result = this.__d1Query(body.statements || []); |
| 7799 | } |
| 7800 | return Response.json({ result }); |
| 7801 | } catch (error) { |
| 7802 | return Response.json({ error: String(error && error.message || error) }, { status: 400 }); |
| 7803 | } |
| 7804 | } |
| 7805 | __d1Exec(source) { |
| 7806 | const result = __d1Run(this.ctx.storage.sql._scope, { |
| 7807 | mode: "exec", |
| 7808 | sql: String(source), |
| 7809 | rows: false, |
| 7810 | }); |
| 7811 | return { count: result.count, duration: result.duration }; |
| 7812 | } |
| 7813 | // Apply one migration and record it. The engine runs the file, the |
| 7814 | // bookkeeping insert (the name is a bound parameter, so a file name never |
| 7815 | // reaches SQL text) and the BEGIN IMMEDIATE .. COMMIT bracket in one |
| 7816 | // request, so a migration that fails part-way rolls back whole and the |
| 7817 | // operator fixes the file and re-runs. Without the transaction the |
| 7818 | // statements that DID land are exactly the ones a re-run trips over. |
| 7819 | __d1Migrate(name, source, table) { |
| 7820 | return __d1Run(this.ctx.storage.sql._scope, { |
| 7821 | mode: "migrate", |
| 7822 | name, |
| 7823 | sql: source, |
| 7824 | table, |
| 7825 | }); |
| 7826 | } |
| 7827 | } |
| 7828 | |
| 7829 | __runtimeClass("__D1Database", __D1DatabaseCell); |
| 7830 | |
| 7831 | // Validate and encode bind values once, at the public boundary, exactly as |
| 7832 | // upstream does (workerd d1-api.ts). Byte-shaped values become byte arrays -- |
| 7833 | // the wire format for a BLOB bind -- and anything unsupported throws |
| 7834 | // D1_TYPE_ERROR here, before any SQL runs. The first version deferred this |
| 7835 | // to a JSON round-trip whose fallthrough was SQL NULL, so a Uint8Array bind |
| 7836 | // stored NULL and nothing said so. |
| 7837 | const __d1BindValue = (value) => { |
| 7838 | const kind = typeof value; |
| 7839 | if (kind === "number") { |
| 7840 | // A non-finite number has no JSON form, so it crosses as null and |
| 7841 | // stores SQL NULL. Upstream does the same (bind(NaN) selects typeof |
| 7842 | // "null"); making it explicit here turns the conversion from an |
| 7843 | // accident of JSON.stringify into a pinned decision. |
| 7844 | return Number.isFinite(value) ? value : null; |
| 7845 | } |
| 7846 | if (kind === "string") return value; |
| 7847 | if (kind === "boolean") return value ? 1 : 0; |
| 7848 | if (kind === "object") { |
| 7849 | if (value === null) return value; |
| 7850 | if ( |
| 7851 | Array.isArray(value) && |
| 7852 | value.every((byte) => typeof byte === "number" && byte >= 0 && byte < 256) |
| 7853 | ) { |
| 7854 | return value; |
| 7855 | } |
| 7856 | if (value instanceof ArrayBuffer) { |
| 7857 | return Array.from(new Uint8Array(value)); |
| 7858 | } |
| 7859 | // A typed view binds its ELEMENT values, each truncated to a byte -- |
| 7860 | // Int8Array([-1]) stores 0xff, Float32Array([1.5]) stores 0x01 -- not |
| 7861 | // its underlying byte window, so Uint16Array([65, 66]) stores 2 bytes |
| 7862 | // and not 4. Upstream behaves this way (verified against workerd's D1; |
| 7863 | // the differential suite pins it), and the bare Array.from that |
| 7864 | // preceded this produced elements the engine then refused as bytes. |
| 7865 | if (ArrayBuffer.isView(value)) return Array.from(Uint8Array.from(value)); |
| 7866 | } |
| 7867 | const error = new Error( |
| 7868 | `D1_TYPE_ERROR: Type '${kind}' not supported for value '${value}'`, |
| 7869 | ); |
| 7870 | error.cause = new Error(`Type '${kind}' not supported for value '${value}'`); |
| 7871 | throw error; |
| 7872 | }; |
| 7873 | |
| 7874 | class D1PreparedStatement { |
| 7875 | constructor(database, sql, params) { |
| 7876 | Object.defineProperty(this, "_database", { value: database }); |
| 7877 | Object.defineProperty(this, "_sql", { value: sql }); |
| 7878 | Object.defineProperty(this, "_params", { value: params }); |
| 7879 | } |
| 7880 | bind(...values) { |
| 7881 | return new D1PreparedStatement( |
| 7882 | this._database, |
| 7883 | this._sql, |
| 7884 | values.map(__d1BindValue), |
| 7885 | ); |
| 7886 | } |
| 7887 | async _run(first) { |
| 7888 | const results = await this._database._query([ |
| 7889 | { sql: this._sql, params: this._params, first }, |
| 7890 | ]); |
| 7891 | return results[0]; |
| 7892 | } |
| 7893 | async all() { |
| 7894 | const result = await this._run(); |
| 7895 | return { |
| 7896 | success: true, |
| 7897 | meta: result.meta, |
| 7898 | results: result.rows.map((row) => __d1Shape(result.columns, row)), |
| 7899 | }; |
| 7900 | } |
| 7901 | async run() { |
| 7902 | return await this.all(); |
| 7903 | } |
| 7904 | async first(column) { |
| 7905 | // `first: true` keeps one row on the cell side, so only that row crosses |
| 7906 | // the isolate boundary and the row cap cannot fire for a first(). |
| 7907 | const result = await this._run(true); |
| 7908 | if (result.rows.length === 0) return null; |
| 7909 | const row = __d1Shape(result.columns, result.rows[0]); |
| 7910 | if (column === undefined) return row; |
| 7911 | // The check runs on the shaped object, as upstream's does, so a column |
| 7912 | // named like an Object.prototype member behaves the same here as there. |
| 7913 | if (row[column] === undefined) { |
| 7914 | const error = new Error( |
| 7915 | `D1_COLUMN_NOTFOUND: Column not found (${column})`, |
| 7916 | ); |
| 7917 | error.cause = new Error("Column not found"); |
| 7918 | throw error; |
| 7919 | } |
| 7920 | return row[column]; |
| 7921 | } |
| 7922 | async raw(options) { |
| 7923 | const result = await this._run(); |
| 7924 | return options && options.columnNames |
| 7925 | ? [result.columns, ...result.rows] |
| 7926 | : result.rows; |
| 7927 | } |
| 7928 | } |
| 7929 | |
| 7930 | // Object.fromEntries, not property assignment: assigning to a column named |
| 7931 | // `__proto__` would walk the prototype chain and silently drop the value, |
| 7932 | // while fromEntries defines an own property whatever the name. |
| 7933 | const __d1Shape = (columns, row) => |
| 7934 | Object.fromEntries(row.map((value, index) => [columns[index], value])); |
| 7935 | |
| 7936 | const __d1PublicResult = (result) => ({ |
| 7937 | success: true, |
| 7938 | meta: result.meta, |
| 7939 | results: result.rows.map((row) => __d1Shape(result.columns, row)), |
| 7940 | }); |
| 7941 | |
| 7942 | // celld has one primary and no replicas, so every completed query satisfies |
| 7943 | // every earlier session constraint. One stable opaque token states that fact |
| 7944 | // without pretending an isolate-local counter is a durable database position. |
| 7945 | const __d1PrimaryBookmark = "celld:primary"; |
| 7946 | |
| 7947 | class D1DatabaseSession { |
| 7948 | constructor(database, constraintOrBookmark) { |
| 7949 | Object.defineProperty(this, "_database", { value: database }); |
| 7950 | const value = constraintOrBookmark == null |
| 7951 | ? "first-unconstrained" |
| 7952 | : String(constraintOrBookmark).trim(); |
| 7953 | if (!value) { |
| 7954 | throw new Error("D1_SESSION_ERROR: invalid bookmark or constraint"); |
| 7955 | } |
| 7956 | Object.defineProperty(this, "_bookmark", { |
| 7957 | value: value === "first-primary" || value === "first-unconstrained" ? null : value, |
| 7958 | writable: true, |
| 7959 | }); |
| 7960 | } |
| 7961 | _advanceBookmark() { |
| 7962 | this._bookmark = __d1PrimaryBookmark; |
| 7963 | } |
| 7964 | async _query(statements) { |
| 7965 | const results = await this._database._query(statements); |
| 7966 | this._advanceBookmark(); |
| 7967 | return results; |
| 7968 | } |
| 7969 | prepare(sql) { |
| 7970 | return new D1PreparedStatement(this, String(sql), []); |
| 7971 | } |
| 7972 | async batch(statements) { |
| 7973 | const results = await this._database._batch(statements); |
| 7974 | this._advanceBookmark(); |
| 7975 | return results; |
| 7976 | } |
| 7977 | getBookmark() { |
| 7978 | return this._bookmark; |
| 7979 | } |
| 7980 | } |
| 7981 | |
| 7982 | // Named so SDKs that sniff a binding by `constructor.name` recognise it. |
| 7983 | class D1Database { |
| 7984 | constructor(databaseName) { |
| 7985 | Object.defineProperty(this, "_databaseName", { value: databaseName }); |
| 7986 | } |
| 7987 | // Resolved per call rather than cached: a cell can move between calls, and |
| 7988 | // `getByName` is the same cost the Durable Object path already pays. |
| 7989 | get _stub() { |
| 7990 | return __cell.makeNamespace("__D1Database").getByName(this._databaseName); |
| 7991 | } |
| 7992 | async _query(statements) { |
| 7993 | try { |
| 7994 | return await this._stub.__d1Query(statements); |
| 7995 | } catch (error) { |
| 7996 | if (__d1IsFamilyError(error && error.message)) throw error; |
| 7997 | throw __d1Error(String(error && error.message || error), error); |
| 7998 | } |
| 7999 | } |
| 8000 | async _batch(statements) { |
| 8001 | try { |
| 8002 | const encoded = statements.map((statement) => ({ |
| 8003 | sql: statement._sql, |
| 8004 | params: statement._params, |
| 8005 | })); |
| 8006 | const results = await this._stub.__d1Batch(encoded); |
| 8007 | return results.map(__d1PublicResult); |
| 8008 | } catch (error) { |
| 8009 | if (__d1IsFamilyError(error && error.message)) throw error; |
| 8010 | throw __d1Error(String(error && error.message || error), error); |
| 8011 | } |
| 8012 | } |
| 8013 | prepare(sql) { |
| 8014 | return new D1PreparedStatement(this, String(sql), []); |
| 8015 | } |
| 8016 | async exec(sql) { |
| 8017 | try { |
| 8018 | return await this._stub.__d1Exec(String(sql)); |
| 8019 | } catch (error) { |
| 8020 | if (__d1IsFamilyError(error && error.message)) throw error; |
| 8021 | throw __d1Error(String(error && error.message || error), error); |
| 8022 | } |
| 8023 | } |
| 8024 | async batch(statements) { |
| 8025 | return await this._batch(statements); |
| 8026 | } |
| 8027 | withSession(constraintOrBookmark) { |
| 8028 | return new D1DatabaseSession(this, constraintOrBookmark); |
| 8029 | } |
| 8030 | async dump() { |
| 8031 | throw __d1Error( |
| 8032 | "dump() is not implemented in celld; the database is a SQLite file in " + |
| 8033 | "your own bucket", |
| 8034 | ); |
| 8035 | } |
| 8036 | } |
| 8037 | |
| 8038 | const __makeD1Database = __celld.__makeD1Database = |
| 8039 | (databaseName) => new D1Database(databaseName); |
| 8040 | // ---- Workflows ---------------------------------------------------------- |
| 8041 | // A workflow instance is one cell of the runtime-supplied `__Workflow` class, |
| 8042 | // named `<workflow_name>/<instance_id>` through getByName, so it inherits |
| 8043 | // ownership, fencing, LTX replication and the output gate from the cell it |
| 8044 | // already is. Execution is replay: `run()` re-executes from the top on every |
| 8045 | // resume and only steps are memoized, in `ctx.storage` KV under `__wf.*`. |
| 8046 | // This half is the server; `__makeWorkflow` below is the client the binding |
| 8047 | // hands to a Worker. The public contract is in docs/cloudflare-compat.md. |
| 8048 | |
| 8049 | // Upstream's limit for a step return, an event payload, and the params. The |
| 8050 | // error is distinct and names the step, because "too large" and "the isolate |
| 8051 | // died" must not read the same (the D1 row-cap precedent). |
| 8052 | const __WF_VALUE_CAP = 1 << 20; |
| 8053 | // Workflow names, instance ids, and event types all share this charset. |
| 8054 | // `/` is outside it, which is what makes the `<name>/<id>` cell-name join |
| 8055 | // unambiguous. |
| 8056 | const __WF_NAME_RE = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/; |
| 8057 | const __wfError = (message) => new Error("WORKFLOW_ERROR: " + message); |
| 8058 | // The suspension primitive: a blocked step returns a promise that never |
| 8059 | // settles in this invocation, so user code simply stops progressing. A |
| 8060 | // sentinel thrown through user code was rejected because `Promise.all` in |
| 8061 | // `run()` would observe it as a rejection and user try/catch would eat it. |
| 8062 | const __wfNever = new Promise(() => {}); |
| 8063 | const __wfTerminal = (status) => |
| 8064 | status === "complete" || status === "errored" || status === "terminated"; |
| 8065 | // Upstream's hard bounds: 10,000 retries per step, 365 days for any sleep or |
| 8066 | // event wait, one second under a waitForEvent timeout. Enforced loudly at the |
| 8067 | // call site -- a config outside them would otherwise misbehave only after |
| 8068 | // the instance is minutes or days into its run. |
| 8069 | const __WF_RETRY_LIMIT_CAP = 10000; |
| 8070 | const __WF_STEP_NAME_LIMIT = 256; |
| 8071 | const __WF_MAX_WAIT_MS = 365 * 86400000; |
| 8072 | const __WF_MIN_EVENT_TIMEOUT_MS = 1000; |
| 8073 | // celld has no account plans, so it exposes the larger published retention |
| 8074 | // ceiling as one stable application limit. Both an omitted policy and an |
| 8075 | // omitted member of a partial policy use this value. |
| 8076 | const __WF_RETENTION_MAX_MS = 30 * 86400000; |
| 8077 | const __WF_LOCATION_HINTS = new Set([ |
| 8078 | "wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", |
| 8079 | "oc", "afr", "me", |
| 8080 | ]); |
| 8081 | // How long run() can stay pending on non-step work while no step runs and |
| 8082 | // none is blocked before the instance fails. Upstream permits un-stepped |
| 8083 | // awaits between steps (they are merely non-durable), so erroring at the |
| 8084 | // first quiescent macrotask would kill any run() whose external await |
| 8085 | // outlives one turn of the loop. Sixty seconds is long enough for any |
| 8086 | // sane un-stepped await and short enough that a truly never-settling |
| 8087 | // promise fails the instance instead of wedging the alarm handler. |
| 8088 | const __WF_STALL_GRACE_MS = 60000; |
| 8089 | const __WF_UNITS = { |
| 8090 | second: 1000, |
| 8091 | minute: 60000, |
| 8092 | hour: 3600000, |
| 8093 | day: 86400000, |
| 8094 | week: 604800000, |
| 8095 | // Upstream does not document its month/year arithmetic; fixed 30/365-day |
| 8096 | // units are used so one expression cannot mean two durations depending on |
| 8097 | // when it runs. |
| 8098 | month: 30 * 86400000, |
| 8099 | year: 365 * 86400000, |
| 8100 | }; |
| 8101 | const __wfDuration = (value, what) => { |
| 8102 | if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value; |
| 8103 | if (typeof value !== "string") { |
| 8104 | throw __wfError( |
| 8105 | `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + |
| 8106 | 'or "<n> <second|minute|hour|day|week|month|year>[s]"', |
| 8107 | ); |
| 8108 | } |
| 8109 | const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week|month|year)s?\s*$/ |
| 8110 | .exec(value); |
| 8111 | if (!match) { |
| 8112 | throw __wfError( |
| 8113 | `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + |
| 8114 | 'or "<n> <second|minute|hour|day|week|month|year>[s]"', |
| 8115 | ); |
| 8116 | } |
| 8117 | return Number(match[1]) * __WF_UNITS[match[2]]; |
| 8118 | }; |
| 8119 | const __wfRetentionDuration = (value, what) => { |
| 8120 | const durationMs = __wfDuration(value, what); |
| 8121 | if (durationMs > __WF_RETENTION_MAX_MS) { |
| 8122 | throw __wfError( |
| 8123 | `${what} is ${durationMs} ms, above celld's 30-day retention limit`, |
| 8124 | ); |
| 8125 | } |
| 8126 | return durationMs; |
| 8127 | }; |
| 8128 | const __wfOwnObject = (value) => |
| 8129 | value !== null && typeof value === "object" && !Array.isArray(value); |
| 8130 | const __wfUnknownKey = (value, allowed) => |
| 8131 | Object.keys(value).find((key) => !allowed.includes(key)); |
| 8132 | const __wfStepName = (name) => { |
| 8133 | // The pinned workers-sdk validator has no minimum length. An empty name is |
| 8134 | // therefore valid, although rejecting it looks safer at first glance. A |
| 8135 | // non-empty check made celld reject Worker code that the upstream runtime |
| 8136 | // accepts, so keep only the upstream length and control-character bounds. |
| 8137 | if ( |
| 8138 | typeof name !== "string" || name.length > __WF_STEP_NAME_LIMIT || |
| 8139 | /[\x00-\x1f]/.test(name) |
| 8140 | ) { |
| 8141 | throw __wfError( |
| 8142 | `invalid step name ${JSON.stringify(name)}: use at most ` + |
| 8143 | `${__WF_STEP_NAME_LIMIT} characters and no control characters`, |
| 8144 | ); |
| 8145 | } |
| 8146 | }; |
| 8147 | const __wfEventType = (type) => { |
| 8148 | if (typeof type !== "string" || type.length > 100 || !__WF_NAME_RE.test(type)) { |
| 8149 | throw __wfError( |
| 8150 | `invalid event type ${JSON.stringify(type)}: use at most 100 letters, ` + |
| 8151 | "digits, hyphens, or underscores", |
| 8152 | ); |
| 8153 | } |
| 8154 | }; |
| 8155 | const __wfSleepDuration = (duration, name) => { |
| 8156 | const durationMs = __wfDuration( |
| 8157 | duration, |
| 8158 | `the duration of sleep ${JSON.stringify(name)}`, |
| 8159 | ); |
| 8160 | if (durationMs > __WF_MAX_WAIT_MS) { |
| 8161 | throw __wfError( |
| 8162 | `sleep ${JSON.stringify(name)} is ${durationMs} ms, above the upstream ` + |
| 8163 | "limit of 365 days", |
| 8164 | ); |
| 8165 | } |
| 8166 | return durationMs; |
| 8167 | }; |
| 8168 | const __wfSleepUntil = (timestamp, name) => { |
| 8169 | const at = timestamp instanceof Date ? timestamp.getTime() : timestamp; |
| 8170 | if (typeof at !== "number" || !Number.isFinite(at)) { |
| 8171 | throw __wfError( |
| 8172 | `invalid sleepUntil timestamp for ${JSON.stringify(name)}: use a Date ` + |
| 8173 | "or a UNIX timestamp in milliseconds", |
| 8174 | ); |
| 8175 | } |
| 8176 | const delay = at - Date.now(); |
| 8177 | if (delay > __WF_MAX_WAIT_MS) { |
| 8178 | throw __wfError( |
| 8179 | `sleepUntil ${JSON.stringify(name)} is ${delay} ms away, above the ` + |
| 8180 | "upstream limit of 365 days", |
| 8181 | ); |
| 8182 | } |
| 8183 | return at; |
| 8184 | }; |
| 8185 | const __wfWaitOptions = (options, name) => { |
| 8186 | if (!__wfOwnObject(options)) { |
| 8187 | throw __wfError(`invalid waitForEvent options for ${JSON.stringify(name)}`); |
| 8188 | } |
| 8189 | __wfEventType(options.type); |
| 8190 | const timeout = options.timeout ?? "24 hours"; |
| 8191 | const timeoutMs = __wfDuration( |
| 8192 | timeout, |
| 8193 | `the timeout of waitForEvent ${JSON.stringify(name)}`, |
| 8194 | ); |
| 8195 | if (timeoutMs < __WF_MIN_EVENT_TIMEOUT_MS || timeoutMs > __WF_MAX_WAIT_MS) { |
| 8196 | throw __wfError( |
| 8197 | `the timeout of waitForEvent ${JSON.stringify(name)} is ${timeoutMs} ms; ` + |
| 8198 | "upstream allows 1 second to 365 days", |
| 8199 | ); |
| 8200 | } |
| 8201 | return { type: options.type, timeout, timeoutMs }; |
| 8202 | }; |
| 8203 | const __wfEventOptions = (options) => { |
| 8204 | if (!__wfOwnObject(options)) { |
| 8205 | throw __wfError("sendEvent() needs an event object"); |
| 8206 | } |
| 8207 | __wfEventType(options.type); |
| 8208 | if (options.payload !== undefined) __wfCheckValue(options.payload, "the event payload"); |
| 8209 | return { type: options.type, payload: options.payload }; |
| 8210 | }; |
| 8211 | const __wfRetentionOptions = (retention, what) => { |
| 8212 | if (retention === undefined) { |
| 8213 | return { |
| 8214 | successMs: __WF_RETENTION_MAX_MS, |
| 8215 | errorMs: __WF_RETENTION_MAX_MS, |
| 8216 | }; |
| 8217 | } |
| 8218 | if (!__wfOwnObject(retention)) { |
| 8219 | throw __wfError(`${what} option retention must be an object`); |
| 8220 | } |
| 8221 | const unknown = __wfUnknownKey(retention, ["successRetention", "errorRetention"]); |
| 8222 | if (unknown !== undefined) { |
| 8223 | throw __wfError( |
| 8224 | `${what} option retention has an unknown field ${JSON.stringify(unknown)}`, |
| 8225 | ); |
| 8226 | } |
| 8227 | return { |
| 8228 | successMs: retention.successRetention === undefined |
| 8229 | ? __WF_RETENTION_MAX_MS |
| 8230 | : __wfRetentionDuration( |
| 8231 | retention.successRetention, |
| 8232 | `${what} successRetention`, |
| 8233 | ), |
| 8234 | errorMs: retention.errorRetention === undefined |
| 8235 | ? __WF_RETENTION_MAX_MS |
| 8236 | : __wfRetentionDuration(retention.errorRetention, `${what} errorRetention`), |
| 8237 | }; |
| 8238 | }; |
| 8239 | const __wfLocationHint = (hint, what) => { |
| 8240 | if (hint !== undefined && !__WF_LOCATION_HINTS.has(hint)) { |
| 8241 | throw __wfError( |
| 8242 | `${what} has invalid locationHint ${JSON.stringify(hint)}`, |
| 8243 | ); |
| 8244 | } |
| 8245 | return hint; |
| 8246 | }; |
| 8247 | const __wfRestartOptions = (options) => { |
| 8248 | if (options === undefined) return {}; |
| 8249 | if (!__wfOwnObject(options)) { |
| 8250 | throw __wfError("restart() options must be an object"); |
| 8251 | } |
| 8252 | const unknown = __wfUnknownKey(options, ["from"]); |
| 8253 | if (unknown !== undefined) { |
| 8254 | throw __wfError(`restart() has an unknown option ${JSON.stringify(unknown)}`); |
| 8255 | } |
| 8256 | if (options.from === undefined) return {}; |
| 8257 | const from = options.from; |
| 8258 | if (!__wfOwnObject(from)) { |
| 8259 | throw __wfError("restart() option from must be an object"); |
| 8260 | } |
| 8261 | const fromUnknown = __wfUnknownKey(from, ["name", "count", "type"]); |
| 8262 | if (fromUnknown !== undefined) { |
| 8263 | throw __wfError( |
| 8264 | `restart() option from has an unknown field ${JSON.stringify(fromUnknown)}`, |
| 8265 | ); |
| 8266 | } |
| 8267 | __wfStepName(from.name); |
| 8268 | const count = from.count ?? 1; |
| 8269 | if (!Number.isInteger(count) || count < 1) { |
| 8270 | throw __wfError("restart() option from.count must be a positive integer"); |
| 8271 | } |
| 8272 | const type = from.type ?? "do"; |
| 8273 | if (!["do", "sleep", "waitForEvent"].includes(type)) { |
| 8274 | throw __wfError( |
| 8275 | 'restart() option from.type must be "do", "sleep", or "waitForEvent"', |
| 8276 | ); |
| 8277 | } |
| 8278 | return { from: { name: from.name, count, type } }; |
| 8279 | }; |
| 8280 | const __wfStepConfig = (config, name) => { |
| 8281 | if (!__wfOwnObject(config)) { |
| 8282 | throw __wfError(`invalid config for step ${JSON.stringify(name)}: use an object`); |
| 8283 | } |
| 8284 | let unknown = __wfUnknownKey(config, ["retries", "timeout", "sensitive"]); |
| 8285 | if (unknown !== undefined) { |
| 8286 | throw __wfError( |
| 8287 | `invalid config for step ${JSON.stringify(name)}: unknown option ` + |
| 8288 | JSON.stringify(unknown), |
| 8289 | ); |
| 8290 | } |
| 8291 | const retries = config.retries; |
| 8292 | if (retries !== undefined) { |
| 8293 | if (!__wfOwnObject(retries)) { |
| 8294 | throw __wfError(`invalid retries config for step ${JSON.stringify(name)}`); |
| 8295 | } |
| 8296 | unknown = __wfUnknownKey(retries, ["limit", "delay", "backoff"]); |
| 8297 | if (unknown !== undefined) { |
| 8298 | throw __wfError( |
| 8299 | `invalid retries config for step ${JSON.stringify(name)}: unknown option ` + |
| 8300 | JSON.stringify(unknown), |
| 8301 | ); |
| 8302 | } |
| 8303 | if ( |
| 8304 | typeof retries.limit !== "number" || !Number.isFinite(retries.limit) || |
| 8305 | retries.limit < 0 |
| 8306 | ) { |
| 8307 | throw __wfError( |
| 8308 | `invalid retries config for step ${JSON.stringify(name)}: ` + |
| 8309 | "limit must be a non-negative number", |
| 8310 | ); |
| 8311 | } |
| 8312 | if (retries.limit > __WF_RETRY_LIMIT_CAP) { |
| 8313 | throw __wfError( |
| 8314 | `invalid retries config for step ${JSON.stringify(name)}: limit is above ` + |
| 8315 | String(__WF_RETRY_LIMIT_CAP), |
| 8316 | ); |
| 8317 | } |
| 8318 | if (typeof retries.delay !== "function") { |
| 8319 | __wfDuration(retries.delay, `the retries config delay of step ${JSON.stringify(name)}`); |
| 8320 | } |
| 8321 | if ( |
| 8322 | retries.backoff !== undefined && |
| 8323 | !["constant", "linear", "exponential"].includes(retries.backoff) |
| 8324 | ) { |
| 8325 | throw __wfError( |
| 8326 | `invalid retries config for step ${JSON.stringify(name)}: ` + |
| 8327 | "backoff must be constant, linear, or exponential", |
| 8328 | ); |
| 8329 | } |
| 8330 | } |
| 8331 | if (config.timeout !== undefined) { |
| 8332 | const timeout = __wfDuration( |
| 8333 | config.timeout, |
| 8334 | `the config timeout of step ${JSON.stringify(name)}`, |
| 8335 | ); |
| 8336 | if (timeout === 0) { |
| 8337 | throw __wfError( |
| 8338 | `invalid config timeout for step ${JSON.stringify(name)}: use a value above zero`, |
| 8339 | ); |
| 8340 | } |
| 8341 | } |
| 8342 | if (config.sensitive !== undefined && config.sensitive !== "output") { |
| 8343 | throw __wfError( |
| 8344 | `invalid config sensitive value for step ${JSON.stringify(name)}: use "output"`, |
| 8345 | ); |
| 8346 | } |
| 8347 | return { |
| 8348 | ...config, |
| 8349 | ...(retries === undefined ? {} : { retries: { ...retries } }), |
| 8350 | }; |
| 8351 | }; |
| 8352 | // Serialization is checked with the same encoder storage and RPC use, so a |
| 8353 | // value that passes here cannot fail later at the isolate boundary. The |
| 8354 | // thrown errors are permanent: retrying cannot make a value cloneable or |
| 8355 | // shrink it. |
| 8356 | const __wfEncodeValue = (value, what) => { |
| 8357 | try { |
| 8358 | return __sc_encode(value); |
| 8359 | } catch (error) { |
| 8360 | const failure = __wfError( |
| 8361 | `${what} is not serializable: ${String(error && error.message || error)}. ` + |
| 8362 | "It must survive structured clone; a ReadableStream return is not implemented in celld.", |
| 8363 | ); |
| 8364 | failure.__wfPermanent = true; |
| 8365 | throw failure; |
| 8366 | } |
| 8367 | }; |
| 8368 | const __wfCheckEncodedValue = (bytes, what) => { |
| 8369 | if (bytes.byteLength > __WF_VALUE_CAP) { |
| 8370 | const failure = __wfError( |
| 8371 | `${what} is ${bytes.byteLength} bytes, above the 1 MiB limit; ` + |
| 8372 | "store large output externally and return a reference", |
| 8373 | ); |
| 8374 | failure.__wfPermanent = true; |
| 8375 | throw failure; |
| 8376 | } |
| 8377 | }; |
| 8378 | const __wfCheckValue = (value, what) => |
| 8379 | __wfCheckEncodedValue(__wfEncodeValue(value, what), what); |
| 8380 | const __wfErrorRecord = (error) => ({ |
| 8381 | name: String(error && error.name || "Error"), |
| 8382 | message: String(error && error.message || error), |
| 8383 | }); |
| 8384 | // A permanently failed step rejects on every replay, so user try/catch |
| 8385 | // around step.do keeps working after a resume, not only on the attempt that |
| 8386 | // failed live. |
| 8387 | const __wfReviveError = (record) => { |
| 8388 | const error = new Error(record.message); |
| 8389 | error.name = record.name; |
| 8390 | return error; |
| 8391 | }; |
| 8392 | const __wfLedgerPrefix = (generation) => `__wf.${generation}.`; |
| 8393 | const __wfEventPrefix = (generation) => |
| 8394 | __wfLedgerPrefix(generation) + "event."; |
| 8395 | const __wfEventKey = (generation, sequence) => |
| 8396 | __wfEventPrefix(generation) + String(sequence).padStart(9, "0"); |
| 8397 | const __wfRetentionMs = (meta, status) => |
| 8398 | status === "complete" |
| 8399 | ? (meta.retention?.successMs ?? __WF_RETENTION_MAX_MS) |
| 8400 | : (meta.retention?.errorMs ?? __WF_RETENTION_MAX_MS); |
| 8401 | const __wfFinishRetention = (meta, transaction) => { |
| 8402 | meta.endedMs = Date.now(); |
| 8403 | meta.expiresMs = meta.endedMs + __wfRetentionMs(meta, meta.status); |
| 8404 | transaction.setAlarm(meta.expiresMs); |
| 8405 | }; |
| 8406 | // A ledger record replays only through the kind of call that wrote it. A |
| 8407 | // `do` renamed into a `sleep`, or two calls reordered under one name, would |
| 8408 | // otherwise read fields the other kind never wrote and continue on |
| 8409 | // undefined -- a deadline of NaN, a value of nothing -- instead of failing. |
| 8410 | const __wfKindCheck = (record, kind, name) => { |
| 8411 | if (record === undefined || record.kind === kind) return record; |
| 8412 | const failure = __wfError( |
| 8413 | `step ${JSON.stringify(name)} replays as ${kind} but its ledger record ` + |
| 8414 | `was written by ${record.kind}; a step keeps one kind across replays`, |
| 8415 | ); |
| 8416 | failure.__wfPermanent = true; |
| 8417 | throw failure; |
| 8418 | }; |
| 8419 | // Each step callback runs under an async-context frame naming its step (the |
| 8420 | // same CPED-backed frame __ctxRun uses, so it survives the callback's |
| 8421 | // awaits). A step started inside another step's callback would wedge |
| 8422 | // quiescence: the outer callback cannot settle while it awaits the blocked |
| 8423 | // inner step, so `running` never reaches zero and the instance can neither |
| 8424 | // suspend nor finish. The frame is what lets the inner call refuse loudly |
| 8425 | // at the nesting site instead. |
| 8426 | const __wfStepKey = Symbol("celld.wfStep"); |
| 8427 | const __wfEnclosingStep = () => { |
| 8428 | const frame = __als_get(); |
| 8429 | return frame === undefined ? undefined : frame.get(__wfStepKey); |
| 8430 | }; |
| 8431 | const __wfEnterStep = (name, fn) => { |
| 8432 | const prior = __als_get(); |
| 8433 | const frame = new Map(prior); |
| 8434 | frame.set(__wfStepKey, name); |
| 8435 | __als_set(frame); |
| 8436 | try { |
| 8437 | return fn(); |
| 8438 | } finally { |
| 8439 | __als_set(prior); |
| 8440 | } |
| 8441 | }; |
| 8442 | |
| 8443 | // Race an attempt against its deadline. The abandoned callback keeps |
| 8444 | // running -- there is no cancellation to send it -- but its result is |
| 8445 | // discarded and the timeout counts as a failed attempt, as upstream. |
| 8446 | const __wfTimeout = (promise, ms, name, attempt) => |
| 8447 | new Promise((resolve, reject) => { |
| 8448 | const timer = setTimeout( |
| 8449 | () => |
| 8450 | reject(new Error( |
| 8451 | `step ${JSON.stringify(name)} timed out after ${ms} ms (attempt ${attempt})`, |
| 8452 | )), |
| 8453 | ms, |
| 8454 | ); |
| 8455 | promise.then( |
| 8456 | (value) => { clearTimeout(timer); resolve(value); }, |
| 8457 | (error) => { clearTimeout(timer); reject(error); }, |
| 8458 | ); |
| 8459 | }); |
| 8460 | |
| 8461 | // Storage failures belong to the engine even when workflow code catches the |
| 8462 | // rejected step promise. Record them outside the Error object, so user code |
| 8463 | // cannot suppress a retry or forge one by returning a marked exception. |
| 8464 | const __wfTrackStorageFailures = (storage, driver) => { |
| 8465 | const tracked = Object.create(storage); |
| 8466 | for (const name of ["get", "put", "transactionSync"]) { |
| 8467 | Object.defineProperty(tracked, name, { |
| 8468 | value(...args) { |
| 8469 | try { |
| 8470 | const result = storage[name](...args); |
| 8471 | if (result !== null && typeof result === "object" && |
| 8472 | typeof result.then === "function") { |
| 8473 | return result.catch((error) => { |
| 8474 | driver.storageFailure ??= error; |
| 8475 | throw error; |
| 8476 | }); |
| 8477 | } |
| 8478 | return result; |
| 8479 | } catch (error) { |
| 8480 | driver.storageFailure ??= error; |
| 8481 | throw error; |
| 8482 | } |
| 8483 | }, |
| 8484 | }); |
| 8485 | } |
| 8486 | return tracked; |
| 8487 | }; |
| 8488 | |
| 8489 | // The WorkflowStep the driver hands to run(). Each method resolves its step |
| 8490 | // record by (name, occurrence count) -- the count is assigned synchronously |
| 8491 | // at call time, so `Promise.all` of two same-named steps gets deterministic |
| 8492 | // distinct keys in call order, and a repeated name in a loop cannot collide. |
| 8493 | const __wfMakeStep = (driver) => { |
| 8494 | const storage = driver.storage; |
| 8495 | // The shared step frame. `body` resolves to {value} or {block: at, kind}; |
| 8496 | // a blocked step leaves its promise unsettled forever in this invocation. |
| 8497 | // The running counter covers the whole body, ledger reads included, so |
| 8498 | // quiescence cannot fire between a step's read and its decision. |
| 8499 | const frame = (name, body) => { |
| 8500 | // A stale replay -- one whose invocation already suspended -- can wake |
| 8501 | // later if user code raced a step against an un-stepped await. It goes |
| 8502 | // quiet instead of executing an attempt beside the fresh replay. |
| 8503 | if (driver.finished) return __wfNever; |
| 8504 | const enclosing = __wfEnclosingStep(); |
| 8505 | if (enclosing !== undefined) { |
| 8506 | const failure = __wfError( |
| 8507 | `step ${JSON.stringify(name)} cannot start inside the callback of ` + |
| 8508 | `step ${JSON.stringify(enclosing)}; a step callback must not use ` + |
| 8509 | "the step API", |
| 8510 | ); |
| 8511 | failure.__wfPermanent = true; |
| 8512 | return Promise.reject(failure); |
| 8513 | } |
| 8514 | const count = (driver.counts.get(name) ?? 0) + 1; |
| 8515 | driver.counts.set(name, count); |
| 8516 | const ordinal = ++driver.ordinal; |
| 8517 | const key = driver.ledgerPrefix + `step.${count}.${name}`; |
| 8518 | // Step activity restarts the stall clock: a pending grace timer was |
| 8519 | // armed against a run() that looked stuck, and this call is progress. |
| 8520 | driver.clearStall(); |
| 8521 | driver.running += 1; |
| 8522 | return new Promise((resolve, reject) => { |
| 8523 | (async () => { |
| 8524 | const meta = await storage.get("__wf.meta"); |
| 8525 | if ( |
| 8526 | meta === undefined || meta.generation !== driver.generation || |
| 8527 | __wfTerminal(meta.status) || meta.status === "paused" || |
| 8528 | meta.status === "waitingForPause" |
| 8529 | ) { |
| 8530 | return { pause: true }; |
| 8531 | } |
| 8532 | return await body(key, count, ordinal); |
| 8533 | })().then( |
| 8534 | (result) => { |
| 8535 | driver.running -= 1; |
| 8536 | driver.clearStall(); |
| 8537 | if (result.pause === true) { |
| 8538 | driver.pauseRequested = true; |
| 8539 | driver.check(); |
| 8540 | return; |
| 8541 | } |
| 8542 | if (result.block !== undefined) { |
| 8543 | if (!driver.finished) { |
| 8544 | driver.blocked.push({ at: result.block, kind: result.kind }); |
| 8545 | } |
| 8546 | driver.check(); |
| 8547 | return; |
| 8548 | } |
| 8549 | driver.check(); |
| 8550 | resolve(result.value); |
| 8551 | }, |
| 8552 | (error) => { |
| 8553 | driver.running -= 1; |
| 8554 | driver.clearStall(); |
| 8555 | driver.check(); |
| 8556 | reject(error); |
| 8557 | }, |
| 8558 | ); |
| 8559 | }); |
| 8560 | }; |
| 8561 | const doStep = (name, configOrCallback, callbackOrRollback, maybeRollback) => { |
| 8562 | const hasConfig = typeof configOrCallback !== "function"; |
| 8563 | let config = hasConfig ? (configOrCallback ?? {}) : {}; |
| 8564 | const callback = hasConfig ? callbackOrRollback : configOrCallback; |
| 8565 | const rollback = hasConfig ? maybeRollback : callbackOrRollback; |
| 8566 | try { |
| 8567 | __wfStepName(name); |
| 8568 | config = __wfStepConfig(config, name); |
| 8569 | } catch (error) { |
| 8570 | return Promise.reject(error); |
| 8571 | } |
| 8572 | if (rollback !== undefined) { |
| 8573 | return Promise.reject(__wfError( |
| 8574 | "step rollbackOptions are not implemented in celld; remove the rollback handler", |
| 8575 | )); |
| 8576 | } |
| 8577 | if (config.sensitive !== undefined) { |
| 8578 | return Promise.reject(__wfError( |
| 8579 | "sensitive step output is not implemented in celld; remove `sensitive`", |
| 8580 | )); |
| 8581 | } |
| 8582 | if (typeof callback !== "function") { |
| 8583 | return Promise.reject(__wfError("step.do needs a callback function")); |
| 8584 | } |
| 8585 | return frame(name, async (key, count, ordinal) => { |
| 8586 | const record = __wfKindCheck(await storage.get(key), "do", name); |
| 8587 | if (record !== undefined && record.status === "completed") { |
| 8588 | return { value: record.value }; |
| 8589 | } |
| 8590 | if (record !== undefined && record.status === "failed") { |
| 8591 | throw __wfReviveError(record.error); |
| 8592 | } |
| 8593 | // A pending retry whose backoff has not elapsed blocks without |
| 8594 | // executing; the deadline was persisted when the attempt failed, so a |
| 8595 | // replay cannot reset the backoff. |
| 8596 | if (record !== undefined && record.nextAt > Date.now()) { |
| 8597 | return { block: record.nextAt, kind: "retry" }; |
| 8598 | } |
| 8599 | const attempt = (record === undefined ? 0 : record.attempt) + 1; |
| 8600 | const historyOrdinal = record?.ordinal ?? ordinal; |
| 8601 | const retries = config.retries ?? |
| 8602 | { limit: 5, delay: 10000, backoff: "exponential" }; |
| 8603 | const timeout = config.timeout ?? "10 minutes"; |
| 8604 | const timeoutMs = __wfDuration( |
| 8605 | timeout, |
| 8606 | `the timeout of step ${JSON.stringify(name)}`, |
| 8607 | ); |
| 8608 | // Upstream omits a dynamic delay from the step context. Copying the |
| 8609 | // config verbatim would expose the callback to itself as retry policy, |
| 8610 | // while callers expect only the serializable limit and backoff fields. |
| 8611 | const contextRetries = typeof retries.delay === "function" |
| 8612 | ? { limit: retries.limit, ...(retries.backoff === undefined |
| 8613 | ? {} |
| 8614 | : { backoff: retries.backoff }) } |
| 8615 | : retries; |
| 8616 | const context = { |
| 8617 | step: { name, count }, |
| 8618 | attempt, |
| 8619 | config: { retries: contextRetries, timeout }, |
| 8620 | }; |
| 8621 | try { |
| 8622 | // Persist the history entry before the callback starts. A concurrent |
| 8623 | // selected restart can therefore name an in-flight occurrence, and |
| 8624 | // its new generation fences the callback's eventual old-ledger write. |
| 8625 | await storage.put(key, { |
| 8626 | kind: "do", |
| 8627 | status: "running", |
| 8628 | attempt: attempt - 1, |
| 8629 | ordinal: historyOrdinal, |
| 8630 | }); |
| 8631 | const value = await __wfTimeout( |
| 8632 | __wfEnterStep(name, async () => callback(context)), |
| 8633 | timeoutMs, |
| 8634 | name, |
| 8635 | attempt, |
| 8636 | ); |
| 8637 | if (value !== undefined) { |
| 8638 | __wfCheckValue(value, `the return value of step ${JSON.stringify(name)}`); |
| 8639 | } |
| 8640 | await storage.put(key, { |
| 8641 | kind: "do", |
| 8642 | status: "completed", |
| 8643 | value, |
| 8644 | ordinal: historyOrdinal, |
| 8645 | }); |
| 8646 | return { value }; |
| 8647 | } catch (error) { |
| 8648 | // NonRetryableError skips retries by contract; a value-cap or |
| 8649 | // serialization failure is marked permanent above because another |
| 8650 | // attempt returns the same value. |
| 8651 | const permanent = error instanceof NonRetryableError || |
| 8652 | (error !== null && typeof error === "object" && |
| 8653 | (error.name === "NonRetryableError" || error.__wfPermanent === true)) || |
| 8654 | attempt > retries.limit; |
| 8655 | if (permanent) { |
| 8656 | await storage.put(key, { |
| 8657 | kind: "do", |
| 8658 | status: "failed", |
| 8659 | error: __wfErrorRecord(error), |
| 8660 | ordinal: historyOrdinal, |
| 8661 | }); |
| 8662 | throw error; |
| 8663 | } |
| 8664 | // Upstream documents the backoff names, not the arithmetic; the |
| 8665 | // simplest reading is used and recorded in the design page. When |
| 8666 | // `retries` is given without `backoff`, celld uses constant -- the |
| 8667 | // documented exponential default is the whole-config-omitted case. |
| 8668 | const dynamic = typeof retries.delay === "function"; |
| 8669 | const delay = dynamic |
| 8670 | ? await __wfEnterStep(name, () => retries.delay({ ctx: context, error })) |
| 8671 | : retries.delay; |
| 8672 | const base = __wfDuration( |
| 8673 | delay, |
| 8674 | `the retry delay of step ${JSON.stringify(name)}`, |
| 8675 | ); |
| 8676 | // A delay callback replaces the fixed base duration, not the backoff |
| 8677 | // policy. Skipping this factor makes a dynamic exponential or linear |
| 8678 | // policy retry earlier than the same policy with a fixed base. |
| 8679 | const factor = retries.backoff === "exponential" |
| 8680 | ? 2 ** (attempt - 1) |
| 8681 | : retries.backoff === "linear" |
| 8682 | ? attempt |
| 8683 | : 1; |
| 8684 | const nextAt = Date.now() + base * factor; |
| 8685 | await storage.put(key, { |
| 8686 | kind: "do", |
| 8687 | status: "retrying", |
| 8688 | attempt, |
| 8689 | nextAt, |
| 8690 | ordinal: historyOrdinal, |
| 8691 | }); |
| 8692 | return { block: nextAt, kind: "retry" }; |
| 8693 | } |
| 8694 | }); |
| 8695 | }; |
| 8696 | const sleepUntilDeadline = (name, key, ordinal, deadline) => (async () => { |
| 8697 | const record = __wfKindCheck(await storage.get(key), "sleep", name); |
| 8698 | if (record !== undefined && record.status === "completed") { |
| 8699 | return { value: undefined }; |
| 8700 | } |
| 8701 | const historyOrdinal = record?.ordinal ?? ordinal; |
| 8702 | let at = record === undefined ? undefined : record.deadline; |
| 8703 | if (at === undefined) { |
| 8704 | // The absolute deadline is computed once and persisted. Recomputing |
| 8705 | // from "now" on replay would extend the sleep by however long the |
| 8706 | // instance was down, so a crash could postpone a deadline forever. |
| 8707 | at = deadline(); |
| 8708 | if (at - Date.now() > __WF_MAX_WAIT_MS) { |
| 8709 | throw __wfError( |
| 8710 | `sleep ${JSON.stringify(name)} ends ${at - Date.now()} ms from now, ` + |
| 8711 | "above the upstream limit of 365 days", |
| 8712 | ); |
| 8713 | } |
| 8714 | await storage.put(key, { |
| 8715 | kind: "sleep", |
| 8716 | status: "sleeping", |
| 8717 | deadline: at, |
| 8718 | ordinal: historyOrdinal, |
| 8719 | }); |
| 8720 | } |
| 8721 | if (at <= Date.now()) { |
| 8722 | await storage.put(key, { |
| 8723 | kind: "sleep", |
| 8724 | status: "completed", |
| 8725 | ordinal: historyOrdinal, |
| 8726 | }); |
| 8727 | return { value: undefined }; |
| 8728 | } |
| 8729 | return { block: at, kind: "sleep" }; |
| 8730 | })(); |
| 8731 | return { |
| 8732 | do: doStep, |
| 8733 | sleep: (name, duration) => { |
| 8734 | let durationMs; |
| 8735 | try { |
| 8736 | __wfStepName(name); |
| 8737 | durationMs = __wfSleepDuration(duration, name); |
| 8738 | } catch (error) { |
| 8739 | return Promise.reject(error); |
| 8740 | } |
| 8741 | return frame(name, (key, _count, ordinal) => |
| 8742 | sleepUntilDeadline( |
| 8743 | name, |
| 8744 | key, |
| 8745 | ordinal, |
| 8746 | () => Date.now() + durationMs, |
| 8747 | )); |
| 8748 | }, |
| 8749 | sleepUntil: (name, timestamp) => { |
| 8750 | let at; |
| 8751 | try { |
| 8752 | __wfStepName(name); |
| 8753 | at = __wfSleepUntil(timestamp, name); |
| 8754 | } catch (error) { |
| 8755 | return Promise.reject(error); |
| 8756 | } |
| 8757 | return frame(name, (key, _count, ordinal) => |
| 8758 | sleepUntilDeadline(name, key, ordinal, () => { |
| 8759 | // A replay uses the persisted deadline after it has passed. Check |
| 8760 | // the moving future bound only while the deadline is first installed, |
| 8761 | // or every successful sleep would fail on the resume that completes it. |
| 8762 | if (at - Date.now() < 0) { |
| 8763 | throw __wfError( |
| 8764 | `sleepUntil ${JSON.stringify(name)} needs a future timestamp`, |
| 8765 | ); |
| 8766 | } |
| 8767 | return at; |
| 8768 | })); |
| 8769 | }, |
| 8770 | waitForEvent: (name, options) => { |
| 8771 | let checked; |
| 8772 | try { |
| 8773 | __wfStepName(name); |
| 8774 | checked = __wfWaitOptions(options, name); |
| 8775 | } catch (error) { |
| 8776 | return Promise.reject(error); |
| 8777 | } |
| 8778 | return frame(name, async (key, _count, ordinal) => { |
| 8779 | let record = __wfKindCheck(await storage.get(key), "event", name); |
| 8780 | if (record !== undefined && record.status === "completed") { |
| 8781 | return { value: record.value }; |
| 8782 | } |
| 8783 | if (record !== undefined && record.status === "failed") { |
| 8784 | throw __wfReviveError(record.error); |
| 8785 | } |
| 8786 | if (record === undefined) { |
| 8787 | record = { |
| 8788 | kind: "event", |
| 8789 | status: "waiting", |
| 8790 | type: checked.type, |
| 8791 | deadline: Date.now() + checked.timeoutMs, |
| 8792 | ordinal, |
| 8793 | }; |
| 8794 | await storage.put(key, record); |
| 8795 | } |
| 8796 | // The deadline is checked before the buffer: an event that arrived |
| 8797 | // after the persisted deadline must time the step out, not succeed |
| 8798 | // because the replay that noticed it ran late. |
| 8799 | if (record.deadline <= Date.now()) { |
| 8800 | const error = new Error( |
| 8801 | `waitForEvent ${JSON.stringify(name)} timed out waiting for an event ` + |
| 8802 | `of type ${JSON.stringify(record.type)}`, |
| 8803 | ); |
| 8804 | await storage.put(key, { |
| 8805 | kind: "event", |
| 8806 | status: "failed", |
| 8807 | error: __wfErrorRecord(error), |
| 8808 | ordinal: record.ordinal, |
| 8809 | }); |
| 8810 | throw error; |
| 8811 | } |
| 8812 | // Delivered events persist until a matching step consumes one, in |
| 8813 | // arrival order -- the zero-padded sequence key makes list order |
| 8814 | // arrival order -- so an event sent before the step is reached is |
| 8815 | // buffered, not lost. |
| 8816 | const consumed = storage.transactionSync(() => { |
| 8817 | const current = __wfKindCheck(storage.kv.get(key), "event", name); |
| 8818 | if (current !== undefined && current.status === "completed") { |
| 8819 | return { value: current.value }; |
| 8820 | } |
| 8821 | if (current !== undefined && current.status === "failed") { |
| 8822 | throw __wfReviveError(current.error); |
| 8823 | } |
| 8824 | for (const [eventKey, event] of storage.kv.list({ |
| 8825 | prefix: __wfEventPrefix(driver.generation), |
| 8826 | })) { |
| 8827 | if (event.type !== current.type) continue; |
| 8828 | const value = { |
| 8829 | payload: event.payload, |
| 8830 | timestamp: new Date(event.timestampMs), |
| 8831 | type: event.type, |
| 8832 | }; |
| 8833 | // The delete and completed ledger record are one SQLite commit. |
| 8834 | // A crash can therefore expose both or neither, so an |
| 8835 | // acknowledged event cannot disappear between them. |
| 8836 | storage.kv.delete(eventKey); |
| 8837 | /*__CELLD_TEST_WORKFLOW_EVENT_CONSUMED__*/ |
| 8838 | storage.kv.put(key, { |
| 8839 | kind: "event", |
| 8840 | status: "completed", |
| 8841 | value, |
| 8842 | ordinal: current.ordinal, |
| 8843 | }); |
| 8844 | return { value }; |
| 8845 | } |
| 8846 | }); |
| 8847 | if (consumed !== undefined) return consumed; |
| 8848 | return { block: record.deadline, kind: "event" }; |
| 8849 | }); |
| 8850 | }, |
| 8851 | }; |
| 8852 | }; |
| 8853 | |
| 8854 | const __WorkflowCell = (() => { |
| 8855 | class StorageTransaction { |
| 8856 | constructor(storage) { |
| 8857 | this.kv = storage.kv; |
| 8858 | this._scope = storage._scope; |
| 8859 | } |
| 8860 | setAlarm(t) { |
| 8861 | __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); |
| 8862 | } |
| 8863 | deleteAlarm() { |
| 8864 | __alarm_delete(this._scope); |
| 8865 | } |
| 8866 | } |
| 8867 | const transactionSync = (storage, callback) => |
| 8868 | storage.transactionSync(() => callback(new StorageTransaction(storage))); |
| 8869 | const clearInstance = (transaction) => { |
| 8870 | for (const [key] of transaction.kv.list({ prefix: "__wf." })) { |
| 8871 | transaction.kv.delete(key); |
| 8872 | } |
| 8873 | transaction.deleteAlarm(); |
| 8874 | }; |
| 8875 | const expireTerminal = (transaction, meta, now) => { |
| 8876 | if (!__wfTerminal(meta.status)) return false; |
| 8877 | if (meta.expiresMs === undefined) { |
| 8878 | meta.endedMs = now; |
| 8879 | meta.expiresMs = now + __wfRetentionMs(meta, meta.status); |
| 8880 | transaction.kv.put("__wf.meta", meta); |
| 8881 | } |
| 8882 | if (meta.expiresMs > now) return false; |
| 8883 | clearInstance(transaction); |
| 8884 | return true; |
| 8885 | }; |
| 8886 | |
| 8887 | // The adapter stays in this closure because Workflow needs synchronous |
| 8888 | // alarm writes inside transactionSync(). The public async alarm API runs |
| 8889 | // after that commit, while a global helper would let application code |
| 8890 | // split metadata from its wake or invoke the raw operation after commit. |
| 8891 | return class __WorkflowCell { |
| 8892 | constructor(state) { |
| 8893 | this._state = state; |
| 8894 | } |
| 8895 | async __wfCreate({ |
| 8896 | workflowName, |
| 8897 | instanceId, |
| 8898 | params, |
| 8899 | retention, |
| 8900 | locationHint, |
| 8901 | skipExisting = false, |
| 8902 | }) { |
| 8903 | const storage = this._state.storage; |
| 8904 | if (params !== undefined) __wfCheckValue(params, "the workflow params"); |
| 8905 | const result = transactionSync(storage, (transaction) => { |
| 8906 | let meta = transaction.kv.get("__wf.meta"); |
| 8907 | if (meta !== undefined && expireTerminal(transaction, meta, Date.now())) { |
| 8908 | meta = undefined; |
| 8909 | } |
| 8910 | if (meta !== undefined && skipExisting) return { id: instanceId, created: false }; |
| 8911 | if (meta !== undefined) { |
| 8912 | throw __wfError( |
| 8913 | `instance ${JSON.stringify(instanceId)} already exists with status ` + |
| 8914 | JSON.stringify(meta.status), |
| 8915 | ); |
| 8916 | } |
| 8917 | const generation = crypto.randomUUID(); |
| 8918 | transaction.kv.put("__wf.meta", { |
| 8919 | workflowName, |
| 8920 | instanceId, |
| 8921 | params, |
| 8922 | retention, |
| 8923 | ...(locationHint === undefined ? {} : { locationHint }), |
| 8924 | generation, |
| 8925 | createdMs: Date.now(), |
| 8926 | status: "queued", |
| 8927 | }); |
| 8928 | // The metadata and alarm are one SQLite commit. A committed creation |
| 8929 | // therefore always has the wake that can start or recover its drive. |
| 8930 | transaction.setAlarm(Date.now()); |
| 8931 | /*__CELLD_TEST_WORKFLOW_META_CREATED__*/ |
| 8932 | return { id: instanceId, created: true }; |
| 8933 | }); |
| 8934 | return result; |
| 8935 | } |
| 8936 | async __wfStatus() { |
| 8937 | const meta = transactionSync(this._state.storage, (transaction) => { |
| 8938 | const current = transaction.kv.get("__wf.meta"); |
| 8939 | if (current === undefined) return undefined; |
| 8940 | return expireTerminal(transaction, current, Date.now()) ? undefined : current; |
| 8941 | }); |
| 8942 | // A cell exists on first address like any cell, so an absent ledger is |
| 8943 | // the only honest "no such instance" signal. Inventing an instance here |
| 8944 | // would turn every typo into an empty workflow. |
| 8945 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8946 | const status = { status: meta.status, rollback: null }; |
| 8947 | if (meta.error !== undefined) status.error = meta.error; |
| 8948 | if (meta.output !== undefined) status.output = meta.output; |
| 8949 | return status; |
| 8950 | } |
| 8951 | async __wfDelete() { |
| 8952 | const storage = this._state.storage; |
| 8953 | const deleted = transactionSync(storage, (transaction) => { |
| 8954 | const meta = transaction.kv.get("__wf.meta"); |
| 8955 | if (meta === undefined) return false; |
| 8956 | if (expireTerminal(transaction, meta, Date.now())) return false; |
| 8957 | clearInstance(transaction); |
| 8958 | return true; |
| 8959 | }); |
| 8960 | // Throw after the transaction commits. An expiry discovered here must |
| 8961 | // keep its cleanup even though delete() reports that the instance is gone. |
| 8962 | if (!deleted) throw __wfError("instance does not exist"); |
| 8963 | // A callback can still be awaiting application I/O when deletion lands. |
| 8964 | // Reset the object after the deletion commit so that callback cannot |
| 8965 | // recreate an old-generation ledger entry after delete() reports success. |
| 8966 | this._state.abort(new Error("WORKFLOW_INSTANCE_DELETED")); |
| 8967 | } |
| 8968 | async __wfPause() { |
| 8969 | const storage = this._state.storage; |
| 8970 | transactionSync(storage, (transaction) => { |
| 8971 | const meta = transaction.kv.get("__wf.meta"); |
| 8972 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8973 | if (__wfTerminal(meta.status) || meta.status === "paused" || |
| 8974 | meta.status === "waitingForPause") return; |
| 8975 | if (meta.status === "running") { |
| 8976 | meta.status = "waitingForPause"; |
| 8977 | // A drive lost after this commit must re-enter and finish the pause. |
| 8978 | transaction.setAlarm(Date.now()); |
| 8979 | } else { |
| 8980 | meta.status = "paused"; |
| 8981 | meta.pausedMs = Date.now(); |
| 8982 | transaction.deleteAlarm(); |
| 8983 | } |
| 8984 | transaction.kv.put("__wf.meta", meta); |
| 8985 | }); |
| 8986 | } |
| 8987 | async __wfResume() { |
| 8988 | const storage = this._state.storage; |
| 8989 | transactionSync(storage, (transaction) => { |
| 8990 | const meta = transaction.kv.get("__wf.meta"); |
| 8991 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8992 | if (meta.status === "waitingForPause") { |
| 8993 | meta.status = "running"; |
| 8994 | transaction.kv.put("__wf.meta", meta); |
| 8995 | transaction.setAlarm(Date.now()); |
| 8996 | return; |
| 8997 | } |
| 8998 | if (meta.status !== "paused") { |
| 8999 | throw __wfError( |
| 9000 | `cannot resume an instance with status ${JSON.stringify(meta.status)}`, |
| 9001 | ); |
| 9002 | } |
| 9003 | const offset = Math.max(0, Date.now() - (meta.pausedMs ?? Date.now())); |
| 9004 | for (const [key, record] of transaction.kv.list({ |
| 9005 | prefix: __wfLedgerPrefix(meta.generation) + "step.", |
| 9006 | })) { |
| 9007 | if (record.status === "retrying") record.nextAt += offset; |
| 9008 | if (record.status === "sleeping" || record.status === "waiting") { |
| 9009 | record.deadline += offset; |
| 9010 | } |
| 9011 | transaction.kv.put(key, record); |
| 9012 | } |
| 9013 | delete meta.pausedMs; |
| 9014 | meta.status = "queued"; |
| 9015 | transaction.kv.put("__wf.meta", meta); |
| 9016 | transaction.setAlarm(Date.now()); |
| 9017 | }); |
| 9018 | } |
| 9019 | async __wfRestart(options) { |
| 9020 | const checked = __wfRestartOptions(options); |
| 9021 | const storage = this._state.storage; |
| 9022 | transactionSync(storage, (transaction) => { |
| 9023 | const meta = transaction.kv.get("__wf.meta"); |
| 9024 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 9025 | const oldPrefix = __wfLedgerPrefix(meta.generation); |
| 9026 | let targetOrdinal; |
| 9027 | if (checked.from !== undefined) { |
| 9028 | const expectedKind = checked.from.type === "waitForEvent" |
| 9029 | ? "event" |
| 9030 | : checked.from.type; |
| 9031 | let occurrence = 0; |
| 9032 | const history = [...transaction.kv.list({ prefix: oldPrefix + "step." })] |
| 9033 | .filter(([, record]) => Number.isInteger(record.ordinal)) |
| 9034 | .sort((left, right) => left[1].ordinal - right[1].ordinal); |
| 9035 | // The ledger key is `<prefix>step.<per-name-count>.<name>`. Derive |
| 9036 | // the name from it because a record stores replay state, not identity. |
| 9037 | for (const [key, record] of history) { |
| 9038 | const marker = oldPrefix + "step."; |
| 9039 | const suffix = key.slice(marker.length); |
| 9040 | const dot = suffix.indexOf("."); |
| 9041 | const name = dot < 0 ? "" : suffix.slice(dot + 1); |
| 9042 | if (record.kind !== expectedKind || name !== checked.from.name) continue; |
| 9043 | occurrence += 1; |
| 9044 | if (occurrence === checked.from.count) { |
| 9045 | targetOrdinal = record.ordinal; |
| 9046 | break; |
| 9047 | } |
| 9048 | } |
| 9049 | if (targetOrdinal === undefined) { |
| 9050 | throw __wfError( |
| 9051 | `restart() could not find ${checked.from.type} step ` + |
| 9052 | `${JSON.stringify(checked.from.name)} occurrence ${checked.from.count}`, |
| 9053 | ); |
| 9054 | } |
| 9055 | } |
| 9056 | const generation = crypto.randomUUID(); |
| 9057 | const newPrefix = __wfLedgerPrefix(generation); |
| 9058 | if (targetOrdinal !== undefined) { |
| 9059 | for (const [key, record] of transaction.kv.list({ prefix: oldPrefix + "step." })) { |
| 9060 | if (Number.isInteger(record.ordinal) && record.ordinal < targetOrdinal) { |
| 9061 | transaction.kv.put(newPrefix + key.slice(oldPrefix.length), record); |
| 9062 | } |
| 9063 | } |
| 9064 | } |
| 9065 | for (const [key] of transaction.kv.list({ prefix: oldPrefix })) { |
| 9066 | transaction.kv.delete(key); |
| 9067 | } |
| 9068 | meta.generation = generation; |
| 9069 | meta.status = "queued"; |
| 9070 | delete meta.pausedMs; |
| 9071 | delete meta.output; |
| 9072 | delete meta.error; |
| 9073 | transaction.kv.put("__wf.meta", meta); |
| 9074 | transaction.setAlarm(Date.now()); |
| 9075 | }); |
| 9076 | } |
| 9077 | async __wfTerminate() { |
| 9078 | const storage = this._state.storage; |
| 9079 | transactionSync(storage, (transaction) => { |
| 9080 | const meta = transaction.kv.get("__wf.meta"); |
| 9081 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 9082 | if (__wfTerminal(meta.status)) { |
| 9083 | throw __wfError( |
| 9084 | `cannot terminate an instance with status ${JSON.stringify(meta.status)}`, |
| 9085 | ); |
| 9086 | } |
| 9087 | meta.status = "terminated"; |
| 9088 | __wfFinishRetention(meta, transaction); |
| 9089 | transaction.kv.put("__wf.meta", meta); |
| 9090 | /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ |
| 9091 | }); |
| 9092 | } |
| 9093 | async __wfSendEvent(options) { |
| 9094 | const storage = this._state.storage; |
| 9095 | // The binding validates first to avoid an unnecessary cell call. Repeat |
| 9096 | // the check here because this RPC owns the durable event invariant: no |
| 9097 | // current or future internal caller can bypass validation before storage. |
| 9098 | const { type, payload } = __wfEventOptions(options); |
| 9099 | transactionSync(storage, (transaction) => { |
| 9100 | const meta = transaction.kv.get("__wf.meta"); |
| 9101 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 9102 | if (__wfTerminal(meta.status)) { |
| 9103 | throw __wfError( |
| 9104 | `cannot send an event to an instance with status ${JSON.stringify(meta.status)}`, |
| 9105 | ); |
| 9106 | } |
| 9107 | const sequenceKey = __wfLedgerPrefix(meta.generation) + "eventSeq"; |
| 9108 | const sequence = transaction.kv.get(sequenceKey) ?? 0; |
| 9109 | transaction.kv.put(sequenceKey, sequence + 1); |
| 9110 | transaction.kv.put(__wfEventKey(meta.generation, sequence), { |
| 9111 | type, |
| 9112 | payload, |
| 9113 | timestampMs: Date.now(), |
| 9114 | }); |
| 9115 | // Allocation, the event body, and the nudge are one commit. Parallel |
| 9116 | // writers cannot reuse a sequence and a crash cannot expose a partial |
| 9117 | // acknowledged send. |
| 9118 | if (meta.status !== "paused" && meta.status !== "waitingForPause") { |
| 9119 | transaction.setAlarm(Date.now()); |
| 9120 | } |
| 9121 | }); |
| 9122 | } |
| 9123 | async alarm() { |
| 9124 | const storage = this._state.storage; |
| 9125 | // One drive at a time. A sendEvent nudge (setAlarm(now)) landing |
| 9126 | // mid-fire replaces the firing alarm in the core, and the replacement |
| 9127 | // can dispatch a second alarm() into this isolate while the first drive |
| 9128 | // still awaits user code. Two concurrent replays would both see the |
| 9129 | // same incomplete steps and double-execute their callbacks. The guard |
| 9130 | // is isolate-local and that is sufficient: every drive for a cell runs |
| 9131 | // in its owner's isolate, and a takeover starts a fresh isolate with no |
| 9132 | // drive in flight. The nudge is not lost -- the in-flight drive folds |
| 9133 | // `_wfNudge` into the minimum it re-arms, and if it suspended before |
| 9134 | // seeing the flag, the re-arm below starts a fresh drive immediately. |
| 9135 | // A failed drive is not re-raised here: the engine already retries the |
| 9136 | // alarm that fired it. |
| 9137 | if (this._wfDriving !== undefined) { |
| 9138 | this._wfNudge = Date.now(); |
| 9139 | await this._wfDriving.catch(() => {}); |
| 9140 | if (this._wfNudge !== undefined) { |
| 9141 | this._wfNudge = undefined; |
| 9142 | const meta = await storage.get("__wf.meta"); |
| 9143 | if ( |
| 9144 | meta !== undefined && !__wfTerminal(meta.status) && |
| 9145 | meta.status !== "paused" && meta.status !== "waitingForPause" |
| 9146 | ) { |
| 9147 | await storage.setAlarm(Date.now()); |
| 9148 | } |
| 9149 | } |
| 9150 | return; |
| 9151 | } |
| 9152 | const meta = await storage.get("__wf.meta"); |
| 9153 | // A terminal instance's pending alarm can still fire. It owns retention: |
| 9154 | // remove expired state, or restore the expiry wake after a stale nudge. |
| 9155 | if (meta === undefined) { |
| 9156 | await storage.deleteAlarm(); |
| 9157 | return; |
| 9158 | } |
| 9159 | if (__wfTerminal(meta.status)) { |
| 9160 | transactionSync(storage, (transaction) => { |
| 9161 | const current = transaction.kv.get("__wf.meta"); |
| 9162 | if (current === undefined) { |
| 9163 | transaction.deleteAlarm(); |
| 9164 | return; |
| 9165 | } |
| 9166 | if (!expireTerminal(transaction, current, Date.now())) { |
| 9167 | transaction.setAlarm(current.expiresMs); |
| 9168 | } |
| 9169 | }); |
| 9170 | return; |
| 9171 | } |
| 9172 | if (meta.status === "paused") { |
| 9173 | await storage.deleteAlarm(); |
| 9174 | return; |
| 9175 | } |
| 9176 | if (meta.status === "waitingForPause") { |
| 9177 | transactionSync(storage, (transaction) => { |
| 9178 | const current = transaction.kv.get("__wf.meta"); |
| 9179 | if (current === undefined || current.generation !== meta.generation || |
| 9180 | current.status !== "waitingForPause") return; |
| 9181 | current.status = "paused"; |
| 9182 | current.pausedMs = Date.now(); |
| 9183 | transaction.kv.put("__wf.meta", current); |
| 9184 | transaction.deleteAlarm(); |
| 9185 | }); |
| 9186 | return; |
| 9187 | } |
| 9188 | // The fired alarm stays armed while the drive runs. The engine consumes |
| 9189 | // it only when this handler returns cleanly, and retries it when the |
| 9190 | // handler fails -- that retry is the crash safety net. Deleting it here |
| 9191 | // would commit the deletion durably mid-drive (durability is per SQLite |
| 9192 | // commit, and replication ships frames per commit), so a SIGKILL before |
| 9193 | // the suspend-time re-arm would strand a "running" instance with no |
| 9194 | // alarm and no wake entry. The suspend path re-arms explicitly, and a |
| 9195 | // terminal drive deletes. |
| 9196 | const driving = this._drive(meta); |
| 9197 | this._wfDriving = driving; |
| 9198 | try { |
| 9199 | await driving; |
| 9200 | } finally { |
| 9201 | this._wfDriving = undefined; |
| 9202 | } |
| 9203 | } |
| 9204 | async _drive(meta) { |
| 9205 | const storage = this._state.storage; |
| 9206 | // The drive owns `status`, `output`, and `error`; every other piece of |
| 9207 | // instance state belongs to the RPCs (sendEvent's sequence lives in its |
| 9208 | // own key for the same reason). The gate is open at every await, so a |
| 9209 | // terminate can land mid-drive: re-reading before each write, and |
| 9210 | // writing nothing once the status is terminal, is what makes "terminate |
| 9211 | // wins the race" true rather than asserted. Writing back the meta this |
| 9212 | // drive entered with would resurrect a terminated instance as "waiting" |
| 9213 | // and re-arm the alarm its terminate deleted. |
| 9214 | const settle = (mutate) => transactionSync(storage, (transaction) => { |
| 9215 | const current = transaction.kv.get("__wf.meta"); |
| 9216 | if (current === undefined || __wfTerminal(current.status) || |
| 9217 | current.generation !== meta.generation) return false; |
| 9218 | mutate(current, transaction); |
| 9219 | transaction.kv.put("__wf.meta", current); |
| 9220 | return true; |
| 9221 | }); |
| 9222 | const className = __cell.workflows[meta.workflowName]; |
| 9223 | const cls = className === undefined ? undefined : __cf.exports[className]; |
| 9224 | if (typeof cls !== "function" || |
| 9225 | typeof (cls.prototype && cls.prototype.run) !== "function") { |
| 9226 | // Deploy cannot see inside the bundle, so a missing export fails |
| 9227 | // here, loudly, with the class and the config key named. |
| 9228 | settle((current, transaction) => { |
| 9229 | current.status = "errored"; |
| 9230 | current.error = { |
| 9231 | name: "Error", |
| 9232 | message: className === undefined |
| 9233 | ? `workflow ${JSON.stringify(meta.workflowName)} is not declared ` + |
| 9234 | "in this deployment's `workflows`" |
| 9235 | : `workflow class ${JSON.stringify(className)} is not a module ` + |
| 9236 | "export with a run() method; export it and extend " + |
| 9237 | "WorkflowEntrypoint", |
| 9238 | }; |
| 9239 | __wfFinishRetention(current, transaction); |
| 9240 | /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ |
| 9241 | }); |
| 9242 | return; |
| 9243 | } |
| 9244 | const driver = { |
| 9245 | storage: undefined, |
| 9246 | storageFailure: undefined, |
| 9247 | generation: meta.generation, |
| 9248 | ledgerPrefix: __wfLedgerPrefix(meta.generation), |
| 9249 | counts: new Map(), |
| 9250 | ordinal: 0, |
| 9251 | running: 0, |
| 9252 | blocked: [], |
| 9253 | pauseRequested: false, |
| 9254 | finished: false, |
| 9255 | checkQueued: false, |
| 9256 | stallTimer: undefined, |
| 9257 | clearStall() { |
| 9258 | if (this.stallTimer !== undefined) { |
| 9259 | clearTimeout(this.stallTimer); |
| 9260 | this.stallTimer = undefined; |
| 9261 | } |
| 9262 | }, |
| 9263 | }; |
| 9264 | driver.storage = __wfTrackStorageFailures(storage, driver); |
| 9265 | const outcome = new Promise((resolve) => { |
| 9266 | driver.finish = (result) => { |
| 9267 | if (driver.finished) return; |
| 9268 | driver.finished = true; |
| 9269 | driver.clearStall(); |
| 9270 | resolve(result); |
| 9271 | }; |
| 9272 | }); |
| 9273 | // Quiescence: when a step is blocked, no step callback is executing, |
| 9274 | // and a macrotask has passed, nothing can progress, so the invocation |
| 9275 | // suspends. The macrotask lets every microtask chain a completed step |
| 9276 | // unblocked drain first; checking on the spot would suspend an instance |
| 9277 | // whose next step is one `await` away from starting. |
| 9278 | driver.check = () => { |
| 9279 | if (driver.checkQueued || driver.finished) return; |
| 9280 | driver.checkQueued = true; |
| 9281 | setTimeout(() => { |
| 9282 | driver.checkQueued = false; |
| 9283 | if (driver.finished || driver.running !== 0) return; |
| 9284 | if (driver.pauseRequested) { |
| 9285 | driver.finish({ kind: "pause" }); |
| 9286 | return; |
| 9287 | } |
| 9288 | if (driver.blocked.length > 0) { |
| 9289 | driver.finish({ kind: "suspend" }); |
| 9290 | return; |
| 9291 | } |
| 9292 | // No step runs, none is blocked, and run() has not settled: it |
| 9293 | // awaits something that is not a step. Upstream permits that -- an |
| 9294 | // un-stepped `await fetch()` between steps is legal, merely |
| 9295 | // non-durable -- so this is not yet an error; but a promise that |
| 9296 | // never settles would wedge the alarm handler in silence, with the |
| 9297 | // instance "running" forever. A grace timer splits the two: if the |
| 9298 | // same nothing-can-progress state still holds when it fires, the |
| 9299 | // instance fails loudly. The timer is a plain in-isolate timeout, |
| 9300 | // not a durable alarm, on purpose: an eviction or a restart replays |
| 9301 | // run() from the top anyway, so losing the timer loses nothing -- |
| 9302 | // the replay re-enters the same stall and re-arms its own grace. |
| 9303 | if (driver.stallTimer !== undefined) return; |
| 9304 | driver.stallTimer = setTimeout(() => { |
| 9305 | driver.stallTimer = undefined; |
| 9306 | if (driver.finished || driver.running !== 0 || driver.blocked.length > 0) { |
| 9307 | return; |
| 9308 | } |
| 9309 | driver.finish({ |
| 9310 | kind: "error", |
| 9311 | error: __wfError( |
| 9312 | "run() has been awaiting something that is not a step for " + |
| 9313 | (__WF_STALL_GRACE_MS / 1000) + " seconds while no step is " + |
| 9314 | "running or blocked; a replay cannot resume this wait, so " + |
| 9315 | "wrap long async work in step.do", |
| 9316 | ), |
| 9317 | }); |
| 9318 | }, __WF_STALL_GRACE_MS); |
| 9319 | }, 0); |
| 9320 | }; |
| 9321 | if ( |
| 9322 | meta.status !== "running" && |
| 9323 | !(await settle((current) => { |
| 9324 | current.status = "running"; |
| 9325 | })) |
| 9326 | ) { |
| 9327 | return; |
| 9328 | } |
| 9329 | const step = __wfMakeStep(driver); |
| 9330 | const event = { |
| 9331 | payload: meta.params, |
| 9332 | timestamp: new Date(meta.createdMs), |
| 9333 | instanceId: meta.instanceId, |
| 9334 | workflowName: meta.workflowName, |
| 9335 | }; |
| 9336 | // ExecutionContext-shaped, as the WorkflowEntrypoint constructor |
| 9337 | // documents upstream. |
| 9338 | const ctx = { |
| 9339 | waitUntil: __registerWaitUntil, |
| 9340 | passThroughOnException() {}, |
| 9341 | }; |
| 9342 | (async () => new cls(ctx, __cell.env).run(event, step))().then( |
| 9343 | (value) => driver.finish({ kind: "complete", value }), |
| 9344 | (error) => driver.finish({ kind: "error", error }), |
| 9345 | ); |
| 9346 | /*__CELLD_TEST_WORKFLOW_AFTER_RUN_STARTED__*/ |
| 9347 | let result = await outcome; |
| 9348 | // The workflow can catch a rejected step promise, but it cannot turn an |
| 9349 | // engine storage failure into a successful run. Preserve the alarm so |
| 9350 | // the runtime retries over the last committed ledger prefix. |
| 9351 | if (driver.storageFailure !== undefined) { |
| 9352 | throw driver.storageFailure; |
| 9353 | } |
| 9354 | const currentMeta = await storage.get("__wf.meta"); |
| 9355 | if ( |
| 9356 | result.kind === "pause" || |
| 9357 | (currentMeta !== undefined && |
| 9358 | currentMeta.generation === meta.generation && |
| 9359 | currentMeta.status === "waitingForPause") |
| 9360 | ) { |
| 9361 | /*__CELLD_TEST_WORKFLOW_BEFORE_PAUSE_SETTLE__*/ |
| 9362 | settle((current, transaction) => { |
| 9363 | // A resume can cancel waitingForPause after this drive selected its |
| 9364 | // pause result. Preserve that newer running state and its alarm, or |
| 9365 | // this stale settlement strands an acknowledged resume as paused. |
| 9366 | if (current.status !== "waitingForPause") return; |
| 9367 | current.status = "paused"; |
| 9368 | current.pausedMs = Date.now(); |
| 9369 | transaction.deleteAlarm(); |
| 9370 | }); |
| 9371 | return; |
| 9372 | } |
| 9373 | if (result.kind === "suspend") { |
| 9374 | let at = Math.min(...driver.blocked.map((entry) => entry.at)); |
| 9375 | // A nudge that landed mid-drive must not wait out the pending |
| 9376 | // deadline. It is visible in one of two places: getAlarm(), when the |
| 9377 | // nudge re-armed and no second alarm dispatched yet, or `_wfNudge`, |
| 9378 | // when a second alarm() already entered and parked on the drive |
| 9379 | // guard -- its dispatch consumed the armed alarm, so getAlarm() |
| 9380 | // alone would miss it. |
| 9381 | const nudge = await storage.getAlarm(); |
| 9382 | if (nudge !== null) at = Math.min(at, nudge); |
| 9383 | if (this._wfNudge !== undefined) { |
| 9384 | at = Math.min(at, this._wfNudge); |
| 9385 | this._wfNudge = undefined; |
| 9386 | } |
| 9387 | settle((current, transaction) => { |
| 9388 | current.status = "waiting"; |
| 9389 | transaction.setAlarm(at); |
| 9390 | }); |
| 9391 | // The explicit re-arm replaces the alarm that fired this drive. |
| 9392 | // Durability is per SQLite commit, not per turn: a crash can persist |
| 9393 | // any prefix of this invocation's ledger writes, and the unconsumed |
| 9394 | // fired alarm is what re-drives the replay over whatever prefix |
| 9395 | // survived. A terminated instance re-arms nothing; its leftover |
| 9396 | // alarm fires once, sees the terminal status, and retires itself. |
| 9397 | return; |
| 9398 | } |
| 9399 | if (result.kind === "complete") { |
| 9400 | try { |
| 9401 | if (result.value !== undefined) { |
| 9402 | __wfCheckValue(result.value, "the run() return value"); |
| 9403 | } |
| 9404 | } catch (error) { |
| 9405 | result = { kind: "error", error }; |
| 9406 | } |
| 9407 | if (result.kind === "complete") { |
| 9408 | // Keep settlement outside the value-validation catch. A storage |
| 9409 | // failure must escape the alarm handler so the engine retries the |
| 9410 | // still-armed drive; converting it to a user error would consume the |
| 9411 | // alarm and make a transient commit failure terminal. |
| 9412 | settle((current, transaction) => { |
| 9413 | current.status = "complete"; |
| 9414 | if (result.value !== undefined) current.output = result.value; |
| 9415 | // The terminal commit installs the expiry wake with the retained |
| 9416 | // state, so a crash can expose neither without the other. |
| 9417 | __wfFinishRetention(current, transaction); |
| 9418 | /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ |
| 9419 | }); |
| 9420 | return; |
| 9421 | } |
| 9422 | } |
| 9423 | settle((current, transaction) => { |
| 9424 | current.status = "errored"; |
| 9425 | current.error = __wfErrorRecord(result.error); |
| 9426 | __wfFinishRetention(current, transaction); |
| 9427 | /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ |
| 9428 | }); |
| 9429 | } |
| 9430 | }; |
| 9431 | })(); |
| 9432 | __runtimeClass("__Workflow", __WorkflowCell); |
| 9433 | |
| 9434 | class NonRetryableError extends Error { |
| 9435 | constructor(message, name = "NonRetryableError") { |
| 9436 | super(message); |
| 9437 | this.name = name; |
| 9438 | } |
| 9439 | } |
| 9440 | // Backing object for the `cloudflare:workflows` builtin module. |
| 9441 | __celld.__cfWorkflows = { NonRetryableError }; |
| 9442 | // `celld:python`, imported only by the Python Worker bundle. |
| 9443 | __celld.__pythonHost = { |
| 9444 | condemnIsolate: (reason) => __isolate_condemn(String(reason)), |
| 9445 | }; |
| 9446 | |
| 9447 | const __wfValidInstanceId = (id) => |
| 9448 | typeof id === "string" && id.length >= 1 && id.length <= 100 && |
| 9449 | __WF_NAME_RE.test(id); |
| 9450 | const __wfCreateOptions = (options, what, validateParams = true) => { |
| 9451 | if (!__wfOwnObject(options)) { |
| 9452 | throw __wfError(`${what} needs an object`); |
| 9453 | } |
| 9454 | const retention = __wfRetentionOptions(options.retention, what); |
| 9455 | const locationHint = __wfLocationHint(options.locationHint, what); |
| 9456 | const id = options.id === undefined ? crypto.randomUUID() : options.id; |
| 9457 | if (!__wfValidInstanceId(id)) { |
| 9458 | throw __wfError( |
| 9459 | `invalid instance id ${JSON.stringify(id)}: use letters, digits, ` + |
| 9460 | "\"-\" and \"_\" (not starting with \"-\"), at most 100 characters", |
| 9461 | ); |
| 9462 | } |
| 9463 | if (validateParams && options.params !== undefined) { |
| 9464 | // The cell repeats this serialization check because it owns the durable |
| 9465 | // create invariant. A single create rejects before it addresses the cell. |
| 9466 | __wfCheckValue(options.params, "the workflow params"); |
| 9467 | } |
| 9468 | return { id, params: options.params, retention, locationHint }; |
| 9469 | }; |
| 9470 | |
| 9471 | // Named so SDKs that sniff a binding by `constructor.name` recognise it. |
| 9472 | class WorkflowInstance { |
| 9473 | constructor(workflowName, id) { |
| 9474 | Object.defineProperty(this, "_workflowName", { value: workflowName }); |
| 9475 | this.id = id; |
| 9476 | } |
| 9477 | // Resolved per call rather than cached: a cell can move between calls. |
| 9478 | get _stub() { |
| 9479 | // The reserved class is script-scoped (`deploy::workflow_class`), because |
| 9480 | // a workflow instance is: two co-hosted scripts must not share one entry |
| 9481 | // in the deployment's flat class registry. `__cell.script` is injected |
| 9482 | // before any binding runs, so this resolves at call time. |
| 9483 | return __cell.makeNamespace("__Workflow." + __cell.script) |
| 9484 | .getByName(this._workflowName + "/" + this.id); |
| 9485 | } |
| 9486 | async status() { |
| 9487 | return await this._stub.__wfStatus(); |
| 9488 | } |
| 9489 | async terminate(options) { |
| 9490 | if (options && options.rollback) { |
| 9491 | throw __wfError( |
| 9492 | "terminate({rollback: true}) is not implemented in celld; step " + |
| 9493 | "rollbackOptions are not implemented, so no handler could run", |
| 9494 | ); |
| 9495 | } |
| 9496 | await this._stub.__wfTerminate(); |
| 9497 | } |
| 9498 | async sendEvent(options) { |
| 9499 | await this._stub.__wfSendEvent(__wfEventOptions(options)); |
| 9500 | } |
| 9501 | async pause() { |
| 9502 | await this._stub.__wfPause(); |
| 9503 | } |
| 9504 | async resume() { |
| 9505 | await this._stub.__wfResume(); |
| 9506 | } |
| 9507 | async restart(options) { |
| 9508 | await this._stub.__wfRestart(__wfRestartOptions(options)); |
| 9509 | } |
| 9510 | async delete() { |
| 9511 | try { |
| 9512 | await this._stub.__wfDelete(); |
| 9513 | } catch (error) { |
| 9514 | // The deletion commit resets an active Workflow cell so an in-flight |
| 9515 | // callback cannot put old ledger state back. That reset rejects this |
| 9516 | // RPC with its private completion marker; it is the successful path. |
| 9517 | if (!String(error && error.message || error).includes("WORKFLOW_INSTANCE_DELETED")) { |
| 9518 | throw error; |
| 9519 | } |
| 9520 | } |
| 9521 | } |
| 9522 | } |
| 9523 | |
| 9524 | class Workflow { |
| 9525 | constructor(workflowName) { |
| 9526 | Object.defineProperty(this, "_workflowName", { value: workflowName }); |
| 9527 | } |
| 9528 | async _create(options, skipExisting) { |
| 9529 | const { id, params, retention, locationHint } = options; |
| 9530 | const instance = new WorkflowInstance(this._workflowName, id); |
| 9531 | const result = await instance._stub.__wfCreate({ |
| 9532 | workflowName: this._workflowName, |
| 9533 | instanceId: id, |
| 9534 | params, |
| 9535 | retention, |
| 9536 | locationHint, |
| 9537 | skipExisting, |
| 9538 | }); |
| 9539 | return result.created ? instance : undefined; |
| 9540 | } |
| 9541 | async create(options = {}) { |
| 9542 | return await this._create(__wfCreateOptions(options, "create()"), false); |
| 9543 | } |
| 9544 | async createBatch(batch) { |
| 9545 | if (!Array.isArray(batch)) { |
| 9546 | throw __wfError("createBatch() needs an array of create options"); |
| 9547 | } |
| 9548 | if (batch.length > 100) { |
| 9549 | throw __wfError( |
| 9550 | `createBatch() accepts at most 100 instances, got ${batch.length}`, |
| 9551 | ); |
| 9552 | } |
| 9553 | if (batch.length === 0) { |
| 9554 | throw __wfError("createBatch() needs at least one instance"); |
| 9555 | } |
| 9556 | // Cloudflare rejects a structural error in any item before it creates the |
| 9557 | // first instance, but it filters a params clone failure per item. Keep |
| 9558 | // these two gates separate so a bad ID stays atomic while a clone failure |
| 9559 | // does not suppress the valid items around it. |
| 9560 | const optionsList = batch.map((options, index) => |
| 9561 | __wfCreateOptions(options, `createBatch() item ${index}`, false)); |
| 9562 | const creatable = []; |
| 9563 | for (const options of optionsList) { |
| 9564 | let encoded; |
| 9565 | try { |
| 9566 | if (options.params !== undefined) { |
| 9567 | encoded = __wfEncodeValue(options.params, "the workflow params"); |
| 9568 | } |
| 9569 | } catch { |
| 9570 | continue; |
| 9571 | } |
| 9572 | if (encoded !== undefined) { |
| 9573 | __wfCheckEncodedValue(encoded, "the workflow params"); |
| 9574 | } |
| 9575 | creatable.push(options); |
| 9576 | } |
| 9577 | const created = []; |
| 9578 | for (const options of creatable) { |
| 9579 | const instance = await this._create(options, true); |
| 9580 | if (instance !== undefined) created.push(instance); |
| 9581 | } |
| 9582 | return created; |
| 9583 | } |
| 9584 | async get(id) { |
| 9585 | if (!__wfValidInstanceId(id)) { |
| 9586 | throw __wfError(`invalid instance id ${JSON.stringify(id)}`); |
| 9587 | } |
| 9588 | const instance = new WorkflowInstance(this._workflowName, id); |
| 9589 | // The cell exists on first address like any cell, but get() must not |
| 9590 | // mint an instance for a typo: an id with no ledger rejects here. |
| 9591 | await instance._stub.__wfStatus(); |
| 9592 | return instance; |
| 9593 | } |
| 9594 | async deleteBatch(instanceIds) { |
| 9595 | if (!Array.isArray(instanceIds)) { |
| 9596 | throw __wfError("deleteBatch() needs an array of instance ids"); |
| 9597 | } |
| 9598 | if (instanceIds.length < 1 || instanceIds.length > 100) { |
| 9599 | throw __wfError( |
| 9600 | `deleteBatch() accepts 1 to 100 instance ids, got ${instanceIds.length}`, |
| 9601 | ); |
| 9602 | } |
| 9603 | for (const id of instanceIds) { |
| 9604 | if (!__wfValidInstanceId(id)) { |
| 9605 | throw __wfError(`invalid instance id ${JSON.stringify(id)}`); |
| 9606 | } |
| 9607 | } |
| 9608 | const uniqueIds = [...new Set(instanceIds)]; |
| 9609 | const settled = await Promise.allSettled(uniqueIds.map(async (id) => { |
| 9610 | const instance = new WorkflowInstance(this._workflowName, id); |
| 9611 | await instance.delete(); |
| 9612 | })); |
| 9613 | const results = new Map(uniqueIds.map((id, index) => [id, settled[index]])); |
| 9614 | const output = { deleted: [], errors: [] }; |
| 9615 | for (const id of instanceIds) { |
| 9616 | const result = results.get(id); |
| 9617 | if (result.status === "fulfilled") { |
| 9618 | output.deleted.push({ id }); |
| 9619 | continue; |
| 9620 | } |
| 9621 | const notFound = String(result.reason && result.reason.message || result.reason) |
| 9622 | .includes("instance does not exist"); |
| 9623 | output.errors.push({ |
| 9624 | id, |
| 9625 | code: notFound ? 10400 : 10001, |
| 9626 | message: notFound |
| 9627 | ? "workflows.api.error.instance.not_found" |
| 9628 | : "workflows.api.error.internal_server", |
| 9629 | }); |
| 9630 | } |
| 9631 | return output; |
| 9632 | } |
| 9633 | } |
| 9634 | |
| 9635 | const __makeWorkflow = __celld.__makeWorkflow = |
| 9636 | (workflowName) => new Workflow(workflowName); |
| 9637 | // `cloudflare:workers` module surface. The DO base class sets ctx/env the |
| 9638 | // way `class X extends DurableObject` expects; env aliases the cell env. |
| 9639 | const __cf = __celld.__cf = { |
| 9640 | DurableObject: class DurableObject { |
| 9641 | constructor(ctx, env) { this.ctx = ctx; this.env = env; } |
| 9642 | }, |
| 9643 | // The enumerable function-valued brand makes V8's structured clone |
| 9644 | // fail on every RpcTarget instance, forcing it off the silent |
| 9645 | // plain-clone path and into the stub lift (Workerd rejects these |
| 9646 | // from plain serialization outright). |
| 9647 | RpcTarget: class RpcTarget { |
| 9648 | constructor() { |
| 9649 | Object.defineProperty(this, "__celldRpcTarget", { |
| 9650 | value: __rpcNoClone, enumerable: true, |
| 9651 | }); |
| 9652 | } |
| 9653 | }, |
| 9654 | // Named entrypoint for `[[services]]` with `entrypoint = "Name"`. |
| 9655 | WorkerEntrypoint: class WorkerEntrypoint { |
| 9656 | constructor(ctx, env) { this.ctx = ctx; this.env = env; } |
| 9657 | }, |
| 9658 | // Base class for `workflows` classes. The reserved workflow cell |
| 9659 | // instantiates a subclass on every replay with an ExecutionContext-shaped |
| 9660 | // ctx -- never the cell's own DurableObjectState, which would hand user |
| 9661 | // code the ledger that replays it. |
| 9662 | WorkflowEntrypoint: class WorkflowEntrypoint { |
| 9663 | constructor(ctx, env) { this.ctx = ctx; this.env = env; } |
| 9664 | }, |
| 9665 | // `new RpcStub(target)` wraps any local object or function in a |
| 9666 | // loopback stub; the constructor returns the proxy, so instanceof |
| 9667 | // works through __makeStub's getPrototypeOf trap. |
| 9668 | RpcStub: class RpcStub { |
| 9669 | constructor(target) { |
| 9670 | if (target === null || |
| 9671 | (typeof target !== "object" && typeof target !== "function")) |
| 9672 | throw new TypeError( |
| 9673 | "RpcStub requires an object or function."); |
| 9674 | return __makeStub( |
| 9675 | __newEntry(target), typeof target === "function"); |
| 9676 | } |
| 9677 | }, |
| 9678 | RpcPromise: class RpcPromise extends Promise {}, |
| 9679 | RpcProperty: class RpcProperty {}, |
| 9680 | ServiceStub: class ServiceStub {}, |
| 9681 | // `import { waitUntil } from "cloudflare:workers"`: register into |
| 9682 | // the current event or extend its active background work. Outside either |
| 9683 | // lifetime this is Workerd's global-scope error. |
| 9684 | waitUntil(promise) { |
| 9685 | if (!__wait_until_active()) |
| 9686 | throw new Error( |
| 9687 | "Disallowed operation called within global scope."); |
| 9688 | __registerWaitUntil(promise); |
| 9689 | }, |
| 9690 | exports: {}, |
| 9691 | get env() { return __cell.env; }, |
| 9692 | }; |
| 9693 | // Proxy standing in for unsupported node:*/cloudflare:* builtins. Property |
| 9694 | // walks stay inert -- real bundles reference these at module scope, and |
| 9695 | // evaluation must not crash on a builtin the fetch path never exercises -- |
| 9696 | // but a call or construct throws: the compat contract is "reject at first |
| 9697 | // use", and the old silent pass-through turned a missing builtin into a |
| 9698 | // wrong result far from the cause. Memoized by dotted path so repeated |
| 9699 | // reads keep identity (`mod.foo === mod.foo`). |
| 9700 | const __stubCache = new Map(); |
| 9701 | const __nodeStubFor = __celld.__nodeStubFor = (path) => { |
| 9702 | let stub = __stubCache.get(path); |
| 9703 | if (stub) return stub; |
| 9704 | stub = new Proxy(function () {}, { |
| 9705 | get: (_t, p) => { |
| 9706 | // Never masquerade as a thenable. `await` probes `.then`; returning |
| 9707 | // a callable here creates a promise that can never settle. |
| 9708 | if (p === "then") return undefined; |
| 9709 | // coerce cleanly in string/number contexts so evaluation never throws |
| 9710 | if (p === Symbol.toPrimitive || p === "toString" || p === "valueOf") |
| 9711 | return () => ""; |
| 9712 | if (p === Symbol.toStringTag) return "NodeStub"; |
| 9713 | if (p === Symbol.iterator) return function* () {}; |
| 9714 | if (typeof p !== "string") return undefined; |
| 9715 | return __nodeStubFor(path + "." + p); |
| 9716 | }, |
| 9717 | apply() { throw new Error(path + " is not implemented in celld"); }, |
| 9718 | construct() { throw new Error(path + " is not implemented in celld"); }, |
| 9719 | }); |
| 9720 | __stubCache.set(path, stub); |
| 9721 | return stub; |
| 9722 | }; |
| 9723 | __celld.__nodeStub = __nodeStubFor("node builtin"); |
| 9724 | if (!globalThis.Event) { |
| 9725 | globalThis.Event = class Event { |
| 9726 | // Private fields: stored in the object itself, so an Event costs no |
| 9727 | // side allocation and no defineProperty call at construction. The |
| 9728 | // public members are accessors because the DOM standard makes them |
| 9729 | // read-only; EventTarget drives them through _begin/_end. |
| 9730 | #type; #bubbles; #cancelable; #composed; |
| 9731 | #defaultPrevented = false; |
| 9732 | #eventPhase = 0; |
| 9733 | #target; #currentTarget; #path; |
| 9734 | #stop = false; #stopImmediate = false; #dispatching = false; |
| 9735 | // Workerd: events the runtime delivers are trusted; events a |
| 9736 | // script constructs and dispatches itself are not. |
| 9737 | #trusted = false; |
| 9738 | constructor(type, init = {}) { |
| 9739 | if (arguments.length === 0) |
| 9740 | throw new TypeError( |
| 9741 | "Failed to construct 'Event': 1 argument required, but only " + |
| 9742 | "0 present."); |
| 9743 | if (init !== undefined && init !== null && |
| 9744 | typeof init !== "object") |
| 9745 | throw new TypeError( |
| 9746 | "Failed to construct 'Event': The provided value is not of " + |
| 9747 | "type 'EventInit'."); |
| 9748 | const options = init || {}; |
| 9749 | // Template interpolation, not String(): it must throw for a |
| 9750 | // Symbol, which String() would happily format. |
| 9751 | this.#type = `${type}`; |
| 9752 | this.#bubbles = !!options.bubbles; |
| 9753 | this.#cancelable = !!options.cancelable; |
| 9754 | this.#composed = !!options.composed; |
| 9755 | } |
| 9756 | get type() { return this.#type; } |
| 9757 | get bubbles() { return this.#bubbles; } |
| 9758 | get cancelable() { return this.#cancelable; } |
| 9759 | get composed() { return this.#composed; } |
| 9760 | get defaultPrevented() { return this.#defaultPrevented; } |
| 9761 | get eventPhase() { return this.#eventPhase; } |
| 9762 | get target() { return this.#target; } |
| 9763 | get currentTarget() { return this.#currentTarget; } |
| 9764 | get isTrusted() { return this.#trusted; } |
| 9765 | get timeStamp() { return 0; } |
| 9766 | get returnValue() { return !this.#defaultPrevented; } |
| 9767 | // The one writable member, per the DOM standard. |
| 9768 | get cancelBubble() { return this.#stop; } |
| 9769 | set cancelBubble(value) { if (value) this.#stop = true; } |
| 9770 | composedPath() { return this.#path ? this.#path.slice() : []; } |
| 9771 | preventDefault() { |
| 9772 | if (this.#cancelable) this.#defaultPrevented = true; |
| 9773 | } |
| 9774 | stopPropagation() { this.#stop = true; } |
| 9775 | stopImmediatePropagation() { |
| 9776 | this.#stop = true; |
| 9777 | this.#stopImmediate = true; |
| 9778 | } |
| 9779 | // Internal dispatch hooks used by EventTarget. |
| 9780 | get _dispatching() { return this.#dispatching; } |
| 9781 | get _stopImmediate() { return this.#stopImmediate; } |
| 9782 | _trust() { this.#trusted = true; } |
| 9783 | _begin(target) { |
| 9784 | this.#dispatching = true; |
| 9785 | this.#target = target; |
| 9786 | this.#currentTarget = target; |
| 9787 | this.#eventPhase = 2; // AT_TARGET |
| 9788 | this.#path = [target]; |
| 9789 | this.#stop = false; |
| 9790 | this.#stopImmediate = false; |
| 9791 | } |
| 9792 | // Workerd leaves currentTarget set after dispatch (the DOM standard |
| 9793 | // nulls it); only the phase is reset. |
| 9794 | _end() { |
| 9795 | this.#eventPhase = 0; |
| 9796 | this.#dispatching = false; |
| 9797 | } |
| 9798 | }; |
| 9799 | { |
| 9800 | const phases = { |
| 9801 | NONE: 0, CAPTURING_PHASE: 1, AT_TARGET: 2, BUBBLING_PHASE: 3, |
| 9802 | }; |
| 9803 | for (const [name, value] of Object.entries(phases)) { |
| 9804 | const d = { value, writable: false, enumerable: true, |
| 9805 | configurable: false }; |
| 9806 | Object.defineProperty(globalThis.Event, name, d); |
| 9807 | Object.defineProperty(globalThis.Event.prototype, name, d); |
| 9808 | } |
| 9809 | } |
| 9810 | } |
| 9811 | if (!globalThis.CustomEvent) { |
| 9812 | globalThis.CustomEvent = class CustomEvent extends Event { |
| 9813 | constructor(type, init = {}) { |
| 9814 | super(type, init); |
| 9815 | this.detail = init.detail === undefined ? null : init.detail; |
| 9816 | } |
| 9817 | }; |
| 9818 | } |
| 9819 | if (!globalThis.ExtendableEvent) { |
| 9820 | // Exists as a type but is not constructable from user code. |
| 9821 | globalThis.ExtendableEvent = class ExtendableEvent extends Event { |
| 9822 | constructor() { |
| 9823 | throw new TypeError("Illegal constructor"); |
| 9824 | } |
| 9825 | }; |
| 9826 | } |
| 9827 | // An event-handler IDL attribute occupies one listener-list position. Replacing |
| 9828 | // its callback must retain that position, or listeners added after `onabort` |
| 9829 | // run before it and observe an order that differs from the web platform. |
| 9830 | const __eventHandlerEntry = Symbol("eventHandlerEntry"); |
| 9831 | const __getEventHandler = (target, type) => |
| 9832 | (target._listeners.get(type) || []) |
| 9833 | .find((entry) => entry[__eventHandlerEntry])?.callback ?? null; |
| 9834 | const __setEventHandler = (target, type, callback) => { |
| 9835 | const list = target._listeners.get(type) || []; |
| 9836 | const entry = list.find((item) => item[__eventHandlerEntry]); |
| 9837 | if (typeof callback !== "function") { |
| 9838 | if (entry) list.splice(list.indexOf(entry), 1); |
| 9839 | return; |
| 9840 | } |
| 9841 | if (entry) { |
| 9842 | entry.callback = callback; |
| 9843 | } else { |
| 9844 | list.push({ callback, once: false, [__eventHandlerEntry]: true }); |
| 9845 | target._listeners.set(type, list); |
| 9846 | } |
| 9847 | }; |
| 9848 | if (!globalThis.EventTarget) { |
| 9849 | globalThis.EventTarget = class EventTarget { |
| 9850 | constructor() { this._listeners = new Map(); } |
| 9851 | addEventListener(type, callback, options = {}) { |
| 9852 | if (callback === null || callback === undefined) return; |
| 9853 | if (typeof callback !== "function" && |
| 9854 | typeof callback.handleEvent !== "function") |
| 9855 | throw new TypeError( |
| 9856 | "Failed to execute 'addEventListener' on 'EventTarget': " + |
| 9857 | "parameter 2 is not of type 'EventListener'."); |
| 9858 | const object = typeof options === "object" && options !== null; |
| 9859 | // Capture and passive are accepted for portability but must be |
| 9860 | // false: Cells dispatches only at the target, so honouring them |
| 9861 | // would silently change ordering. |
| 9862 | if (object ? options.capture || options.passive : !!options) |
| 9863 | throw new TypeError( |
| 9864 | "Cells does not support the 'capture' or 'passive' options " + |
| 9865 | "on addEventListener()."); |
| 9866 | const signal = object ? options.signal : undefined; |
| 9867 | if (signal && signal.aborted) return; |
| 9868 | const key = String(type); |
| 9869 | const list = this._listeners.get(key) || []; |
| 9870 | if (list.some((e) => e.callback === callback)) return; |
| 9871 | list.push({ callback, once: object && !!options.once }); |
| 9872 | this._listeners.set(key, list); |
| 9873 | if (signal) |
| 9874 | signal.addEventListener("abort", () => |
| 9875 | this.removeEventListener(key, callback), { once: true }); |
| 9876 | } |
| 9877 | removeEventListener(type, callback, options = {}) { |
| 9878 | const object = typeof options === "object" && options !== null; |
| 9879 | if (object ? options.capture : !!options) |
| 9880 | throw new TypeError( |
| 9881 | "Cells does not support the 'capture' option on " + |
| 9882 | "removeEventListener()."); |
| 9883 | const list = this._listeners.get(String(type)); |
| 9884 | if (!list) return; |
| 9885 | const index = list.findIndex((e) => e.callback === callback); |
| 9886 | if (index >= 0) list.splice(index, 1); |
| 9887 | } |
| 9888 | dispatchEvent(event) { |
| 9889 | if (!(event instanceof Event)) |
| 9890 | throw new TypeError("argument is not an Event"); |
| 9891 | if (event._dispatching) |
| 9892 | throw new DOMException( |
| 9893 | "The event is already being dispatched.", |
| 9894 | "InvalidStateError"); |
| 9895 | event._begin(this); |
| 9896 | // Copy: a listener may add or remove listeners mid-dispatch. |
| 9897 | for (const item of (this._listeners.get(event.type) || []).slice()) { |
| 9898 | if (event._stopImmediate) break; |
| 9899 | if (item.once) |
| 9900 | this.removeEventListener(event.type, item.callback); |
| 9901 | if (typeof item.callback === "function") |
| 9902 | item.callback.call(this, event); |
| 9903 | else item.callback.handleEvent(event); |
| 9904 | } |
| 9905 | const handler = this["on" + event.type]; |
| 9906 | const hasEventHandler = (this._listeners.get(event.type) || []) |
| 9907 | .some((item) => item[__eventHandlerEntry]); |
| 9908 | if (!hasEventHandler && !event._stopImmediate && |
| 9909 | typeof handler === "function") |
| 9910 | handler.call(this, event); |
| 9911 | event._end(); |
| 9912 | return !event.defaultPrevented; |
| 9913 | } |
| 9914 | }; |
| 9915 | } |
| 9916 | // The global scope is itself an EventTarget. |
| 9917 | if (typeof globalThis.addEventListener !== "function") { |
| 9918 | const globalTarget = new EventTarget(); |
| 9919 | for (const name of |
| 9920 | ["addEventListener", "removeEventListener", "dispatchEvent"]) |
| 9921 | globalThis[name] = globalTarget[name].bind(globalTarget); |
| 9922 | } |
| 9923 | if (!globalThis.MessageEvent) { |
| 9924 | globalThis.MessageEvent = class MessageEvent extends Event { |
| 9925 | constructor(type, init = {}) { |
| 9926 | super(type, init); |
| 9927 | this.data = init.data; |
| 9928 | this.origin = String(init.origin || ""); |
| 9929 | this.lastEventId = String(init.lastEventId || ""); |
| 9930 | } |
| 9931 | }; |
| 9932 | } |
| 9933 | if (!globalThis.CloseEvent) { |
| 9934 | globalThis.CloseEvent = class CloseEvent extends Event { |
| 9935 | constructor(type, init = {}) { |
| 9936 | super(type, init); |
| 9937 | this.code = Number(init.code || 0); |
| 9938 | // `reason` is a USVString: a lone surrogate becomes U+FFFD rather than |
| 9939 | // travelling as an unpaired code unit. |
| 9940 | this.reason = String(init.reason || "").toWellFormed |
| 9941 | ? String(init.reason || "").toWellFormed() |
| 9942 | : String(init.reason || "").replace( |
| 9943 | /[\uD800-\uDFFF]/g, |
| 9944 | (unit, index, whole) => { |
| 9945 | const code = unit.charCodeAt(0); |
| 9946 | const next = whole.charCodeAt(index + 1); |
| 9947 | const prev = whole.charCodeAt(index - 1); |
| 9948 | const paired = code <= 0xDBFF |
| 9949 | ? next >= 0xDC00 && next <= 0xDFFF |
| 9950 | : prev >= 0xD800 && prev <= 0xDBFF; |
| 9951 | return paired ? unit : "\uFFFD"; |
| 9952 | }, |
| 9953 | ); |
| 9954 | this.wasClean = !!init.wasClean; |
| 9955 | } |
| 9956 | }; |
| 9957 | } |
| 9958 | if (!globalThis.DOMException) { |
| 9959 | globalThis.DOMException = class DOMException extends Error { |
| 9960 | constructor(message = "", name = "Error") { super(message); this.name = name; } |
| 9961 | }; |
| 9962 | // WebIDL legacy code constants, enumerable on both the interface |
| 9963 | // object and its prototype, in spec order. |
| 9964 | { |
| 9965 | const codes = [ |
| 9966 | ["INDEX_SIZE_ERR", 1], ["DOMSTRING_SIZE_ERR", 2], |
| 9967 | ["HIERARCHY_REQUEST_ERR", 3], ["WRONG_DOCUMENT_ERR", 4], |
| 9968 | ["INVALID_CHARACTER_ERR", 5], ["NO_DATA_ALLOWED_ERR", 6], |
| 9969 | ["NO_MODIFICATION_ALLOWED_ERR", 7], ["NOT_FOUND_ERR", 8], |
| 9970 | ["NOT_SUPPORTED_ERR", 9], ["INUSE_ATTRIBUTE_ERR", 10], |
| 9971 | ["INVALID_STATE_ERR", 11], ["SYNTAX_ERR", 12], |
| 9972 | ["INVALID_MODIFICATION_ERR", 13], ["NAMESPACE_ERR", 14], |
| 9973 | ["INVALID_ACCESS_ERR", 15], ["VALIDATION_ERR", 16], |
| 9974 | ["TYPE_MISMATCH_ERR", 17], ["SECURITY_ERR", 18], |
| 9975 | ["NETWORK_ERR", 19], ["ABORT_ERR", 20], |
| 9976 | ["URL_MISMATCH_ERR", 21], ["QUOTA_EXCEEDED_ERR", 22], |
| 9977 | ["TIMEOUT_ERR", 23], ["INVALID_NODE_TYPE_ERR", 24], |
| 9978 | ["DATA_CLONE_ERR", 25], |
| 9979 | ]; |
| 9980 | for (const [name, value] of codes) { |
| 9981 | const d = { value, writable: false, enumerable: true, |
| 9982 | configurable: false }; |
| 9983 | Object.defineProperty(globalThis.DOMException, name, d); |
| 9984 | Object.defineProperty(globalThis.DOMException.prototype, name, d); |
| 9985 | } |
| 9986 | // The legacy `code` member maps the error name to its constant, per |
| 9987 | // WebIDL; names outside the table (and every modern name) are 0. |
| 9988 | const legacy = { |
| 9989 | IndexSizeError: 1, HierarchyRequestError: 3, WrongDocumentError: 4, |
| 9990 | InvalidCharacterError: 5, NoModificationAllowedError: 7, |
| 9991 | NotFoundError: 8, NotSupportedError: 9, InUseAttributeError: 10, |
| 9992 | InvalidStateError: 11, SyntaxError: 12, InvalidModificationError: 13, |
| 9993 | NamespaceError: 14, InvalidAccessError: 15, TypeMismatchError: 17, |
| 9994 | SecurityError: 18, NetworkError: 19, AbortError: 20, |
| 9995 | URLMismatchError: 21, QuotaExceededError: 22, TimeoutError: 23, |
| 9996 | InvalidNodeTypeError: 24, DataCloneError: 25, |
| 9997 | }; |
| 9998 | Object.defineProperty(globalThis.DOMException.prototype, "code", { |
| 9999 | get() { return legacy[this.name] ?? 0; }, |
| 10000 | enumerable: true, configurable: true, |
| 10001 | }); |
| 10002 | } |
| 10003 | } |
| 10004 | if (!globalThis.AbortSignal) { |
| 10005 | const __abortBrand = Symbol("abortSignal"); |
| 10006 | globalThis.AbortSignal = class AbortSignal extends EventTarget { |
| 10007 | // The Headers/Blob clone-poisoning brand: V8's structured |
| 10008 | // clone throws on functions, so a live signal reaches the |
| 10009 | // RPC lift instead of silently flattening to plain data. |
| 10010 | constructor() { |
| 10011 | // Per spec AbortSignal has no constructor: it is only reachable |
| 10012 | // through AbortController, AbortSignal.abort/timeout/any. The internal |
| 10013 | // paths pass the brand to get past this. |
| 10014 | if (arguments[0] !== __abortBrand) { |
| 10015 | throw new TypeError("Illegal constructor"); |
| 10016 | } |
| 10017 | super(); |
| 10018 | this.aborted = false; |
| 10019 | this.reason = undefined; |
| 10020 | this.__celldHost = __rpcNoClone; |
| 10021 | } |
| 10022 | throwIfAborted() { if (this.aborted) throw this.reason; } |
| 10023 | static abort(reason = new DOMException("This operation was aborted", "AbortError")) { |
| 10024 | const c = new AbortController(); c.abort(reason); return c.signal; |
| 10025 | } |
| 10026 | static timeout(ms) { |
| 10027 | const c = new AbortController(); |
| 10028 | setTimeout(() => c.abort(new DOMException( |
| 10029 | "The operation was aborted due to timeout", "TimeoutError", |
| 10030 | )), ms); |
| 10031 | return c.signal; |
| 10032 | } |
| 10033 | static any(signals) { |
| 10034 | const c = new AbortController(); |
| 10035 | for (const signal of signals) { |
| 10036 | if (signal.aborted) { c.abort(signal.reason); break; } |
| 10037 | signal.addEventListener("abort", () => c.abort(signal.reason), { once: true }); |
| 10038 | } |
| 10039 | return c.signal; |
| 10040 | } |
| 10041 | }; |
| 10042 | Object.defineProperty(globalThis.AbortSignal.prototype, "onabort", { |
| 10043 | configurable: true, |
| 10044 | enumerable: true, |
| 10045 | get() { |
| 10046 | if (!(this instanceof globalThis.AbortSignal)) |
| 10047 | throw new TypeError("Illegal invocation"); |
| 10048 | return __getEventHandler(this, "abort"); |
| 10049 | }, |
| 10050 | set(value) { |
| 10051 | if (!(this instanceof globalThis.AbortSignal)) |
| 10052 | throw new TypeError("Illegal invocation"); |
| 10053 | __setEventHandler(this, "abort", value); |
| 10054 | }, |
| 10055 | }); |
| 10056 | globalThis.AbortController = class AbortController { |
| 10057 | constructor() { this.signal = new AbortSignal(__abortBrand); } |
| 10058 | abort(reason = new DOMException("This operation was aborted", "AbortError")) { |
| 10059 | __abortSignal(this.signal, reason); |
| 10060 | } |
| 10061 | }; |
| 10062 | } |
| 10063 | if (!globalThis.Blob) { |
| 10064 | // Same clone-poisoning brand as Headers: an enumerable |
| 10065 | // function-valued property makes V8's structured clone throw, so |
| 10066 | // a Blob reaches the RPC lift instead of silently flattening. |
| 10067 | const __blobNoClone = () => {}; |
| 10068 | globalThis.Blob = class Blob { |
| 10069 | constructor(parts = [], options = {}) { |
| 10070 | // size is assigned before type so both land in the order the |
| 10071 | // inspect output below reports them. |
| 10072 | if (options && options.endings !== undefined) |
| 10073 | throw new Error( |
| 10074 | "The 'endings' field on 'Options' is not implemented."); |
| 10075 | this.size = 0; |
| 10076 | // A type outside U+0020..U+007E is not a valid MIME type and is |
| 10077 | // dropped rather than stored. |
| 10078 | const rawType = String(options.type || ""); |
| 10079 | this.type = /^[\u0020-\u007e]*$/.test(rawType) |
| 10080 | ? rawType.toLowerCase() : ""; |
| 10081 | this.__celldHost = __blobNoClone; |
| 10082 | // Two passes. First convert every part in order -- string |
| 10083 | // conversion runs user code (Symbol.toPrimitive), which may |
| 10084 | // resize a backing buffer. Buffers and views are carried through |
| 10085 | // as-is so a length-tracking view is measured *after* those side |
| 10086 | // effects, matching Workerd. Then allocate once and copy. |
| 10087 | // |
| 10088 | // The previous shape pushed every byte into a plain array with a |
| 10089 | // spread, costing roughly 8x the memory and exceeding the |
| 10090 | // argument limit on multi-megabyte parts. |
| 10091 | const sources = []; |
| 10092 | for (const part of parts) { |
| 10093 | if (part instanceof Blob) sources.push(part._bytes); |
| 10094 | else if (part instanceof ArrayBuffer || |
| 10095 | ArrayBuffer.isView(part)) sources.push(part); |
| 10096 | else sources.push(new TextEncoder().encode(String(part))); |
| 10097 | } |
| 10098 | const chunks = sources.map((source) => |
| 10099 | source instanceof Uint8Array ? source |
| 10100 | : source instanceof ArrayBuffer ? new Uint8Array(source) |
| 10101 | : new Uint8Array( |
| 10102 | source.buffer, source.byteOffset, source.byteLength)); |
| 10103 | let total = 0; |
| 10104 | for (const chunk of chunks) total += chunk.byteLength; |
| 10105 | const LIMIT = 134217728; |
| 10106 | if (total > LIMIT) |
| 10107 | throw new RangeError( |
| 10108 | `Blob size ${total} exceeds limit ${LIMIT}`); |
| 10109 | const bytes = new Uint8Array(total); |
| 10110 | let offset = 0; |
| 10111 | for (const chunk of chunks) { |
| 10112 | bytes.set(chunk, offset); |
| 10113 | offset += chunk.byteLength; |
| 10114 | } |
| 10115 | // Non-enumerable: the backing store is not part of the object's |
| 10116 | // observable shape (inspect, JSON, spread). |
| 10117 | Object.defineProperty(this, "_bytes", { |
| 10118 | value: bytes, writable: true, configurable: true, |
| 10119 | }); |
| 10120 | this.size = total; |
| 10121 | } |
| 10122 | async arrayBuffer() { return this._bytes.slice().buffer; } |
| 10123 | async bytes() { return this._bytes.slice(); } |
| 10124 | async text() { return new TextDecoder().decode(this._bytes); } |
| 10125 | stream() { |
| 10126 | const bytes = this._bytes; |
| 10127 | return new ReadableStream({ |
| 10128 | start(controller) { |
| 10129 | if (bytes.byteLength) controller.enqueue(bytes.slice()); |
| 10130 | controller.close(); |
| 10131 | }, |
| 10132 | }); |
| 10133 | } |
| 10134 | [Symbol.for("nodejs.util.inspect.custom")]() { |
| 10135 | return `Blob { size: ${this.size}, type: '${this.type}' }`; |
| 10136 | } |
| 10137 | slice(start = 0, end = this.size, type = "") { |
| 10138 | const norm = (n, fallback) => { |
| 10139 | n = n === undefined ? fallback : Number(n); |
| 10140 | return n < 0 ? Math.max(this.size + n, 0) : Math.min(n, this.size); |
| 10141 | }; |
| 10142 | const a = norm(start, 0), b = norm(end, this.size); |
| 10143 | return new Blob( |
| 10144 | [this._bytes.subarray(a, Math.max(a, b))], { type }); |
| 10145 | } |
| 10146 | get [Symbol.toStringTag]() { return "Blob"; } |
| 10147 | }; |
| 10148 | } |
| 10149 | if (!globalThis.File) { |
| 10150 | // WebIDL-ish per Workerd: name is required, name/lastModified are |
| 10151 | // brand-checked prototype getters (enumerable, matching the |
| 10152 | // workers_api_getters_setters_on_prototype flag), and lastModified |
| 10153 | // coerces via ToNumber (throws for BigInt), NaN becoming 0. |
| 10154 | globalThis.File = class File extends Blob { |
| 10155 | #name; |
| 10156 | #lastModified; |
| 10157 | constructor(parts, name, options = {}) { |
| 10158 | if (arguments.length < 2) |
| 10159 | throw new TypeError( |
| 10160 | "Failed to construct 'File': 2 arguments required, but " + |
| 10161 | `only ${arguments.length} present.`); |
| 10162 | super(parts, options); |
| 10163 | this.#name = String(name); |
| 10164 | const lm = options == null ? undefined : options.lastModified; |
| 10165 | if (lm === undefined) this.#lastModified = Date.now(); |
| 10166 | else { |
| 10167 | const n = +lm; // ToNumber: throws for BigInt, like WebIDL |
| 10168 | this.#lastModified = Number.isFinite(n) ? Math.trunc(n) : 0; |
| 10169 | } |
| 10170 | } |
| 10171 | get name() { return this.#name; } |
| 10172 | get lastModified() { return this.#lastModified; } |
| 10173 | get [Symbol.toStringTag]() { return "File"; } |
| 10174 | [Symbol.for("nodejs.util.inspect.custom")]() { |
| 10175 | return `File { name: '${this.name}', ` + |
| 10176 | `lastModified: ${this.lastModified}, size: ${this.size}, ` + |
| 10177 | `type: '${this.type}' }`; |
| 10178 | } |
| 10179 | }; |
| 10180 | for (const key of ["name", "lastModified"]) { |
| 10181 | const desc = |
| 10182 | Object.getOwnPropertyDescriptor(File.prototype, key); |
| 10183 | desc.enumerable = true; |
| 10184 | Object.defineProperty(File.prototype, key, desc); |
| 10185 | } |
| 10186 | } |
| 10187 | if (!globalThis.FormData) { |
| 10188 | // Byte offsets the multipart scanner compares against. A part body is |
| 10189 | // arbitrary bytes, so every framing decision below is made on bytes. |
| 10190 | const __CR = 13, __LF = 10, __DASH = 45; |
| 10191 | const __bytesIndexOf = (haystack, needle, from) => { |
| 10192 | const last = haystack.length - needle.length; |
| 10193 | outer: for (let i = from; i <= last; i++) { |
| 10194 | for (let j = 0; j < needle.length; j++) |
| 10195 | if (haystack[i + j] !== needle[j]) continue outer; |
| 10196 | return i; |
| 10197 | } |
| 10198 | return -1; |
| 10199 | }; |
| 10200 | // A boundary delimiter is a delimiter only at the start of a line (RFC 2046 |
| 10201 | // section 5.1.1). Searching for the bytes anywhere would let a binary part |
| 10202 | // that happens to contain `--<boundary>` split itself, which is a corrupt |
| 10203 | // upload rather than a parse error, so the caller never learns of it. |
| 10204 | const __delimiterIndex = (bytes, delimiter, from) => { |
| 10205 | for (let at = from;;) { |
| 10206 | const found = __bytesIndexOf(bytes, delimiter, at); |
| 10207 | if (found < 0) return -1; |
| 10208 | if (found === 0 || bytes[found - 1] === __LF) return found; |
| 10209 | at = found + 1; |
| 10210 | } |
| 10211 | }; |
| 10212 | // A `Content-Disposition` parameter, anchored to the start of a parameter: |
| 10213 | // the parameter name must follow the header name or a `;`. An unanchored |
| 10214 | // pattern found the `name=` inside `filename=`, so a part whose header wrote |
| 10215 | // the filename first landed under the filename. The grammar does not |
| 10216 | // constrain the parameter order, and both orders occur in the wild. Hoisted |
| 10217 | // because the previous shape compiled a regex per parameter per part. |
| 10218 | const __CD_NAME = |
| 10219 | /(?:^|;)\s*name\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i; |
| 10220 | const __CD_FILENAME = |
| 10221 | /(?:^|;)\s*filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i; |
| 10222 | // Body -> FormData for multipart/form-data and |
| 10223 | // application/x-www-form-urlencoded. Kept out of the class so V8 only |
| 10224 | // pre-parses it; the body is compiled on first actual formData() call. |
| 10225 | // |
| 10226 | // `bytes` is the undecoded body. A file part must reach `File` as the bytes |
| 10227 | // that arrived: decoding the body first and slicing part bodies out of the |
| 10228 | // string replaced every non-UTF-8 sequence with U+FFFD, and the re-encode in |
| 10229 | // the `Blob` constructor then wrote those replacement bytes into the file. |
| 10230 | __celld.__parseFormData = (bytes, contentType) => { |
| 10231 | const ct = String(contentType || ""); |
| 10232 | if (/^\s*application\/x-www-form-urlencoded/i.test(ct)) { |
| 10233 | // This form is decoded as UTF-8, so a declared charset that is not UTF-8 |
| 10234 | // cannot be honoured. Refuse rather than mis-decode. |
| 10235 | const charset = /;\s*charset\s*=\s*"?([^";]+)/i.exec(ct); |
| 10236 | if (charset && !/^utf-?8$/i.test(charset[1].trim())) |
| 10237 | throw new TypeError( |
| 10238 | `Unsupported charset "${charset[1].trim()}". FormData can only ` + |
| 10239 | "parse UTF-8 encoded bodies."); |
| 10240 | const form = new FormData(); |
| 10241 | for (const [key, value] of new URLSearchParams( |
| 10242 | new TextDecoder().decode(bytes))) |
| 10243 | form.append(key, value); |
| 10244 | return form; |
| 10245 | } |
| 10246 | if (!/^\s*multipart\/form-data/i.test(ct)) |
| 10247 | throw new TypeError( |
| 10248 | "Unrecognized Content-Type header value. FormData can only " + |
| 10249 | "parse the following MIME types: multipart/form-data, " + |
| 10250 | "application/x-www-form-urlencoded"); |
| 10251 | const found = /boundary\s*=\s*(?:"([^"]*)"|([^;]+))/i.exec(ct); |
| 10252 | if (!found) |
| 10253 | throw new TypeError( |
| 10254 | "No boundary was found in the multipart/form-data " + |
| 10255 | "Content-Type header."); |
| 10256 | const boundary = (found[1] !== undefined ? found[1] : found[2]).trim(); |
| 10257 | const form = new FormData(); |
| 10258 | const delimiter = new TextEncoder().encode("--" + boundary); |
| 10259 | // Walk the delimiters rather than splitting on them, so that a body whose |
| 10260 | // framing is truncated or corrupt is refused instead of silently yielding |
| 10261 | // the parts that happened to parse. Only the framing is checked; a part's |
| 10262 | // own bytes are carried through unexamined. The preamble before the first |
| 10263 | // delimiter and the epilogue after the closing one are ignored. |
| 10264 | let cursor = __delimiterIndex(bytes, delimiter, 0); |
| 10265 | if (cursor < 0) |
| 10266 | throw new TypeError( |
| 10267 | "No boundary delimiter was found in the multipart/form-data body."); |
| 10268 | cursor += delimiter.length; |
| 10269 | for (;;) { |
| 10270 | // What follows a delimiter decides everything: "--" closes the body, a |
| 10271 | // line break opens another part, and anything else is malformed. |
| 10272 | if (bytes[cursor] === __DASH && bytes[cursor + 1] === __DASH) break; |
| 10273 | const lineBreak = bytes[cursor] === __CR && bytes[cursor + 1] === __LF |
| 10274 | ? 2 |
| 10275 | : bytes[cursor] === __LF ? 1 : 0; |
| 10276 | if (lineBreak === 0) |
| 10277 | throw new TypeError( |
| 10278 | "A boundary delimiter must be followed by CRLF, LF, or \"--\"."); |
| 10279 | cursor += lineBreak; |
| 10280 | const partStart = cursor; |
| 10281 | const next = __delimiterIndex(bytes, delimiter, partStart); |
| 10282 | if (next < 0) |
| 10283 | throw new TypeError( |
| 10284 | "The multipart/form-data body ended without a closing boundary " + |
| 10285 | "delimiter."); |
| 10286 | // The line break before a delimiter belongs to the delimiter, not to the |
| 10287 | // part it terminates. |
| 10288 | let chunkEnd = next; |
| 10289 | if (chunkEnd > partStart && bytes[chunkEnd - 1] === __LF) { |
| 10290 | chunkEnd -= 1; |
| 10291 | if (chunkEnd > partStart && bytes[chunkEnd - 1] === __CR) chunkEnd -= 1; |
| 10292 | } |
| 10293 | cursor = next + delimiter.length; |
| 10294 | // The headers end at the first blank line. Either line break can be CRLF |
| 10295 | // or a bare LF, which accepted inputs can contain. |
| 10296 | let headerEnd = -1, bodyStart = -1; |
| 10297 | for (let i = partStart; i < chunkEnd; i++) { |
| 10298 | const first = bytes[i] === __CR && bytes[i + 1] === __LF |
| 10299 | ? 2 |
| 10300 | : bytes[i] === __LF ? 1 : 0; |
| 10301 | if (first === 0) continue; |
| 10302 | const after = i + first; |
| 10303 | const second = bytes[after] === __CR && bytes[after + 1] === __LF |
| 10304 | ? 2 |
| 10305 | : bytes[after] === __LF ? 1 : 0; |
| 10306 | if (second === 0) continue; |
| 10307 | headerEnd = i; |
| 10308 | bodyStart = after + second; |
| 10309 | break; |
| 10310 | } |
| 10311 | if (headerEnd < 0) |
| 10312 | throw new TypeError( |
| 10313 | "A FormData part's headers must be terminated by a blank line."); |
| 10314 | // Part headers are text. Decoding this slice as UTF-8 keeps a non-ASCII |
| 10315 | // name or filename intact and cannot reach the part body. |
| 10316 | const rawHeaders = new TextDecoder().decode( |
| 10317 | bytes.subarray(partStart, headerEnd)); |
| 10318 | const body = bytes.subarray(bodyStart, chunkEnd); |
| 10319 | let disposition = null; |
| 10320 | let type = ""; |
| 10321 | for (const line of rawHeaders.split(/\r?\n/)) { |
| 10322 | const colon = line.indexOf(":"); |
| 10323 | if (colon < 0) continue; |
| 10324 | const name = line.slice(0, colon).trim().toLowerCase(); |
| 10325 | const value = line.slice(colon + 1).trim(); |
| 10326 | if (name === "content-disposition") disposition = value; |
| 10327 | else if (name === "content-type") type = value; |
| 10328 | } |
| 10329 | if (disposition === null) |
| 10330 | throw new TypeError( |
| 10331 | "Content-Disposition header is required for each FormData " + |
| 10332 | "part."); |
| 10333 | const kind = disposition.split(";")[0].trim(); |
| 10334 | if (kind.toLowerCase() !== "form-data") |
| 10335 | throw new TypeError( |
| 10336 | "Content-Disposition header for FormData part must have the " + |
| 10337 | "value \"form-data\", possibly followed by parameters. Got: " + |
| 10338 | "\"" + kind + "\""); |
| 10339 | const param = (pattern) => { |
| 10340 | const m = pattern.exec(disposition); |
| 10341 | if (!m) return undefined; |
| 10342 | const raw = m[1] !== undefined ? m[1] : (m[2] || "").trim(); |
| 10343 | if (/\\$/.test(raw.replace(/\\\\/g, ""))) |
| 10344 | throw new TypeError( |
| 10345 | "Name or filename can't end with backslash"); |
| 10346 | return raw.replace(/\\(.)/g, "$1"); |
| 10347 | }; |
| 10348 | const name = param(__CD_NAME); |
| 10349 | if (name === undefined) |
| 10350 | throw new TypeError( |
| 10351 | "Content-Disposition header for FormData part must have a " + |
| 10352 | "name parameter."); |
| 10353 | const filename = param(__CD_FILENAME); |
| 10354 | // A part without a filename is an entry value, which the spec defines as a |
| 10355 | // string, so this one part is decoded as UTF-8. A file part keeps its |
| 10356 | // bytes. |
| 10357 | if (filename === undefined) |
| 10358 | form.append(name, new TextDecoder().decode(body)); |
| 10359 | else |
| 10360 | form.append( |
| 10361 | name, new File([body], filename, { type: type || "" })); |
| 10362 | } |
| 10363 | return form; |
| 10364 | }; |
| 10365 | // Spec entry conversion: strings stay strings; a Blob becomes a |
| 10366 | // File named "blob" (or `filename`); a File is renamed only when a |
| 10367 | // filename is supplied. |
| 10368 | const __formDataValue = (value, filename) => { |
| 10369 | if (!(value instanceof Blob)) return String(value); |
| 10370 | if (value instanceof File && filename === undefined) return value; |
| 10371 | return new File( |
| 10372 | [value], |
| 10373 | filename === undefined ? "blob" : String(filename), |
| 10374 | { |
| 10375 | type: value.type, |
| 10376 | lastModified: |
| 10377 | value instanceof File ? value.lastModified : undefined, |
| 10378 | }, |
| 10379 | ); |
| 10380 | }; |
| 10381 | globalThis.FormData = class FormData { |
| 10382 | constructor() { this._entries = []; } |
| 10383 | append(name, value, filename) { |
| 10384 | this._entries.push( |
| 10385 | [String(name), __formDataValue(value, filename)]); |
| 10386 | } |
| 10387 | set(name, value, filename) { |
| 10388 | value = __formDataValue(value, filename); |
| 10389 | const key = String(name); |
| 10390 | // Spec: replace the first match in place, keeping its position, |
| 10391 | // and drop any later matches. |
| 10392 | const first = this._entries.findIndex(([k]) => k === key); |
| 10393 | if (first < 0) { this._entries.push([key, value]); return; } |
| 10394 | this._entries[first] = [key, value]; |
| 10395 | for (let i = this._entries.length - 1; i > first; i--) |
| 10396 | if (this._entries[i][0] === key) this._entries.splice(i, 1); |
| 10397 | } |
| 10398 | get(name) { |
| 10399 | const row = this._entries.find(([key]) => key === String(name)); |
| 10400 | return row ? row[1] : null; |
| 10401 | } |
| 10402 | getAll(name) { |
| 10403 | return this._entries.filter(([key]) => key === String(name)).map(([, value]) => value); |
| 10404 | } |
| 10405 | has(name) { return this._entries.some(([key]) => key === String(name)); } |
| 10406 | delete(name) { |
| 10407 | const key = String(name); |
| 10408 | // Splice in place: the iterators below read the live list, so the |
| 10409 | // array identity must survive a delete during iteration. |
| 10410 | for (let i = this._entries.length - 1; i >= 0; i--) |
| 10411 | if (this._entries[i][0] === key) this._entries.splice(i, 1); |
| 10412 | } |
| 10413 | // Iteration is live: the iterator holds an index and re-reads the |
| 10414 | // entry list, so entries appended during iteration are visited and |
| 10415 | // an exhausted iterator resumes if entries are added later. A |
| 10416 | // generator cannot do this -- once it returns it is done forever. |
| 10417 | _iterate(pick) { |
| 10418 | const self = this; |
| 10419 | let index = 0; |
| 10420 | const iterator = { |
| 10421 | next() { |
| 10422 | if (index >= self._entries.length) |
| 10423 | return { value: undefined, done: true }; |
| 10424 | return { value: pick(self._entries[index++]), done: false }; |
| 10425 | }, |
| 10426 | [Symbol.iterator]() { return iterator; }, |
| 10427 | }; |
| 10428 | return iterator; |
| 10429 | } |
| 10430 | entries() { return this._iterate((e) => [e[0], e[1]]); } |
| 10431 | keys() { return this._iterate((e) => e[0]); } |
| 10432 | values() { return this._iterate((e) => e[1]); } |
| 10433 | [Symbol.iterator]() { return this.entries(); } |
| 10434 | forEach(callback, thisArg) { |
| 10435 | if (typeof callback !== "function") |
| 10436 | throw new TypeError( |
| 10437 | "Failed to execute 'forEach' on 'FormData': parameter 1 is " + |
| 10438 | "not of type 'Function'."); |
| 10439 | for (const [key, value] of this.entries()) |
| 10440 | callback.call(thisArg, value, key, this); |
| 10441 | } |
| 10442 | }; |
| 10443 | } |
| 10444 | // Node's Buffer lives in src/js/node_buffer.js, compiled |
| 10445 | // lazily (LAZY_GLOBALS / LAZY_MODULES) on first use. |
| 10446 | if (!globalThis.ErrorEvent) { |
| 10447 | globalThis.ErrorEvent = class ErrorEvent extends Event { |
| 10448 | constructor(type, init = {}) { |
| 10449 | super(type, init); |
| 10450 | this.message = String(init.message ?? ""); |
| 10451 | this.filename = String(init.filename ?? ""); |
| 10452 | this.lineno = Number(init.lineno ?? 0); |
| 10453 | this.colno = Number(init.colno ?? 0); |
| 10454 | this.error = init.error; |
| 10455 | } |
| 10456 | }; |
| 10457 | } |
| 10458 | // Web API globals a real bundle references at module scope but that the |
| 10459 | // prelude doesn't provide. Stub as empty classes (guarded so we never |
| 10460 | // clobber a real prelude implementation). Enough to LOAD; every name in |
| 10461 | // this first list has a real implementation elsewhere, so the empty class |
| 10462 | // only exists for the load-order window. |
| 10463 | for (const n of ["WebSocket", "EventTarget", "Event", "MessageEvent", |
| 10464 | "CloseEvent", "ErrorEvent", "SubtleCrypto", "TransformStream", |
| 10465 | "ReadableStream", "WritableStream", "ReadableStreamDefaultReader", |
| 10466 | "WritableStreamDefaultWriter", |
| 10467 | "ByteLengthQueuingStrategy", "CountQueuingStrategy", |
| 10468 | "TextEncoderStream", "TextDecoderStream"]) { |
| 10469 | if (!globalThis[n]) globalThis[n] = class {}; |
| 10470 | } |
| 10471 | // These have no implementation anywhere in celld. An empty class would |
| 10472 | // let `new BroadcastChannel(...)` hand back an inert object that fails |
| 10473 | // far from the cause; the compat contract is "reject at first use", so |
| 10474 | // the name loads but construction throws. (EventSource, MessageChannel, |
| 10475 | // and MessagePort are real; their scripts run after the harness.) |
| 10476 | for (const n of ["BroadcastChannel", "FileReader"]) { |
| 10477 | if (!globalThis[n]) globalThis[n] = class { |
| 10478 | constructor() { |
| 10479 | throw new Error(n + " is not implemented in celld"); |
| 10480 | } |
| 10481 | }; |
| 10482 | } |
| 10483 | const __sockets = __celld.__sockets = new Map(); |
| 10484 | globalThis.WebSocket = class WebSocket extends EventTarget { |
| 10485 | // The spec names, which workerd exposes and real bundles use. celld only |
| 10486 | // had the READY_STATE_* aliases, which no other runtime defines. |
| 10487 | static CONNECTING = 0; |
| 10488 | static OPEN = 1; |
| 10489 | static CLOSING = 2; |
| 10490 | static CLOSED = 3; |
| 10491 | static READY_STATE_CONNECTING = 0; |
| 10492 | static READY_STATE_OPEN = 1; |
| 10493 | static READY_STATE_CLOSING = 2; |
| 10494 | static READY_STATE_CLOSED = 3; |
| 10495 | constructor(id, protocols = [], boundTarget = null) { |
| 10496 | super(); |
| 10497 | const dialed = typeof id === "string"; |
| 10498 | // A socket bound to a Durable Object's socket behaves like a dialed one |
| 10499 | // in every way that matters here: the host carries its frames, so every |
| 10500 | // operation goes out through `__ws_*` on this id rather than to a peer |
| 10501 | // in this heap. |
| 10502 | const outbound = dialed || boundTarget !== null; |
| 10503 | this._outbound = outbound; |
| 10504 | this._boundTarget = boundTarget; |
| 10505 | this._bound = false; |
| 10506 | this._pendingClose = null; |
| 10507 | this._id = outbound ? __ws_alloc() : Number(id); |
| 10508 | this._attachment = undefined; |
| 10509 | this._target = null; |
| 10510 | this._accepted = false; |
| 10511 | this._hibernatable = false; |
| 10512 | this._pending = []; |
| 10513 | // The other end of an in-isolate upgrade (a WebSocketPair served |
| 10514 | // over a same-script service binding); frames route to it |
| 10515 | // directly instead of through the host connection. |
| 10516 | this._loopback = null; |
| 10517 | this.readyState = outbound ? 0 : 1; |
| 10518 | this._binaryType = __cell.compat?.websocketStandardBinaryType |
| 10519 | ? "blob" |
| 10520 | : "arraybuffer"; |
| 10521 | // A server-side socket has no URL, and reports null rather than an empty |
| 10522 | // string -- workerd's inspect output pins this. A socket that came back |
| 10523 | // from an upgrade has none either: nothing in this isolate dialed it. |
| 10524 | this.url = dialed ? id : null; |
| 10525 | this.protocol = ""; |
| 10526 | this.extensions = ""; |
| 10527 | if (boundTarget !== null) { |
| 10528 | // The caller drives this socket itself, exactly as a Worker drives one |
| 10529 | // it opened. The host pipe is not built until `accept()`, so a |
| 10530 | // response passed straight back out is left alone. |
| 10531 | this._polled = true; |
| 10532 | this._target = boundTarget; |
| 10533 | } |
| 10534 | if (dialed) { |
| 10535 | // workerd validates the URL in the constructor and throws |
| 10536 | // synchronously; letting the connector reject later would surface a |
| 10537 | // scheme mistake as a network failure instead of a TypeError. |
| 10538 | let parsed; |
| 10539 | try { |
| 10540 | parsed = new URL(id); |
| 10541 | } catch { |
| 10542 | throw new DOMException( |
| 10543 | "WebSocket Constructor: The url is invalid.", |
| 10544 | "SyntaxError"); |
| 10545 | } |
| 10546 | if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") { |
| 10547 | throw new DOMException( |
| 10548 | "WebSocket Constructor: The url scheme must be ws or wss.", |
| 10549 | "SyntaxError"); |
| 10550 | } |
| 10551 | // A Durable Object socket is pushed events by the host so it can revive |
| 10552 | // a hibernated cell. A Worker socket has no cell: the isolate polls it, |
| 10553 | // and it lives and dies with the request, which is the lifetime |
| 10554 | // Cloudflare gives one too. |
| 10555 | const scope = __currentActorScope(); |
| 10556 | this._polled = !scope; |
| 10557 | const requested = typeof protocols === "string" |
| 10558 | ? [protocols] |
| 10559 | : Array.from(protocols, String); |
| 10560 | for (const value of requested) { |
| 10561 | // RFC 6455 subprotocols are HTTP tokens; a space or separator would |
| 10562 | // otherwise be smuggled into the Sec-WebSocket-Protocol header. |
| 10563 | if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) { |
| 10564 | throw new DOMException( |
| 10565 | `WebSocket Constructor: The subprotocol '${value}' is invalid.`, |
| 10566 | "SyntaxError"); |
| 10567 | } |
| 10568 | } |
| 10569 | if (new Set(requested).size !== requested.length) { |
| 10570 | throw new DOMException( |
| 10571 | "WebSocket Constructor: The subprotocols must be unique.", |
| 10572 | "SyntaxError"); |
| 10573 | } |
| 10574 | __sockets.set(this._id, this); |
| 10575 | const connection = __ws_connect(this._id, scope, id, JSON.stringify(requested)); |
| 10576 | __registerWaitUntil(connection); |
| 10577 | if (this._polled) this._startPump(); |
| 10578 | connection.then((protocol) => { |
| 10579 | if (this.readyState === WebSocket.READY_STATE_CLOSING) { |
| 10580 | if (this._pendingClose) { |
| 10581 | const [code, reason] = this._pendingClose; |
| 10582 | __ws_close(this._id, code, reason); |
| 10583 | } |
| 10584 | return; |
| 10585 | } |
| 10586 | if (this.readyState !== WebSocket.READY_STATE_CONNECTING) return; |
| 10587 | this.protocol = protocol; |
| 10588 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 10589 | this.dispatchEvent(new Event("open")); |
| 10590 | }, (error) => { |
| 10591 | this.readyState = WebSocket.READY_STATE_CLOSED; |
| 10592 | __sockets.delete(this._id); |
| 10593 | this.dispatchEvent(new ErrorEvent("error", { message: String(error?.message || error), error })); |
| 10594 | this._dispatchClose(1006, "", false); |
| 10595 | }); |
| 10596 | } |
| 10597 | } |
| 10598 | // The pump ends only when the socket closes, so it must NOT be registered |
| 10599 | // as waitUntil work: that would hold the request open for as long as the |
| 10600 | // socket lives, and the host reclaims an abandoned socket only once the |
| 10601 | // request has retired. Its `__ws_next` ops are driven while the request |
| 10602 | // runs and normally resolve with the host's 1001 "request ended" close. |
| 10603 | // They resolve as 1006 only if the sender disappears without a close frame. |
| 10604 | _startPump() { |
| 10605 | if (this._pumping) return; |
| 10606 | this._pumping = true; |
| 10607 | this._pump().catch(() => {}); |
| 10608 | } |
| 10609 | // Drain the host queue for an isolate-polled socket. Each `__ws_next` is an |
| 10610 | // ordinary async op the request owns; a request that retires with the |
| 10611 | // socket still open closes it, which ends this loop with a close frame. |
| 10612 | async _pump() { |
| 10613 | for (;;) { |
| 10614 | const frame = await __ws_next(this._id); |
| 10615 | const tag = frame[0]; |
| 10616 | const body = frame.subarray(1); |
| 10617 | if (tag === 0) { |
| 10618 | this._dispatchMessage(new TextDecoder().decode(body)); |
| 10619 | } else if (tag === 1) { |
| 10620 | this._dispatchMessage( |
| 10621 | body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength), |
| 10622 | ); |
| 10623 | } else if (tag === 2) { |
| 10624 | if (this.readyState === WebSocket.READY_STATE_CONNECTING) { |
| 10625 | this.protocol = new TextDecoder().decode(body); |
| 10626 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 10627 | this.dispatchEvent(new Event("open")); |
| 10628 | } |
| 10629 | } else { |
| 10630 | const info = JSON.parse(new TextDecoder().decode(body)); |
| 10631 | this._dispatchClose(info.code, info.reason, info.wasClean); |
| 10632 | return; |
| 10633 | } |
| 10634 | } |
| 10635 | } |
| 10636 | // Deliver whatever this end queued before it had somewhere to send. |
| 10637 | _flushToPeer() { |
| 10638 | const peer = this._loopback; |
| 10639 | if (!peer) return; |
| 10640 | for (const frame of this._pending.splice(0)) { |
| 10641 | if (frame[0] === "send") { |
| 10642 | queueMicrotask(() => peer._dispatchMessage(frame[1])); |
| 10643 | } else if (frame[0] === "send-binary") { |
| 10644 | const data = frame[1]; |
| 10645 | const bytes = data instanceof ArrayBuffer |
| 10646 | ? data |
| 10647 | : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); |
| 10648 | queueMicrotask(() => peer._dispatchMessage(bytes)); |
| 10649 | } else { |
| 10650 | queueMicrotask(() => peer._dispatchClose(frame[1], frame[2], true)); |
| 10651 | } |
| 10652 | } |
| 10653 | } |
| 10654 | get binaryType() { return this._binaryType; } |
| 10655 | // The spec ignores an unrecognised value rather than throwing. |
| 10656 | set binaryType(value) { |
| 10657 | if (value === "blob" || value === "arraybuffer") this._binaryType = value; |
| 10658 | } |
| 10659 | accept() { |
| 10660 | this._accepted = true; |
| 10661 | // A pair used directly, without being returned through a 101 response, |
| 10662 | // still has to carry frames once both ends are accepted. celld only |
| 10663 | // linked a pair on the upgrade path, so such a pair queued forever. |
| 10664 | if (this._peer && this._peer._accepted && !this._loopback) { |
| 10665 | this._loopback = this._peer; |
| 10666 | this._peer._loopback = this; |
| 10667 | this._flushToPeer(); |
| 10668 | this._peer._flushToPeer(); |
| 10669 | } |
| 10670 | // A socket obtained from a `fetch()` upgrade is already connected and |
| 10671 | // delivers nothing until it is accepted; this is where it starts. |
| 10672 | if (this._outbound && this.readyState === WebSocket.READY_STATE_CONNECTING) { |
| 10673 | // Bind before the pump: the op registers this socket's queue on this |
| 10674 | // thread, so the first `__ws_next` cannot run ahead of it. |
| 10675 | if (this._boundTarget !== null && !this._bound) { |
| 10676 | this._bound = true; |
| 10677 | __ws_bind_target( |
| 10678 | this._id, |
| 10679 | JSON.stringify(this._boundTarget), |
| 10680 | __currentActorScope(), |
| 10681 | ); |
| 10682 | } |
| 10683 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 10684 | if (this._polled) this._startPump(); |
| 10685 | } |
| 10686 | } |
| 10687 | send(data) { |
| 10688 | if (this.readyState !== WebSocket.READY_STATE_OPEN) |
| 10689 | throw new DOMException("WebSocket is not open", "InvalidStateError"); |
| 10690 | const binary = data instanceof ArrayBuffer || ArrayBuffer.isView(data); |
| 10691 | const text = binary ? null : String(data); |
| 10692 | if (this._loopback) { |
| 10693 | const peer = this._loopback; |
| 10694 | const message = binary |
| 10695 | ? (data instanceof ArrayBuffer ? data.slice(0) : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)) |
| 10696 | : text; |
| 10697 | queueMicrotask(() => peer._dispatchMessage(message)); |
| 10698 | return; |
| 10699 | } |
| 10700 | // The pending queue belongs to an inbound pair socket that has been |
| 10701 | // accepted but not yet bound to a host transport. An outbound socket is |
| 10702 | // already bound -- queueing here would silently swallow its frames. |
| 10703 | if (!this._outbound && this._accepted && !this._target) { |
| 10704 | this._pending.push([binary ? "send-binary" : "send", binary ? data : text]); |
| 10705 | return; |
| 10706 | } |
| 10707 | if (binary) { |
| 10708 | const bytes = data instanceof ArrayBuffer |
| 10709 | ? new Uint8Array(data) |
| 10710 | : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); |
| 10711 | __ws_send_binary(this._id, bytes); |
| 10712 | } else { |
| 10713 | __ws_send(this._id, text); |
| 10714 | } |
| 10715 | } |
| 10716 | close(code = 1000, reason = "") { |
| 10717 | // WHATWG: an application may send 1000 or 3000-4999. Everything else is |
| 10718 | // reserved for the protocol itself. |
| 10719 | const wanted = Number(code); |
| 10720 | if (wanted !== 1000 && !(wanted >= 3000 && wanted <= 4999)) { |
| 10721 | throw new DOMException( |
| 10722 | `WebSocket close code ${code} is not permitted`, |
| 10723 | "InvalidAccessError"); |
| 10724 | } |
| 10725 | // RFC 6455 5.5: the close frame body is at most 125 bytes, two of which |
| 10726 | // are the code. Measured in UTF-8, so a multibyte reason can exceed the |
| 10727 | // cap at well under 123 characters. |
| 10728 | if (new TextEncoder().encode(String(reason)).length > 123) { |
| 10729 | throw new DOMException( |
| 10730 | "WebSocket close reason must not exceed 123 bytes", |
| 10731 | "SyntaxError"); |
| 10732 | } |
| 10733 | // Outbound sockets follow the WebSocket spec: closing a closed socket is a |
| 10734 | // no-op. Inbound sockets must NOT take that shortcut -- a Durable Object |
| 10735 | // answers a peer-initiated close from inside `webSocketClose`, by which |
| 10736 | // point `_dispatchClose` has already marked this side closed, and its |
| 10737 | // reply carries the reason the client is entitled to see. |
| 10738 | if (this._outbound && this.readyState === WebSocket.READY_STATE_CLOSED) { |
| 10739 | return; |
| 10740 | } |
| 10741 | const connecting = this.readyState === WebSocket.READY_STATE_CONNECTING; |
| 10742 | this.readyState = WebSocket.READY_STATE_CLOSING; |
| 10743 | if (this._outbound && connecting) { |
| 10744 | this._pendingClose = [code, reason]; |
| 10745 | return; |
| 10746 | } |
| 10747 | if (this._outbound) { |
| 10748 | __ws_close(this._id, code, reason); |
| 10749 | return; |
| 10750 | } |
| 10751 | this.readyState = 3; |
| 10752 | if (this._loopback) { |
| 10753 | const peer = this._loopback; |
| 10754 | queueMicrotask(() => peer._dispatchClose(code, reason, true)); |
| 10755 | return; |
| 10756 | } |
| 10757 | if (this._accepted && !this._target) { |
| 10758 | this._pending.push(["close", code, reason]); |
| 10759 | return; |
| 10760 | } |
| 10761 | __ws_close(this._id, code, reason); |
| 10762 | } |
| 10763 | _flushPending() { |
| 10764 | const pending = this._pending.splice(0); |
| 10765 | for (const frame of pending) { |
| 10766 | if (frame[0] === "send") __ws_send(this._id, frame[1]); |
| 10767 | else if (frame[0] === "send-binary") { |
| 10768 | const data = frame[1]; |
| 10769 | const bytes = data instanceof ArrayBuffer |
| 10770 | ? new Uint8Array(data) |
| 10771 | : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); |
| 10772 | __ws_send_binary(this._id, bytes); |
| 10773 | } |
| 10774 | else __ws_close(this._id, frame[1], frame[2]); |
| 10775 | } |
| 10776 | } |
| 10777 | serializeAttachment(value) { |
| 10778 | // Structured clone, not JSON: Cloudflare accepts anything cloneable |
| 10779 | // here, so a Date must come back a Date and a Map a Map. |
| 10780 | this._attachment = value; |
| 10781 | __ws_attachment_set(this._id, __sc_encode(value)); |
| 10782 | } |
| 10783 | deserializeAttachment() { return this._attachment; } |
| 10784 | _dispatchMessage(data) { |
| 10785 | if (this._binaryType === "blob" && data instanceof ArrayBuffer) { |
| 10786 | data = new Blob([data]); |
| 10787 | } |
| 10788 | const event = new MessageEvent("message", { data }); |
| 10789 | event._trust(); |
| 10790 | this.dispatchEvent(event); |
| 10791 | } |
| 10792 | _dispatchClose(code, reason, wasClean) { |
| 10793 | if (this.readyState === WebSocket.READY_STATE_CLOSED) return; |
| 10794 | this.readyState = WebSocket.READY_STATE_CLOSED; |
| 10795 | __sockets.delete(this._id); |
| 10796 | // An abnormal closure fires `error` before `close`. Code written against |
| 10797 | // the standard onerror never ran otherwise, which matters most for an |
| 10798 | // outbound socket: its peer is a remote server that can simply vanish. |
| 10799 | // An abnormal closure fires `error` before `close`. Code written against |
| 10800 | // the standard onerror never ran otherwise, which matters most for an |
| 10801 | // outbound socket: its peer is a remote server that can simply vanish. |
| 10802 | // An abnormal closure fires `error` before `close`. Code written against |
| 10803 | // the standard onerror never ran otherwise, which matters most for an |
| 10804 | // outbound socket: its peer is a remote server that can simply vanish. |
| 10805 | if (!wasClean) { |
| 10806 | this.dispatchEvent(new ErrorEvent("error", { |
| 10807 | message: reason |
| 10808 | ? `WebSocket closed abnormally: ${reason}` |
| 10809 | : "WebSocket closed abnormally", |
| 10810 | })); |
| 10811 | } |
| 10812 | const event = new CloseEvent("close", { code, reason, wasClean }); |
| 10813 | event._trust(); |
| 10814 | this.dispatchEvent(event); |
| 10815 | } |
| 10816 | }; |
| 10817 | const __makeSocket = __celld.__makeSocket = (id) => new WebSocket(id); |
| 10818 | const __socketFromRow = __celld.__socketFromRow = (row) => { |
| 10819 | let ws = __sockets.get(Number(row.id)); |
| 10820 | if (!ws) { |
| 10821 | ws = __makeSocket(row.id); |
| 10822 | __sockets.set(Number(row.id), ws); |
| 10823 | } |
| 10824 | ws._tags = row.tags || []; |
| 10825 | ws._hibernatable = true; |
| 10826 | if (row.attachment != null) { |
| 10827 | try { |
| 10828 | ws._attachment = __sc_decode(new Uint8Array(row.attachment)); |
| 10829 | } catch { |
| 10830 | ws._attachment = undefined; |
| 10831 | } |
| 10832 | } |
| 10833 | return ws; |
| 10834 | }; |
| 10835 | // Workerd's api::WebSocketRequestResponsePair (websocket.h): an immutable |
| 10836 | // request/response pair for state.setWebSocketAutoResponse. |
| 10837 | globalThis.WebSocketRequestResponsePair = |
| 10838 | class WebSocketRequestResponsePair { |
| 10839 | #request; |
| 10840 | #response; |
| 10841 | constructor(request, response) { |
| 10842 | this.#request = String(request); |
| 10843 | this.#response = String(response); |
| 10844 | } |
| 10845 | get request() { return this.#request; } |
| 10846 | get response() { return this.#response; } |
| 10847 | }; |
| 10848 | globalThis.WebSocketPair = function WebSocketPair() { |
| 10849 | const id = __ws_alloc(); |
| 10850 | const client = __makeSocket(id); |
| 10851 | const server = __makeSocket(id); |
| 10852 | client._peer = server; |
| 10853 | server._peer = client; |
| 10854 | // Indexed AND iterable: `const [client, server] = new WebSocketPair()` is |
| 10855 | // the form most Cloudflare code uses. |
| 10856 | return { |
| 10857 | 0: client, |
| 10858 | 1: server, |
| 10859 | length: 2, |
| 10860 | [Symbol.iterator]() { |
| 10861 | return [client, server][Symbol.iterator](); |
| 10862 | }, |
| 10863 | }; |
| 10864 | }; |
| 10865 | // Cloudflare exposes the time of the last I/O, not a clock that advances |
| 10866 | // while JavaScript runs. Keep Date and performance on one turn timestamp so |
| 10867 | // neither becomes a timing side channel and the two APIs cannot disagree. |
| 10868 | const __NativeDate = Date; |
| 10869 | let __ioTimestamp = 0; |
| 10870 | const __CloudflareDate = function Date(...args) { |
| 10871 | if (new.target) { |
| 10872 | return Reflect.construct( |
| 10873 | __NativeDate, |
| 10874 | args.length === 0 ? [__ioTimestamp] : args, |
| 10875 | new.target, |
| 10876 | ); |
| 10877 | } |
| 10878 | return new __NativeDate(__ioTimestamp).toString(); |
| 10879 | }; |
| 10880 | Object.defineProperties(__CloudflareDate, { |
| 10881 | length: { value: 7 }, |
| 10882 | prototype: { value: __NativeDate.prototype }, |
| 10883 | now: { |
| 10884 | value: () => __ioTimestamp, |
| 10885 | writable: true, |
| 10886 | configurable: true, |
| 10887 | }, |
| 10888 | parse: { |
| 10889 | value: __NativeDate.parse, |
| 10890 | writable: true, |
| 10891 | configurable: true, |
| 10892 | }, |
| 10893 | UTC: { |
| 10894 | value: __NativeDate.UTC, |
| 10895 | writable: true, |
| 10896 | configurable: true, |
| 10897 | }, |
| 10898 | }); |
| 10899 | Object.defineProperty(__NativeDate.prototype, "constructor", { |
| 10900 | value: __CloudflareDate, |
| 10901 | writable: true, |
| 10902 | configurable: true, |
| 10903 | }); |
| 10904 | globalThis.Date = __CloudflareDate; |
| 10905 | globalThis.performance = { |
| 10906 | now: () => __ioTimestamp, |
| 10907 | timeOrigin: 0, |
| 10908 | mark() {}, |
| 10909 | measure() {}, |
| 10910 | }; |
| 10911 | __celld.__advanceIoTime = (timestamp) => { |
| 10912 | __ioTimestamp = timestamp; |
| 10913 | }; |
| 10914 | // Workerd ServiceWorkerGlobalScope: `self` is the global scope, as a writable, |
| 10915 | // enumerable data property. Libraries probe it to find the global, and |
| 10916 | // @cloudflare/worker-bundler throws when it is absent. |
| 10917 | globalThis.self = globalThis; |
| 10918 | if (!globalThis.navigator) globalThis.navigator = { |
| 10919 | userAgent: "Cloudflare-Workers", hardwareConcurrency: 1, |
| 10920 | language: "en", languages: ["en"], |
| 10921 | }; |
| 10922 | if (!globalThis.queueMicrotask) |
| 10923 | globalThis.queueMicrotask = (f) => Promise.resolve().then(f); |
| 10924 | if (!globalThis.scheduler) |
| 10925 | globalThis.scheduler = { |
| 10926 | wait: (ms) => new Promise((resolve) => setTimeout(resolve, Number(ms) || 0)), |
| 10927 | }; |
| 10928 | if (!globalThis.structuredClone) { |
| 10929 | const hostBrand = Symbol("Cells.structuredCloneHost"); |
| 10930 | const deserializers = { |
| 10931 | Blob: (data) => new Blob([data.bytes], { type: data.mimeType }), |
| 10932 | File: (data) => new File([data.bytes], data.name, { |
| 10933 | type: data.mimeType, |
| 10934 | lastModified: data.lastModified, |
| 10935 | }), |
| 10936 | CryptoKey: (data) => new CryptoKey( |
| 10937 | data.keyType, data.algorithm, data.extractable, data.usages, data.material), |
| 10938 | DOMException: (data) => { |
| 10939 | const exception = new DOMException(data.message, data.name); |
| 10940 | if (data.stack !== undefined) |
| 10941 | Object.defineProperty(exception, "stack", { |
| 10942 | value: data.stack, configurable: true, writable: true, |
| 10943 | }); |
| 10944 | return exception; |
| 10945 | }, |
| 10946 | }; |
| 10947 | const defineHostType = (prototype, serialize) => { |
| 10948 | if (!Object.prototype.hasOwnProperty.call(prototype, hostBrand)) |
| 10949 | Object.defineProperty(prototype, hostBrand, { value: serialize }); |
| 10950 | }; |
| 10951 | const defineUnsupportedType = (constructor) => { |
| 10952 | if (typeof constructor === "function") |
| 10953 | defineHostType(constructor.prototype, null); |
| 10954 | }; |
| 10955 | |
| 10956 | defineHostType(Blob.prototype, function() { |
| 10957 | return { |
| 10958 | type: "Blob", bytes: this._bytes, |
| 10959 | mimeType: this.type, |
| 10960 | }; |
| 10961 | }); |
| 10962 | defineHostType(File.prototype, function() { |
| 10963 | return { |
| 10964 | type: "File", bytes: this._bytes, |
| 10965 | mimeType: this.type, name: this.name, |
| 10966 | lastModified: this.lastModified, |
| 10967 | }; |
| 10968 | }); |
| 10969 | defineHostType(DOMException.prototype, function() { |
| 10970 | return { |
| 10971 | type: "DOMException", message: this.message, |
| 10972 | name: this.name, stack: this.stack, |
| 10973 | }; |
| 10974 | }); |
| 10975 | |
| 10976 | globalThis.structuredClone = function(value, options) { |
| 10977 | if (arguments.length < 1) |
| 10978 | throw new TypeError( |
| 10979 | "Failed to execute 'structuredClone': 1 argument required"); |
| 10980 | const transfer = options?.transfer === undefined |
| 10981 | ? [] : Array.from(options.transfer); |
| 10982 | const seen = new Set(); |
| 10983 | for (let index = 0; index < transfer.length; index++) { |
| 10984 | const item = transfer[index]; |
| 10985 | if (!(item instanceof ArrayBuffer)) |
| 10986 | throw new DOMException( |
| 10987 | `Value at index ${index} is not transferable`, "DataCloneError"); |
| 10988 | if (item.detached) |
| 10989 | throw new DOMException( |
| 10990 | `ArrayBuffer at index ${index} is already detached`, |
| 10991 | "DataCloneError"); |
| 10992 | if (seen.has(item)) |
| 10993 | throw new DOMException( |
| 10994 | `ArrayBuffer at index ${index} is a duplicate`, "DataCloneError"); |
| 10995 | seen.add(item); |
| 10996 | } |
| 10997 | |
| 10998 | // Crypto loads after this harness, and MessagePort is also installed by a |
| 10999 | // later bootstrap script. Register every late type before V8 traverses the |
| 11000 | // graph. The delegate then sees host objects at any depth without a second |
| 11001 | // JavaScript traversal, which follows Deno's structured-clone design. |
| 11002 | if (typeof CryptoKey === "function") |
| 11003 | defineHostType(CryptoKey.prototype, function() { |
| 11004 | return { |
| 11005 | type: "CryptoKey", keyType: this.type, |
| 11006 | algorithm: this.algorithm, extractable: this.extractable, |
| 11007 | usages: this.usages, material: this.__celldMaterial, |
| 11008 | }; |
| 11009 | }); |
| 11010 | for (const constructor of [ |
| 11011 | URL, URLSearchParams, Headers, FormData, Request, Response, |
| 11012 | typeof MessagePort === "function" ? MessagePort : undefined, |
| 11013 | ]) defineUnsupportedType(constructor); |
| 11014 | |
| 11015 | let result; |
| 11016 | try { |
| 11017 | result = __structured_clone(value, hostBrand, deserializers); |
| 11018 | } catch (error) { |
| 11019 | if (error instanceof TypeError) |
| 11020 | throw new DOMException(error.message, "DataCloneError"); |
| 11021 | throw error; |
| 11022 | } |
| 11023 | // Validate the complete list and clone the value before detaching any |
| 11024 | // source. A later invalid entry therefore cannot leave an earlier buffer |
| 11025 | // detached after the operation fails. |
| 11026 | for (const item of transfer) item.transfer(); |
| 11027 | return result; |
| 11028 | }; |
| 11029 | } |
| 11030 | // Web Crypto is installed after the rest of the harness so it can use |
| 11031 | // DOMException, structuredClone, and Buffer. |
| 11032 | // `Buffer` is read at call time, which materializes the lazy global. |
| 11033 | const __zlibSync = (mode, data) => |
| 11034 | Buffer.from(__zlib(mode, Buffer.from(data))); |
| 11035 | __celld.__zlibModule = { |
| 11036 | constants: { |
| 11037 | Z_NO_FLUSH: 0, |
| 11038 | Z_PARTIAL_FLUSH: 1, |
| 11039 | Z_SYNC_FLUSH: 2, |
| 11040 | Z_FULL_FLUSH: 3, |
| 11041 | Z_FINISH: 4, |
| 11042 | Z_BLOCK: 5, |
| 11043 | }, |
| 11044 | gzipSync: (data, _options) => __zlibSync("gzip", data), |
| 11045 | gunzipSync: (data, _options) => __zlibSync("gunzip", data), |
| 11046 | deflateSync: (data, _options) => __zlibSync("deflate", data), |
| 11047 | inflateSync: (data, _options) => __zlibSync("inflate", data), |
| 11048 | deflateRawSync: (data, _options) => __zlibSync("deflateRaw", data), |
| 11049 | inflateRawSync: (data, _options) => __zlibSync("inflateRaw", data), |
| 11050 | }; |
| 11051 | // A Node dependency reads a `process` field at module scope and passes it |
| 11052 | // straight to something that rejects `undefined` -- `dirname(process.execPath)` |
| 11053 | // is one such case. Workerd defines every field |
| 11054 | // below with a neutral value, so the same bundle evaluates there. A missing |
| 11055 | // field therefore fails the whole Worker at load, which is why each one is |
| 11056 | // defined even though nothing in a cell has an executable path, a parent |
| 11057 | // process, or a real exit code. The values match workerd's |
| 11058 | // `src/node/internal/public_process.ts` at workerd revision 04a08513a419 |
| 11059 | // (2026-09-04); celld does not invent its own, because a dependency that reads |
| 11060 | // them is comparing them to what workerd reports. A field whose workerd |
| 11061 | // implementation throws at that revision -- `kill`, `binding`, `dlopen`, |
| 11062 | // `cpuUsage` -- stays absent, because it fails on both runtimes and a stub |
| 11063 | // here would only change the message. |
| 11064 | if (!globalThis.process) globalThis.process = { |
| 11065 | env: {}, platform: "linux", arch: "x64", version: "v20.0.0", |
| 11066 | versions: { node: "20.0.0" }, cwd: () => "/", |
| 11067 | title: "workerd", argv: ["workerd"], argv0: "workerd", execArgv: [], |
| 11068 | execPath: "", pid: 1, ppid: 0, exitCode: undefined, |
| 11069 | allowedNodeEnvironmentFlags: new Set(), |
| 11070 | release: { name: "node", lts: true, sourceUrl: "", headersUrl: "" }, |
| 11071 | channel: null, connected: false, debugPort: 0, domain: null, |
| 11072 | noDeprecation: false, traceDeprecation: false, throwDeprecation: false, |
| 11073 | sourceMapsEnabled: false, moduleLoadList: [], |
| 11074 | stdin: { fd: 0, isTTY: false }, |
| 11075 | stdout: { fd: 1, isTTY: false, write: (s) => { __log(String(s)); return true; } }, |
| 11076 | stderr: { fd: 2, isTTY: false, write: (s) => { __log(String(s)); return true; } }, |
| 11077 | nextTick: (f, ...a) => queueMicrotask(() => f(...a)), |
| 11078 | on() {}, once() {}, off() {}, emit() {}, hrtime: () => [0, 0], |
| 11079 | // Workerd routes a warning to the process 'warning' event, and this |
| 11080 | // process emits nothing, so a no-op keeps the two runtimes equivalent. |
| 11081 | emitWarning() {}, |
| 11082 | ref() {}, unref() {}, uptime: () => 0, |
| 11083 | constrainedMemory: () => 0, availableMemory: () => 0, |
| 11084 | memoryUsage: () => ({ |
| 11085 | rss: 0, heapTotal: 0, heapUsed: 0, external: 0, arrayBuffers: 0, |
| 11086 | }), |
| 11087 | }; |
| 11088 | globalThis.process.exit = (code = 0) => { |
| 11089 | const actorScope = __currentActorScope(); |
| 11090 | if (actorScope) { |
| 11091 | const instance = __cell.instances[actorScope]; |
| 11092 | if (instance?.__celldState) |
| 11093 | instance.__celldState._resetAfterConcurrencyFailure(); |
| 11094 | } |
| 11095 | __process_exit(Number(code) || 0, actorScope); |
| 11096 | }; |
| 11097 | globalThis.process.getBuiltinModule = |
| 11098 | (id) => __builtin_module(String(id)); |
| 11099 | if (!globalThis.global) globalThis.global = globalThis; |
| 11100 | // Events belong to the request, and the host owns the request. `__event_*` |
| 11101 | // and `__wait_until` operate on whichever context the host has made current |
| 11102 | // for this turn, so nothing here has to know which request is running -- and |
| 11103 | // two requests sharing an isolate cannot pop each other's events. |
| 11104 | const __registerWaitUntil = __celld.__registerWaitUntil = (promise) => { |
| 11105 | const tracked = Promise.resolve(promise).catch((error) => { |
| 11106 | console.error("waitUntil rejected", error); |
| 11107 | }); |
| 11108 | __wait_until(tracked); |
| 11109 | }; |
| 11110 | // `props` are the per-stub props a loopback service stub carries |
| 11111 | // (ctx.props); `exports` is built once, on first access. |
| 11112 | const __defaultProps = {}; |
| 11113 | const __entrypointContext = (props = __defaultProps) => ({ |
| 11114 | waitUntil: __registerWaitUntil, |
| 11115 | passThroughOnException() {}, |
| 11116 | abort: __ctxAbortCurrent, |
| 11117 | props, |
| 11118 | get exports() { return __ctxExports(); }, |
| 11119 | }); |
| 11120 | const __beginEvent = __celld.__beginEvent = (props = __defaultProps) => { |
| 11121 | __rpcSignalRefresh(); |
| 11122 | __event_begin(); |
| 11123 | return __entrypointContext(props); |
| 11124 | }; |
| 11125 | const __endEvent = __celld.__endEvent = () => __event_end(); |
| 11126 | // Workerd's writable filesystem is memory-backed and request-scoped. The |
| 11127 | // native IoContext owns the directory tree; this facade supplies Node's path, |
| 11128 | // error, Promise, and Stats shapes without exposing a host filesystem. |
| 11129 | const __fsPath = (value) => { |
| 11130 | if (value instanceof URL) { |
| 11131 | if (value.protocol !== "file:") { |
| 11132 | const error = new TypeError('The URL must be of scheme file'); |
| 11133 | error.code = "ERR_INVALID_URL_SCHEME"; |
| 11134 | throw error; |
| 11135 | } |
| 11136 | value = decodeURIComponent(value.pathname); |
| 11137 | } else if (globalThis.Buffer?.isBuffer(value)) { |
| 11138 | value = value.toString(); |
| 11139 | } else if (typeof value !== "string") { |
| 11140 | const error = new TypeError( |
| 11141 | 'The "path" argument must be of type string or an instance of Buffer or URL', |
| 11142 | ); |
| 11143 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11144 | throw error; |
| 11145 | } |
| 11146 | if (value.includes("\0")) { |
| 11147 | const error = new TypeError('The argument "path" must not contain null bytes'); |
| 11148 | error.code = "ERR_INVALID_ARG_VALUE"; |
| 11149 | throw error; |
| 11150 | } |
| 11151 | const absolute = value.startsWith("/") ? value : process.cwd() + "/" + value; |
| 11152 | const parts = []; |
| 11153 | for (const part of absolute.split("/")) { |
| 11154 | if (!part || part === ".") continue; |
| 11155 | if (part === "..") parts.pop(); |
| 11156 | else parts.push(part); |
| 11157 | } |
| 11158 | return "/" + parts.join("/"); |
| 11159 | }; |
| 11160 | const __fsError = (code, syscall, path) => { |
| 11161 | const e = new Error(`${code}: ${syscall} '${path}'`); |
| 11162 | e.errno = { EPERM: -1, ENOENT: -2, EEXIST: -17, ENOTDIR: -20 }[code]; |
| 11163 | e.code = code; |
| 11164 | e.syscall = syscall; |
| 11165 | e.path = path; |
| 11166 | return e; |
| 11167 | }; |
| 11168 | const __enoent = (path = "") => { throw __fsError("ENOENT", "open", path); }; |
| 11169 | const __fsStatsBadge = Symbol("fs.Stats"); |
| 11170 | class __FsStats { |
| 11171 | constructor(badge, kind, size, bigint) { |
| 11172 | if (badge !== __fsStatsBadge) throw new TypeError("Illegal constructor"); |
| 11173 | const file = kind === 3; |
| 11174 | this.dev = 0; |
| 11175 | this.ino = 0; |
| 11176 | // A bundle file is 0o100444 and a writable temporary directory is 0o40666, |
| 11177 | // matching the mode values workerd's fs-stat-test.js asserts. |
| 11178 | this.mode = (file ? 0o100000 : 0o40000) | 0o444 | (kind === 2 ? 0o222 : 0); |
| 11179 | this.nlink = 1; |
| 11180 | this.uid = 0; |
| 11181 | this.gid = 0; |
| 11182 | this.rdev = 0; |
| 11183 | this.size = size; |
| 11184 | this.blksize = 0; |
| 11185 | this.blocks = 0; |
| 11186 | this.atimeMs = this.mtimeMs = this.ctimeMs = this.birthtimeMs = 0; |
| 11187 | this.atime = new Date(0); |
| 11188 | this.mtime = new Date(0); |
| 11189 | this.ctime = new Date(0); |
| 11190 | this.birthtime = new Date(0); |
| 11191 | Object.defineProperty(this, "__kind", { value: file ? "file" : "directory" }); |
| 11192 | if (bigint) { |
| 11193 | for (const name of [ |
| 11194 | "dev", "ino", "mode", "nlink", "uid", "gid", "rdev", "size", |
| 11195 | "blksize", "blocks", "atimeMs", "mtimeMs", "ctimeMs", "birthtimeMs", |
| 11196 | ]) this[name] = BigInt(this[name]); |
| 11197 | this.atimeNs = 0n; |
| 11198 | this.mtimeNs = 0n; |
| 11199 | this.ctimeNs = 0n; |
| 11200 | this.birthtimeNs = 0n; |
| 11201 | } |
| 11202 | } |
| 11203 | isFile() { return this.__kind === "file"; } |
| 11204 | isDirectory() { return this.__kind === "directory"; } |
| 11205 | isBlockDevice() { return false; } |
| 11206 | isCharacterDevice() { return false; } |
| 11207 | isSymbolicLink() { return false; } |
| 11208 | isFIFO() { return false; } |
| 11209 | isSocket() { return false; } |
| 11210 | } |
| 11211 | const __fsOptions = (options, names) => { |
| 11212 | if (options === undefined) return {}; |
| 11213 | if (options === null || typeof options !== "object") { |
| 11214 | const error = new TypeError('The "options" argument must be of type object'); |
| 11215 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11216 | throw error; |
| 11217 | } |
| 11218 | for (const name of names) { |
| 11219 | if (options[name] !== undefined && typeof options[name] !== "boolean") { |
| 11220 | const error = new TypeError(`The "options.${name}" property must be of type boolean`); |
| 11221 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11222 | throw error; |
| 11223 | } |
| 11224 | } |
| 11225 | return options; |
| 11226 | }; |
| 11227 | const __fsMkdirSync = (value, options = {}) => { |
| 11228 | const path = __fsPath(value); |
| 11229 | if (typeof options === "number") options = { mode: options }; |
| 11230 | options = __fsOptions(options, ["recursive"]); |
| 11231 | const result = __vfs_mkdir(path, options.recursive === true); |
| 11232 | if (result && !result.startsWith("/")) throw __fsError(result, "mkdir", path); |
| 11233 | return result || undefined; |
| 11234 | }; |
| 11235 | const __fsStatSync = (value, options, syscall = "stat") => { |
| 11236 | const path = __fsPath(value); |
| 11237 | options = __fsOptions(options, ["bigint", "throwIfNoEntry"]); |
| 11238 | const [kind, size] = __vfs_stat(path); |
| 11239 | if (!kind) { |
| 11240 | if (options.throwIfNoEntry === false) return undefined; |
| 11241 | throw __fsError("ENOENT", syscall, path); |
| 11242 | } |
| 11243 | return new __FsStats(__fsStatsBadge, kind, size, options.bigint === true); |
| 11244 | }; |
| 11245 | const __fsLstatSync = (value, options) => __fsStatSync(value, options, "lstat"); |
| 11246 | const __fsRealpathSync = (value) => { |
| 11247 | const path = __fsPath(value); |
| 11248 | if (!__vfs_stat(path)[0]) throw __fsError("ENOENT", "realpath", path); |
| 11249 | return path; |
| 11250 | }; |
| 11251 | const __fsExistsSync = (value) => { |
| 11252 | try { return __vfs_stat(__fsPath(value))[0] !== 0; } |
| 11253 | catch { return false; } |
| 11254 | }; |
| 11255 | // Node returns a Buffer unless an encoding is given, as a string or as |
| 11256 | // `options.encoding`. Only `utf8` is decoded here; any other encoding falls |
| 11257 | // through to Buffer's own decoder. |
| 11258 | const __fsReadFileSync = (value, options) => { |
| 11259 | const path = __fsPath(value); |
| 11260 | const encoding = typeof options === "string" ? options : options?.encoding; |
| 11261 | const bytes = __vfs_read_file(path); |
| 11262 | if (bytes === undefined) { |
| 11263 | // A directory read fails differently from a missing path, so the stat |
| 11264 | // decides which error the caller sees. |
| 11265 | if (__vfs_stat(path)[0]) throw __fsError("EISDIR", "read", path); |
| 11266 | throw __fsError("ENOENT", "open", path); |
| 11267 | } |
| 11268 | const buffer = Buffer.from(bytes); |
| 11269 | return encoding ? buffer.toString(encoding) : buffer; |
| 11270 | }; |
| 11271 | // `fs.constants`, with the four access modes from workerd's |
| 11272 | // `src/node/internal/internal_fs_constants.ts`. The table carries only the |
| 11273 | // modes `access` reads. Every other constant belongs to an operation the |
| 11274 | // virtual filesystem does not implement, and that operation already fails |
| 11275 | // loudly at the unimplemented-builtin stub, so publishing its constants would |
| 11276 | // only make a caller build a mode for a call it cannot make. |
| 11277 | const __fsConstants = Object.freeze({ F_OK: 0, X_OK: 1, W_OK: 2, R_OK: 4 }); |
| 11278 | // Node validates a mode before it reaches the filesystem, so a bad mode is an |
| 11279 | // argument error and never a filesystem error. The range is the union of the |
| 11280 | // four access modes, which is what workerd's `validateMode` allows. |
| 11281 | const __fsMode = (mode) => { |
| 11282 | if (mode === undefined) return __fsConstants.F_OK; |
| 11283 | if (typeof mode !== "number") { |
| 11284 | const error = new TypeError('The "mode" argument must be of type number'); |
| 11285 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11286 | throw error; |
| 11287 | } |
| 11288 | if (!Number.isInteger(mode) || mode < 0 || mode > 7) { |
| 11289 | const error = new RangeError( |
| 11290 | `The value of "mode" is out of range. It must be >= 0 && <= 7. Received ${mode}`, |
| 11291 | ); |
| 11292 | error.code = "ERR_OUT_OF_RANGE"; |
| 11293 | throw error; |
| 11294 | } |
| 11295 | return mode; |
| 11296 | }; |
| 11297 | // `access` reports what the virtual filesystem can do and not a POSIX |
| 11298 | // permission, so it follows workerd's `accessSyncImpl`: no file is executable, |
| 11299 | // therefore `X_OK` always fails, and an unwritable path fails exactly like a |
| 11300 | // missing one, so a caller cannot tell the two apart. Kind 2 is the writable |
| 11301 | // tree; see `op_vfs_stat`. |
| 11302 | const __fsAccessSync = (value, mode) => { |
| 11303 | const path = __fsPath(value); |
| 11304 | mode = __fsMode(mode); |
| 11305 | const [kind] = __vfs_stat(path); |
| 11306 | const denied = mode & __fsConstants.X_OK |
| 11307 | || !kind |
| 11308 | || (mode & __fsConstants.W_OK && kind !== 2); |
| 11309 | if (denied) throw __fsError("ENOENT", "access", path); |
| 11310 | }; |
| 11311 | // The callback forms run the same synchronous core as `fs.promises`. |
| 11312 | // Validation and the operation are separate arguments, not one function, |
| 11313 | // because they fail differently: an argument error throws, and only a |
| 11314 | // filesystem error reaches the callback. One combined body would route both to |
| 11315 | // the callback and hide a caller's bug behind an error it did not expect. |
| 11316 | // |
| 11317 | // `validate()` runs before the callback check, which is workerd's order: each |
| 11318 | // entry point in `internal_fs_callback.ts` validates its path and its options, |
| 11319 | // and only then calls `callWithSingleArgCallback`. Node checks the callback |
| 11320 | // first, so a call that has a bad path and no callback reports the path here |
| 11321 | // and reports the callback in Node. Both are `ERR_INVALID_ARG_TYPE`, and the |
| 11322 | // runtime follows workerd. |
| 11323 | const __fsDeliver = (validate, run, callback, deliver) => { |
| 11324 | validate(); |
| 11325 | if (typeof callback !== "function") { |
| 11326 | const error = new TypeError('The "cb" argument must be of type function'); |
| 11327 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11328 | throw error; |
| 11329 | } |
| 11330 | let result; |
| 11331 | try { |
| 11332 | result = run(); |
| 11333 | } catch (error) { |
| 11334 | // A callback delivered in this turn would let a caller observe the result |
| 11335 | // before its own call returned, which Node never does. |
| 11336 | queueMicrotask(() => callback(error)); |
| 11337 | return; |
| 11338 | } |
| 11339 | queueMicrotask(() => deliver(result)); |
| 11340 | }; |
| 11341 | // An operation with a result calls back with `(error, result)`, and one |
| 11342 | // without calls back with `(error)` alone. Workerd splits the two the same way |
| 11343 | // (`callWithSingleArgCallback` and `callWithErrorOnlyCallback`), because a |
| 11344 | // caller can read `arguments.length` and see the difference. |
| 11345 | const __fsCallback = (validate, run, callback) => |
| 11346 | __fsDeliver(validate, run, callback, (result) => callback(null, result)); |
| 11347 | const __fsErrorOnlyCallback = (validate, run, callback) => |
| 11348 | __fsDeliver(validate, run, callback, () => callback(null)); |
| 11349 | // Node accepts `(path, callback)` or `(path, options, callback)` everywhere. |
| 11350 | const __fsCallbackArgs = (options, callback) => |
| 11351 | typeof options === "function" ? [undefined, options] : [options, callback]; |
| 11352 | const __fsAccess = (value, mode, callback) => { |
| 11353 | [mode, callback] = __fsCallbackArgs(mode, callback); |
| 11354 | __fsErrorOnlyCallback( |
| 11355 | () => { __fsPath(value); __fsMode(mode); }, |
| 11356 | () => __fsAccessSync(value, mode), |
| 11357 | callback, |
| 11358 | ); |
| 11359 | }; |
| 11360 | const __fsStat = (value, options, callback) => { |
| 11361 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11362 | __fsCallback( |
| 11363 | () => { __fsPath(value); __fsOptions(options, ["bigint", "throwIfNoEntry"]); }, |
| 11364 | () => __fsStatSync(value, options), |
| 11365 | callback, |
| 11366 | ); |
| 11367 | }; |
| 11368 | const __fsLstat = (value, options, callback) => { |
| 11369 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11370 | __fsCallback( |
| 11371 | () => { __fsPath(value); __fsOptions(options, ["bigint", "throwIfNoEntry"]); }, |
| 11372 | () => __fsLstatSync(value, options), |
| 11373 | callback, |
| 11374 | ); |
| 11375 | }; |
| 11376 | const __fsRealpath = (value, options, callback) => { |
| 11377 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11378 | __fsCallback( |
| 11379 | () => __fsPath(value), |
| 11380 | () => __fsRealpathSync(value), |
| 11381 | callback, |
| 11382 | ); |
| 11383 | }; |
| 11384 | const __fsReadFile = (value, options, callback) => { |
| 11385 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11386 | __fsCallback( |
| 11387 | () => __fsPath(value), |
| 11388 | () => __fsReadFileSync(value, options), |
| 11389 | callback, |
| 11390 | ); |
| 11391 | }; |
| 11392 | const __fsMkdir = (value, options, callback) => { |
| 11393 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11394 | __fsCallback( |
| 11395 | () => { |
| 11396 | __fsPath(value); |
| 11397 | // A number is the mode, which `mkdirSync` validates but does not apply. |
| 11398 | if (typeof options !== "number") __fsOptions(options, ["recursive"]); |
| 11399 | }, |
| 11400 | () => __fsMkdirSync(value, options), |
| 11401 | callback, |
| 11402 | ); |
| 11403 | }; |
| 11404 | const __fsPromisesSurface = { |
| 11405 | // The promise form validates inside the promise, so an argument error |
| 11406 | // rejects instead of throwing. Workerd makes the same split, because a |
| 11407 | // caller of a promise API has no synchronous frame to catch. |
| 11408 | async access(...args) { return __fsAccessSync(...args); }, |
| 11409 | async mkdir(...args) { return __fsMkdirSync(...args); }, |
| 11410 | async stat(...args) { return __fsStatSync(...args); }, |
| 11411 | async lstat(...args) { return __fsLstatSync(...args); }, |
| 11412 | async realpath(...args) { return __fsRealpathSync(...args); }, |
| 11413 | async readFile(...args) { return __fsReadFileSync(...args); }, |
| 11414 | }; |
| 11415 | // A namespace import gets a fixed export set when V8 links the module, so a |
| 11416 | // partial module must enumerate unsupported Node exports too. A get trap alone |
| 11417 | // keeps default and named imports loud but silently omits these names from a |
| 11418 | // namespace. Keep the unsupported names lazy: materializing every stub in |
| 11419 | // every isolate would charge Workers that use only the implemented subset. |
| 11420 | const __fsNamespaceProxy = (surface, path, names, enoentNames = []) => { |
| 11421 | const namespaceNames = new Set([...Reflect.ownKeys(surface), ...names]); |
| 11422 | const enoentNameSet = new Set(enoentNames); |
| 11423 | return new Proxy(surface, { |
| 11424 | get: (target, p) => { |
| 11425 | if (Reflect.has(target, p)) return Reflect.get(target, p); |
| 11426 | if (enoentNameSet.has(p)) return __enoent; |
| 11427 | if (typeof p !== "string") return undefined; |
| 11428 | return __nodeStubFor(path + "." + p); |
| 11429 | }, |
| 11430 | ownKeys: () => [...namespaceNames], |
| 11431 | // A lazy name has no descriptor on the target, so the synthetic one below |
| 11432 | // completes to `writable: false`. Without this trap an assignment would |
| 11433 | // reach OrdinarySet, read that descriptor off the proxy as the receiver, |
| 11434 | // and throw "Cannot redefine property". CommonJS dependencies patch a |
| 11435 | // builtin at module scope, so the throw takes the whole Worker down at |
| 11436 | // load. Write through to the surface instead, which also promotes the name |
| 11437 | // to a real own property and keeps the descriptor honest from then on. |
| 11438 | // Materializing a complete descriptor in the trap below would fix the |
| 11439 | // assignment too, but it would charge every Worker for all the stubs the |
| 11440 | // moment anything enumerates the namespace. |
| 11441 | set: (target, p, value) => Reflect.set(target, p, value), |
| 11442 | getOwnPropertyDescriptor: (target, p) => |
| 11443 | Reflect.getOwnPropertyDescriptor(target, p) ?? |
| 11444 | (namespaceNames.has(p) |
| 11445 | ? { configurable: true, enumerable: true } |
| 11446 | : undefined), |
| 11447 | }); |
| 11448 | }; |
| 11449 | const __fsPromises = __celld.__fsPromises = __fsNamespaceProxy( |
| 11450 | __fsPromisesSurface, |
| 11451 | "node:fs/promises", |
| 11452 | [ |
| 11453 | "appendFile", "chmod", "chown", "copyFile", "cp", "lchmod", "lchown", |
| 11454 | "link", "lutimes", "mkdtemp", "open", "opendir", "readdir", "readlink", |
| 11455 | "rename", "rm", "rmdir", "statfs", "symlink", "truncate", "unlink", |
| 11456 | "utimes", "watch", "writeFile", |
| 11457 | ], |
| 11458 | ); |
| 11459 | const __fsSurface = { |
| 11460 | Stats: __FsStats, |
| 11461 | constants: __fsConstants, |
| 11462 | promises: __fsPromises, |
| 11463 | accessSync: __fsAccessSync, |
| 11464 | access: __fsAccess, |
| 11465 | existsSync: __fsExistsSync, |
| 11466 | mkdirSync: __fsMkdirSync, |
| 11467 | statSync: __fsStatSync, |
| 11468 | lstatSync: __fsLstatSync, |
| 11469 | realpathSync: __fsRealpathSync, |
| 11470 | readFileSync: __fsReadFileSync, |
| 11471 | stat: __fsStat, |
| 11472 | lstat: __fsLstat, |
| 11473 | realpath: __fsRealpath, |
| 11474 | readFile: __fsReadFile, |
| 11475 | mkdir: __fsMkdir, |
| 11476 | }; |
| 11477 | const __fsNamespaceNames = [ |
| 11478 | "Dir", "Dirent", "ReadStream", "WriteStream", "_toUnixTimestamp", |
| 11479 | "appendFile", "appendFileSync", "chmod", "chmodSync", "chown", "chownSync", |
| 11480 | "close", "closeSync", "copyFile", "copyFileSync", "cp", "cpSync", |
| 11481 | "createReadStream", "createWriteStream", "exists", "fchmod", "fchmodSync", |
| 11482 | "fchown", "fchownSync", "fdatasync", "fdatasyncSync", "fstat", "fstatSync", |
| 11483 | "fsync", "fsyncSync", "ftruncate", "ftruncateSync", "futimes", "futimesSync", |
| 11484 | "lchmod", "lchmodSync", "lchown", "lchownSync", "link", "linkSync", |
| 11485 | "lutimes", "lutimesSync", "mkdtemp", "mkdtempSync", "open", "openSync", |
| 11486 | "opendir", "opendirSync", "read", "readSync", "readdir", "readdirSync", |
| 11487 | "readlink", "readlinkSync", "readv", "readvSync", "rename", "renameSync", |
| 11488 | "rm", "rmSync", "rmdir", "rmdirSync", "statfs", "statfsSync", "symlink", |
| 11489 | "symlinkSync", "truncate", "truncateSync", "unlink", "unlinkSync", |
| 11490 | "unwatchFile", "utimes", "utimesSync", "watch", "watchFile", "write", |
| 11491 | "writeFile", "writeFileSync", "writeSync", "writev", "writevSync", |
| 11492 | ]; |
| 11493 | // Writable file contents and every mutation remain explicit unsupported |
| 11494 | // surfaces until a failing application seam requires them. These two reads |
| 11495 | // use ENOENT so dependencies can take their no-filesystem fallback path. |
| 11496 | __celld.__fs = __fsNamespaceProxy( |
| 11497 | __fsSurface, |
| 11498 | "node:fs", |
| 11499 | __fsNamespaceNames, |
| 11500 | ["readdirSync", "readlinkSync"], |
| 11501 | ); |
| 11502 | const __bridgeResponseStream = (body, requestControllers) => { |
| 11503 | const streamId = __response_stream_create(); |
| 11504 | const pump = (async () => { |
| 11505 | const reader = body.getReader(); |
| 11506 | const consumerClosed = __response_stream_closed(streamId) |
| 11507 | .then((status) => status === "cancelled" |
| 11508 | ? { consumerClosed: true } |
| 11509 | : new Promise(() => {})); |
| 11510 | const cancelProducer = async () => { |
| 11511 | const reason = new Error("The client has disconnected"); |
| 11512 | for (const controller of requestControllers || []) { |
| 11513 | if (!controller.signal.aborted) controller.abort(reason); |
| 11514 | } |
| 11515 | try { |
| 11516 | await reader.cancel(reason); |
| 11517 | } catch {} |
| 11518 | await __response_stream_close(streamId, ""); |
| 11519 | }; |
| 11520 | try { |
| 11521 | for (;;) { |
| 11522 | const result = await Promise.race([ |
| 11523 | reader.read().then((read) => ({ read })), |
| 11524 | consumerClosed, |
| 11525 | ]); |
| 11526 | if (result.consumerClosed) { |
| 11527 | await cancelProducer(); |
| 11528 | return; |
| 11529 | } |
| 11530 | if (result.read.done) { |
| 11531 | await __response_stream_close(streamId, ""); |
| 11532 | return; |
| 11533 | } |
| 11534 | const bytes = __bodyBytes(result.read.value); |
| 11535 | for (let offset = 0; offset < bytes.byteLength; offset += 64 * 1024) { |
| 11536 | await __response_stream_write( |
| 11537 | streamId, |
| 11538 | bytes.subarray(offset, offset + 64 * 1024), |
| 11539 | ); |
| 11540 | } |
| 11541 | } |
| 11542 | } catch (error) { |
| 11543 | if (String(error).includes("response stream consumer canceled")) { |
| 11544 | await cancelProducer(); |
| 11545 | return; |
| 11546 | } |
| 11547 | await __response_stream_close(streamId, String(error)); |
| 11548 | } |
| 11549 | })(); |
| 11550 | __registerWaitUntil(pump); |
| 11551 | return streamId; |
| 11552 | }; |
| 11553 | __celld.__readResponse = (r) => { |
| 11554 | if (!(r instanceof Response)) { |
| 11555 | return { |
| 11556 | status: 200, |
| 11557 | bodyBytes: new TextEncoder().encode(String(r)), |
| 11558 | bodyStreamId: 0, |
| 11559 | headersJson: "[]", |
| 11560 | wsTargetJson: "null", |
| 11561 | workerSocketId: 0, |
| 11562 | }; |
| 11563 | } |
| 11564 | // Keep the network-error marker out of the HTTP response fields. If status |
| 11565 | // zero reaches Rust as an ordinary response, the outer server can report |
| 11566 | // only a generic invalid status instead of the Worker contract failure. |
| 11567 | if (r.type === "error" || r.status === 0) |
| 11568 | return { error: __ERROR_RESPONSE_MESSAGE }; |
| 11569 | let workerSocketId = 0; |
| 11570 | let wsTarget = r._wsTarget || (r.webSocket && r.webSocket._target) || null; |
| 11571 | if (r.status === 101 && r.webSocket && wsTarget === null) { |
| 11572 | const server = r.webSocket._peer; |
| 11573 | if (server && server._accepted) { |
| 11574 | workerSocketId = server._id; |
| 11575 | // Install the host queue before the pump asks for its first frame. The |
| 11576 | // target marker makes sends use that queue instead of remaining in the |
| 11577 | // pair's pre-upgrade buffer. |
| 11578 | __ws_prepare_worker_handoff(workerSocketId); |
| 11579 | server._target = { id: workerSocketId, scope: "" }; |
| 11580 | server._polled = true; |
| 11581 | __sockets.set(workerSocketId, server); |
| 11582 | server._startPump(); |
| 11583 | server._flushPending(); |
| 11584 | } |
| 11585 | } |
| 11586 | const bodyStreamId = r._bodyBytes === null |
| 11587 | ? typeof r.body?.__celldStreamId === "number" && |
| 11588 | !r.__celldRequestControllers |
| 11589 | ? r.body.__celldStreamId |
| 11590 | : __bridgeResponseStream( |
| 11591 | r.body, |
| 11592 | r.__celldRequestControllers, |
| 11593 | ) |
| 11594 | : 0; |
| 11595 | if (bodyStreamId) { |
| 11596 | return { |
| 11597 | status: r.status, |
| 11598 | bodyBytes: new Uint8Array(), |
| 11599 | bodyStreamId, |
| 11600 | headersJson: JSON.stringify(Array.from(r.headers)), |
| 11601 | wsTargetJson: JSON.stringify(wsTarget), |
| 11602 | workerSocketId, |
| 11603 | }; |
| 11604 | } |
| 11605 | const bytes = r._bodyBytes; |
| 11606 | return { |
| 11607 | status: r.status, |
| 11608 | bodyBytes: bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), |
| 11609 | bodyStreamId: 0, |
| 11610 | headersJson: JSON.stringify(Array.from(r.headers)), |
| 11611 | wsTargetJson: JSON.stringify(wsTarget), |
| 11612 | workerSocketId, |
| 11613 | }; |
| 11614 | }; |