| 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 | if (this._bodyBytes === null) |
| 364 | throw new TypeError("Cannot clone a streaming response before consumption"); |
| 365 | const response = new Response( |
| 366 | this.body === null ? null : this._bodyBytes, |
| 367 | { |
| 368 | status: this.status, statusText: this.statusText, headers: this.headers, |
| 369 | webSocket: this.webSocket, __wsTarget: this._wsTarget, cf: this.cf, |
| 370 | }, |
| 371 | ); |
| 372 | response.type = this.type; |
| 373 | return response; |
| 374 | } |
| 375 | }; |
| 376 | // Hoisted: this would otherwise allocate an array and scan it on |
| 377 | // every Request construction, which is the HTTP hot path. |
| 378 | const __HTTP_METHODS = new Set( |
| 379 | ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]); |
| 380 | const __FETCH_REDIRECT_MODES = new Set(["follow", "manual", "error"]); |
| 381 | globalThis.Request = class Request { |
| 382 | constructor(input, init = {}) { |
| 383 | const prior = input instanceof Request ? input : null; |
| 384 | const suppliedSignal = init.signal !== undefined; |
| 385 | // The cache option needs the cache_option_enabled compat flag, |
| 386 | // which Cells does not implement (Workerd's cache-disabled path). |
| 387 | if (init.cache !== undefined) |
| 388 | throw new Error("The 'cache' field on 'RequestInitializerDict' " + |
| 389 | "is not implemented."); |
| 390 | this.url = prior ? prior.url : String(input); |
| 391 | { |
| 392 | // Workers upper-cases every method (the |
| 393 | // upper_case_all_http_methods flag) but rejects anything outside |
| 394 | // the known set, reporting the original casing. |
| 395 | const raw = String(init.method === undefined |
| 396 | ? (prior ? prior.method : "GET") : init.method); |
| 397 | const upper = raw.toUpperCase(); |
| 398 | if (!__HTTP_METHODS.has(upper)) |
| 399 | throw new TypeError(`Invalid HTTP method string: ${raw}`); |
| 400 | this.method = upper; |
| 401 | } |
| 402 | const hasBody = |
| 403 | Object.prototype.hasOwnProperty.call(init, "body"); |
| 404 | let body = hasBody ? init.body : null; |
| 405 | let stream = null; |
| 406 | let typed = null; |
| 407 | if (hasBody && body !== null && typeof body === "object") { |
| 408 | if (body instanceof ReadableStream) stream = body; |
| 409 | else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ } |
| 410 | else { |
| 411 | const iterable = __iterableBody(body); |
| 412 | if (iterable instanceof ReadableStream) stream = iterable; |
| 413 | else if (iterable !== null) body = iterable; |
| 414 | } |
| 415 | } |
| 416 | if (!hasBody && prior && prior._bodyBytes === null) { |
| 417 | // Adopt the prior request's stream; per spec the prior body |
| 418 | // is disturbed by the new request. |
| 419 | stream = prior.body; |
| 420 | prior.bodyUsed = true; |
| 421 | } |
| 422 | this._bodyBytes = stream !== null |
| 423 | ? null |
| 424 | : hasBody |
| 425 | ? (typed ? typed.bytes : __bodyBytes(body)) |
| 426 | : (prior ? prior._bodyBytes.slice() : new Uint8Array()); |
| 427 | // Body text is decoded on the first text()/json(), not here: a request |
| 428 | // whose body is never read never pays the decode. |
| 429 | this._body = undefined; |
| 430 | // Headers are stored raw and built on the first `.headers` access. The |
| 431 | // hot paths -- a hello world, a Worker that only forwards to a cell -- |
| 432 | // read none, so `new Headers` and the JSON.parse behind it never run. |
| 433 | if (init.__headersJson !== undefined) { |
| 434 | this._headersJson = init.__headersJson; |
| 435 | this._headersInit = undefined; |
| 436 | } else if (init.headers === undefined && prior) { |
| 437 | this._headersJson = prior._headersJson; |
| 438 | // Per spec `new Request(request)` copies the header list. The prior |
| 439 | // request's `Headers` object cannot stand in for it: `new Headers(h)` |
| 440 | // reads `h` through its iterator, which sorts, lower-cases and |
| 441 | // combines, so forwarding a request whose headers were read would |
| 442 | // undo the wire shape the outbound paths preserve. |
| 443 | this._headersInit = prior._headers |
| 444 | ? prior._headers.__celldHeaderList |
| 445 | : prior._headersInit; |
| 446 | } else { |
| 447 | this._headersJson = undefined; |
| 448 | this._headersInit = init.headers; |
| 449 | } |
| 450 | this._headers = null; |
| 451 | // A typed body's default content-type must land now; only user-built |
| 452 | // typed bodies reach this, never the incoming request path. |
| 453 | if (typed && typed.type && !this.headers.has("content-type")) { |
| 454 | this.headers.set("content-type", typed.type); |
| 455 | } |
| 456 | this.bodyUsed = false; |
| 457 | // The body stream and the signal stay eager, own properties: the RPC and |
| 458 | // storage serializers fall back to the lift-into-marker path only when a |
| 459 | // value is not directly structured-cloneable, and a Request's un-cloneable |
| 460 | // body stream (or AbortSignal) is what triggers that. Making them lazy |
| 461 | // getters let `__sc_encode` clone the Request into a broken plain object |
| 462 | // and skip the lift -- the serializeHttpTypes conformance failure. |
| 463 | this.body = stream !== null |
| 464 | ? stream |
| 465 | : ["GET", "HEAD"].includes(this.method) |
| 466 | ? null : new CelldBodyStream(this); |
| 467 | this.redirect = String(init.redirect === undefined |
| 468 | ? (prior ? prior.redirect : "follow") |
| 469 | : init.redirect); |
| 470 | if (!__FETCH_REDIRECT_MODES.has(this.redirect)) { |
| 471 | throw new TypeError(`Invalid redirect mode: ${this.redirect}`); |
| 472 | } |
| 473 | const cf = init.cf === undefined |
| 474 | ? (prior ? prior.cf : undefined) : init.cf; |
| 475 | if (cf !== undefined) this.cf = cf; |
| 476 | this.signal = suppliedSignal |
| 477 | ? init.signal |
| 478 | : (prior ? prior.signal : new AbortController().signal); |
| 479 | this._signalForSubrequests = init.__celldIncomingSignal |
| 480 | ? null |
| 481 | : suppliedSignal |
| 482 | ? this.signal |
| 483 | : (prior ? prior._signalForSubrequests : null); |
| 484 | } |
| 485 | get headers() { |
| 486 | if (this._headers === null) { |
| 487 | const src = this._headersJson !== undefined |
| 488 | ? JSON.parse(this._headersJson) |
| 489 | : this._headersInit; |
| 490 | this._headers = new Headers(src); |
| 491 | this._headersJson = undefined; |
| 492 | this._headersInit = undefined; |
| 493 | } |
| 494 | return this._headers; |
| 495 | } |
| 496 | set headers(value) { |
| 497 | this._headers = value instanceof Headers ? value : new Headers(value); |
| 498 | this._headersJson = undefined; |
| 499 | this._headersInit = undefined; |
| 500 | } |
| 501 | async _consume() { |
| 502 | if (this._bodyBytes !== null) return this._bodyBytes; |
| 503 | return __drainBody(this); |
| 504 | } |
| 505 | async text() { |
| 506 | this.bodyUsed = true; |
| 507 | const bytes = await this._consume(); |
| 508 | return this._body ??= new TextDecoder().decode(bytes); |
| 509 | } |
| 510 | async json() { return JSON.parse(await this.text()); } |
| 511 | async formData() { |
| 512 | // The undecoded bytes, not `text()`: a UTF-8 decode replaces each invalid |
| 513 | // sequence in a binary file part with one U+FFFD, so both the bytes and |
| 514 | // the length change. |
| 515 | this.bodyUsed = true; |
| 516 | return __celld.__parseFormData( |
| 517 | await this._consume(), this.headers.get('content-type')); |
| 518 | } |
| 519 | async arrayBuffer() { |
| 520 | this.bodyUsed = true; |
| 521 | return (await this._consume()).slice().buffer; |
| 522 | } |
| 523 | async blob() { |
| 524 | return new Blob([await this.arrayBuffer()], |
| 525 | { type: this.headers.get("content-type") || "" }); |
| 526 | } |
| 527 | clone() { |
| 528 | if (this.bodyUsed) throw new TypeError("Body has already been consumed"); |
| 529 | if (this._bodyBytes === null) { |
| 530 | // Streaming body: tee, keep one branch, clone the other. |
| 531 | const [left, right] = this.body.tee(); |
| 532 | this.body = left; |
| 533 | return new Request(this, { body: right }); |
| 534 | } |
| 535 | return new Request(this); |
| 536 | } |
| 537 | }; |
| 538 | const __makeRequest = __celld.__makeRequest = ( |
| 539 | url, method, body, headersJson = "[]", signal = undefined, |
| 540 | incomingSignal = false, |
| 541 | ) => new Request(url, { |
| 542 | // The raw header JSON, not a parsed object: an incoming request whose |
| 543 | // handler never reads `.headers` (a hello world, or a Worker that only |
| 544 | // routes to a cell) then never parses it. See `get headers()`. |
| 545 | // celld cannot prove Cloudflare edge metadata, so the object stays empty. |
| 546 | // In particular, no client-controlled header becomes a country or a colo; |
| 547 | // the forwarded-authority trust flag does not establish geolocation trust. |
| 548 | method, body, __headersJson: headersJson, signal, cf: {}, |
| 549 | __celldIncomingSignal: incomingSignal, |
| 550 | }); |
| 551 | const __fmt = (a) => a.map((x) => { |
| 552 | if (typeof x === "string") return x; |
| 553 | if (x instanceof Error) return x.stack || (x.name + ": " + x.message); |
| 554 | try { return JSON.stringify(x); } catch { return String(x); } |
| 555 | }).join(" "); |
| 556 | const __consoleNoop = () => {}; |
| 557 | globalThis.console = { |
| 558 | debug: (...a) => __log("debug", __fmt(a)), |
| 559 | error: (...a) => __log("error", __fmt(a)), |
| 560 | info: (...a) => __log("info", __fmt(a)), |
| 561 | log: (...a) => __log("log", __fmt(a)), |
| 562 | warn: (...a) => __log("warn", __fmt(a)), |
| 563 | clear: __consoleNoop, |
| 564 | count: __consoleNoop, |
| 565 | group: __consoleNoop, |
| 566 | table: __consoleNoop, |
| 567 | trace: __consoleNoop, |
| 568 | assert: __consoleNoop, |
| 569 | countReset: __consoleNoop, |
| 570 | dir: __consoleNoop, |
| 571 | dirxml: __consoleNoop, |
| 572 | groupCollapsed: __consoleNoop, |
| 573 | groupEnd: __consoleNoop, |
| 574 | profile: __consoleNoop, |
| 575 | profileEnd: __consoleNoop, |
| 576 | time: __consoleNoop, |
| 577 | timeEnd: __consoleNoop, |
| 578 | timeLog: __consoleNoop, |
| 579 | timeStamp: __consoleNoop, |
| 580 | createTask: () => { |
| 581 | throw new Error("console.createTask() is not implemented"); |
| 582 | }, |
| 583 | }; |
| 584 | |
| 585 | // async-op shims: outbound fetch + timers, driven by the host event loop. |
| 586 | // Move one request body through a host subrequest seam. A body that already |
| 587 | // names a host stream keeps that stream incremental. An ordinary JavaScript |
| 588 | // stream has no host owner, so it uses the existing byte fallback. |
| 589 | const __subrequestBody = async (req, absent = false) => { |
| 590 | if (absent) return { body: undefined, streamId: undefined }; |
| 591 | if (req._bodyBytes !== null) |
| 592 | return { body: req._bodyBytes, streamId: undefined }; |
| 593 | const streamId = req.body?.__celldStreamId; |
| 594 | if (streamId === undefined) { |
| 595 | req.bodyUsed = true; |
| 596 | return { body: await req._consume(), streamId: undefined }; |
| 597 | } |
| 598 | // The receiver now owns the one host source. Lock the wrapper so a later |
| 599 | // read fails instead of racing the receiver, and expose the transfer through |
| 600 | // the standard Body flag. |
| 601 | req.bodyUsed = true; |
| 602 | req.body.getReader(); |
| 603 | return { body: new Uint8Array(), streamId }; |
| 604 | }; |
| 605 | // A data: URL carries its response inline; RFC 2397 percent-decoding |
| 606 | // happens byte-wise, so a payload that is deliberately invalid UTF-8 |
| 607 | // survives to the consumer (HTMLRewriter's own suite depends on it). |
| 608 | const __dataUrlResponse = (url) => { |
| 609 | // The URL parser strips leading and trailing C0 controls and spaces |
| 610 | // before doing anything else; a literal trailing space in a data: URL |
| 611 | // is therefore not part of the payload, while an encoded %20 is. |
| 612 | url = url.replace(/^[\x00-\x20]+/, "").replace(/[\x00-\x20]+$/, ""); |
| 613 | const match = /^data:([^,]*),([\s\S]*)$/.exec(url); |
| 614 | if (!match) throw new TypeError("Invalid data: URL"); |
| 615 | let [, meta, payload] = match; |
| 616 | const base64 = /;base64$/i.test(meta); |
| 617 | if (base64) meta = meta.replace(/;base64$/i, ""); |
| 618 | let bytes; |
| 619 | if (base64) { |
| 620 | // The data: URL processor percent-decodes the body before it decodes the |
| 621 | // base64, so `data:text/plain;base64,YQ%3D%3D` carries the padding of |
| 622 | // "YQ==". Decode byte-wise, as the non-base64 branch below does: a `%` |
| 623 | // that does not start a valid escape stays literal and the base64 decode |
| 624 | // rejects it. |
| 625 | payload = payload.replace( |
| 626 | /%([0-9a-f]{2})/gi, |
| 627 | (_, hex) => String.fromCharCode(parseInt(hex, 16)), |
| 628 | ); |
| 629 | const bin = atob(payload); |
| 630 | bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0)); |
| 631 | } else { |
| 632 | const out = []; |
| 633 | for (let i = 0; i < payload.length; i++) { |
| 634 | const c = payload[i]; |
| 635 | if (c === "%" && /^[0-9A-Fa-f]{2}$/.test(payload.slice(i + 1, i + 3))) { |
| 636 | out.push(parseInt(payload.slice(i + 1, i + 3), 16)); |
| 637 | i += 2; |
| 638 | } else { |
| 639 | out.push(payload.charCodeAt(i) & 0xff); |
| 640 | } |
| 641 | } |
| 642 | bytes = Uint8Array.from(out); |
| 643 | } |
| 644 | return new Response(bytes, { |
| 645 | headers: { "content-type": meta || "text/plain;charset=US-ASCII" }, |
| 646 | }); |
| 647 | }; |
| 648 | globalThis.fetch = async (input, init) => { |
| 649 | const rawUrl = typeof input === "string" ? input : input?.url; |
| 650 | if (typeof rawUrl === "string" && rawUrl.startsWith("data:")) { |
| 651 | return __dataUrlResponse(rawUrl); |
| 652 | } |
| 653 | const req = new Request(input, init); |
| 654 | // `fetch(url, { headers: { Upgrade: "websocket" } })` is the other way |
| 655 | // Cloudflare opens an outbound socket, and the one most examples use. |
| 656 | if ((req.headers.get("upgrade") ?? "").toLowerCase() === "websocket") { |
| 657 | return await __fetchWebSocketUpgrade(req); |
| 658 | } |
| 659 | // The caller's signal, never the incoming request's own. |
| 660 | const signal = req._signalForSubrequests; |
| 661 | if (signal?.aborted) throw signal.reason; |
| 662 | // The bytes go to the host as a typed array, the same way every other |
| 663 | // subrequest op takes a body. Encoding them as a JSON number array cost |
| 664 | // roughly ten times the body in transient allocation, and it corrupted |
| 665 | // nothing only because the host decoded the same shape back. |
| 666 | const { body, streamId } = await __subrequestBody( |
| 667 | req, ["GET", "HEAD"].includes(req.method)); |
| 668 | // The header list, not the iterator: the iterator sorts, lower-cases and |
| 669 | // combines, so `Array.from(req.headers)` would send one `X-Trace: a, b` |
| 670 | // for two appends and put celld's casing on the wire in place of the |
| 671 | // author's. `op_fetch` builds the request with `RequestBuilder::header`, |
| 672 | // which appends, so repeats survive. |
| 673 | let raw; |
| 674 | try { |
| 675 | const dispatch = __op_fetch( |
| 676 | req.method, req.url, body, |
| 677 | JSON.stringify(req.headers.__celldHeaderList), req.redirect, |
| 678 | streamId, signal != null, |
| 679 | ); |
| 680 | if (signal) { |
| 681 | // An abort and the response can cross, leaving a body stream nobody |
| 682 | // reads holding its upstream connection until the sweeper expires it. |
| 683 | // Every arm is silenced because the caller already owns both outcomes. |
| 684 | dispatch.then((late) => { |
| 685 | if (!signal.aborted) return; |
| 686 | const abandoned = JSON.parse(late).streamId; |
| 687 | if (abandoned !== undefined) __http_stream_cancel(abandoned); |
| 688 | }, () => {}).catch(() => {}); |
| 689 | } |
| 690 | raw = await (signal ? __awaitCancellableDoCall(dispatch, signal) : dispatch); |
| 691 | } catch (error) { |
| 692 | // An abort is the caller's reason, not a network error, so it skips |
| 693 | // every translation below. |
| 694 | if (signal?.aborted && error === signal.reason) throw error; |
| 695 | // The Fetch API represents a redirect refusal as a network error, which |
| 696 | // rejects with TypeError. Keep the host message for diagnostics. |
| 697 | if (req.redirect === "error") { |
| 698 | throw new TypeError(error?.message ?? String(error)); |
| 699 | } |
| 700 | throw error; |
| 701 | } |
| 702 | const r = JSON.parse(raw); |
| 703 | // Direct network responses always carry a stream id. A transferred |
| 704 | // globalOutbound Fetcher can answer with an inline body, as service |
| 705 | // bindings do, so preserve both response representations. |
| 706 | const responseBody = r.streamId !== undefined |
| 707 | ? new CelldHttpBodyStream(r.streamId) |
| 708 | : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); |
| 709 | const response = new Response( |
| 710 | responseBody, |
| 711 | { status: r.status, headers: r.headers }, |
| 712 | ); |
| 713 | response.url = req.url; |
| 714 | return response; |
| 715 | }; |
| 716 | const __fetchWebSocketUpgrade = __celld.__fetchWebSocketUpgrade = |
| 717 | async (req) => { |
| 718 | const scope = __currentActorScope(); |
| 719 | const id = __ws_alloc(); |
| 720 | const socket = __makeSocket(id); |
| 721 | socket._outbound = true; |
| 722 | socket._polled = !scope; |
| 723 | socket.url = req.url; |
| 724 | socket.readyState = WebSocket.READY_STATE_CONNECTING; |
| 725 | __sockets.set(id, socket); |
| 726 | let raw; |
| 727 | try { |
| 728 | raw = JSON.parse(await __ws_upgrade( |
| 729 | id, |
| 730 | scope, |
| 731 | req.url, |
| 732 | // The iterator, not the header list, unlike every other outbound |
| 733 | // path. The handshake builder on the host side puts these into a |
| 734 | // `HeaderMap` with `insert`, which replaces, and it reads the |
| 735 | // offered subprotocols with a first-match `find`. Both would drop |
| 736 | // every repeat but one. Sending the combined form keeps |
| 737 | // `Sec-WebSocket-Protocol: a` plus `: b` meaning `a, b`, which is |
| 738 | // what the peer must see. Moving this to the header list needs the |
| 739 | // host to append instead, so it is a separate change. |
| 740 | JSON.stringify(Array.from(req.headers)), |
| 741 | )); |
| 742 | } catch (error) { |
| 743 | __sockets.delete(id); |
| 744 | throw error; |
| 745 | } |
| 746 | if (!raw.upgraded) { |
| 747 | // The server answered without upgrading. That is an ordinary response, |
| 748 | // not a connection error, and it is returned unchanged. |
| 749 | __sockets.delete(id); |
| 750 | const response = new Response(new Uint8Array(raw.body), { |
| 751 | status: raw.status, |
| 752 | headers: raw.headers, |
| 753 | }); |
| 754 | response.url = req.url; |
| 755 | return response; |
| 756 | } |
| 757 | socket.protocol = raw.protocol ?? ""; |
| 758 | const response = new Response(null, { status: 101 }); |
| 759 | response.webSocket = socket; |
| 760 | response.url = req.url; |
| 761 | return response; |
| 762 | }; |
| 763 | __celld.__makeAssetsBinding = (script) => ({ |
| 764 | async fetch(input, init) { |
| 765 | const req = input instanceof Request ? new Request(input, init) : new Request(input, init); |
| 766 | const r = JSON.parse(await __asset_fetch( |
| 767 | script, |
| 768 | req.method, |
| 769 | req.url, |
| 770 | JSON.stringify(Array.from(req.headers)), |
| 771 | )); |
| 772 | const responseBody = r.streamId !== undefined |
| 773 | ? new CelldHttpBodyStream(r.streamId) |
| 774 | : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); |
| 775 | const response = new Response( |
| 776 | responseBody, |
| 777 | { status: r.status, headers: r.headers }, |
| 778 | ); |
| 779 | response.url = req.url; |
| 780 | return response; |
| 781 | }, |
| 782 | }); |
| 783 | // An `r2_buckets` binding, served out of the fleet bucket under the |
| 784 | // reserved `r2/<bucketName>/` prefix. celld runs on blob storage rather |
| 785 | // than providing it, so a binding gets the store the node already holds |
| 786 | // credentials for; a node started without a bucket has nowhere to put a |
| 787 | // blob and every method says so. |
| 788 | // |
| 789 | // The whole `R2Bucket` surface is here: `head`, `get`, `put`, `delete`, |
| 790 | // `list`, `createMultipartUpload` and `resumeMultipartUpload`, with |
| 791 | // `httpMetadata`, `customMetadata`, `checksums`, `storageClass`, `onlyIf` |
| 792 | // and every range spelling. What celld cannot honor still fails loudly |
| 793 | // rather than pretending -- a silent gap is the failure mode the binding |
| 794 | // is written to avoid. Those are `ssecKey` (celld has no customer-key |
| 795 | // encryption), a conditional `put` of a body too big for one request, and |
| 796 | // a multipart upload resumed on a node other than the one that opened it. |
| 797 | const __r2Reject = (bucket, method, detail) => { |
| 798 | throw new Error( |
| 799 | `R2 ${method} is not implemented in celld (binding ${bucket})` + |
| 800 | (detail ? `: ${detail}` : ""), |
| 801 | ); |
| 802 | }; |
| 803 | // R2's key rules, checked here so a key the real thing refuses is refused |
| 804 | // here too rather than quietly written. |
| 805 | const __r2Key = (binding, method, key) => { |
| 806 | const text = String(key); |
| 807 | const length = new TextEncoder().encode(text).length; |
| 808 | if (length === 0 || length > 1024) { |
| 809 | throw new Error( |
| 810 | `R2 ${method} (binding ${binding}): a key is 1 to 1024 bytes, not ${length}`, |
| 811 | ); |
| 812 | } |
| 813 | return text; |
| 814 | }; |
| 815 | const __r2Hex = (value) => { |
| 816 | if (typeof value === "string") return value.trim().toLowerCase(); |
| 817 | const bytes = value instanceof ArrayBuffer |
| 818 | ? new Uint8Array(value) |
| 819 | : ArrayBuffer.isView(value) |
| 820 | ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) |
| 821 | : null; |
| 822 | if (!bytes) return null; |
| 823 | let out = ""; |
| 824 | for (const byte of bytes) out += byte.toString(16).padStart(2, "0"); |
| 825 | return out; |
| 826 | }; |
| 827 | const __r2Bytes = (hex) => { |
| 828 | const out = new Uint8Array(hex.length >> 1); |
| 829 | for (let at = 0; at < out.length; at++) { |
| 830 | out[at] = parseInt(hex.substr(at * 2, 2), 16); |
| 831 | } |
| 832 | return out.buffer; |
| 833 | }; |
| 834 | // Read a `ReadableStream` to one `Uint8Array`. Bodies drained this way |
| 835 | // are the ones the caller asked to have whole. |
| 836 | const __r2Drain = async (stream) => { |
| 837 | const reader = stream.getReader(); |
| 838 | const chunks = []; |
| 839 | let total = 0; |
| 840 | for (;;) { |
| 841 | const { done, value } = await reader.read(); |
| 842 | if (done) break; |
| 843 | chunks.push(value); |
| 844 | total += value.length; |
| 845 | } |
| 846 | const out = new Uint8Array(total); |
| 847 | let at = 0; |
| 848 | for (const chunk of chunks) { |
| 849 | out.set(chunk, at); |
| 850 | at += chunk.length; |
| 851 | } |
| 852 | return out; |
| 853 | }; |
| 854 | const __r2Ms = (value) => { |
| 855 | if (value === undefined || value === null) return undefined; |
| 856 | const ms = value instanceof Date ? value.getTime() : Number(value); |
| 857 | return Number.isFinite(ms) ? ms : undefined; |
| 858 | }; |
| 859 | // `httpMetadata` is either an `R2HTTPMetadata` or a `Headers`, and R2 |
| 860 | // takes both on the way in. |
| 861 | const __r2Http = (value) => { |
| 862 | if (value === undefined || value === null) return {}; |
| 863 | const from = (name, key) => |
| 864 | typeof value.get === "function" ? value.get(name) ?? undefined : value[key]; |
| 865 | const http = { |
| 866 | contentType: from("content-type", "contentType"), |
| 867 | contentLanguage: from("content-language", "contentLanguage"), |
| 868 | contentDisposition: from("content-disposition", "contentDisposition"), |
| 869 | contentEncoding: from("content-encoding", "contentEncoding"), |
| 870 | cacheControl: from("cache-control", "cacheControl"), |
| 871 | cacheExpiry: __r2Ms( |
| 872 | typeof value.get === "function" ? value.get("expires") : value.cacheExpiry, |
| 873 | ), |
| 874 | }; |
| 875 | for (const [name, entry] of Object.entries(http)) { |
| 876 | if (entry === undefined || entry === null) delete http[name]; |
| 877 | else if (name !== "cacheExpiry") http[name] = String(entry); |
| 878 | } |
| 879 | return http; |
| 880 | }; |
| 881 | // `onlyIf` is either an `R2Conditional` or a `Headers`; the header |
| 882 | // spelling of "only if it has not changed since" is If-Unmodified-Since, |
| 883 | // which is `uploadedBefore`. |
| 884 | const __r2OnlyIf = (value) => { |
| 885 | if (value === undefined || value === null) return undefined; |
| 886 | const only = typeof value.get === "function" |
| 887 | ? { |
| 888 | etagMatches: value.get("if-match") ?? undefined, |
| 889 | etagDoesNotMatch: value.get("if-none-match") ?? undefined, |
| 890 | uploadedAfter: __r2Ms(Date.parse(value.get("if-modified-since") ?? "")), |
| 891 | uploadedBefore: __r2Ms(Date.parse(value.get("if-unmodified-since") ?? "")), |
| 892 | } |
| 893 | : { |
| 894 | etagMatches: value.etagMatches, |
| 895 | etagDoesNotMatch: value.etagDoesNotMatch, |
| 896 | uploadedAfter: __r2Ms(value.uploadedAfter), |
| 897 | uploadedBefore: __r2Ms(value.uploadedBefore), |
| 898 | }; |
| 899 | for (const [name, entry] of Object.entries(only)) { |
| 900 | if (entry === undefined || entry === null || Number.isNaN(entry)) { |
| 901 | delete only[name]; |
| 902 | } else if (name.startsWith("etag")) only[name] = String(entry); |
| 903 | } |
| 904 | return Object.keys(only).length ? only : undefined; |
| 905 | }; |
| 906 | // A range is an `R2Range` or a `Headers` carrying a Range header. R2 |
| 907 | // takes `offset` alone, `length` alone, both, or `suffix`. |
| 908 | const __r2Range = (binding, value) => { |
| 909 | if (value === undefined || value === null) return undefined; |
| 910 | if (typeof value.get === "function") { |
| 911 | const header = value.get("range"); |
| 912 | if (!header) return undefined; |
| 913 | const parsed = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); |
| 914 | if (!parsed) { |
| 915 | __r2Reject(binding, "get(range)", `celld cannot parse ${header}`); |
| 916 | } |
| 917 | const [, first, last] = parsed; |
| 918 | if (first === "") return { suffix: Number(last) }; |
| 919 | if (last === "") return { offset: Number(first) }; |
| 920 | return { offset: Number(first), length: Number(last) - Number(first) + 1 }; |
| 921 | } |
| 922 | const range = {}; |
| 923 | if (value.suffix !== undefined && value.suffix !== null) { |
| 924 | range.suffix = Number(value.suffix); |
| 925 | } |
| 926 | if (value.offset !== undefined && value.offset !== null) { |
| 927 | range.offset = Number(value.offset); |
| 928 | } |
| 929 | if (value.length !== undefined && value.length !== null) { |
| 930 | range.length = Number(value.length); |
| 931 | } |
| 932 | for (const [name, entry] of Object.entries(range)) { |
| 933 | if (!Number.isFinite(entry) || entry < 0) { |
| 934 | __r2Reject(binding, "get(range)", `\`${name}\` must be a whole number`); |
| 935 | } |
| 936 | } |
| 937 | return Object.keys(range).length ? range : undefined; |
| 938 | }; |
| 939 | // R2 hashes an object's bytes and hands the digests back as |
| 940 | // `ArrayBuffer`s, with a `toJSON()` that spells them in hex. |
| 941 | const __r2Checksums = (hex) => { |
| 942 | const checksums = { |
| 943 | toJSON() { |
| 944 | const json = {}; |
| 945 | for (const [name, digest] of Object.entries(hex)) json[name] = digest; |
| 946 | return json; |
| 947 | }, |
| 948 | }; |
| 949 | for (const [name, digest] of Object.entries(hex)) { |
| 950 | checksums[name] = __r2Bytes(digest); |
| 951 | } |
| 952 | return checksums; |
| 953 | }; |
| 954 | // One object as R2 describes it. `object` is the host's record; `body`, |
| 955 | // when there is one, makes this an `R2ObjectBody`. |
| 956 | const __r2Object = (object, body) => { |
| 957 | const http = { ...object.http }; |
| 958 | if (http.cacheExpiry !== undefined) { |
| 959 | http.cacheExpiry = new Date(http.cacheExpiry); |
| 960 | } |
| 961 | const etag = object.etag ? String(object.etag).replace(/^"|"$/g, "") : ""; |
| 962 | const r2 = { |
| 963 | key: object.key, |
| 964 | version: object.version ?? etag, |
| 965 | size: object.size, |
| 966 | etag, |
| 967 | httpEtag: etag ? `"${etag}"` : "", |
| 968 | uploaded: new Date(object.uploaded), |
| 969 | httpMetadata: http, |
| 970 | customMetadata: object.custom ?? {}, |
| 971 | checksums: __r2Checksums(object.checksums ?? {}), |
| 972 | storageClass: object.storageClass ?? "Standard", |
| 973 | // R2 fills the response headers from the object's own metadata, which |
| 974 | // is what makes `return new Response(object.body, { headers })` serve |
| 975 | // a stored file correctly. |
| 976 | writeHttpMetadata(headers) { |
| 977 | const write = (name, value) => { |
| 978 | if (value !== undefined && value !== null) headers.set(name, value); |
| 979 | }; |
| 980 | write("content-type", http.contentType); |
| 981 | write("content-language", http.contentLanguage); |
| 982 | write("content-disposition", http.contentDisposition); |
| 983 | write("content-encoding", http.contentEncoding); |
| 984 | write("cache-control", http.cacheControl); |
| 985 | if (http.cacheExpiry !== undefined) { |
| 986 | headers.set("expires", http.cacheExpiry.toUTCString()); |
| 987 | } |
| 988 | }, |
| 989 | }; |
| 990 | if (object.range) r2.range = { ...object.range }; |
| 991 | if (!body) return r2; |
| 992 | const drain = () => __r2Drain(body); |
| 993 | r2.body = body; |
| 994 | Object.defineProperty(r2, "bodyUsed", { |
| 995 | get: () => body.locked || body._disturbed === true, |
| 996 | }); |
| 997 | r2.arrayBuffer = async () => (await drain()).buffer; |
| 998 | r2.bytes = drain; |
| 999 | r2.text = async () => new TextDecoder().decode(await drain()); |
| 1000 | r2.json = async () => JSON.parse(new TextDecoder().decode(await drain())); |
| 1001 | r2.blob = async () => new Blob([await drain()]); |
| 1002 | return r2; |
| 1003 | }; |
| 1004 | // The write-side options every writing method shares, in the shape the |
| 1005 | // host ops read. |
| 1006 | const __r2WriteOptions = (binding, method, options) => { |
| 1007 | const o = options ?? {}; |
| 1008 | if (o.ssecKey !== undefined) { |
| 1009 | __r2Reject( |
| 1010 | binding, |
| 1011 | `${method}(ssecKey)`, |
| 1012 | "celld has no customer-key encryption", |
| 1013 | ); |
| 1014 | } |
| 1015 | const custom = {}; |
| 1016 | for (const [name, value] of Object.entries(o.customMetadata ?? {})) { |
| 1017 | custom[name] = String(value); |
| 1018 | } |
| 1019 | const verify = {}; |
| 1020 | for (const name of ["md5", "sha1", "sha256", "sha384", "sha512"]) { |
| 1021 | if (o[name] === undefined || o[name] === null) continue; |
| 1022 | const hex = __r2Hex(o[name]); |
| 1023 | if (hex === null) { |
| 1024 | __r2Reject( |
| 1025 | binding, |
| 1026 | `${method}(${name})`, |
| 1027 | "a checksum is hex or an ArrayBuffer", |
| 1028 | ); |
| 1029 | } |
| 1030 | verify[name] = hex; |
| 1031 | } |
| 1032 | const storageClass = o.storageClass === undefined || o.storageClass === null |
| 1033 | ? undefined |
| 1034 | : String(o.storageClass); |
| 1035 | if (storageClass !== undefined && |
| 1036 | !["Standard", "InfrequentAccess"].includes(storageClass) |
| 1037 | ) { |
| 1038 | __r2Reject( |
| 1039 | binding, |
| 1040 | `${method}(storageClass)`, |
| 1041 | `${storageClass} is not an R2 storage class`, |
| 1042 | ); |
| 1043 | } |
| 1044 | return { |
| 1045 | http: __r2Http(o.httpMetadata), |
| 1046 | custom, |
| 1047 | storageClass, |
| 1048 | onlyIf: __r2OnlyIf(o.onlyIf), |
| 1049 | verify, |
| 1050 | }; |
| 1051 | }; |
| 1052 | // A `put` body, as either the bytes to send in one request or the stream |
| 1053 | // to feed the host chunk by chunk. R2 takes all of these. |
| 1054 | const __r2Value = async (binding, value) => { |
| 1055 | if (value === undefined || value === null) return new Uint8Array(0); |
| 1056 | if (typeof value === "string") return new TextEncoder().encode(value); |
| 1057 | if (value instanceof Uint8Array) return value; |
| 1058 | if (ArrayBuffer.isView(value)) { |
| 1059 | return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); |
| 1060 | } |
| 1061 | if (value instanceof ArrayBuffer) return new Uint8Array(value); |
| 1062 | if (typeof Blob !== "undefined" && value instanceof Blob) { |
| 1063 | return new Uint8Array(await value.arrayBuffer()); |
| 1064 | } |
| 1065 | if (value && typeof value.getReader === "function") return value; |
| 1066 | return __r2Reject( |
| 1067 | binding, |
| 1068 | "put", |
| 1069 | "a body is a string, an ArrayBuffer, a view, a Blob, a ReadableStream, or null", |
| 1070 | ); |
| 1071 | }; |
| 1072 | // Feed a `ReadableStream` body to the host one chunk at a time. The host |
| 1073 | // writes one request when the whole body fits in a part and a multipart |
| 1074 | // upload when it does not, so a Worker can stream a body far larger than |
| 1075 | // its heap. |
| 1076 | const __r2PutStream = async (bucketName, key, stream, options) => { |
| 1077 | const id = Number(await __r2_put_begin(bucketName, key, JSON.stringify(options))); |
| 1078 | const reader = stream.getReader(); |
| 1079 | try { |
| 1080 | for (;;) { |
| 1081 | const { done, value } = await reader.read(); |
| 1082 | if (done) break; |
| 1083 | if (!value || value.length === 0) continue; |
| 1084 | await __r2_put_chunk( |
| 1085 | id, |
| 1086 | value instanceof Uint8Array |
| 1087 | ? value |
| 1088 | : new Uint8Array(value.buffer, value.byteOffset, value.byteLength), |
| 1089 | ); |
| 1090 | } |
| 1091 | } catch (error) { |
| 1092 | await __r2_put_end(id, true); |
| 1093 | throw error; |
| 1094 | } |
| 1095 | return JSON.parse(await __r2_put_end(id, false)); |
| 1096 | }; |
| 1097 | // One open multipart upload. `id` resolves to the host's upload id, so |
| 1098 | // `resumeMultipartUpload` can hand back a handle without awaiting -- as R2 |
| 1099 | // does -- and surface a bad id on the first method that uses it. |
| 1100 | const __r2Multipart = (binding, bucketName, key, id) => ({ |
| 1101 | key, |
| 1102 | get uploadId() { |
| 1103 | return String(id.value ?? ""); |
| 1104 | }, |
| 1105 | async uploadPart(partNumber, value, options) { |
| 1106 | if (options?.ssecKey !== undefined) { |
| 1107 | __r2Reject(binding, "uploadPart(ssecKey)", "celld has no customer-key encryption"); |
| 1108 | } |
| 1109 | const body = await __r2Value(binding, value); |
| 1110 | const bytes = body instanceof Uint8Array ? body : await __r2Drain(body); |
| 1111 | const r = JSON.parse(await __r2_mp_part(await id.host, partNumber | 0, bytes)); |
| 1112 | // The object store owns the part list this completion acts on, so it |
| 1113 | // never hands back a part etag to name one with. |
| 1114 | return { partNumber: r.partNumber, etag: "" }; |
| 1115 | }, |
| 1116 | async complete(parts) { |
| 1117 | const numbers = (parts ?? []).map((part) => part.partNumber | 0); |
| 1118 | return __r2Object(JSON.parse( |
| 1119 | await __r2_mp_complete(await id.host, JSON.stringify(numbers)), |
| 1120 | )); |
| 1121 | }, |
| 1122 | async abort() { |
| 1123 | await __r2_mp_abort(await id.host); |
| 1124 | }, |
| 1125 | }); |
| 1126 | __celld.__makeR2Bucket = (binding, bucketName) => ({ |
| 1127 | async head(key) { |
| 1128 | const name = __r2Key(binding, "head", key); |
| 1129 | const r = JSON.parse(await __r2_head(bucketName, name)); |
| 1130 | return r.state === "miss" ? null : __r2Object(r.object); |
| 1131 | }, |
| 1132 | async get(key, options) { |
| 1133 | const name = __r2Key(binding, "get", key); |
| 1134 | const o = options ?? {}; |
| 1135 | if (o.ssecKey !== undefined) { |
| 1136 | __r2Reject(binding, "get(ssecKey)", "celld has no customer-key encryption"); |
| 1137 | } |
| 1138 | const request = { |
| 1139 | range: __r2Range(binding, o.range), |
| 1140 | onlyIf: __r2OnlyIf(o.onlyIf), |
| 1141 | }; |
| 1142 | const r = JSON.parse(await __r2_get(bucketName, name, JSON.stringify(request))); |
| 1143 | if (r.state === "miss") return null; |
| 1144 | // A refused `onlyIf` answers the object without its body, which is how |
| 1145 | // a caller tells "not modified" from "not there". |
| 1146 | if (r.state === "unmet") return __r2Object(r.object); |
| 1147 | return __r2Object(r.object, new CelldHttpBodyStream(r.streamId)); |
| 1148 | }, |
| 1149 | async put(key, value, options) { |
| 1150 | const name = __r2Key(binding, "put", key); |
| 1151 | const write = __r2WriteOptions(binding, "put", options); |
| 1152 | const body = await __r2Value(binding, value); |
| 1153 | const r = body instanceof Uint8Array |
| 1154 | ? JSON.parse(await __r2_put(bucketName, name, body, JSON.stringify(write))) |
| 1155 | : await __r2PutStream(bucketName, name, body, write); |
| 1156 | // R2 answers a refused `onlyIf` with `null` rather than throwing. |
| 1157 | return r.stored ? __r2Object(r.object) : null; |
| 1158 | }, |
| 1159 | async delete(keys) { |
| 1160 | const list = (Array.isArray(keys) ? keys : [keys]).map((key) => |
| 1161 | __r2Key(binding, "delete", key) |
| 1162 | ); |
| 1163 | if (list.length > 1000) { |
| 1164 | throw new Error( |
| 1165 | `R2 delete (binding ${binding}) takes at most 1000 keys, not ${list.length}`, |
| 1166 | ); |
| 1167 | } |
| 1168 | if (list.length) await __r2_delete(bucketName, JSON.stringify(list)); |
| 1169 | }, |
| 1170 | async list(options) { |
| 1171 | const o = options ?? {}; |
| 1172 | const include = Array.isArray(o.include) ? o.include : []; |
| 1173 | for (const entry of include) { |
| 1174 | if (!["httpMetadata", "customMetadata"].includes(entry)) { |
| 1175 | __r2Reject(binding, "list(include)", `${entry} is not an R2 listing extra`); |
| 1176 | } |
| 1177 | } |
| 1178 | const request = { |
| 1179 | prefix: o.prefix === undefined || o.prefix === null ? "" : String(o.prefix), |
| 1180 | cursor: o.cursor === undefined || o.cursor === null ? null : String(o.cursor), |
| 1181 | startAfter: o.startAfter === undefined || o.startAfter === null |
| 1182 | ? null |
| 1183 | : String(o.startAfter), |
| 1184 | limit: o.limit === undefined || o.limit === null ? 0 : o.limit | 0, |
| 1185 | delimiter: o.delimiter === undefined || o.delimiter === null |
| 1186 | ? null |
| 1187 | : String(o.delimiter), |
| 1188 | include: include.length > 0, |
| 1189 | }; |
| 1190 | const r = JSON.parse(await __r2_list(bucketName, JSON.stringify(request))); |
| 1191 | const objects = r.objects.map((object) => { |
| 1192 | // A listing carries the extras it was asked for and nothing else, |
| 1193 | // so a caller cannot mistake an empty map for an empty object. |
| 1194 | if (!include.includes("httpMetadata")) object.http = {}; |
| 1195 | if (!include.includes("customMetadata")) object.custom = {}; |
| 1196 | return __r2Object(object); |
| 1197 | }); |
| 1198 | // R2 omits `cursor` entirely when the listing is complete, and callers |
| 1199 | // test `truncated` before reading it. |
| 1200 | const page = { objects, truncated: r.truncated, delimitedPrefixes: r.prefixes }; |
| 1201 | if (r.truncated && r.cursor) page.cursor = r.cursor; |
| 1202 | return page; |
| 1203 | }, |
| 1204 | async createMultipartUpload(key, options) { |
| 1205 | const name = __r2Key(binding, "createMultipartUpload", key); |
| 1206 | const write = __r2WriteOptions(binding, "createMultipartUpload", options); |
| 1207 | if (write.onlyIf) { |
| 1208 | __r2Reject( |
| 1209 | binding, |
| 1210 | "createMultipartUpload(onlyIf)", |
| 1211 | "a multipart completion takes no precondition", |
| 1212 | ); |
| 1213 | } |
| 1214 | // R2 takes a checksum on `put`, which sees the whole body, and not on a |
| 1215 | // multipart upload, which never does. |
| 1216 | for (const name of Object.keys(write.verify)) { |
| 1217 | __r2Reject(binding, `createMultipartUpload(${name})`, "R2 takes a checksum on `put`"); |
| 1218 | } |
| 1219 | const uploadId = await __r2_mp_begin(bucketName, name, JSON.stringify(write)); |
| 1220 | return __r2Multipart(binding, bucketName, name, { |
| 1221 | value: uploadId, |
| 1222 | host: Promise.resolve(Number(uploadId)), |
| 1223 | }); |
| 1224 | }, |
| 1225 | // R2 hands back a handle without checking it; so does this, and the |
| 1226 | // first method that uses it says whether the upload is still open. |
| 1227 | resumeMultipartUpload(key, uploadId) { |
| 1228 | const name = __r2Key(binding, "resumeMultipartUpload", key); |
| 1229 | const id = String(uploadId); |
| 1230 | const host = __r2_mp_resume(bucketName, name, id).then(Number); |
| 1231 | // A handle nobody uses must not become an unhandled rejection; the |
| 1232 | // first method that awaits `host` still sees the failure. |
| 1233 | host.catch(() => {}); |
| 1234 | return __r2Multipart(binding, bucketName, name, { value: id, host }); |
| 1235 | }, |
| 1236 | }); |
| 1237 | // A host timer op resolves once, so an interval arms a new one after every |
| 1238 | // round. `__timers` maps the id the caller holds to the op that is armed |
| 1239 | // right now: for a timeout that is the same id, and for an interval it is a |
| 1240 | // fresh id each round. Clearing therefore cancels the armed op, not the id. |
| 1241 | const __timers = new Map(); |
| 1242 | const __clearTimer = (id) => { |
| 1243 | const armed = __timers.get(id); |
| 1244 | if (armed === undefined) return; |
| 1245 | __timers.delete(id); |
| 1246 | __timer_cancel(armed); |
| 1247 | }; |
| 1248 | globalThis.setTimeout = (cb, ms, ...a) => { |
| 1249 | const id = __timer_alloc(); |
| 1250 | __timers.set(id, id); |
| 1251 | __op_timer(id, ms | 0).then(() => { |
| 1252 | if (!__timers.delete(id)) return; |
| 1253 | cb(...a); |
| 1254 | }); |
| 1255 | return id; |
| 1256 | }; |
| 1257 | globalThis.setInterval = (cb, ms, ...a) => { |
| 1258 | const id = __timer_alloc(); |
| 1259 | const delay = ms | 0; |
| 1260 | const arm = (armed) => { |
| 1261 | __timers.set(id, armed); |
| 1262 | __op_timer(armed, delay).then(() => { |
| 1263 | // Cancelling drops the entry and cancelling then re-arming replaces |
| 1264 | // it, so a round whose op is no longer the armed one is dead and |
| 1265 | // stops here. A cancelled op still resolves, which is why this test |
| 1266 | // is on identity and not on the op alone. |
| 1267 | if (__timers.get(id) !== armed) return; |
| 1268 | // Arm the next round before the callback runs. A `clearInterval` |
| 1269 | // inside the callback must end the interval, and arming after the |
| 1270 | // callback would undo it. |
| 1271 | arm(__timer_alloc()); |
| 1272 | cb(...a); |
| 1273 | }); |
| 1274 | }; |
| 1275 | arm(id); |
| 1276 | return id; |
| 1277 | }; |
| 1278 | // One id space and one cancel, because a caller can cross the two. |
| 1279 | globalThis.clearTimeout = __clearTimer; |
| 1280 | globalThis.clearInterval = __clearTimer; |
| 1281 | |
| 1282 | const __sqlCursorFinalizer = typeof FinalizationRegistry === "function" |
| 1283 | ? new FinalizationRegistry((cursorId) => __sql_cursor_close(cursorId)) |
| 1284 | : null; |
| 1285 | |
| 1286 | // A `SqlStorageCursor` over one exec's result (Cloudflare DO SQL API). |
| 1287 | class SqlCursor { |
| 1288 | // `res` is what `__sql_cursor_start` returns: V8 values throughout, with the |
| 1289 | // first row already stepped. A failing query throws out of the op, so there |
| 1290 | // is no in-band error field to test here. |
| 1291 | constructor(res) { |
| 1292 | this.columns = res.columns; |
| 1293 | this.rowsWritten = Number(res.rowsWritten || 0); |
| 1294 | this.reusedCachedQueryForTest = Boolean(res.reusedCachedQuery); |
| 1295 | this._deferredError = null; |
| 1296 | this._cursorId = Number(res.cursorId || 0); |
| 1297 | this._prefetched = res.row; |
| 1298 | this.rowsRead = this._prefetched === null ? 0 : 1; |
| 1299 | this._finalizerToken = null; |
| 1300 | if (this._cursorId && __sqlCursorFinalizer) { |
| 1301 | this._finalizerToken = {}; |
| 1302 | __sqlCursorFinalizer.register( |
| 1303 | this, this._cursorId, this._finalizerToken, |
| 1304 | ); |
| 1305 | } |
| 1306 | } |
| 1307 | _obj(r) { const o = {}; for (let i = 0; i < this.columns.length; i++) o[this.columns[i]] = r[i]; return o; } |
| 1308 | _finishNative() { |
| 1309 | if (this._finalizerToken && __sqlCursorFinalizer) |
| 1310 | __sqlCursorFinalizer.unregister(this._finalizerToken); |
| 1311 | this._finalizerToken = null; |
| 1312 | this._cursorId = 0; |
| 1313 | } |
| 1314 | _advanceNative() { |
| 1315 | if (!this._cursorId) { |
| 1316 | this._prefetched = null; |
| 1317 | return; |
| 1318 | } |
| 1319 | // The op answers with V8 values, not JSON: an array is a row, a number is |
| 1320 | // the cursor's final rowsWritten, and a failure throws. The throw is |
| 1321 | // caught and deferred, because a consumer must still receive the last good |
| 1322 | // row -- the error belongs to the call after it, not to this one. |
| 1323 | let result; |
| 1324 | try { |
| 1325 | result = __sql_cursor_next(this._cursorId); |
| 1326 | } catch (error) { |
| 1327 | this._deferredError = error; |
| 1328 | this._prefetched = null; |
| 1329 | this._finishNative(); |
| 1330 | return; |
| 1331 | } |
| 1332 | if (Array.isArray(result)) { |
| 1333 | this._prefetched = result; |
| 1334 | this.rowsRead++; |
| 1335 | return; |
| 1336 | } |
| 1337 | this.rowsWritten = Number(result || this.rowsWritten); |
| 1338 | this._prefetched = null; |
| 1339 | this._finishNative(); |
| 1340 | } |
| 1341 | _nextRaw() { |
| 1342 | if (this._deferredError) { |
| 1343 | const error = this._deferredError; |
| 1344 | this._deferredError = null; |
| 1345 | throw error; |
| 1346 | } |
| 1347 | if (this._prefetched === null) return { done: true }; |
| 1348 | const value = this._prefetched; |
| 1349 | this._advanceNative(); |
| 1350 | return { done: false, value }; |
| 1351 | } |
| 1352 | toArray() { |
| 1353 | const rows = []; |
| 1354 | while (true) { |
| 1355 | const result = this.next(); |
| 1356 | if (result.done) return rows; |
| 1357 | rows.push(result.value); |
| 1358 | if (__heap_limit_excessively_exceeded()) |
| 1359 | throw new Error( |
| 1360 | "the isolate is over its V8 heap limit, so it stopped " + |
| 1361 | "materializing a result set (see CELLD_V8_HEAP_LIMIT_MB)"); |
| 1362 | } |
| 1363 | } |
| 1364 | one() { |
| 1365 | const first = this.next(); |
| 1366 | if (first.done) |
| 1367 | throw new Error("Expected exactly one result from SQL query, but got no results"); |
| 1368 | if (!this.next().done) |
| 1369 | throw new Error("Expected exactly one result from SQL query, but got multiple results"); |
| 1370 | return first.value; |
| 1371 | } |
| 1372 | *raw() { |
| 1373 | while (true) { |
| 1374 | const result = this._nextRaw(); |
| 1375 | if (result.done) return; |
| 1376 | yield result.value; |
| 1377 | } |
| 1378 | } |
| 1379 | get columnNames() { return this.columns; } |
| 1380 | next() { |
| 1381 | const result = this._nextRaw(); |
| 1382 | return result.done ? result : { done: false, value: this._obj(result.value) }; |
| 1383 | } |
| 1384 | [Symbol.iterator]() { return this; } |
| 1385 | } |
| 1386 | class SqlStorage { |
| 1387 | // The state is what the abort guard in `exec` reads; a storage built |
| 1388 | // without one would bypass the guard silently. |
| 1389 | constructor(scope, state, storage) { |
| 1390 | if (!state) throw new TypeError("SqlStorage requires its DurableObjectState"); |
| 1391 | this._scope = scope; |
| 1392 | this._state = state; |
| 1393 | this._storage = storage; |
| 1394 | } |
| 1395 | prepare(query) { |
| 1396 | this._storage._assertTransactionActive("sql.prepare"); |
| 1397 | const storage = this; |
| 1398 | const source = String(query); |
| 1399 | return (...binds) => storage.exec(source, ...binds); |
| 1400 | } |
| 1401 | exec(query, ...binds) { |
| 1402 | this._storage._assertTransactionActive("sql.exec"); |
| 1403 | // A callback that outlived its block runs on an object that was reset, |
| 1404 | // whose replacement uses the same connection: a statement from it |
| 1405 | // would land in the replacement's state. The KV surface drops such |
| 1406 | // writes silently; SQL refuses aloud, since a cursor can carry reads. |
| 1407 | if (this._state._aborted) { |
| 1408 | throw new Error("the Durable Object was reset; this event's storage is closed"); |
| 1409 | } |
| 1410 | const jsonBinds = []; |
| 1411 | const byteBinds = []; |
| 1412 | for (let index = 0; index < binds.length; index++) { |
| 1413 | const value = binds[index]; |
| 1414 | let bytes; |
| 1415 | if (value instanceof ArrayBuffer) { |
| 1416 | bytes = new Uint8Array(value); |
| 1417 | } else if (ArrayBuffer.isView(value)) { |
| 1418 | bytes = new Uint8Array( |
| 1419 | value.buffer, value.byteOffset, value.byteLength, |
| 1420 | ); |
| 1421 | } |
| 1422 | if (bytes === undefined) { |
| 1423 | jsonBinds.push(value); |
| 1424 | } else { |
| 1425 | // Copy every buffer before JSON.stringify can call a later value's |
| 1426 | // toJSON(). That callback can resize, detach, or mutate this backing |
| 1427 | // buffer, but exec() has already accepted the bytes at this point. |
| 1428 | byteBinds.push([index, new Uint8Array(bytes)]); |
| 1429 | jsonBinds.push(null); |
| 1430 | } |
| 1431 | } |
| 1432 | const json = JSON.stringify(jsonBinds); |
| 1433 | return new SqlCursor(byteBinds.length === 0 |
| 1434 | ? __sql_cursor_start(this._scope, query, json) |
| 1435 | : __sql_cursor_start(this._scope, query, json, byteBinds)); |
| 1436 | } |
| 1437 | ingest(input) { |
| 1438 | this._storage._assertTransactionActive("sql.ingest"); |
| 1439 | const result = JSON.parse(__sql_ingest(this._scope, String(input))); |
| 1440 | if (result.error) throw new Error("SQL error: " + result.error); |
| 1441 | return result; |
| 1442 | } |
| 1443 | get databaseSize() { |
| 1444 | this._storage._assertTransactionActive("sql.databaseSize"); |
| 1445 | return __sql_database_size(this._scope); |
| 1446 | } |
| 1447 | setMaxPageCountForTest(pages) { |
| 1448 | if (typeof __sql_set_max_page_count_for_test !== "function") |
| 1449 | throw new Error("setMaxPageCountForTest is only available in tests"); |
| 1450 | __sql_set_max_page_count_for_test(this._scope, Number(pages)); |
| 1451 | } |
| 1452 | setWriteFaultForTest(enabled) { |
| 1453 | if (typeof __sql_set_write_fault_for_test !== "function") |
| 1454 | throw new Error("setWriteFaultForTest is only available in tests"); |
| 1455 | __sql_set_write_fault_for_test(!!enabled); |
| 1456 | } |
| 1457 | setCacheSizeForTest(pages) { |
| 1458 | if (typeof __sql_set_cache_size_for_test !== "function") |
| 1459 | throw new Error("setCacheSizeForTest is only available in tests"); |
| 1460 | __sql_set_cache_size_for_test(this._scope, Number(pages)); |
| 1461 | } |
| 1462 | setInterruptFaultForTest(enabled) { |
| 1463 | if (typeof __sql_set_interrupt_fault_for_test !== "function") |
| 1464 | throw new Error( |
| 1465 | "setInterruptFaultForTest is only available in tests"); |
| 1466 | __sql_set_interrupt_fault_for_test(this._scope, !!enabled); |
| 1467 | } |
| 1468 | registerNomemFunctionForTest() { |
| 1469 | if (typeof __sql_register_nomem_function_for_test !== "function") |
| 1470 | throw new Error( |
| 1471 | "registerNomemFunctionForTest is only available in tests"); |
| 1472 | __sql_register_nomem_function_for_test(this._scope); |
| 1473 | } |
| 1474 | } |
| 1475 | function __readStoredValue(scope, key, read) { |
| 1476 | try { |
| 1477 | return read(); |
| 1478 | } catch (error) { |
| 1479 | const message = String(error && error.message || error); |
| 1480 | if (!message.toLowerCase().includes("deserialize cloned data")) |
| 1481 | throw error; |
| 1482 | const contextual = new Error( |
| 1483 | "actor storage deserialization failed; actorId = " + |
| 1484 | scope + "; key = " + key + "; " + message, |
| 1485 | ); |
| 1486 | contextual.cause = error; |
| 1487 | throw contextual; |
| 1488 | } |
| 1489 | } |
| 1490 | class SyncKvListIterator { |
| 1491 | constructor(root, generation, cursor) { |
| 1492 | this._root = root; |
| 1493 | this._generation = generation; |
| 1494 | this._cursor = cursor; |
| 1495 | } |
| 1496 | [Symbol.iterator]() { return this; } |
| 1497 | next() { |
| 1498 | if (this._generation !== this._root._syncKvListGeneration) { |
| 1499 | throw new Error( |
| 1500 | "kv.list() iterator was invalidated because a new call to kv.list() was started. " + |
| 1501 | "Only one kv.list() iterator can exist at a time.", |
| 1502 | ); |
| 1503 | } |
| 1504 | const value = |
| 1505 | __storage_sync_list_next(this._cursor, __storedSentinel); |
| 1506 | if (value === null) return { done: true, value: undefined }; |
| 1507 | value[1] = __unwrapStored(value[1]); |
| 1508 | return { done: false, value }; |
| 1509 | } |
| 1510 | } |
| 1511 | class SyncKvStorage { |
| 1512 | constructor(storage) { |
| 1513 | this._storage = storage; |
| 1514 | this._root = storage._transactionRoot; |
| 1515 | } |
| 1516 | get(key) { |
| 1517 | this._storage._assertTransactionActive("kv.get"); |
| 1518 | key = String(key); |
| 1519 | return __unwrapStored(__readStoredValue( |
| 1520 | this._storage._scope, key, |
| 1521 | () => __storage_get(this._storage._scope, key, |
| 1522 | __storedSentinel), |
| 1523 | )); |
| 1524 | } |
| 1525 | put(key, value) { |
| 1526 | this._storage._assertTransactionActive("kv.put"); |
| 1527 | key = String(key); |
| 1528 | try { |
| 1529 | __storage_put(this._storage._scope, key, value); |
| 1530 | } catch (error) { |
| 1531 | __storage_put_serialized(this._storage._scope, key, |
| 1532 | __storedBytes(value, error)); |
| 1533 | } |
| 1534 | } |
| 1535 | delete(key) { |
| 1536 | this._storage._assertTransactionActive("kv.delete"); |
| 1537 | return __storage_delete(this._storage._scope, String(key)); |
| 1538 | } |
| 1539 | list(options = {}) { |
| 1540 | this._storage._assertTransactionActive("kv.list"); |
| 1541 | const generation = ++this._root._syncKvListGeneration; |
| 1542 | const cursor = __storage_sync_list_start( |
| 1543 | this._storage._scope, JSON.stringify(options), |
| 1544 | ); |
| 1545 | return new SyncKvListIterator( |
| 1546 | this._root, generation, cursor, |
| 1547 | ); |
| 1548 | } |
| 1549 | } |
| 1550 | class DurableObjectStorage { |
| 1551 | constructor( |
| 1552 | scope, |
| 1553 | state = null, |
| 1554 | transactionRoot = null, |
| 1555 | transactionDepth = 0, |
| 1556 | transactionControl = null, |
| 1557 | ) { |
| 1558 | this._scope = scope; |
| 1559 | this._state = state; |
| 1560 | this.sql = new SqlStorage(scope, state, this); |
| 1561 | this._transactionRoot = transactionRoot || this; |
| 1562 | this._transactionDepth = transactionDepth; |
| 1563 | this._transactionControl = transactionControl; |
| 1564 | if (!transactionRoot) { |
| 1565 | this._transactionSerial = 0; |
| 1566 | this._transactionTail = Promise.resolve(); |
| 1567 | this._transactionOwner = ""; |
| 1568 | this._activeTransaction = null; |
| 1569 | this._activeSyncTransaction = null; |
| 1570 | this._syncKvListGeneration = 0; |
| 1571 | } |
| 1572 | this._kv = new SyncKvStorage(this); |
| 1573 | } |
| 1574 | get kv() { return this._kv; } |
| 1575 | _transactionStatus() { |
| 1576 | let status = null; |
| 1577 | for (let control = this._transactionControl; control; control = control.parent) { |
| 1578 | if (control.rolledBack) return "rolled back"; |
| 1579 | if (control.committed) status = "committed"; |
| 1580 | } |
| 1581 | return status; |
| 1582 | } |
| 1583 | _assertTransactionActive(operation) { |
| 1584 | const status = this._transactionStatus(); |
| 1585 | // workerd's wording, which applications match on. |
| 1586 | if (status === "committed") |
| 1587 | throw new Error( |
| 1588 | "Cannot call " + operation + "() on transaction that has already committed: " + |
| 1589 | "did you move `txn` outside of the closure?", |
| 1590 | ); |
| 1591 | if (status) throw new Error("Cannot " + operation + "() on " + status + " transaction"); |
| 1592 | } |
| 1593 | _flushPendingPuts() { |
| 1594 | // An admitted put can resume after its boundary flushed and ended the |
| 1595 | // transaction. Its promise completes without flushing a later scope. |
| 1596 | if (this._transactionStatus()) return false; |
| 1597 | if (this._state && this._state._aborted) return false; |
| 1598 | __storage_flush_pending_puts(this._scope); |
| 1599 | return true; |
| 1600 | } |
| 1601 | async get(k) { |
| 1602 | this._assertTransactionActive("get"); |
| 1603 | // Transaction operations reach SQLite before their caller can roll back. |
| 1604 | if (!this._transactionControl) await Promise.resolve(); |
| 1605 | if (!this._flushPendingPuts()) return; |
| 1606 | const key = Array.isArray(k) ? JSON.stringify(k) : String(k); |
| 1607 | return __readStoredValue(this._scope, key, () => { |
| 1608 | if (Array.isArray(k)) |
| 1609 | return __unwrapStoredMap( |
| 1610 | __storage_get_many(this._scope, k, __storedSentinel)); |
| 1611 | return __unwrapStored( |
| 1612 | __storage_get(this._scope, k, __storedSentinel)); |
| 1613 | }); |
| 1614 | } |
| 1615 | async put(k, val) { |
| 1616 | this._assertTransactionActive("put"); |
| 1617 | if (typeof k === "string") { |
| 1618 | try { |
| 1619 | __storage_queue_put(this._scope, k, val); |
| 1620 | } catch (error) { |
| 1621 | __storage_queue_put_serialized(this._scope, k, |
| 1622 | __storedBytes(val, error)); |
| 1623 | } |
| 1624 | await Promise.resolve(); |
| 1625 | this._flushPendingPuts(); |
| 1626 | return; |
| 1627 | } |
| 1628 | const source = k instanceof Map ? Array.from(k) : Object.entries(k); |
| 1629 | if (source.length === 0) return; |
| 1630 | const entries = |
| 1631 | source.map(([key, value]) => [String(key), value]); |
| 1632 | try { |
| 1633 | __storage_queue_put_many(this._scope, entries); |
| 1634 | } catch (error) { |
| 1635 | // A batch with a stub entry: encode every entry first (plain |
| 1636 | // entries keep their native clone bytes, stub entries take |
| 1637 | // the stored-stub envelope), then queue -- so a genuinely |
| 1638 | // uncloneable entry still queues nothing, like the batch op, |
| 1639 | // which serializes fully before queueing. |
| 1640 | const encoded = entries.map(([key, value]) => { |
| 1641 | try { |
| 1642 | return [key, __sc_encode(value)]; |
| 1643 | } catch (error_) { |
| 1644 | return [key, __storedBytes(value, error_)]; |
| 1645 | } |
| 1646 | }); |
| 1647 | for (const [key, bytes] of encoded) |
| 1648 | __storage_queue_put_serialized(this._scope, key, bytes); |
| 1649 | } |
| 1650 | await Promise.resolve(); |
| 1651 | this._flushPendingPuts(); |
| 1652 | } |
| 1653 | async delete(k) { |
| 1654 | this._assertTransactionActive("delete"); |
| 1655 | if (!this._transactionControl) await Promise.resolve(); |
| 1656 | if (!this._flushPendingPuts()) return; |
| 1657 | if (Array.isArray(k)) { |
| 1658 | if (k.length === 0) return 0; |
| 1659 | return __storage_delete_many(this._scope, k); |
| 1660 | } |
| 1661 | return __storage_delete(this._scope, k); |
| 1662 | } |
| 1663 | async list(options = {}) { |
| 1664 | this._assertTransactionActive("list"); |
| 1665 | if (!this._transactionControl) await Promise.resolve(); |
| 1666 | if (!this._flushPendingPuts()) return new Map(); |
| 1667 | return __unwrapStoredMap(__storage_list( |
| 1668 | this._scope, JSON.stringify(options), __storedSentinel)); |
| 1669 | } |
| 1670 | async deleteAll() { |
| 1671 | this._assertTransactionActive("deleteAll"); |
| 1672 | if (!this._transactionControl) await Promise.resolve(); |
| 1673 | if (!this._flushPendingPuts()) return; |
| 1674 | __storage_delete_all(this._scope, __cell.deleteAllDeletesAlarm); |
| 1675 | } |
| 1676 | // Resolves once every write this cell committed before the call is |
| 1677 | // proven durable, by the proof the output gate requires before it releases |
| 1678 | // an egress. Workerd resolves when the pending writes have completed; on |
| 1679 | // celld the local file is a cache, so "completed" is "proven". The host op |
| 1680 | // rejects when that proof fails or times out, so an application never |
| 1681 | // treats a lost write as safe. |
| 1682 | async sync() { |
| 1683 | this._assertTransactionActive("sync"); |
| 1684 | await Promise.resolve(); |
| 1685 | const status = this._transactionStatus(); |
| 1686 | // An admitted sync can resume after transactionSync commits or rolls |
| 1687 | // back. Its boundary settled the queued puts, so prove the surviving |
| 1688 | // state without flushing a later transaction through this handle. A |
| 1689 | // new call after that boundary still fails the entry guard above. |
| 1690 | if (this._state?._aborted || (status === null && !this._flushPendingPuts())) |
| 1691 | throw new Error( |
| 1692 | "storage.sync: " + this._scope + " was aborted; the object is no " + |
| 1693 | "longer running"); |
| 1694 | await __storage_sync(this._scope); |
| 1695 | } |
| 1696 | async setAlarm(t) { |
| 1697 | this._assertTransactionActive("setAlarm"); |
| 1698 | if (!this._transactionControl) await Promise.resolve(); |
| 1699 | if (!this._flushPendingPuts()) return; |
| 1700 | if (this._state?._facetDepth > 0) |
| 1701 | throw new Error("Facets currently cannot set alarms."); |
| 1702 | __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); |
| 1703 | } |
| 1704 | async getAlarm() { |
| 1705 | this._assertTransactionActive("getAlarm"); |
| 1706 | if (!this._transactionControl) await Promise.resolve(); |
| 1707 | if (!this._flushPendingPuts()) return null; |
| 1708 | const v = __alarm_get(this._scope); |
| 1709 | return v === null ? null : v; |
| 1710 | } |
| 1711 | async deleteAlarm() { |
| 1712 | this._assertTransactionActive("deleteAlarm"); |
| 1713 | if (!this._transactionControl) await Promise.resolve(); |
| 1714 | if (!this._flushPendingPuts()) return; |
| 1715 | __alarm_delete(this._scope); |
| 1716 | } |
| 1717 | _transactionStart() { |
| 1718 | const root = this._transactionRoot; |
| 1719 | const savepoint = "cells_tx_" + (++root._transactionSerial); |
| 1720 | __storage_transaction_control( |
| 1721 | this._scope, "start", this._transactionDepth > 0, savepoint, |
| 1722 | ); |
| 1723 | return savepoint; |
| 1724 | } |
| 1725 | _transactionCommit(savepoint) { |
| 1726 | __storage_transaction_control( |
| 1727 | this._scope, "commit", this._transactionDepth > 0, savepoint, |
| 1728 | ); |
| 1729 | } |
| 1730 | _transactionRollback(savepoint, explicit = false) { |
| 1731 | __storage_transaction_control( |
| 1732 | this._scope, |
| 1733 | explicit ? "rollback_explicit" : "rollback", |
| 1734 | this._transactionDepth > 0, |
| 1735 | savepoint, |
| 1736 | ); |
| 1737 | } |
| 1738 | _transactionView(transactionControl) { |
| 1739 | return new DurableObjectStorage( |
| 1740 | this._scope, |
| 1741 | this._state, |
| 1742 | this._transactionRoot, |
| 1743 | this._transactionDepth + 1, |
| 1744 | transactionControl, |
| 1745 | ); |
| 1746 | } |
| 1747 | rollback() { |
| 1748 | const control = this._transactionControl; |
| 1749 | if (!control) |
| 1750 | throw new TypeError("rollback() must be called on a transaction"); |
| 1751 | if (control.rolledBack) return; |
| 1752 | this._assertTransactionActive("rollback"); |
| 1753 | // An asynchronous child can still own a nested savepoint. Mark this view |
| 1754 | // terminal now, but let its runner release the child before it rolls this |
| 1755 | // layer back. |
| 1756 | if (control.pending.size === 0) control.rollback(); |
| 1757 | control.rolledBack = true; |
| 1758 | } |
| 1759 | transactionSync(f) { |
| 1760 | this._assertTransactionActive("transactionSync"); |
| 1761 | const root = this._transactionRoot; |
| 1762 | if (this._transactionDepth === 0) { |
| 1763 | // A callback can call a helper that reaches the root `ctx.storage` |
| 1764 | // handle instead of the transaction view, and the helper starts its own |
| 1765 | // synchronous transaction. Workerd nests that one under the open |
| 1766 | // transaction; celld attempted a second top-level BEGIN and failed with |
| 1767 | // "cannot start a transaction within a transaction" |
| 1768 | // (denoland/celld#226). The open view takes the call instead, so it |
| 1769 | // becomes a savepoint: an inner rollback then discards only the inner |
| 1770 | // writes, and an outer rollback discards both layers. |
| 1771 | // |
| 1772 | // The synchronous transaction is preferred over an asynchronous one, |
| 1773 | // because it is the innermost open layer whenever both are open. |
| 1774 | if (root._activeSyncTransaction !== null) |
| 1775 | return root._activeSyncTransaction.transactionSync(f); |
| 1776 | const owner = String(__io_context_id()); |
| 1777 | if (owner !== "" && root._transactionOwner === owner && |
| 1778 | root._activeTransaction !== null) |
| 1779 | return root._activeTransaction.transactionSync(f); |
| 1780 | } |
| 1781 | const savepoint = this._transactionStart(); |
| 1782 | const control = this._newTransactionControl(savepoint); |
| 1783 | const view = this._transactionView(control); |
| 1784 | // No owner check guards this slot, unlike `_activeTransaction`, which an |
| 1785 | // asynchronous transaction publishes across awaits and must therefore keep |
| 1786 | // with the event that opened it. The callback below runs to its end before |
| 1787 | // any other event starts, so only that event can read the slot, and the |
| 1788 | // restore below runs at exactly the point the savepoint ends. |
| 1789 | const previousSync = root._activeSyncTransaction; |
| 1790 | root._activeSyncTransaction = view; |
| 1791 | try { |
| 1792 | // workerd hands the callback nothing: the root's own methods write |
| 1793 | // inside the transaction, and a throw rolls it back. |
| 1794 | const value = f(); |
| 1795 | if (!control.rolledBack) { |
| 1796 | this._transactionCommit(savepoint); |
| 1797 | control.committed = true; |
| 1798 | } |
| 1799 | return value; |
| 1800 | } catch (error) { |
| 1801 | if (!control.rolledBack) { |
| 1802 | try { |
| 1803 | this._transactionRollback(savepoint); |
| 1804 | control.rolledBack = true; |
| 1805 | } catch (rollbackError) { |
| 1806 | this._abortAfterFailedRollback(rollbackError, error); |
| 1807 | } |
| 1808 | } |
| 1809 | throw error; |
| 1810 | } finally { |
| 1811 | root._activeSyncTransaction = previousSync; |
| 1812 | } |
| 1813 | } |
| 1814 | _newTransactionControl(savepoint) { |
| 1815 | const control = { |
| 1816 | rolledBack: false, |
| 1817 | rollbackPerformed: false, |
| 1818 | committed: false, |
| 1819 | parent: this._transactionControl, |
| 1820 | pending: new Set(), |
| 1821 | rollback: () => { |
| 1822 | this._transactionRollback(savepoint, true); |
| 1823 | control.rollbackPerformed = true; |
| 1824 | }, |
| 1825 | }; |
| 1826 | return control; |
| 1827 | } |
| 1828 | async _drainNestedTransactions(control) { |
| 1829 | while (control.pending.size !== 0) |
| 1830 | await Promise.allSettled(Array.from(control.pending)); |
| 1831 | } |
| 1832 | async _runTransactionWith(f, savepoint, control) { |
| 1833 | const view = this._transactionView(control); |
| 1834 | const root = this._transactionRoot; |
| 1835 | const owner = String(__io_context_id()); |
| 1836 | const installsActive = owner !== "" && root._transactionOwner === owner; |
| 1837 | const previousActive = root._activeTransaction; |
| 1838 | if (installsActive) root._activeTransaction = view; |
| 1839 | try { |
| 1840 | const value = await f(view); |
| 1841 | // A helper can start a reentrant transaction through the root storage |
| 1842 | // handle and omit the returned promise. That child already owns a |
| 1843 | // savepoint, so ending this layer first would make SQLite release the |
| 1844 | // child's savepoint and let its continuation run against a false owner. |
| 1845 | await this._drainNestedTransactions(control); |
| 1846 | if (!control.rolledBack) { |
| 1847 | this._transactionCommit(savepoint); |
| 1848 | control.committed = true; |
| 1849 | } else if (!control.rollbackPerformed) { |
| 1850 | control.rollback(); |
| 1851 | } |
| 1852 | return value; |
| 1853 | } catch (error) { |
| 1854 | await this._drainNestedTransactions(control); |
| 1855 | if (!control.rollbackPerformed) { |
| 1856 | // The flag records a rollback that happened, not one that was |
| 1857 | // attempted: a rollback that fails leaves the savepoint open, and a |
| 1858 | // later transaction on the same connection would commit its writes. |
| 1859 | // Nothing can be said about the connection then, so the object is |
| 1860 | // aborted rather than left to serve from it. |
| 1861 | try { |
| 1862 | this._transactionRollback(savepoint); |
| 1863 | control.rolledBack = true; |
| 1864 | control.rollbackPerformed = true; |
| 1865 | } catch (rollbackError) { |
| 1866 | this._abortAfterFailedRollback(rollbackError, error); |
| 1867 | } |
| 1868 | } |
| 1869 | throw error; |
| 1870 | } finally { |
| 1871 | if (installsActive && root._activeTransaction === view) |
| 1872 | root._activeTransaction = previousActive; |
| 1873 | } |
| 1874 | } |
| 1875 | // `cause` is the failure that led to the rollback; the abort's error keeps |
| 1876 | // it, so a debugger can walk back to the callback's own throw. The |
| 1877 | // rollback failure is reported even when the object is already aborted, |
| 1878 | // as it is after a block's limit: the abort then changes nothing, and the |
| 1879 | // log line is the only trace the failure leaves. |
| 1880 | _abortAfterFailedRollback(rollbackError, cause) { |
| 1881 | // Inside a catch, so the log must not become the throw that leaves it: |
| 1882 | // the slot release after the caller's rethrow depends on that. |
| 1883 | try { console.error("transaction rollback failed", rollbackError); } catch {} |
| 1884 | const state = this._transactionRoot._state; |
| 1885 | if (state && !state._aborted) { |
| 1886 | state.abort( |
| 1887 | new Error( |
| 1888 | "a transaction rollback failed: " + __describeFailure(rollbackError), |
| 1889 | { cause }, |
| 1890 | ), |
| 1891 | ); |
| 1892 | } |
| 1893 | } |
| 1894 | async _runTransaction(f) { |
| 1895 | const savepoint = this._transactionStart(); |
| 1896 | return this._runTransactionWith(f, savepoint, this._newTransactionControl(savepoint)); |
| 1897 | } |
| 1898 | async transaction(f) { |
| 1899 | this._assertTransactionActive("transaction"); |
| 1900 | if (this._transactionDepth > 0) { |
| 1901 | const nested = this._runTransaction(f); |
| 1902 | const pending = this._transactionControl.pending; |
| 1903 | pending.add(nested); |
| 1904 | nested.then( |
| 1905 | () => pending.delete(nested), |
| 1906 | () => pending.delete(nested), |
| 1907 | ); |
| 1908 | return nested; |
| 1909 | } |
| 1910 | const root = this._transactionRoot; |
| 1911 | const owner = String(__io_context_id()); |
| 1912 | if (owner !== "" && root._transactionOwner === owner && |
| 1913 | root._activeTransaction !== null) |
| 1914 | return root._activeTransaction.transaction(f); |
| 1915 | // Workerd runs the callback under blockConcurrencyWhile: the input gate |
| 1916 | // shuts, so no other event starts in the object while the transaction is |
| 1917 | // open. Without it another event's reads saw uncommitted rows, its |
| 1918 | // writes joined the open transaction on the same connection, and a |
| 1919 | // rollback discarded a write celld had already acknowledged (#714). The |
| 1920 | // callback's failure is caught inside the block: a failed transaction |
| 1921 | // rolls back and rejects, and must not reset the object the way a failed |
| 1922 | // critical section does. |
| 1923 | // |
| 1924 | // The tail orders transactions one event starts concurrently, which the |
| 1925 | // gate does not separate. Its slot is taken here, in call order: taken |
| 1926 | // inside the block it would be taken in the order the gate woke the |
| 1927 | // callers, which is not theirs to keep. It is released inside the block, |
| 1928 | // when the callback has settled, and not when the block has: a second |
| 1929 | // transaction the same event starts while the first runs rides the |
| 1930 | // outer hold as a nested block, and the outer block waits for nested |
| 1931 | // ones before it releases, so a slot held until the block's end would |
| 1932 | // wait on itself. |
| 1933 | const previous = root._transactionTail; |
| 1934 | let release; |
| 1935 | root._transactionTail = new Promise((resolve) => { release = resolve; }); |
| 1936 | let control = null; |
| 1937 | let started = false; |
| 1938 | let abandoned = null; |
| 1939 | const guarded = async () => { |
| 1940 | started = true; |
| 1941 | let ownsTransaction = false; |
| 1942 | try { |
| 1943 | await previous; |
| 1944 | // The block ended while this waited for its slot, or the object was |
| 1945 | // reset under it by an enclosing block that failed: the caller has |
| 1946 | // its rejection and the gate is open again, so starting the |
| 1947 | // transaction now would run it beside whatever the object serves. |
| 1948 | if (abandoned !== null) return { error: abandoned }; |
| 1949 | if (root._state._aborted) { |
| 1950 | return { error: new Error("the Durable Object was reset before the transaction started") }; |
| 1951 | } |
| 1952 | // A callback can compose a helper which reaches the root |
| 1953 | // `ctx.storage` handle instead of the transaction view. The input |
| 1954 | // gate excludes other events, but an event which entered before the |
| 1955 | // gate closed can still be waiting for this slot. Keep the owner with |
| 1956 | // the open transaction so only the callback's event takes the |
| 1957 | // savepoint path; another event still waits on the tail. |
| 1958 | root._transactionOwner = owner; |
| 1959 | ownsTransaction = true; |
| 1960 | // The start is a host op that can fail like any other statement, and |
| 1961 | // a failure there is the transaction's to report, not the block's: |
| 1962 | // a throw that escaped here would reset the object. |
| 1963 | try { |
| 1964 | const savepoint = this._transactionStart(); |
| 1965 | control = this._newTransactionControl(savepoint); |
| 1966 | return { value: await this._runTransactionWith(f, savepoint, control) }; |
| 1967 | } catch (error) { |
| 1968 | return { error }; |
| 1969 | } |
| 1970 | } finally { |
| 1971 | if (ownsTransaction && root._transactionOwner === owner) { |
| 1972 | root._activeTransaction = null; |
| 1973 | root._transactionOwner = ""; |
| 1974 | } |
| 1975 | release(); |
| 1976 | } |
| 1977 | }; |
| 1978 | let outcome; |
| 1979 | try { |
| 1980 | outcome = await root._state.blockConcurrencyWhile(guarded); |
| 1981 | } catch (error) { |
| 1982 | // The block itself failed: its limit ended the callback while it still |
| 1983 | // ran, or the block ahead of it failed and this one never started. A |
| 1984 | // transaction the callback still holds would otherwise stay open on |
| 1985 | // the connection the object's replacement uses, and the callback's |
| 1986 | // late commit would carry the replacement's writes with it. Roll it |
| 1987 | // back now, unless the callback's continuation committed in the same |
| 1988 | // tick the limit won; the callback's own commit is skipped from here |
| 1989 | // on. The slot stays with the callback until it settles: the callback |
| 1990 | // still runs on the connection, and a transaction started beside it |
| 1991 | // would interleave with its remaining statements. A routed child must |
| 1992 | // release its savepoint before this layer rolls back, so a live child |
| 1993 | // leaves the rollback for `_runTransactionWith`. A block that failed |
| 1994 | // before the callback started holds nothing, so its slot is released |
| 1995 | // here or nothing ever would. |
| 1996 | abandoned = error; |
| 1997 | if (control && !control.rolledBack && !control.committed) { |
| 1998 | try { |
| 1999 | if (control.pending.size === 0) control.rollback(); |
| 2000 | control.rolledBack = true; |
| 2001 | } catch (rollbackError) { |
| 2002 | this._abortAfterFailedRollback(rollbackError, error); |
| 2003 | } |
| 2004 | } |
| 2005 | if (!started) release(); |
| 2006 | throw error; |
| 2007 | } |
| 2008 | if ("error" in outcome) throw outcome.error; |
| 2009 | return outcome.value; |
| 2010 | } |
| 2011 | } |
| 2012 | class DurableObjectId { |
| 2013 | constructor(className, value, name = undefined) { |
| 2014 | Object.defineProperties(this, { |
| 2015 | _className: { value: className }, |
| 2016 | _value: { value }, |
| 2017 | }); |
| 2018 | this.name = name; |
| 2019 | this.jurisdiction = undefined; |
| 2020 | } |
| 2021 | toString() { return this._value; } |
| 2022 | equals(other) { |
| 2023 | return other instanceof DurableObjectId && other._value === this._value; |
| 2024 | } |
| 2025 | _scope() { return this._className + ":" + this._value; } |
| 2026 | } |
| 2027 | globalThis.DurableObjectRoutingError = class DurableObjectRoutingError |
| 2028 | extends Error { |
| 2029 | constructor(detail = {}) { |
| 2030 | super("The Durable Object owner is currently unreachable"); |
| 2031 | this.name = "DurableObjectRoutingError"; |
| 2032 | this.code = "owner_unreachable"; |
| 2033 | this.retryable = true; |
| 2034 | if (typeof detail.scope === "string") this.scope = detail.scope; |
| 2035 | if (typeof detail.owner === "string") this.owner = detail.owner; |
| 2036 | } |
| 2037 | }; |
| 2038 | const __durableObjectRoutingError = (error) => { |
| 2039 | const marker = "__CELLD_DO_ROUTING_ERROR__:"; |
| 2040 | const message = String(error && error.message || error); |
| 2041 | const offset = message.indexOf(marker); |
| 2042 | if (offset < 0) return null; |
| 2043 | try { |
| 2044 | return new DurableObjectRoutingError( |
| 2045 | JSON.parse(message.slice(offset + marker.length)), |
| 2046 | ); |
| 2047 | } catch { |
| 2048 | return new DurableObjectRoutingError(); |
| 2049 | } |
| 2050 | }; |
| 2051 | // A cell's input gate as the isolate sees it, for the one delivery |
| 2052 | // point that is inside the isolate rather than in front of it: an |
| 2053 | // RPC stub op. `events` records every block that has asked for the |
| 2054 | // gate, so no window exists in which a block has started and the |
| 2055 | // isolate still thinks the cell is open. `holder` names the block |
| 2056 | // actually running; another event can still be queued. |
| 2057 | // |
| 2058 | // A stub minted while a block runs carries that block's token and |
| 2059 | // re-enters it instead of queueing behind it. That is Workerd's |
| 2060 | // `IoContext::makeReentryCallback`, and without it a callback the |
| 2061 | // block itself sent out could never come back. |
| 2062 | const __cellBlocks = new Map(); |
| 2063 | const __blockEnter = (scope, event, owner) => { |
| 2064 | let settleReady; |
| 2065 | let rejectReady; |
| 2066 | const ready = new Promise((resolve, reject) => { |
| 2067 | settleReady = resolve; |
| 2068 | rejectReady = reject; |
| 2069 | }); |
| 2070 | const record = { |
| 2071 | owner, |
| 2072 | reaction: String(__io_context_id()), |
| 2073 | actorEvent: __currentActorEvent(), |
| 2074 | retired: false, |
| 2075 | ready, |
| 2076 | settleReady, |
| 2077 | rejectReady, |
| 2078 | }; |
| 2079 | const block = __cellBlocks.get(scope); |
| 2080 | if (block !== undefined) { |
| 2081 | block.events.set(event, record); |
| 2082 | return { block, record }; |
| 2083 | } |
| 2084 | const fresh = { |
| 2085 | holder: null, |
| 2086 | events: new Map([[event, record]]), |
| 2087 | }; |
| 2088 | __cellBlocks.set(scope, fresh); |
| 2089 | return { block: fresh, record }; |
| 2090 | }; |
| 2091 | const __blockLeave = (scope, block, event) => { |
| 2092 | if (!block.events.delete(event)) return; |
| 2093 | if (block.holder === event) block.holder = null; |
| 2094 | if (block.events.size === 0 && __cellBlocks.get(scope) === block) |
| 2095 | __cellBlocks.delete(scope); |
| 2096 | }; |
| 2097 | const __durableClassMeta = new WeakMap(); |
| 2098 | let __nextFacetOwner = 1; |
| 2099 | // Takes encoded props, not the caller's options bag: an options bag reaching |
| 2100 | // here is a bag nothing validated, and reading one key out of it is how every |
| 2101 | // other key came to be dropped in silence. The loader stub validates the bag |
| 2102 | // and encodes its value before it creates the class. |
| 2103 | const __makeDurableObjectClass = (loadPromise, name, propsSc) => { |
| 2104 | const value = {}; |
| 2105 | __durableClassMeta.set(value, { |
| 2106 | loadPromise, |
| 2107 | name: name === null || name === undefined ? "default" : String(name), |
| 2108 | propsSc, |
| 2109 | }); |
| 2110 | return value; |
| 2111 | }; |
| 2112 | // Loopback classes are callable; a specialized class is only a handle. Capture |
| 2113 | // props now, so later mutation of the caller's options cannot change startup. |
| 2114 | const __makeLoopbackDurableObjectClass = (name) => { |
| 2115 | const loadPromise = Promise.resolve({ id: 0 }); |
| 2116 | const specialize = function(options) { |
| 2117 | if (arguments.length === 0) |
| 2118 | throw new TypeError("DurableObjectClass requires an options argument."); |
| 2119 | if (options !== undefined && options !== null && |
| 2120 | typeof options !== "object" && typeof options !== "function") |
| 2121 | throw new TypeError("DurableObjectClass options must be an object."); |
| 2122 | const props = options?.props; |
| 2123 | if (props !== undefined && |
| 2124 | (props === null || (typeof props !== "object" && typeof props !== "function"))) |
| 2125 | throw new TypeError("DurableObjectClass props must be an object."); |
| 2126 | return __makeDurableObjectClass( |
| 2127 | loadPromise, name, __rpcOut(props === undefined ? {} : props, false)); |
| 2128 | }; |
| 2129 | __durableClassMeta.set(specialize, { |
| 2130 | loadPromise, name, propsSc: __rpcOut({}, false), |
| 2131 | }); |
| 2132 | return specialize; |
| 2133 | }; |
| 2134 | class DurableObjectFacets { |
| 2135 | constructor(state) { |
| 2136 | this._state = state; |
| 2137 | this._owner = String(__nextFacetOwner++); |
| 2138 | this._next = 1; |
| 2139 | this._running = new Map(); |
| 2140 | this._barriers = new Map(); |
| 2141 | } |
| 2142 | _validName(name) { |
| 2143 | name = String(name); |
| 2144 | if (new TextEncoder().encode(name).length > 256) |
| 2145 | throw new TypeError("Facet name is too long (max 256 characters)."); |
| 2146 | return name; |
| 2147 | } |
| 2148 | get(name, getStartupOptions) { |
| 2149 | name = this._validName(name); |
| 2150 | if (this._state._facetDepth >= 3) |
| 2151 | throw new Error( |
| 2152 | "Facet nesting depth limit exceeded. The maximum depth including the root Durable Object is 4."); |
| 2153 | if (typeof getStartupOptions !== "function") |
| 2154 | throw new TypeError("The facet startup callback must be a function."); |
| 2155 | let record = this._running.get(name); |
| 2156 | if (record !== undefined) return record.stub; |
| 2157 | // Each run gets a distinct host scope. An aborted request can still have |
| 2158 | // a pending continuation, so reusing its scope would let that continuation |
| 2159 | // enter the replacement instance after the abort barrier opens. |
| 2160 | record = { |
| 2161 | aborted: false, |
| 2162 | error: undefined, |
| 2163 | owner: this._owner + ":" + this._next++, |
| 2164 | started: null, |
| 2165 | stub: null, |
| 2166 | }; |
| 2167 | const barrier = this._barriers.get(name); |
| 2168 | const start = () => record.started ??= Promise.resolve(barrier) |
| 2169 | .then(getStartupOptions) |
| 2170 | .then(async (options) => { |
| 2171 | const meta = __durableClassMeta.get(options?.class); |
| 2172 | if (meta === undefined) |
| 2173 | throw new TypeError( |
| 2174 | "FacetStartupOptions.class must be a DurableObjectClass."); |
| 2175 | const { id: loader } = await meta.loadPromise; |
| 2176 | const id = options.id === undefined ? this._state.id : options.id; |
| 2177 | // Keep the ID kind and name in one clone. A string round-trip erases |
| 2178 | // named IDs and turns a literal string ID into a DurableObjectId. |
| 2179 | const idSc = __sc_encode(id instanceof DurableObjectId |
| 2180 | ? [id._className, id.toString(), id.name] : String(id)); |
| 2181 | // Keep the load alive after the startup callback and class are gone. |
| 2182 | return [loader, meta.name, idSc, meta.propsSc, meta]; |
| 2183 | }); |
| 2184 | const invoke = async (operation) => { |
| 2185 | if (record.aborted) throw record.error; |
| 2186 | return operation(await start()); |
| 2187 | }; |
| 2188 | const target = {}; |
| 2189 | // Methods share the loaded-worker RPC transport. A facet stub is not |
| 2190 | // awaitable, and a property is a single callable pipeline node. |
| 2191 | const session = { |
| 2192 | get: () => Promise.reject(new Error( |
| 2193 | "Awaitable properties on facets are not supported yet.")), |
| 2194 | call: (path, args) => invoke(async ([loader, className, id, propsSc]) => { |
| 2195 | if (path.length !== 1) |
| 2196 | throw new Error( |
| 2197 | "Pipelined property paths on facets are not supported yet."); |
| 2198 | return __rpcDes(await __facet_rpc( |
| 2199 | loader, className, this._state._scope, record.owner, name, id, |
| 2200 | propsSc, path[0], __rpcOut(args, false))); |
| 2201 | }), |
| 2202 | }; |
| 2203 | // Arrow closures retain the manager because `target.fetch`'s method |
| 2204 | // receiver is the target object, not the DurableObjectFacets instance. |
| 2205 | const manager = this; |
| 2206 | target.fetch = async function(input, init) { |
| 2207 | return invoke(async ([loader, className, id, propsSc]) => { |
| 2208 | const req = new Request(input, init); |
| 2209 | const headers = JSON.stringify(req.headers.__celldHeaderList); |
| 2210 | const { body, streamId } = await __subrequestBody(req); |
| 2211 | const response = JSON.parse(await __facet_fetch( |
| 2212 | loader, className, manager._state._scope, record.owner, name, id, |
| 2213 | propsSc, req.url, req.method, body, headers, streamId)); |
| 2214 | const responseBody = response.streamId !== undefined |
| 2215 | ? new CelldHttpBodyStream(response.streamId) |
| 2216 | : response.body !== undefined ? response.body |
| 2217 | : Uint8Array.from(response.bodyBytes || []); |
| 2218 | // The facet's socket lives in the facet's isolate. The target lets |
| 2219 | // the root return the upgrade, or accept the client end that the |
| 2220 | // wrapper binds to the facet's socket. |
| 2221 | return __wrapServiceResponse(new Response(responseBody, { |
| 2222 | status: response.status, |
| 2223 | headers: response.headers, |
| 2224 | __wsTarget: response.wsTarget, |
| 2225 | }), req.url); |
| 2226 | }); |
| 2227 | }; |
| 2228 | record.stub = new Proxy(target, { |
| 2229 | get(base, prop) { |
| 2230 | if (prop === "then") return undefined; |
| 2231 | if (Reflect.has(base, prop)) return Reflect.get(base, prop); |
| 2232 | if (typeof prop !== "string") return undefined; |
| 2233 | return __makeNode(session, [prop], null); |
| 2234 | }, |
| 2235 | }); |
| 2236 | this._running.set(name, record); |
| 2237 | return record.stub; |
| 2238 | } |
| 2239 | _abort(name, reason) { |
| 2240 | name = this._validName(name); |
| 2241 | const record = this._running.get(name); |
| 2242 | if (record === undefined) return Promise.resolve(); |
| 2243 | record.aborted = true; |
| 2244 | record.error = reason; |
| 2245 | this._running.delete(name); |
| 2246 | const barrier = record.started === null ? Promise.resolve() : record.started |
| 2247 | .then(([loader, className]) => |
| 2248 | __facet_abort( |
| 2249 | loader, className, this._state._scope, record.owner, name), () => {}); |
| 2250 | this._barriers.set(name, barrier); |
| 2251 | const clear = () => { |
| 2252 | if (this._barriers.get(name) === barrier) this._barriers.delete(name); |
| 2253 | }; |
| 2254 | barrier.then(clear, clear); |
| 2255 | return barrier; |
| 2256 | } |
| 2257 | abort(name, reason) { |
| 2258 | this._abort(name, reason); |
| 2259 | } |
| 2260 | delete(name) { |
| 2261 | name = this._validName(name); |
| 2262 | const barrier = this._abort(name, new Error("Facet was deleted.")).then(() => |
| 2263 | __facet_delete(this._state._scope, name)); |
| 2264 | this._barriers.set(name, barrier); |
| 2265 | const clear = () => { |
| 2266 | if (this._barriers.get(name) === barrier) this._barriers.delete(name); |
| 2267 | }; |
| 2268 | // Keep a failed delete as the name's barrier. Clearing it would let the |
| 2269 | // next get reload the image which the failed operation did not delete. |
| 2270 | barrier.then(clear, () => {}); |
| 2271 | } |
| 2272 | _release() { |
| 2273 | // The host closes these facets during give-back. Queuing _abort here |
| 2274 | // leaves an undriven op whose promise retains the manager, its root, |
| 2275 | // and the loaded classes after the root has stopped. |
| 2276 | const reason = new Error("The parent Durable Object was released."); |
| 2277 | for (const record of this._running.values()) { |
| 2278 | record.aborted = true; |
| 2279 | record.error = reason; |
| 2280 | } |
| 2281 | this._running.clear(); |
| 2282 | this._barriers.clear(); |
| 2283 | } |
| 2284 | } |
| 2285 | // The reason a failed critical section gives its waiters. It must not throw: |
| 2286 | // it runs where a throw would skip the gate's release, and a value with no |
| 2287 | // string form, such as `Object.create(null)`, is a legal thing to throw. |
| 2288 | function __describeFailure(error) { |
| 2289 | try { |
| 2290 | return String((error && error.message) || error); |
| 2291 | } catch { |
| 2292 | return "critical section failed"; |
| 2293 | } |
| 2294 | } |
| 2295 | // ---- Containers ----------------------------------------------------------- |
| 2296 | // `ctx.container` for a class named in the deployment's `containers`. The |
| 2297 | // surface and every message follow workerd's api/container.c++; the host |
| 2298 | // ops perform the effects against the node's container engine, and the |
| 2299 | // scope names the cell the way the storage ops do. |
| 2300 | const __containerEnvList = (env, what) => { |
| 2301 | const list = []; |
| 2302 | if (env === undefined || env === null) return list; |
| 2303 | for (const [name, value] of Object.entries(env)) { |
| 2304 | const text = String(value); |
| 2305 | if (name.includes("=")) |
| 2306 | throw new Error(`Environment variable names cannot contain '=': ${name}`); |
| 2307 | if (name.includes("\0")) |
| 2308 | throw new Error(`Environment variable names cannot contain '\\0': ${name}`); |
| 2309 | if (text.includes("\0")) |
| 2310 | throw new Error(`Environment variable values cannot contain '\\0': ${name}`); |
| 2311 | list.push([name, text]); |
| 2312 | } |
| 2313 | return list; |
| 2314 | }; |
| 2315 | const __execOutputMode = (mode, kind) => { |
| 2316 | const value = mode === undefined ? "pipe" : String(mode); |
| 2317 | if (value === "pipe" || value === "ignore" || |
| 2318 | (kind === "stderr" && value === "combined")) return value; |
| 2319 | throw new TypeError(`Invalid ${kind} option: ${value}`); |
| 2320 | }; |
| 2321 | const __validSignal = (signo) => Number.isInteger(signo) && signo > 0 && signo <= 64; |
| 2322 | const __execStream = (id, which) => new ReadableStream({ |
| 2323 | type: "bytes", |
| 2324 | async pull(controller) { |
| 2325 | const chunk = await __container_exec_read(id, which); |
| 2326 | if (chunk.byteLength === 0) controller.close(); |
| 2327 | else controller.enqueue(new Uint8Array(chunk)); |
| 2328 | }, |
| 2329 | }); |
| 2330 | class ContainerExecOutput { |
| 2331 | constructor(stdout, stderr, exitCode) { |
| 2332 | this.stdout = stdout; |
| 2333 | this.stderr = stderr; |
| 2334 | this.exitCode = exitCode; |
| 2335 | } |
| 2336 | } |
| 2337 | class ContainerExecProcess { |
| 2338 | constructor(id, pid, stdinMode, stdoutMode, stderrMode) { |
| 2339 | this._id = id; |
| 2340 | this.pid = pid; |
| 2341 | this._outputCalled = false; |
| 2342 | this._exitCode = null; |
| 2343 | this.stdout = stdoutMode === "pipe" ? __execStream(id, 1) : null; |
| 2344 | this.stderr = stderrMode === "pipe" ? __execStream(id, 2) : null; |
| 2345 | this.stdin = stdinMode === "pipe" |
| 2346 | ? new WritableStream({ |
| 2347 | write: (chunk) => __container_exec_write(id, __bytesOf(chunk)), |
| 2348 | close: () => __container_exec_close(id), |
| 2349 | abort: () => __container_exec_close(id), |
| 2350 | }) |
| 2351 | : null; |
| 2352 | } |
| 2353 | get exitCode() { |
| 2354 | if (this._exitCode === null) { |
| 2355 | this._exitCode = __container_exec_wait(this._id).then(Number); |
| 2356 | } |
| 2357 | return this._exitCode; |
| 2358 | } |
| 2359 | async output() { |
| 2360 | if (this._outputCalled) throw new TypeError("output() can only be called once."); |
| 2361 | this._outputCalled = true; |
| 2362 | for (const [stream, name] of [[this.stdout, "stdout"], [this.stderr, "stderr"]]) { |
| 2363 | if (stream && stream.locked) |
| 2364 | throw new TypeError(`Cannot call output() after ${name} has started being consumed.`); |
| 2365 | } |
| 2366 | const all = (stream) => stream |
| 2367 | ? new Response(stream).arrayBuffer() |
| 2368 | : Promise.resolve(new ArrayBuffer(0)); |
| 2369 | const [stdout, stderr] = await Promise.all([all(this.stdout), all(this.stderr)]); |
| 2370 | const exitCode = await this.exitCode; |
| 2371 | // Nothing else can read the process now, so the host can forget it. |
| 2372 | __container_exec_drop(this._id); |
| 2373 | return new ContainerExecOutput(stdout, stderr, exitCode); |
| 2374 | } |
| 2375 | kill(signal = 15) { |
| 2376 | if (!__validSignal(signal)) throw new RangeError("Invalid signal number."); |
| 2377 | __container_exec_kill(this._id, signal).catch(() => {}); |
| 2378 | } |
| 2379 | } |
| 2380 | const __bytesOf = (chunk) => { |
| 2381 | if (chunk instanceof Uint8Array) return chunk; |
| 2382 | if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk); |
| 2383 | if (ArrayBuffer.isView(chunk)) |
| 2384 | return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); |
| 2385 | throw new TypeError("stdin accepts bytes"); |
| 2386 | }; |
| 2387 | // The Fetcher `getTcpPort()` returns: `fetch()` speaks HTTP to the port over |
| 2388 | // the node's route to the container, and `connect()` is the raw socket. |
| 2389 | class ContainerPort { |
| 2390 | constructor(scope, port) { |
| 2391 | this._scope = scope; |
| 2392 | this._port = port; |
| 2393 | } |
| 2394 | async fetch(input, init) { |
| 2395 | const request = new Request(input, init); |
| 2396 | const url = new URL(request.url); |
| 2397 | if (url.protocol === "https:") |
| 2398 | throw new Error( |
| 2399 | "Connecting to a container using HTTPS is not currently supported; use HTTP " + |
| 2400 | "instead. TLS is unnecessary anyway, as the connection is already secure by default.", |
| 2401 | ); |
| 2402 | if (url.protocol !== "http:") throw new TypeError(`Fetch API cannot load: ${url}`); |
| 2403 | const authority = url.host; |
| 2404 | url.host = __container_address(this._scope, this._port); |
| 2405 | const forwarded = new Request(url.toString(), request); |
| 2406 | forwarded.headers.set("host", authority); |
| 2407 | try { |
| 2408 | return await fetch(forwarded); |
| 2409 | } catch (error) { |
| 2410 | // A refused or reset connection is the port not listening yet, which |
| 2411 | // the `@cloudflare/containers` start loop recognizes by this phrase |
| 2412 | // and retries; any other failure keeps its own message. |
| 2413 | const message = error?.message ?? String(error); |
| 2414 | if (/error sending request|connection|connect/i.test(message)) { |
| 2415 | throw new Error( |
| 2416 | `The container is not listening on port ${this._port}: ${message}`, |
| 2417 | ); |
| 2418 | } |
| 2419 | throw error; |
| 2420 | } |
| 2421 | } |
| 2422 | connect(address, options) { |
| 2423 | if (options?.secureTransport === "on") |
| 2424 | throw new Error( |
| 2425 | "Connencting to a container using TLS is not currently supported. It is " + |
| 2426 | "unnecessary anyway, as the connection is already secure by default.", |
| 2427 | ); |
| 2428 | return __celld.__cfSockets.connect( |
| 2429 | __container_address(this._scope, this._port), options); |
| 2430 | } |
| 2431 | } |
| 2432 | class Container { |
| 2433 | constructor(scope) { |
| 2434 | this._scope = scope; |
| 2435 | this._destroyReason = undefined; |
| 2436 | } |
| 2437 | // The host's answer, not a JavaScript flag: a monitor() promise can be |
| 2438 | // dropped with its event, so the flag it would maintain could go stale. |
| 2439 | get running() { return __container_running(this._scope); } |
| 2440 | start(options) { |
| 2441 | if (this.running) |
| 2442 | throw new Error("start() cannot be called on a container that is already running."); |
| 2443 | const o = options ?? {}; |
| 2444 | const params = { enableInternet: !!o.enableInternet, labels: [] }; |
| 2445 | if (o.entrypoint !== undefined) params.entrypoint = Array.from(o.entrypoint, String); |
| 2446 | params.env = __containerEnvList(o.env); |
| 2447 | if (o.labels !== undefined) { |
| 2448 | for (const [name, value] of Object.entries(o.labels)) { |
| 2449 | if (name.length === 0) throw new Error("Label names cannot be empty"); |
| 2450 | for (const text of [name, String(value)]) { |
| 2451 | for (let i = 0; i < text.length; i++) { |
| 2452 | if (text.charCodeAt(i) < 0x20) |
| 2453 | throw new Error(`Label names cannot contain control characters (index ${i})`); |
| 2454 | } |
| 2455 | } |
| 2456 | params.labels.push([name, String(value)]); |
| 2457 | } |
| 2458 | } |
| 2459 | if (o.hardTimeout !== undefined && !(o.hardTimeout > 0)) |
| 2460 | throw new RangeError("Hard timeout must be greater than 0"); |
| 2461 | // Fire and forget, as on Cloudflare: a start that fails reports |
| 2462 | // through monitor(). The host marks the run as running at once. |
| 2463 | this._destroyReason = undefined; |
| 2464 | __container_start(this._scope, JSON.stringify(params)).catch(() => {}); |
| 2465 | } |
| 2466 | async monitor() { |
| 2467 | if (!this.running) |
| 2468 | throw new Error("monitor() cannot be called on a container that is not running."); |
| 2469 | let raw; |
| 2470 | try { |
| 2471 | raw = await __container_monitor(this._scope); |
| 2472 | } catch (error) { |
| 2473 | this._destroyReason = undefined; |
| 2474 | throw error; |
| 2475 | } |
| 2476 | const exitCode = Number(raw); |
| 2477 | if (this._destroyReason !== undefined) { |
| 2478 | const reason = this._destroyReason; |
| 2479 | this._destroyReason = undefined; |
| 2480 | throw reason; |
| 2481 | } |
| 2482 | if (exitCode !== 0) { |
| 2483 | const error = new Error(`Container exited with unexpected exit code: ${exitCode}`); |
| 2484 | error.exitCode = exitCode; |
| 2485 | throw error; |
| 2486 | } |
| 2487 | } |
| 2488 | async destroy(error) { |
| 2489 | if (!this.running) return; |
| 2490 | if (this._destroyReason === undefined) this._destroyReason = error; |
| 2491 | await __container_destroy(this._scope); |
| 2492 | } |
| 2493 | signal(signo) { |
| 2494 | if (!__validSignal(signo)) throw new RangeError("Invalid signal number."); |
| 2495 | if (!this.running) |
| 2496 | throw new Error("signal() cannot be called on a container that is not running."); |
| 2497 | __container_signal(this._scope, signo).catch(() => {}); |
| 2498 | } |
| 2499 | getTcpPort(port) { |
| 2500 | if (!(Number.isInteger(port) && port > 0 && port < 65536)) |
| 2501 | throw new TypeError(`Invalid port number: ${port}`); |
| 2502 | return new ContainerPort(this._scope, port); |
| 2503 | } |
| 2504 | setInactivityTimeout(durationMs) { |
| 2505 | if (!(durationMs > 0)) |
| 2506 | throw new Error(`setInactivityTimeout() requires durationMs > 0, got ${durationMs}`); |
| 2507 | return __container_inactivity(this._scope, durationMs); |
| 2508 | } |
| 2509 | async exec(cmd, options) { |
| 2510 | if (!this.running) |
| 2511 | throw new Error("exec() cannot be called on a container that is not running."); |
| 2512 | if (!Array.isArray(cmd) || cmd.length === 0) |
| 2513 | throw new TypeError("exec() requires a non-empty command array."); |
| 2514 | const o = options ?? {}; |
| 2515 | const stdoutMode = __execOutputMode(o.stdout, "stdout"); |
| 2516 | const stderrMode = __execOutputMode(o.stderr, "stderr"); |
| 2517 | const combined = stderrMode === "combined"; |
| 2518 | if (combined && stdoutMode !== "pipe") |
| 2519 | throw new TypeError('stderr: "combined" requires stdout to be "pipe".'); |
| 2520 | if (o.cwd !== undefined && String(o.cwd).includes("\0")) |
| 2521 | throw new TypeError("cwd cannot contain '\\0' characters."); |
| 2522 | if (o.user !== undefined && String(o.user).includes("\0")) |
| 2523 | throw new TypeError("user cannot contain '\\0' characters."); |
| 2524 | let stdinMode = "none"; |
| 2525 | if (o.stdin !== undefined) { |
| 2526 | if (o.stdin === "pipe") stdinMode = "pipe"; |
| 2527 | else if (o.stdin instanceof ReadableStream) stdinMode = "stream"; |
| 2528 | else throw new TypeError('stdin must be a ReadableStream or the string "pipe".'); |
| 2529 | } |
| 2530 | const params = { |
| 2531 | cmd: Array.from(cmd, String), |
| 2532 | env: __containerEnvList(o.env), |
| 2533 | combined, |
| 2534 | }; |
| 2535 | if (o.cwd !== undefined) params.cwd = String(o.cwd); |
| 2536 | if (o.user !== undefined) params.user = String(o.user); |
| 2537 | const { id, pid } = JSON.parse( |
| 2538 | await __container_exec(this._scope, JSON.stringify(params)), |
| 2539 | ); |
| 2540 | if (stdinMode === "stream") { |
| 2541 | // Pump the caller's stream to the process; the pump is pending work |
| 2542 | // of the event, like a subrequest body. |
| 2543 | (async () => { |
| 2544 | const reader = o.stdin.getReader(); |
| 2545 | try { |
| 2546 | for (;;) { |
| 2547 | const { value, done } = await reader.read(); |
| 2548 | if (done) break; |
| 2549 | await __container_exec_write(id, __bytesOf(value)); |
| 2550 | } |
| 2551 | } finally { |
| 2552 | await __container_exec_close(id); |
| 2553 | } |
| 2554 | })().catch(() => {}); |
| 2555 | } else if (stdinMode === "none") { |
| 2556 | __container_exec_close(id).catch(() => {}); |
| 2557 | } |
| 2558 | return new ContainerExecProcess(id, pid, stdinMode, stdoutMode, stderrMode); |
| 2559 | } |
| 2560 | inspect() { |
| 2561 | return Promise.reject(new Error("inspect() is not implemented in celld")); |
| 2562 | } |
| 2563 | snapshotDirectory() { |
| 2564 | return Promise.reject(new Error("snapshotDirectory() is not implemented in celld")); |
| 2565 | } |
| 2566 | snapshotContainer() { |
| 2567 | return Promise.reject(new Error("snapshotContainer() is not implemented in celld")); |
| 2568 | } |
| 2569 | interceptOutboundHttp() { |
| 2570 | return Promise.reject(new Error("interceptOutboundHttp() is not implemented in celld")); |
| 2571 | } |
| 2572 | interceptOutboundHttps() { |
| 2573 | return Promise.reject(new Error("interceptOutboundHttps() is not implemented in celld")); |
| 2574 | } |
| 2575 | interceptAllOutboundHttp() { |
| 2576 | return Promise.reject(new Error("interceptAllOutboundHttp() is not implemented in celld")); |
| 2577 | } |
| 2578 | interceptOutboundTcp() { |
| 2579 | return Promise.reject(new Error("interceptOutboundTcp() is not implemented in celld")); |
| 2580 | } |
| 2581 | } |
| 2582 | class DurableObjectState { |
| 2583 | constructor(scope) { |
| 2584 | this._scope = scope; |
| 2585 | this._aborted = false; |
| 2586 | this.storage = new DurableObjectStorage(scope, this); |
| 2587 | this.facets = new DurableObjectFacets(this); |
| 2588 | this._gate = Promise.resolve(); |
| 2589 | this._blockDepth = 0; |
| 2590 | const facet = __cell.facetConfigs[scope]; |
| 2591 | this._facetDepth = facet?.depth ?? 0; |
| 2592 | const separator = scope.indexOf(":"); |
| 2593 | const className = separator < 0 ? scope : scope.slice(0, separator); |
| 2594 | this.id = facet === undefined |
| 2595 | ? new DurableObjectId( |
| 2596 | className, separator < 0 ? scope : scope.slice(separator + 1), |
| 2597 | __cell.idNames[scope]) |
| 2598 | : typeof facet.id === "string" ? facet.id : new DurableObjectId(...facet.id); |
| 2599 | this.props = facet?.props; |
| 2600 | // A class outside `containers` has no `ctx.container`, which is what |
| 2601 | // the `@cloudflare/containers` constructor checks. |
| 2602 | if (__cell.containers[className]) this.container = new Container(scope); |
| 2603 | } |
| 2604 | // Workerd's DurableObjectState.exports (actor-state.h): the same |
| 2605 | // loopback surface as ctx.exports on stateless entrypoints. |
| 2606 | get exports() { return __ctxExports(); } |
| 2607 | blockConcurrencyWhile(f) { |
| 2608 | // The native context binds the gate and its operations to one driver. |
| 2609 | // Its async continuations keep that driver even inside a foreign turn. |
| 2610 | return __with_input_gate_context(() => this._blockConcurrencyWhile(f)); |
| 2611 | } |
| 2612 | _blockConcurrencyWhile(f) { |
| 2613 | if (typeof f !== "function") |
| 2614 | throw new TypeError("blockConcurrencyWhile() requires a function"); |
| 2615 | if (this._blockDepth >= 64) |
| 2616 | throw new Error( |
| 2617 | "blockConcurrencyWhile() calls are nested too deeply.", |
| 2618 | ); |
| 2619 | if (this._blockDepth > 0) { |
| 2620 | // A stale reaction can run while an unrelated live block makes this |
| 2621 | // actor's depth nonzero. It cannot ride that hold when either half of |
| 2622 | // its retained [origin, driver] pair has already retired. |
| 2623 | if (__io_context_id() === "" || __io_context_id(true) === "") { |
| 2624 | return Promise.reject(new Error( |
| 2625 | "the cell event ended before it could acquire an input gate", |
| 2626 | )); |
| 2627 | } |
| 2628 | // A nested block rides the outer hold. One the outer body starts and |
| 2629 | // does not await would outlive that hold, and a `transaction()` |
| 2630 | // started that way is the shape that mattered: the outer block |
| 2631 | // returned, the gate opened, and another event wrote into the still |
| 2632 | // open transaction (#714). The outer block drains these before it |
| 2633 | // releases, so the hold lasts as long as any block under it. A nested |
| 2634 | // block that fails resets the object as any block does, and the outer |
| 2635 | // release must carry that failure, or the waiters would be admitted to |
| 2636 | // an object that no longer exists: the drain records it. |
| 2637 | const nested = this._runConcurrencyBlock(f); |
| 2638 | (this._nestedBlocks ||= []).push(nested.then(() => null, __describeFailure)); |
| 2639 | return nested; |
| 2640 | } |
| 2641 | // The host owns the gate (celld_logic::gate::InputGate). It replaces a |
| 2642 | // promise chain that could only order blocks against each other; the |
| 2643 | // gate sits at the delivery points, so nothing else is delivered to this |
| 2644 | // cell at all while the block runs. |
| 2645 | // |
| 2646 | // The acquire waits. It used to be synchronous, and had to be: a cell's |
| 2647 | // events came off one channel, so yielding even one microtask reopened a |
| 2648 | // window in which this cell delivered an event that then waited on a |
| 2649 | // gate nothing would release. Events are independent tasks now, so two |
| 2650 | // can reach a block together and the second has to queue -- and nothing |
| 2651 | // nests, so waiting cannot deadlock on an event suspended beneath it. |
| 2652 | // Asked for synchronously, awaited asynchronously, and the split is the |
| 2653 | // whole point. The op shuts the gate in this very call, so no event can |
| 2654 | // be delivered to this cell from here on -- that immediacy is what makes |
| 2655 | // `failCriticalSection()` reject a `ping()` issued right after it. |
| 2656 | // Waiting for the *ticket* is separate: events are independent tasks |
| 2657 | // now, so two of them can reach a block together and the second has to |
| 2658 | // queue behind the first. Calling this inside the async body instead |
| 2659 | // costs one microtask, and an event delivered in that window walks |
| 2660 | // straight into the critical section. |
| 2661 | const [eventText, owner, acquired] = __gate_acquire(this._scope); |
| 2662 | // An empty owner is an immediate refusal. Return its already-rejected |
| 2663 | // promise before recording the block, because no driver exists to settle |
| 2664 | // native work or to repair a readiness gate installed for stale work. |
| 2665 | if (owner === "") return acquired; |
| 2666 | const event = Number(eventText); |
| 2667 | const { block, record } = __blockEnter(this._scope, event, owner); |
| 2668 | const next = (async () => { |
| 2669 | try { |
| 2670 | await acquired; |
| 2671 | // A shutdown can retire the promise reaction while another event |
| 2672 | // owns this queued acquisition. The owner still has to consume its |
| 2673 | // ticket, but the retired callback must not run. |
| 2674 | if (record.retired) { |
| 2675 | __gate_release(this._scope, event, owner, null); |
| 2676 | return; |
| 2677 | } |
| 2678 | block.holder = event; |
| 2679 | // A critical section that fails resets the actor, so whatever queued |
| 2680 | // behind its gate must be refused rather than handed to the reset |
| 2681 | // one -- it was sent to a cell whose state no longer exists. The |
| 2682 | // failure rides with the release for that: waiters are woken with it |
| 2683 | // instead of merely woken. |
| 2684 | let failure = null; |
| 2685 | try { |
| 2686 | return await this._runConcurrencyBlock(f); |
| 2687 | } catch (error) { |
| 2688 | failure = __describeFailure(error); |
| 2689 | throw error; |
| 2690 | } finally { |
| 2691 | // Nested blocks are drained only after a body that returned: a |
| 2692 | // body that failed has reset the object, its waiters are refused |
| 2693 | // whatever the nested blocks do, and waiting for them would only |
| 2694 | // delay the refusal and a transaction's rollback behind it. Each |
| 2695 | // nested block has its own limit, so a drain is bounded by the |
| 2696 | // last one started, as workerd's nested critical sections are. |
| 2697 | while (failure === null && this._nestedBlocks && this._nestedBlocks.length > 0) { |
| 2698 | for (const nestedFailure of await Promise.all(this._nestedBlocks.splice(0))) { |
| 2699 | if (nestedFailure !== null && failure === null) failure = nestedFailure; |
| 2700 | } |
| 2701 | } |
| 2702 | this._nestedBlocks = undefined; |
| 2703 | __gate_release(this._scope, event, owner, failure); |
| 2704 | } |
| 2705 | } finally { |
| 2706 | // Also on a rejected `acquired`: the block ahead failed, this one |
| 2707 | // never ran, and the cell must not stay shut on its behalf. |
| 2708 | __blockLeave(this._scope, block, event); |
| 2709 | } |
| 2710 | })(); |
| 2711 | // `_ready()` awaits this. The host gate stops *other* events, but a |
| 2712 | // block taken in the constructor runs inside the very event that is |
| 2713 | // being delivered, so nothing external can hold that event back -- the |
| 2714 | // promise does. Concurrent blocks within one event go through |
| 2715 | // `_blockDepth` above and never reach here. |
| 2716 | this._gate = Promise.all([this._gate, record.ready]).then(() => undefined); |
| 2717 | // `_ready()` observes the original promise. This extra handler prevents |
| 2718 | // a constructor-time rejection from becoming unhandled before an event |
| 2719 | // reaches `_ready()`. |
| 2720 | this._gate.catch(() => {}); |
| 2721 | next.then(record.settleReady, record.rejectReady); |
| 2722 | return next; |
| 2723 | } |
| 2724 | _runConcurrencyBlock(f) { |
| 2725 | this._blockDepth++; |
| 2726 | let result; |
| 2727 | try { |
| 2728 | result = f(); |
| 2729 | } catch (error) { |
| 2730 | this._blockDepth--; |
| 2731 | this._resetAfterConcurrencyFailure(error); |
| 2732 | throw error; |
| 2733 | } |
| 2734 | const timerId = __timer_alloc(); |
| 2735 | let settled = false; |
| 2736 | const timeout = __op_timer( |
| 2737 | timerId, |
| 2738 | 30_000, |
| 2739 | ).then(() => { |
| 2740 | if (!settled) { |
| 2741 | throw new Error( |
| 2742 | "A call to blockConcurrencyWhile() in a Durable Object waited for " + |
| 2743 | "too long. The call was canceled and the Durable Object was reset.", |
| 2744 | ); |
| 2745 | } |
| 2746 | }); |
| 2747 | return Promise.race([Promise.resolve(result), timeout]).then( |
| 2748 | (value) => { |
| 2749 | settled = true; |
| 2750 | __timer_cancel(timerId); |
| 2751 | this._blockDepth--; |
| 2752 | return value; |
| 2753 | }, |
| 2754 | (error) => { |
| 2755 | settled = true; |
| 2756 | __timer_cancel(timerId); |
| 2757 | this._blockDepth--; |
| 2758 | this._resetAfterConcurrencyFailure(error); |
| 2759 | throw error; |
| 2760 | }, |
| 2761 | ); |
| 2762 | } |
| 2763 | _resetAfterConcurrencyFailure(error) { |
| 2764 | if (this._aborted) return; |
| 2765 | this._aborted = true; |
| 2766 | __storage_cancel_pending_puts(this._scope); |
| 2767 | const instance = __cell.instances[this._scope]; |
| 2768 | if (instance && instance.__celldState === this) |
| 2769 | delete __cell.instances[this._scope]; |
| 2770 | // Under a stub-mediated caller (this scope is not the current |
| 2771 | // event) the failure breaks the actor, as Workerd joins it |
| 2772 | // into the on-abort promise; a direct event keeps reset-only |
| 2773 | // semantics -- its caller sees the rejection itself. |
| 2774 | if (__currentActorScope() !== this._scope) |
| 2775 | __actorBreak(this._scope, error); |
| 2776 | } |
| 2777 | abort(reason) { |
| 2778 | if (this._aborted) return; |
| 2779 | this._aborted = true; |
| 2780 | __storage_cancel_pending_puts(this._scope); |
| 2781 | const instance = __cell.instances[this._scope]; |
| 2782 | if (instance && instance.__celldState === this) |
| 2783 | delete __cell.instances[this._scope]; |
| 2784 | const message = reason instanceof Error |
| 2785 | ? reason.message |
| 2786 | : String(reason); |
| 2787 | // Direct host-dispatched event on this actor: the uncatchable |
| 2788 | // terminate_execution path. Under a same-isolate stub caller, |
| 2789 | // termination would unwind the caller too, so break in JS. |
| 2790 | if (__currentActorScope() === this._scope) { |
| 2791 | __actor_abort(this._scope, message); |
| 2792 | return; |
| 2793 | } |
| 2794 | __actorBreak(this._scope, |
| 2795 | reason instanceof Error ? reason : new Error(message)); |
| 2796 | } |
| 2797 | _ready() { return this._gate; } |
| 2798 | getWebSockets(tag) { |
| 2799 | return JSON.parse(__ws_list(this._scope, tag)).map((row) => __socketFromRow(row)); |
| 2800 | } |
| 2801 | getTags(ws) { |
| 2802 | if (!(ws instanceof WebSocket) || !ws._hibernatable) { |
| 2803 | throw new Error( |
| 2804 | "you must call 'acceptWebSocket()' before attempting to access " + |
| 2805 | "the tags of a WebSocket."); |
| 2806 | } |
| 2807 | return Array.from(ws._tags); |
| 2808 | } |
| 2809 | acceptWebSocket(ws, tags = []) { |
| 2810 | if (__heap_over_admission_share()) |
| 2811 | throw new Error( |
| 2812 | "the isolate is near its V8 heap limit, so it refused a " + |
| 2813 | "WebSocket (see CELLD_V8_HEAP_LIMIT_MB)"); |
| 2814 | ws._target = { id: ws._id, scope: this._scope }; |
| 2815 | if (ws._peer) ws._peer._target = ws._target; |
| 2816 | ws._hibernatable = true; |
| 2817 | if (ws._peer) ws._peer._hibernatable = true; |
| 2818 | ws._tags = Array.from(tags, String); |
| 2819 | __ws_accept(ws._id, this._scope, JSON.stringify(ws._tags)); |
| 2820 | __sockets.set(ws._id, ws); |
| 2821 | } |
| 2822 | _socket(id) { |
| 2823 | return __sockets.get(Number(id)) || |
| 2824 | this.getWebSockets().find((ws) => ws._id === id) || |
| 2825 | __wsStub(id); |
| 2826 | } |
| 2827 | // Workerd actor-state.c++ setWebSocketAutoResponse: no pair unsets, and |
| 2828 | // each side is capped at 2048 UTF-8 bytes. The pair itself lives in the |
| 2829 | // shell -- a matched message is answered without waking this cell. |
| 2830 | setWebSocketAutoResponse(pair) { |
| 2831 | if (pair === undefined || pair === null) { |
| 2832 | __ws_auto_response_set(this._scope, null, null); |
| 2833 | return; |
| 2834 | } |
| 2835 | if (!(pair instanceof WebSocketRequestResponsePair)) |
| 2836 | throw new TypeError( |
| 2837 | "Failed to execute 'setWebSocketAutoResponse' on " + |
| 2838 | "'DurableObjectState': parameter 1 is not of type " + |
| 2839 | "'WebSocketRequestResponsePair'.", |
| 2840 | ); |
| 2841 | const max = 2048; |
| 2842 | const bytes = (s) => new TextEncoder().encode(s).length; |
| 2843 | const requestSize = bytes(pair.request); |
| 2844 | if (requestSize > max) |
| 2845 | throw new RangeError( |
| 2846 | `Request cannot be larger than ${max} bytes. ` + |
| 2847 | `A request of size ${requestSize} was provided.`, |
| 2848 | ); |
| 2849 | const responseSize = bytes(pair.response); |
| 2850 | if (responseSize > max) |
| 2851 | throw new RangeError( |
| 2852 | `Response cannot be larger than ${max} bytes. ` + |
| 2853 | `A response of size ${responseSize} was provided.`, |
| 2854 | ); |
| 2855 | __ws_auto_response_set(this._scope, pair.request, pair.response); |
| 2856 | } |
| 2857 | getWebSocketAutoResponse() { |
| 2858 | const pair = JSON.parse(__ws_auto_response_get(this._scope)); |
| 2859 | if (pair === null) return null; |
| 2860 | return new WebSocketRequestResponsePair(pair[0], pair[1]); |
| 2861 | } |
| 2862 | getWebSocketAutoResponseTimestamp(ws) { |
| 2863 | const ms = __ws_auto_response_ts(ws._id); |
| 2864 | return ms === null ? null : new Date(ms); |
| 2865 | } |
| 2866 | waitUntil(promise) { |
| 2867 | __registerWaitUntil(promise); |
| 2868 | } |
| 2869 | } |
| 2870 | function _instance(scope) { |
| 2871 | let inst = __cell.instances[scope]; |
| 2872 | if (!inst) { |
| 2873 | const className = scope.split(":")[0]; |
| 2874 | const cls = __cell.classes[className]; |
| 2875 | if (!cls) throw new Error("no DO class " + className); |
| 2876 | const state = new DurableObjectState(scope); |
| 2877 | inst = new cls(state, __cell.env); |
| 2878 | Object.defineProperty(inst, "__celldState", { value: state }); |
| 2879 | // Workerd worker-rpc.c++ getTargetInfo(): RPC needs `extends |
| 2880 | // DurableObject` unless the js_rpc compat flag is on. Decided |
| 2881 | // once here; dispatch reads a boolean. |
| 2882 | state._rpcOk = __cell.compat.jsRpc || |
| 2883 | __cell.doExports[className] === true; |
| 2884 | __cell.instances[scope] = inst; |
| 2885 | } |
| 2886 | return inst; |
| 2887 | } |
| 2888 | async function _readyInstance(scope) { |
| 2889 | const inst = _instance(scope); |
| 2890 | await inst.__celldState._ready(); |
| 2891 | return inst; |
| 2892 | } |
| 2893 | const __actorEventStack = []; |
| 2894 | const __currentActorEvent = () => { |
| 2895 | const context = String(__io_context_id()); |
| 2896 | if (context === "") return undefined; |
| 2897 | for (let index = __actorEventStack.length - 1; index >= 0; index--) { |
| 2898 | const event = __actorEventStack[index]; |
| 2899 | if (event.context === context) return event; |
| 2900 | } |
| 2901 | return undefined; |
| 2902 | }; |
| 2903 | const __currentActorScope = () => __currentActorEvent()?.scope ?? ""; |
| 2904 | const __beginActorEvent = (scope) => { |
| 2905 | __rpcSignalRefresh(); |
| 2906 | const event = { scope, context: String(__io_context_id()) }; |
| 2907 | __actorEventStack.push(event); |
| 2908 | return event; |
| 2909 | }; |
| 2910 | const __endActorEvent = (event) => { |
| 2911 | const index = __actorEventStack.lastIndexOf(event); |
| 2912 | if (index >= 0) __actorEventStack.splice(index, 1); |
| 2913 | }; |
| 2914 | const __endActorEventsForContext = (context) => { |
| 2915 | for (let index = __actorEventStack.length - 1; index >= 0; index--) { |
| 2916 | if (__actorEventStack[index].context === context) |
| 2917 | __actorEventStack.splice(index, 1); |
| 2918 | } |
| 2919 | }; |
| 2920 | const __incomingRequestSignals = new Map(); |
| 2921 | const __abortSignal = (signal, reason) => { |
| 2922 | if (signal.aborted) return; |
| 2923 | signal.aborted = true; |
| 2924 | signal.reason = reason; |
| 2925 | signal.dispatchEvent(new Event("abort")); |
| 2926 | }; |
| 2927 | const __abortIncomingRequest = __celld.__abortIncomingRequest = (requestId) => { |
| 2928 | const signal = __incomingRequestSignals.get(String(requestId)); |
| 2929 | if (signal && !signal.aborted) { |
| 2930 | __abortSignal(signal, new Error("The client has disconnected")); |
| 2931 | return true; |
| 2932 | } |
| 2933 | return false; |
| 2934 | }; |
| 2935 | __celld.__registerIncomingRequest = (requestId, request) => { |
| 2936 | __incomingRequestSignals.set(String(requestId), request.signal); |
| 2937 | }; |
| 2938 | __celld.__finishIncomingRequest = (requestId) => { |
| 2939 | __incomingRequestSignals.delete(String(requestId)); |
| 2940 | }; |
| 2941 | __celld.__retireInputGateContext = (context) => { |
| 2942 | for (const [scope, block] of __cellBlocks) { |
| 2943 | const retired = [...block.events].filter(([, record]) => |
| 2944 | record.owner === context || record.reaction === context |
| 2945 | ); |
| 2946 | if (retired.length === 0) continue; |
| 2947 | const holder = retired.find(([event]) => block.holder === event); |
| 2948 | if (holder === undefined) { |
| 2949 | // A queued callback has not changed the actor. Remove only that |
| 2950 | // callback, and let an unrelated holder continue with the same state. |
| 2951 | for (const [event, record] of retired) { |
| 2952 | record.retired = true; |
| 2953 | record.settleReady(); |
| 2954 | block.events.delete(event); |
| 2955 | if (record.actorEvent !== undefined) |
| 2956 | __endActorEvent(record.actorEvent); |
| 2957 | } |
| 2958 | if (block.events.size === 0 && __cellBlocks.get(scope) === block) |
| 2959 | __cellBlocks.delete(scope); |
| 2960 | continue; |
| 2961 | } |
| 2962 | // A running callback changed this actor and cannot reach its own |
| 2963 | // `finally`. Reset the actor, and release the host gate when the context |
| 2964 | // that started the callback differs from the turn that owns its work. |
| 2965 | const [holderEvent, holderRecord] = holder; |
| 2966 | __gate_release( |
| 2967 | scope, |
| 2968 | holderEvent, |
| 2969 | holderRecord.owner, |
| 2970 | "the cell's critical section ended without releasing", |
| 2971 | ); |
| 2972 | const instance = __cell.instances[scope]; |
| 2973 | if (instance !== undefined) instance.__celldState._aborted = true; |
| 2974 | __storage_cancel_pending_puts(scope); |
| 2975 | if (instance !== undefined && __cell.instances[scope] === instance) |
| 2976 | delete __cell.instances[scope]; |
| 2977 | for (const record of block.events.values()) { |
| 2978 | record.retired = true; |
| 2979 | record.settleReady(); |
| 2980 | if (record.actorEvent !== undefined) |
| 2981 | __endActorEvent(record.actorEvent); |
| 2982 | } |
| 2983 | // The old actor cannot run any block `finally`. A later event creates an |
| 2984 | // instance whose ready promise contains none of this actor's work. |
| 2985 | if (__cellBlocks.get(scope) === block) __cellBlocks.delete(scope); |
| 2986 | } |
| 2987 | __endActorEventsForContext(context); |
| 2988 | }; |
| 2989 | // Race a pending dispatch against the caller's abort signal: on abort, |
| 2990 | // run `abandon` (which reaches the target's side) and reject with the |
| 2991 | // caller's reason. The dispatch keeps its settle handlers, so a late |
| 2992 | // settlement after abandonment cannot trip the unhandled-rejection |
| 2993 | // signal. |
| 2994 | const __raceCallerAbort = (dispatch, signal, abandon) => |
| 2995 | new Promise((resolve, reject) => { |
| 2996 | let settled = false; |
| 2997 | const onAbort = () => { |
| 2998 | if (settled) return; |
| 2999 | settled = true; |
| 3000 | abandon(); |
| 3001 | reject(signal.reason); |
| 3002 | }; |
| 3003 | signal.addEventListener("abort", onAbort, { once: true }); |
| 3004 | dispatch.then( |
| 3005 | (value) => { |
| 3006 | if (settled) return; |
| 3007 | settled = true; |
| 3008 | signal.removeEventListener("abort", onAbort); |
| 3009 | resolve(value); |
| 3010 | }, |
| 3011 | (error) => { |
| 3012 | if (settled) return; |
| 3013 | settled = true; |
| 3014 | signal.removeEventListener("abort", onAbort); |
| 3015 | reject(error); |
| 3016 | }, |
| 3017 | ); |
| 3018 | }); |
| 3019 | const __awaitCancellableDoCall = (operation, signal) => { |
| 3020 | if (signal.aborted) { |
| 3021 | __do_call_cancel(operation.__celldCancelId); |
| 3022 | return Promise.reject(signal.reason); |
| 3023 | } |
| 3024 | return __raceCallerAbort(operation, signal, |
| 3025 | () => __do_call_cancel(operation.__celldCancelId)); |
| 3026 | }; |
| 3027 | // Workerd semantics: a Response crossing a service binding is a fresh |
| 3028 | // fetch-shaped Response -- immutable headers, default reason phrase, |
| 3029 | // the request URL, and a real body stream -- never the callee's own |
| 3030 | // mutable object. |
| 3031 | const __STATUS_TEXT = { |
| 3032 | 100: "Continue", 101: "Switching Protocols", 102: "Processing", |
| 3033 | 103: "Early Hints", 200: "OK", 201: "Created", 202: "Accepted", |
| 3034 | 203: "Non-Authoritative Information", 204: "No Content", |
| 3035 | 205: "Reset Content", 206: "Partial Content", 207: "Multi-Status", |
| 3036 | 208: "Already Reported", 226: "IM Used", 300: "Multiple Choices", |
| 3037 | 301: "Moved Permanently", 302: "Found", 303: "See Other", |
| 3038 | 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", |
| 3039 | 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", |
| 3040 | 402: "Payment Required", 403: "Forbidden", 404: "Not Found", |
| 3041 | 405: "Method Not Allowed", 406: "Not Acceptable", |
| 3042 | 407: "Proxy Authentication Required", 408: "Request Timeout", |
| 3043 | 409: "Conflict", 410: "Gone", 411: "Length Required", |
| 3044 | 412: "Precondition Failed", 413: "Payload Too Large", |
| 3045 | 414: "URI Too Long", 415: "Unsupported Media Type", |
| 3046 | 416: "Range Not Satisfiable", 417: "Expectation Failed", |
| 3047 | 418: "I'm a teapot", 421: "Misdirected Request", |
| 3048 | 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", |
| 3049 | 425: "Too Early", 426: "Upgrade Required", |
| 3050 | 428: "Precondition Required", 429: "Too Many Requests", |
| 3051 | 431: "Request Header Fields Too Large", |
| 3052 | 451: "Unavailable For Legal Reasons", 500: "Internal Server Error", |
| 3053 | 501: "Not Implemented", 502: "Bad Gateway", |
| 3054 | 503: "Service Unavailable", 504: "Gateway Timeout", |
| 3055 | 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", |
| 3056 | 507: "Insufficient Storage", 508: "Loop Detected", |
| 3057 | 510: "Not Extended", 511: "Network Authentication Required", |
| 3058 | }; |
| 3059 | const __ERROR_RESPONSE_MESSAGE = |
| 3060 | "Return value from serve handler must not be an error " + |
| 3061 | "response (like Response.error())"; |
| 3062 | const __wrapServiceResponse = (res, url) => { |
| 3063 | // Response.error() represents a Fetch network error, not an HTTP response. |
| 3064 | // Letting status 0 cross this seam turns it into an ordinary response and |
| 3065 | // makes callers continue after the target explicitly reported failure. |
| 3066 | if (res.type === "error" || res.status === 0) { |
| 3067 | throw new TypeError(__ERROR_RESPONSE_MESSAGE); |
| 3068 | } |
| 3069 | // A 101 that crossed isolates carries a target rather than a socket: the |
| 3070 | // pair's other end is in the isolate that answered, and the two cannot be |
| 3071 | // linked the way the loopback below links them. Give the caller a client |
| 3072 | // end the host can join to that target, on the same terms as a Durable |
| 3073 | // Object subrequest -- nothing binds until `accept()`, so a response |
| 3074 | // passed straight back out keeps the direct route to the real client. |
| 3075 | const bound = !res.webSocket && res._wsTarget && res.status === 101 |
| 3076 | ? new WebSocket(undefined, [], res._wsTarget) |
| 3077 | : undefined; |
| 3078 | const wrapped = new Response( |
| 3079 | // Buffered bodies re-stream (an empty buffer still yields a |
| 3080 | // stream, as over real HTTP); a streaming body passes through. |
| 3081 | res._bodyBytes !== null ? res._bodyBytes : res.body, |
| 3082 | { |
| 3083 | status: res.status, |
| 3084 | statusText: |
| 3085 | res.statusText || __STATUS_TEXT[res.status] || "", |
| 3086 | headers: res.headers, |
| 3087 | webSocket: res.webSocket || bound, |
| 3088 | __wsTarget: res._wsTarget, |
| 3089 | }, |
| 3090 | ); |
| 3091 | // The constructor copies headers, so mark the copy. |
| 3092 | Object.defineProperty(wrapped.headers, "_immutable", { value: true }); |
| 3093 | wrapped.url = url; |
| 3094 | // An upgraded pair whose both ends live in this isolate: link them |
| 3095 | // directly -- the host connection seam only reaches external |
| 3096 | // clients. Frames the handler queued before linking flush first. |
| 3097 | const client = wrapped.webSocket; |
| 3098 | if (wrapped.status === 101 && client && client._peer) { |
| 3099 | const server = client._peer; |
| 3100 | client._loopback = server; |
| 3101 | server._loopback = client; |
| 3102 | for (const frame of server._pending.splice(0)) { |
| 3103 | // "send-binary" joined this queue with outbound sockets; without a case |
| 3104 | // of its own it fell through to the close branch and tore the pair down |
| 3105 | // instead of delivering the frame. |
| 3106 | if (frame[0] === "send") |
| 3107 | queueMicrotask(() => client._dispatchMessage(frame[1])); |
| 3108 | else if (frame[0] === "send-binary") |
| 3109 | queueMicrotask(() => { |
| 3110 | const data = frame[1]; |
| 3111 | client._dispatchMessage( |
| 3112 | data instanceof ArrayBuffer ? data : data.buffer.slice( |
| 3113 | data.byteOffset, |
| 3114 | data.byteOffset + data.byteLength, |
| 3115 | ), |
| 3116 | ); |
| 3117 | }); |
| 3118 | else |
| 3119 | queueMicrotask( |
| 3120 | () => client._dispatchClose(frame[1], frame[2], true)); |
| 3121 | } |
| 3122 | } |
| 3123 | return wrapped; |
| 3124 | }; |
| 3125 | const __SERVICE_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); |
| 3126 | const __REQUEST_BODY_HEADERS = [ |
| 3127 | "content-encoding", "content-language", "content-length", |
| 3128 | "content-location", "content-type", "transfer-encoding", |
| 3129 | ]; |
| 3130 | const __CROSS_ORIGIN_SENSITIVE_HEADERS = [ |
| 3131 | "authorization", "cookie", "proxy-authorization", |
| 3132 | ]; |
| 3133 | // A service target only produces the first response. Fetch redirect handling |
| 3134 | // belongs to the caller, because the Location leaves through the caller's |
| 3135 | // ambient outbound policy rather than gaining the target service's authority. |
| 3136 | // Capture the replayable request state before dispatch: a same-isolate target |
| 3137 | // receives the Request itself and can consume or mutate it before it redirects. |
| 3138 | const __serviceRedirectState = (req) => ({ |
| 3139 | method: req.method, |
| 3140 | headers: req.headers.__celldHeaderList, |
| 3141 | body: req.body === null ? undefined |
| 3142 | : req._bodyBytes === null ? null : req._bodyBytes.slice(), |
| 3143 | signal: req._signalForSubrequests, |
| 3144 | }); |
| 3145 | const __finishServiceFetch = async (res, req, replay) => { |
| 3146 | const response = __wrapServiceResponse(res, req.url); |
| 3147 | if (!__SERVICE_REDIRECT_STATUSES.has(response.status)) return response; |
| 3148 | const location = response.headers.get("location"); |
| 3149 | if (location === null) return response; |
| 3150 | if (req.redirect === "manual") return response; |
| 3151 | |
| 3152 | // Nobody can consume the redirect response after this branch. Cancelling it |
| 3153 | // releases a cross-isolate body stream instead of waiting for its idle TTL. |
| 3154 | if (response.body !== null) { |
| 3155 | try { await response.body.cancel(); } catch { /* the redirect still wins */ } |
| 3156 | } |
| 3157 | if (req.redirect === "error") |
| 3158 | throw new TypeError("A redirect was returned for a request with redirect mode error."); |
| 3159 | |
| 3160 | const url = new URL(location, req.url).href; |
| 3161 | let method = replay.method; |
| 3162 | let body = replay.body; |
| 3163 | const headers = new Headers(replay.headers); |
| 3164 | if ((response.status === 301 || response.status === 302) && method === "POST" || |
| 3165 | response.status === 303 && method !== "GET" && method !== "HEAD") { |
| 3166 | method = "GET"; |
| 3167 | body = undefined; |
| 3168 | for (const name of __REQUEST_BODY_HEADERS) headers.delete(name); |
| 3169 | } else if (body === null) { |
| 3170 | // A transferred or live JavaScript stream has no replay copy. Fetch treats |
| 3171 | // the redirect as a network error instead of sending an empty replacement. |
| 3172 | throw new TypeError("Cannot follow a redirect with a non-replayable request body."); |
| 3173 | } |
| 3174 | // The ambient fetch starts a new native request, so its HTTP client cannot |
| 3175 | // know that these credentials came from another origin and remove them. Do |
| 3176 | // that at the service-to-network boundary before they can leak to Location. |
| 3177 | if (new URL(req.url).origin !== new URL(url).origin) { |
| 3178 | for (const name of __CROSS_ORIGIN_SENSITIVE_HEADERS) headers.delete(name); |
| 3179 | } |
| 3180 | const init = { method, headers, redirect: "follow" }; |
| 3181 | if (body !== undefined) init.body = body; |
| 3182 | if (replay.signal !== null) init.signal = replay.signal; |
| 3183 | const followed = await globalThis.fetch(url, init); |
| 3184 | followed.redirected = true; |
| 3185 | if (followed.url === "") followed.url = url; |
| 3186 | return followed; |
| 3187 | }; |
| 3188 | // `[[services]]` binding: a Fetcher pointed at another Worker in this |
| 3189 | // process. No identity to resolve, so it goes straight to __svc_call. |
| 3190 | // Worker Loader (Code Mode): spawn a fresh isolate from supplied code and |
| 3191 | // invoke its default or named entrypoint through the cross-isolate request and |
| 3192 | // RPC paths. |
| 3193 | // A Fetcher can cross into a loaded isolate only as this host-minted route. |
| 3194 | // Reading properties from a Proxy is not a trustworthy brand check, so the |
| 3195 | // metadata lives in a side table that application objects cannot forge. |
| 3196 | const __outboundMeta = new WeakMap(); |
| 3197 | const __loaderServiceMarker = "__celld$loaderSvc"; |
| 3198 | __celld.__makeLoader = () => { |
| 3199 | // A name weakly caches a shared load; `load()` is anonymous. Keep the load |
| 3200 | // promise itself on every derived capability, including a running facet, |
| 3201 | // so collection cannot evict a Worker while that capability still uses it. |
| 3202 | const byName = new Map(); |
| 3203 | const loaderOptions = (method, options, supportsLimits) => { |
| 3204 | if (options === null || options === undefined) return undefined; |
| 3205 | if (typeof options !== "object") |
| 3206 | throw new TypeError(method + "() options must be an object."); |
| 3207 | const extra = Object.keys(options).filter( |
| 3208 | (key) => key !== "props" && !(supportsLimits && key === "limits")); |
| 3209 | if (extra.length !== 0) |
| 3210 | throw new TypeError( |
| 3211 | method + '() does not support the option "' + extra.join('", "') + |
| 3212 | '".'); |
| 3213 | return options; |
| 3214 | }; |
| 3215 | // `props` cross to the loaded isolate by structured clone, on the same |
| 3216 | // transport that already carries the call's arguments (`__rpcOut` below). |
| 3217 | // JSON is the obvious alternative and it is wrong: JSON.stringify turns a |
| 3218 | // Map, a Set, a Date, a typed array, and a RegExp into a plain object or a |
| 3219 | // string and reports no error, so the callee reads a mangled value that the |
| 3220 | // same call's arguments would have carried intact. Encoding here, once per |
| 3221 | // loader API call, also rejects an unclonable value at that call rather than |
| 3222 | // at the first operation. |
| 3223 | const loaderPropsSc = (method, options) => { |
| 3224 | const props = loaderOptions(method, options, false)?.props; |
| 3225 | if (props === undefined) return undefined; |
| 3226 | // `lift` false: the props cross an isolate boundary, so a stub inside them |
| 3227 | // is a DataCloneError, exactly as a stub inside an argument of the same |
| 3228 | // call is. |
| 3229 | return __rpcOut(props, false); |
| 3230 | }; |
| 3231 | const loaderEntrypointOptions = (options) => { |
| 3232 | options = loaderOptions("getEntrypoint", options, true); |
| 3233 | const props = options?.props; |
| 3234 | return { |
| 3235 | propsSc: props === undefined ? undefined : __rpcOut(props, false), |
| 3236 | limitsJson: JSON.stringify(options?.limits ?? null), |
| 3237 | }; |
| 3238 | }; |
| 3239 | const makeEntrypoint = (loadPromise, entrypoint, propsSc, limitsJson) => { |
| 3240 | const target = { |
| 3241 | async fetch(input, init) { |
| 3242 | const { id, tails } = await loadPromise; |
| 3243 | const req = new Request(input, init); |
| 3244 | // The caller's signal, never the incoming request's own, as for a |
| 3245 | // service binding. |
| 3246 | const signal = req._signalForSubrequests; |
| 3247 | if (signal?.aborted) throw signal.reason; |
| 3248 | // The verbatim header list; see the note on the outbound `fetch`. |
| 3249 | // The loaded worker rebuilds a `Headers` from these pairs, so a |
| 3250 | // repeat and its casing survive the isolate boundary. |
| 3251 | const headers = JSON.stringify(req.headers.__celldHeaderList); |
| 3252 | const { body, streamId } = await __subrequestBody(req); |
| 3253 | const loaded = __loader_fetch( |
| 3254 | id, req.url, req.method, body, headers, streamId, entrypoint, |
| 3255 | propsSc === undefined ? new Uint8Array() : propsSc, |
| 3256 | limitsJson, tails.length !== 0, signal != null); |
| 3257 | const dispatch = tails.length === 0 ? loaded : loaded[0]; |
| 3258 | const response = signal |
| 3259 | ? __awaitCancellableDoCall(dispatch, signal) |
| 3260 | : dispatch; |
| 3261 | if (tails.length !== 0) { |
| 3262 | const delivery = loaded[1] |
| 3263 | .then((report) => JSON.parse(report)) |
| 3264 | .then((events) => Promise.allSettled( |
| 3265 | tails.map((tail) => tail.tail(events)))) |
| 3266 | .then((results) => { |
| 3267 | for (const result of results) { |
| 3268 | if (result.status === "rejected") |
| 3269 | console.error("Tail Worker failed:", result.reason); |
| 3270 | } |
| 3271 | }) |
| 3272 | .catch((error) => console.error("Tail delivery failed:", error)); |
| 3273 | // The loaded fetch answers before its report because the child can |
| 3274 | // still have waitUntil work. Keep this chain on the loader event so |
| 3275 | // its IoContext cannot retire and abort the report operation. |
| 3276 | __registerWaitUntil(delivery); |
| 3277 | } |
| 3278 | const r = JSON.parse(await response); |
| 3279 | const responseBody = r.streamId !== undefined |
| 3280 | ? new CelldHttpBodyStream(r.streamId) |
| 3281 | : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); |
| 3282 | return __wrapServiceResponse( |
| 3283 | new Response(responseBody, { status: r.status, headers: r.headers }), |
| 3284 | req.url); |
| 3285 | }, |
| 3286 | }; |
| 3287 | // Both the default and named entrypoints expose RPC: property access is a |
| 3288 | // callable pipeline node dispatched via __loader_rpc to that entrypoint in |
| 3289 | // the loaded worker (default -> the "default" export, which |
| 3290 | // register_entrypoints registers like any other). fetch stays on the |
| 3291 | // target. Only single-method calls are supported for now. |
| 3292 | const session = { |
| 3293 | get: () => Promise.reject(new Error( |
| 3294 | "Awaitable properties on loaded workers are not supported yet.")), |
| 3295 | call: (path, args) => (async () => { |
| 3296 | if (path.length !== 1) |
| 3297 | throw new Error( |
| 3298 | "Pipelined property paths on loaded workers are not supported " + |
| 3299 | "yet."); |
| 3300 | const { id } = await loadPromise; |
| 3301 | return __rpcDes( |
| 3302 | await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false), |
| 3303 | propsSc, limitsJson)); |
| 3304 | })(), |
| 3305 | }; |
| 3306 | return new Proxy(target, { |
| 3307 | get: (base, prop) => { |
| 3308 | if (prop === "then") return undefined; |
| 3309 | if (Reflect.has(base, prop)) return Reflect.get(base, prop); |
| 3310 | if (typeof prop !== "string") return undefined; |
| 3311 | return __makeNode(session, [prop], null); |
| 3312 | }, |
| 3313 | }); |
| 3314 | }; |
| 3315 | // The load promise is the shared lifetime, retained by stubs, entrypoints, |
| 3316 | // classes, and running facets. Finalizing only the original stub can evict |
| 3317 | // a Worker that one of its derived capabilities still uses. |
| 3318 | const finalizer = new FinalizationRegistry(({ id, name, ref }) => { |
| 3319 | if (ref !== undefined && byName.get(name) === ref) byName.delete(name); |
| 3320 | if (id !== undefined) __loader_drop(id); |
| 3321 | }); |
| 3322 | const track = (loadPromise, name, ref) => { |
| 3323 | // Register before settlement, so failed loads also release their names. |
| 3324 | const held = { id: undefined, name, ref }; |
| 3325 | finalizer.register(loadPromise, held, loadPromise); |
| 3326 | loadPromise.then(({ id }) => { held.id = id; }, () => {}); |
| 3327 | return loadPromise; |
| 3328 | }; |
| 3329 | const makeStub = (loadPromise, name, ref) => { |
| 3330 | const drop = () => { |
| 3331 | if (ref !== undefined && byName.get(name) === ref) byName.delete(name); |
| 3332 | finalizer.unregister(loadPromise); |
| 3333 | loadPromise.then(({ id }) => __loader_drop(id), () => {}); |
| 3334 | }; |
| 3335 | const stub = { |
| 3336 | getEntrypoint(name = null, options = {}) { |
| 3337 | const { propsSc, limitsJson } = loaderEntrypointOptions(options); |
| 3338 | return makeEntrypoint( |
| 3339 | loadPromise, name === null ? "default" : String(name), |
| 3340 | propsSc, limitsJson); |
| 3341 | }, |
| 3342 | getDurableObjectClass(name = null, options = {}) { |
| 3343 | return __makeDurableObjectClass( |
| 3344 | loadPromise, name, loaderPropsSc("getDurableObjectClass", options)); |
| 3345 | }, |
| 3346 | dispose: drop, |
| 3347 | }; |
| 3348 | if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; |
| 3349 | return stub; |
| 3350 | }; |
| 3351 | // JSON.stringify silently drops binary values, so each non-string module -- |
| 3352 | // an explicit module shape such as `{ wasm: bytes }` -- is normalized |
| 3353 | // first. JavaScript modules become plain strings, and wasm moves into a |
| 3354 | // side-band `[name, Uint8Array]` list so multi-MB blobs never take a |
| 3355 | // base64/JSON round-trip. |
| 3356 | const toBytes = (v) => v instanceof ArrayBuffer ? new Uint8Array(v) |
| 3357 | : ArrayBuffer.isView(v) |
| 3358 | ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : null; |
| 3359 | const moduleKinds = [ |
| 3360 | "js", "cjs", "py", "text", "data", "json", "wasm", |
| 3361 | ]; |
| 3362 | const encodeLoaderEnv = (value) => { |
| 3363 | if (value === undefined || value === null) |
| 3364 | return { env: undefined, envRoutes: [] }; |
| 3365 | const envRoutes = []; |
| 3366 | const seen = new Map(); |
| 3367 | const project = (v) => { |
| 3368 | if (v === null || |
| 3369 | (typeof v !== "object" && typeof v !== "function")) return v; |
| 3370 | const cached = seen.get(v); |
| 3371 | if (cached !== undefined) return cached; |
| 3372 | const route = __outboundMeta.get(v); |
| 3373 | if (route !== undefined) { |
| 3374 | const marker = { [__loaderServiceMarker]: envRoutes.length }; |
| 3375 | seen.set(v, marker); |
| 3376 | envRoutes.push([ |
| 3377 | route.script, |
| 3378 | route.entrypoint, |
| 3379 | route.propsSc ?? (route.props === undefined |
| 3380 | ? new Uint8Array() : __rpcOut(route.props, false)), |
| 3381 | ]); |
| 3382 | return marker; |
| 3383 | } |
| 3384 | if (Object.prototype.hasOwnProperty.call(v, __loaderServiceMarker)) |
| 3385 | throw new DOMException( |
| 3386 | `Worker Loader env contains the reserved key ` + |
| 3387 | `${JSON.stringify(__loaderServiceMarker)}.`, |
| 3388 | "DataCloneError"); |
| 3389 | if (typeof v === "function" || v instanceof __cf.RpcTarget || |
| 3390 | __stubMeta.has(v) || __doStubMeta.has(v)) |
| 3391 | throw new DOMException( |
| 3392 | "Worker Loader env supports only Service Binding capabilities.", |
| 3393 | "DataCloneError"); |
| 3394 | if (v instanceof Map) { |
| 3395 | const out = new Map(); |
| 3396 | seen.set(v, out); |
| 3397 | for (const [key, item] of v) out.set(project(key), project(item)); |
| 3398 | return out; |
| 3399 | } |
| 3400 | if (v instanceof Set) { |
| 3401 | const out = new Set(); |
| 3402 | seen.set(v, out); |
| 3403 | for (const item of v) out.add(project(item)); |
| 3404 | return out; |
| 3405 | } |
| 3406 | const proto = Object.getPrototypeOf(v); |
| 3407 | if (!Array.isArray(v) && proto !== Object.prototype && proto !== null) |
| 3408 | return v; |
| 3409 | const out = Array.isArray(v) ? [] : {}; |
| 3410 | seen.set(v, out); |
| 3411 | for (const key of Object.keys(v)) out[key] = project(v[key]); |
| 3412 | return out; |
| 3413 | }; |
| 3414 | return { env: __sc_encode(project(value)), envRoutes }; |
| 3415 | }; |
| 3416 | const encodeModules = (c) => { |
| 3417 | if (c === null || typeof c !== "object" || c.modules === null |
| 3418 | || typeof c.modules !== "object") |
| 3419 | return { config: c, wasm: [], outbound: undefined, tails: [] }; |
| 3420 | // workerd requires the date, and names the missing value as it does. |
| 3421 | if (typeof c.compatibilityDate !== "string") |
| 3422 | throw new Error(`Invalid compatibility date: ${c.compatibilityDate}`); |
| 3423 | const modules = {}; |
| 3424 | const wasm = []; |
| 3425 | for (const [name, value] of Object.entries(c.modules)) { |
| 3426 | const wrapped = value !== null && typeof value === "object" ? value : {}; |
| 3427 | const explicitKinds = moduleKinds.filter((kind) => |
| 3428 | Object.prototype.hasOwnProperty.call(wrapped, kind) |
| 3429 | ); |
| 3430 | // An object is a module shape with one kind, as in workerd; bare bytes |
| 3431 | // are not a module. |
| 3432 | if (value !== null && typeof value === "object" && |
| 3433 | !(value instanceof WebAssembly.Module) && explicitKinds.length !== 1) |
| 3434 | throw new TypeError( |
| 3435 | "Each module must contain exactly one of 'js', 'cjs', 'text', " + |
| 3436 | `'data', 'json', 'py', or 'wasm'. Module '${name}' contained ` + |
| 3437 | `${explicitKinds.length} properties.`); |
| 3438 | const kind = explicitKinds[0]; |
| 3439 | if (kind === "js") { |
| 3440 | const source = wrapped[kind]; |
| 3441 | if (typeof source !== "string") |
| 3442 | throw new TypeError( |
| 3443 | `Worker Loader module ${JSON.stringify(name)} field ` + |
| 3444 | `${JSON.stringify(kind)} must be a string.`); |
| 3445 | modules[name] = source; |
| 3446 | continue; |
| 3447 | } |
| 3448 | const bytes = kind === "wasm" ? toBytes(wrapped.wasm) : null; |
| 3449 | if (bytes !== null) wasm.push([name, bytes]); |
| 3450 | else modules[name] = value; |
| 3451 | } |
| 3452 | let outbound; |
| 3453 | let outboundProps; |
| 3454 | if (Object.prototype.hasOwnProperty.call(c, "globalOutbound")) { |
| 3455 | if (c.globalOutbound === undefined) { |
| 3456 | outbound = undefined; |
| 3457 | } else if (c.globalOutbound === null) { |
| 3458 | outbound = null; |
| 3459 | } else { |
| 3460 | const meta = __outboundMeta.get(c.globalOutbound); |
| 3461 | if (meta === undefined) |
| 3462 | throw new TypeError("globalOutbound must be a Fetcher or null."); |
| 3463 | // JSON carries only the host-minted route. Props use V8 structured |
| 3464 | // clone bytes, so their types and the cross-isolate clone boundary |
| 3465 | // match the other parameterized ctx.exports transports. |
| 3466 | outboundProps = meta.propsSc ?? (meta.props === undefined |
| 3467 | ? new Uint8Array() |
| 3468 | : __rpcOut(meta.props, false)); |
| 3469 | outbound = JSON.stringify({ |
| 3470 | script: meta.script, |
| 3471 | entrypoint: meta.entrypoint, |
| 3472 | }); |
| 3473 | } |
| 3474 | } |
| 3475 | const { env, envRoutes } = encodeLoaderEnv(c.env); |
| 3476 | let tails = []; |
| 3477 | if (Object.prototype.hasOwnProperty.call(c, "tails")) { |
| 3478 | if (!Array.isArray(c.tails)) |
| 3479 | throw new TypeError("tails must be an array of Fetchers."); |
| 3480 | tails = c.tails.map((tail) => { |
| 3481 | if (!__outboundMeta.has(tail)) |
| 3482 | throw new TypeError("tails must be an array of Fetchers."); |
| 3483 | return tail; |
| 3484 | }); |
| 3485 | } |
| 3486 | const { |
| 3487 | globalOutbound: _globalOutbound, |
| 3488 | env: _env, |
| 3489 | tails: _tails, |
| 3490 | ...rest |
| 3491 | } = c; |
| 3492 | return { |
| 3493 | config: { ...rest, modules }, wasm, outbound, outboundProps, |
| 3494 | env, envRoutes, tails, |
| 3495 | }; |
| 3496 | }; |
| 3497 | // getCode is deferred into a microtask so a throw (or async getCode) |
| 3498 | // surfaces as a rejection when the worker is first used, not at get()/load(). |
| 3499 | const loadFrom = (getCode) => |
| 3500 | Promise.resolve().then(getCode) |
| 3501 | .then((c) => { |
| 3502 | const { |
| 3503 | config, wasm, outbound, outboundProps, env, envRoutes, tails, |
| 3504 | } = encodeModules(c); |
| 3505 | const id = __loader_load( |
| 3506 | JSON.stringify(config), wasm, outbound, outboundProps, env, |
| 3507 | envRoutes, tails.length !== 0); |
| 3508 | return { id, tails }; |
| 3509 | }); |
| 3510 | return { |
| 3511 | load(code) { return makeStub(track(loadFrom(() => code))); }, |
| 3512 | get(name, getCode) { |
| 3513 | let ref = byName.get(name); |
| 3514 | let loadPromise = ref?.deref(); |
| 3515 | if (loadPromise === undefined) { |
| 3516 | loadPromise = loadFrom(getCode); |
| 3517 | ref = new WeakRef(loadPromise); |
| 3518 | byName.set(name, ref); |
| 3519 | track(loadPromise, name, ref); |
| 3520 | } |
| 3521 | return makeStub(loadPromise, name, ref); |
| 3522 | }, |
| 3523 | }; |
| 3524 | }; |
| 3525 | |
| 3526 | const __makeServiceBinding = __celld.__makeServiceBinding = |
| 3527 | (script, entrypoint = null, propsSc = undefined) => { |
| 3528 | const target = { |
| 3529 | async fetch(input, init) { |
| 3530 | const req = new Request(input, init); |
| 3531 | const signal = req._signalForSubrequests; |
| 3532 | if (signal?.aborted) throw signal.reason; |
| 3533 | // A stream body advertises its length the way the HTTP layer |
| 3534 | // would: known length -> Content-Length, unknown -> chunked. |
| 3535 | if (req._bodyBytes === null && |
| 3536 | !req.headers.has("content-length") && |
| 3537 | !req.headers.has("transfer-encoding")) { |
| 3538 | const length = req.body._expectedLength; |
| 3539 | if (length === undefined) |
| 3540 | req.headers.set("transfer-encoding", "chunked"); |
| 3541 | else req.headers.set("content-length", String(length)); |
| 3542 | } |
| 3543 | const redirectState = __serviceRedirectState(req); |
| 3544 | // Fast path: the target is this same script, so its handler lives in |
| 3545 | // this isolate. Skip the op + pool-thread hop and call it directly, |
| 3546 | // inside its own event so the target's waitUntil does not attach to |
| 3547 | // the caller's. Cross-script targets still need their own isolate. |
| 3548 | if (script === __cell.script && entrypoint !== null && |
| 3549 | propsSc === undefined) { |
| 3550 | // Mirror __dispatchTo: the target sees a fresh incoming signal, |
| 3551 | // aborted with "The client has disconnected" when the caller |
| 3552 | // abandons the call or cancels the response body; the caller's |
| 3553 | // own signal races the dispatch so an abandoned call rejects |
| 3554 | // immediately instead of pinning on a hung target. |
| 3555 | const requestController = new AbortController(); |
| 3556 | const dispatch = __dispatchEntrypointFetch( |
| 3557 | entrypoint, |
| 3558 | new Request(req, { |
| 3559 | signal: requestController.signal, |
| 3560 | __celldIncomingSignal: true, |
| 3561 | })); |
| 3562 | const response = signal |
| 3563 | ? await __raceCallerAbort(dispatch, signal, () => |
| 3564 | requestController.abort( |
| 3565 | new Error("The client has disconnected"))) |
| 3566 | : await dispatch; |
| 3567 | __attachResponseRequestCancellation( |
| 3568 | response, requestController, true); |
| 3569 | return __finishServiceFetch(response, req, redirectState); |
| 3570 | } |
| 3571 | if (script === __cell.script && entrypoint === null && |
| 3572 | typeof __cell.selfFetch === "function") { |
| 3573 | if (__cell.svcDepth >= 8) |
| 3574 | throw new Error( |
| 3575 | "Service binding recursion limit exceeded (8)"); |
| 3576 | __cell.svcDepth = (__cell.svcDepth || 0) + 1; |
| 3577 | const ctx = __beginEvent(); |
| 3578 | try { |
| 3579 | return __finishServiceFetch( |
| 3580 | await __ctxRun(undefined, |
| 3581 | () => __cell.selfFetch(req, __cell.env, ctx)), |
| 3582 | req, redirectState); |
| 3583 | } finally { |
| 3584 | __cell.svcDepth--; |
| 3585 | __endEvent(); |
| 3586 | } |
| 3587 | } |
| 3588 | // The verbatim header list; see the note on the outbound `fetch`. The |
| 3589 | // target isolate rebuilds a `Headers` from these pairs, so a repeat and |
| 3590 | // its casing survive the crossing. |
| 3591 | const headers = JSON.stringify(req.headers.__celldHeaderList); |
| 3592 | // Cross-isolate calls carry exact bytes. A host-backed stream transfers |
| 3593 | // its one source to the target, and another stream uses the byte fallback. |
| 3594 | const { body, streamId } = await __subrequestBody(req); |
| 3595 | const r = JSON.parse(await (signal |
| 3596 | ? __awaitCancellableDoCall( |
| 3597 | __svc_call_cancellable( |
| 3598 | script, req.url, req.method, body, headers, streamId, entrypoint, |
| 3599 | propsSc), |
| 3600 | signal) |
| 3601 | : __svc_call( |
| 3602 | script, req.url, req.method, body, headers, streamId, entrypoint, |
| 3603 | propsSc))); |
| 3604 | const responseBody = r.streamId !== undefined |
| 3605 | ? new CelldHttpBodyStream(r.streamId) |
| 3606 | : r.body !== undefined |
| 3607 | ? r.body |
| 3608 | : Uint8Array.from(r.bodyBytes || []); |
| 3609 | return __finishServiceFetch( |
| 3610 | new Response(responseBody, { |
| 3611 | status: r.status, headers: r.headers, __wsTarget: r.wsTarget, |
| 3612 | }), |
| 3613 | req, redirectState); |
| 3614 | }, |
| 3615 | // Workerd's test-visible Fetcher.scheduled(): invoke the target's |
| 3616 | // scheduled handler and report the outcome. |
| 3617 | async scheduled(options = {}) { |
| 3618 | if (script !== __cell.script || entrypoint !== null || |
| 3619 | typeof __cell.selfScheduled !== "function") |
| 3620 | throw new Error( |
| 3621 | "scheduled() is only implemented for same-script service " + |
| 3622 | "bindings whose target has a scheduled handler"); |
| 3623 | let noRetry = false; |
| 3624 | const ctrl = { |
| 3625 | scheduledTime: options.scheduledTime === undefined |
| 3626 | ? Date.now() : Number(options.scheduledTime), |
| 3627 | cron: options.cron === undefined ? "" : String(options.cron), |
| 3628 | noRetry() { noRetry = true; }, |
| 3629 | }; |
| 3630 | const ctx = __beginEvent(); |
| 3631 | try { |
| 3632 | await __cell.selfScheduled(ctrl, __cell.env, ctx); |
| 3633 | return { outcome: "ok", noRetry }; |
| 3634 | } finally { |
| 3635 | const drain = __endEvent(); |
| 3636 | // scheduled() reports the event outcome, so it cannot return while the |
| 3637 | // work that defines that event is still pending. Fetch replies differ: |
| 3638 | // a streamed response can depend on waitUntil work and must return first. |
| 3639 | if (drain !== null) await drain; |
| 3640 | } |
| 3641 | }, |
| 3642 | }; |
| 3643 | // An omitted entrypoint selects the module's default export, which may be a |
| 3644 | // WorkerEntrypoint or an object handler. `entrypoint = "Name"` selects that |
| 3645 | // named class. Any property other than a reserved Fetcher method is an |
| 3646 | // awaitable/callable pipeline node: awaiting |
| 3647 | // resolves the property remotely (a property-GET wire op), calling |
| 3648 | // invokes it, and deeper access extends the path, resolved on the |
| 3649 | // receiver side in one op. Same-script dispatch stays in this |
| 3650 | // isolate, so stub-able values may cross. A property path rooted |
| 3651 | // directly at the binding is context-free (ctx null): awaiting it |
| 3652 | // starts a fresh session, as in Workerd. |
| 3653 | const rpcEntrypoint = entrypoint === null ? "default" : entrypoint; |
| 3654 | const session = __entrypointSession( |
| 3655 | rpcEntrypoint, script === __cell.script, script, undefined, propsSc); |
| 3656 | const binding = new Proxy(target, { |
| 3657 | getPrototypeOf: () => __cf.ServiceStub.prototype, |
| 3658 | get: (base, prop) => { |
| 3659 | if (prop === "then") return undefined; // a stub is not a thenable |
| 3660 | if (Reflect.has(base, prop)) return Reflect.get(base, prop); |
| 3661 | if (typeof prop !== "string") return undefined; |
| 3662 | // Workerd's test hook: the named method as a callable handle, |
| 3663 | // resolved -- and refused -- on the receiver side. |
| 3664 | if (prop === "getRpcMethodForTestOnly") |
| 3665 | return (name) => __makeNode(session, [String(name)], null); |
| 3666 | return __makeNode(session, [prop], null); |
| 3667 | }}); |
| 3668 | __outboundMeta.set(binding, { script, entrypoint, propsSc }); |
| 3669 | return binding; |
| 3670 | }; |
| 3671 | |
| 3672 | __celld.__installLoaderEnv = (bytes, routes) => { |
| 3673 | const env = __sc_decode(bytes); |
| 3674 | const seen = new Set(); |
| 3675 | const revive = (v) => { |
| 3676 | if (v === null || typeof v !== "object") return v; |
| 3677 | const routeIndex = Object.prototype.hasOwnProperty.call( |
| 3678 | v, __loaderServiceMarker) ? v[__loaderServiceMarker] : undefined; |
| 3679 | if (Number.isSafeInteger(routeIndex) && routeIndex >= 0) { |
| 3680 | // Rust supplies flat [script, entrypoint, props] triples, and the marker |
| 3681 | // stores the triple index rather than an offset into that array. |
| 3682 | const routeOffset = routeIndex * 3; |
| 3683 | if (!Number.isSafeInteger(routeOffset) || routeOffset + 2 >= routes.length) |
| 3684 | throw new DOMException( |
| 3685 | "Worker Loader env contains an invalid capability.", |
| 3686 | "DataCloneError"); |
| 3687 | return __makeServiceBinding( |
| 3688 | routes[routeOffset], routes[routeOffset + 1], routes[routeOffset + 2]); |
| 3689 | } |
| 3690 | if (seen.has(v)) return v; |
| 3691 | seen.add(v); |
| 3692 | if (v instanceof Map) { |
| 3693 | const entries = [...v]; |
| 3694 | v.clear(); |
| 3695 | for (const [key, item] of entries) v.set(revive(key), revive(item)); |
| 3696 | return v; |
| 3697 | } |
| 3698 | if (v instanceof Set) { |
| 3699 | const items = [...v]; |
| 3700 | v.clear(); |
| 3701 | for (const item of items) v.add(revive(item)); |
| 3702 | return v; |
| 3703 | } |
| 3704 | if (Array.isArray(v) || Object.getPrototypeOf(v) === Object.prototype || |
| 3705 | Object.getPrototypeOf(v) === null) |
| 3706 | for (const key of Object.keys(v)) v[key] = revive(v[key]); |
| 3707 | return v; |
| 3708 | }; |
| 3709 | Object.assign(__cell.env, revive(env)); |
| 3710 | }; |
| 3711 | // RPC marshalling: V8 structured clone (Workerd js-rpc semantics), so |
| 3712 | // undefined, Date, Map, Set, BigInt, typed arrays, and cycles survive. |
| 3713 | // A value V8 cannot clone throws DataCloneError, as in Workerd. |
| 3714 | // |
| 3715 | // The envelope's first byte tags the payload. 0xff (the clone version |
| 3716 | // header) = plain clone, decoded as-is. 0x01 = clone of a lifted tree in |
| 3717 | // which RpcTarget instances, functions, and Durable Object stubs were |
| 3718 | // replaced by stub markers; the lift runs only after a plain clone |
| 3719 | // already threw. A projection walk happens first because V8 silently erases |
| 3720 | // custom and null prototypes. 0x02 = a lifted tree carrying only by-value |
| 3721 | // host types (Blob/File, Headers, |
| 3722 | // Request/Response) and no capabilities -- decoded like 0x01, but a |
| 3723 | // reply so tagged does not root its callee context. 0x00 = clone of |
| 3724 | // [error, ownProps] -- a callee exception crossing as a real Error. |
| 3725 | const __dataCloneError = (error) => new DOMException( |
| 3726 | String(error && error.message || error), "DataCloneError"); |
| 3727 | const __rpcUnsupportedType = (value) => new DOMException( |
| 3728 | 'Could not serialize object of type "' + |
| 3729 | (__util_constructor_name(value) || "Object") + |
| 3730 | '". This type does not support serialization.', |
| 3731 | "DataCloneError"); |
| 3732 | // V8 clones a user-class instance and a null-prototype object as plain data, |
| 3733 | // but Workerd refuses both over RPC. Project the value graph before V8 can |
| 3734 | // erase that distinction. The projection also snapshots enumerable getters, |
| 3735 | // so validation and serialization cannot invoke one getter twice. Native |
| 3736 | // clone types and RPC host types keep their own serializers. |
| 3737 | const __rpcProject = (value) => { |
| 3738 | const seen = new Map(); |
| 3739 | const originals = new WeakMap(); |
| 3740 | const set = (target, key, value) => Object.defineProperty(target, key, { |
| 3741 | value, enumerable: true, configurable: true, writable: true, |
| 3742 | }); |
| 3743 | const project = (v) => { |
| 3744 | if (v === null || (typeof v !== "object" && typeof v !== "function")) |
| 3745 | return v; |
| 3746 | const cached = seen.get(v); |
| 3747 | if (cached !== undefined) return cached; |
| 3748 | if (typeof v === "function" || v instanceof __cf.RpcTarget || |
| 3749 | __stubMeta.has(v) || __svcMeta.has(v) || __doStubMeta.has(v) || |
| 3750 | v instanceof Headers || v instanceof Blob || v instanceof Request || |
| 3751 | v instanceof Response || v instanceof ReadableStream || |
| 3752 | v instanceof WritableStream || v instanceof AbortSignal || |
| 3753 | v instanceof Date || v instanceof RegExp || v instanceof Error || |
| 3754 | v instanceof ArrayBuffer || ArrayBuffer.isView(v) || |
| 3755 | (typeof SharedArrayBuffer !== "undefined" && |
| 3756 | v instanceof SharedArrayBuffer) || |
| 3757 | (typeof CryptoKey !== "undefined" && v instanceof CryptoKey) || |
| 3758 | (typeof WebAssembly !== "undefined" && |
| 3759 | v instanceof WebAssembly.Module) || |
| 3760 | __util_proxy_details(v) !== undefined) return v; |
| 3761 | if (v instanceof Map) { |
| 3762 | const out = new Map(); |
| 3763 | seen.set(v, out); |
| 3764 | for (const [key, entry] of v) { |
| 3765 | out.set(project(key), project(entry)); |
| 3766 | } |
| 3767 | return out; |
| 3768 | } |
| 3769 | if (v instanceof Set) { |
| 3770 | const out = new Set(); |
| 3771 | seen.set(v, out); |
| 3772 | for (const entry of v) out.add(project(entry)); |
| 3773 | return out; |
| 3774 | } |
| 3775 | if (Array.isArray(v)) { |
| 3776 | const out = new Array(v.length); |
| 3777 | seen.set(v, out); |
| 3778 | originals.set(out, v); |
| 3779 | for (const key of Object.keys(v)) set(out, key, project(v[key])); |
| 3780 | return out; |
| 3781 | } |
| 3782 | if (Object.getPrototypeOf(v) !== Object.prototype) |
| 3783 | throw __rpcUnsupportedType(v); |
| 3784 | const out = {}; |
| 3785 | seen.set(v, out); |
| 3786 | originals.set(out, v); |
| 3787 | for (const key of Object.keys(v)) set(out, key, project(v[key])); |
| 3788 | return out; |
| 3789 | }; |
| 3790 | return { tree: project(value), originals }; |
| 3791 | }; |
| 3792 | const __tagged = (tag, sc) => { |
| 3793 | const out = new Uint8Array(sc.length + 1); |
| 3794 | out[0] = tag; |
| 3795 | out.set(sc, 1); |
| 3796 | return out; |
| 3797 | }; |
| 3798 | // ---- request-context confinement ------------------------------- |
| 3799 | // Workerd ties I/O objects to the IoContext of the event that made |
| 3800 | // them. Cells' equivalent: each dispatched event enters an |
| 3801 | // async-context frame (the same CPED the ALS rides, so it survives |
| 3802 | // awaits) carrying a context id. Stubs remember their owning |
| 3803 | // context and refuse to serialize elsewhere; pipeline nodes refuse |
| 3804 | // foreign awaits and calls -- each with Workerd's exact error. |
| 3805 | let __nextCtxId = 1; |
| 3806 | const __ctxKey = Symbol("celld.ctx"); |
| 3807 | const __ctxNow = () => { |
| 3808 | const frame = __als_get(); |
| 3809 | return frame === undefined ? undefined : frame.get(__ctxKey); |
| 3810 | }; |
| 3811 | // Run `fn` under context `id` (undefined = a fresh one). An async |
| 3812 | // fn started inside keeps the frame across its awaits. The prior |
| 3813 | // frame is cloned so user AsyncLocalStorage stores still flow into |
| 3814 | // same-isolate callees, as they did before contexts existed. |
| 3815 | const __ctxRun = (id, fn) => { |
| 3816 | const prior = __als_get(); |
| 3817 | const frame = new Map(prior); |
| 3818 | frame.set(__ctxKey, id ?? __nextCtxId++); |
| 3819 | __als_set(frame); |
| 3820 | try { |
| 3821 | return fn(); |
| 3822 | } finally { |
| 3823 | __als_set(prior); |
| 3824 | } |
| 3825 | }; |
| 3826 | const __ctxError = (kind) => new Error( |
| 3827 | "Cannot perform I/O on behalf of a different request. I/O " + |
| 3828 | "objects (such as streams, request/response bodies, and others) " + |
| 3829 | "created in the context of one request handler cannot be " + |
| 3830 | "accessed from a different request's handler. This is a " + |
| 3831 | "limitation of Cloudflare Workers which allows us to improve " + |
| 3832 | "overall performance. (I/O type: " + kind + ")"); |
| 3833 | // ---- abortable request contexts -------------------------------- |
| 3834 | // Workerd's ctx.abort(reason) on an entrypoint aborts the request's |
| 3835 | // IoContext: the in-flight call rejects with the reason, and stubs |
| 3836 | // the context holds are disposed (their disposal callbacks fire). |
| 3837 | // State is allocated only when a context first holds a stub handle |
| 3838 | // or aborts, so plain-data dispatch pays nothing; call paths gate |
| 3839 | // every abort lookup on `__abortedCtxs.size` (one field read). |
| 3840 | // Aborted ids stay recorded: a stub rooted in a dead context must |
| 3841 | // keep rejecting with the reason. |
| 3842 | const __abortedCtxs = new Map(); |
| 3843 | // An actor-flavored abort reason: in-flight ops reject with the |
| 3844 | // wrapped reason, later ops with Workerd's post-abort message |
| 3845 | // (upstream TODO(bug): should propagate the reason, but doesn't). |
| 3846 | class __ActorAbort { constructor(reason) { this.reason = reason; } } |
| 3847 | const __postAbortError = (aborted) => aborted instanceof __ActorAbort |
| 3848 | ? new Error("The execution context which hosts this callback " + |
| 3849 | "is no longer running.") |
| 3850 | : aborted; |
| 3851 | // ctx id -> Set of live stub handles (metas) the context holds. |
| 3852 | const __ctxStubs = new Map(); |
| 3853 | // ctx id -> Set of reject callbacks for stub ops in flight against |
| 3854 | // that context. A hung callee never settles, so a context abort |
| 3855 | // must reject its pending callers directly. |
| 3856 | const __ctxPendingOps = new Map(); |
| 3857 | const __opTrack = (ctx, reject) => { |
| 3858 | let set = __ctxPendingOps.get(ctx); |
| 3859 | if (set === undefined) __ctxPendingOps.set(ctx, set = new Set()); |
| 3860 | set.add(reject); |
| 3861 | return () => { |
| 3862 | set.delete(reject); |
| 3863 | if (set.size === 0) __ctxPendingOps.delete(ctx); |
| 3864 | }; |
| 3865 | }; |
| 3866 | const __ctxRegister = (meta) => { |
| 3867 | if (meta.ctx === undefined) return; |
| 3868 | let set = __ctxStubs.get(meta.ctx); |
| 3869 | if (set === undefined) __ctxStubs.set(meta.ctx, set = new Set()); |
| 3870 | set.add(meta); |
| 3871 | }; |
| 3872 | const __ctxUnregister = (meta) => { |
| 3873 | const set = __ctxStubs.get(meta.ctx); |
| 3874 | if (set === undefined) return; |
| 3875 | set.delete(meta); |
| 3876 | if (set.size === 0) __ctxStubs.delete(meta.ctx); |
| 3877 | }; |
| 3878 | // Tear down a context: dispose every handle it still holds, so a |
| 3879 | // dup() leaked into it reaches the sender's disposal callback. |
| 3880 | const __ctxEnd = (id) => { |
| 3881 | const set = __ctxStubs.get(id); |
| 3882 | if (set === undefined) return; |
| 3883 | __ctxStubs.delete(id); |
| 3884 | for (const meta of set) __disposeStub(meta); |
| 3885 | }; |
| 3886 | const __ctxAbort = (id, reason) => { |
| 3887 | if (id === undefined || __abortedCtxs.has(id)) return; |
| 3888 | const stored = reason === undefined |
| 3889 | ? new Error("The execution context has been aborted.") |
| 3890 | : reason; |
| 3891 | __abortedCtxs.set(id, stored); |
| 3892 | __ctxEnd(id); |
| 3893 | const pending = __ctxPendingOps.get(id); |
| 3894 | if (pending === undefined) return; |
| 3895 | __ctxPendingOps.delete(id); |
| 3896 | const live = |
| 3897 | stored instanceof __ActorAbort ? stored.reason : stored; |
| 3898 | for (const reject of pending) reject(live); |
| 3899 | }; |
| 3900 | // The entrypoint ctx.abort. Instances are cached across calls, so |
| 3901 | // the construction-time ctx cannot pin a request id (Workerd |
| 3902 | // constructs per request); the current frame's id at abort() time |
| 3903 | // is the request being served, which matches Workerd observably. |
| 3904 | const __ctxAbortCurrent = |
| 3905 | (reason) => __ctxAbort(__ctxNow(), reason); |
| 3906 | // ---- same-process RPC stubs ------------------------------------ |
| 3907 | // A stub entry owns a local target; `refs` counts live handles |
| 3908 | // across dup()s. When the last handle is disposed the target's own |
| 3909 | // Symbol.dispose runs (async, matching Workerd's disposal callback). |
| 3910 | // Stubs cross same-isolate transports only (same-script entrypoint |
| 3911 | // RPC and same-process routed dispatch); a marker revived elsewhere fails |
| 3912 | // loudly on use instead of aliasing an unrelated local entry. |
| 3913 | // `ctx` records the owning request context: the entry's for |
| 3914 | // running its target, the handle's for the serialize-elsewhere |
| 3915 | // check. |
| 3916 | const __stubEntries = new Map(); |
| 3917 | const __stubMeta = new WeakMap(); |
| 3918 | // Keep the Durable Object brand outside the user-visible object. Reading a |
| 3919 | // string property here would invoke an inherited getter before validation can |
| 3920 | // reject its unsupported prototype. |
| 3921 | const __doStubMeta = new WeakMap(); |
| 3922 | let __nextStubId = 1; |
| 3923 | const __stubIsolate = Math.random().toString(36).slice(2); |
| 3924 | const __newEntry = (target) => { |
| 3925 | // `scope` records the actor event that minted the entry (top of |
| 3926 | // the event stack at lift time), so an actor breakage can find |
| 3927 | // and abort the contexts hosting its exported stubs, and an op on |
| 3928 | // the stub can queue on that cell's input gate. `section` is the |
| 3929 | // critical section running at lift time, if any -- an op on this |
| 3930 | // stub re-enters it rather than queueing behind it. |
| 3931 | const scope = __currentActorScope() || undefined; |
| 3932 | const entry = { |
| 3933 | id: __nextStubId++, target, refs: 1, ctx: __ctxNow(), scope, |
| 3934 | section: __cellBlocks.get(scope)?.holder ?? null, |
| 3935 | }; |
| 3936 | __stubEntries.set(entry.id, entry); |
| 3937 | return entry; |
| 3938 | }; |
| 3939 | // Actors broken in JS: scope -> reason. Workerd's DO ctx.abort |
| 3940 | // rejects in-flight and future calls; when the abort fires under a |
| 3941 | // same-isolate stub caller, terminate_execution would unwind that |
| 3942 | // caller too (the routed dispatch re-enters the isolate), so the |
| 3943 | // breakage is recorded here instead: contexts hosting the actor's |
| 3944 | // exported stubs abort (in-flight ops reject with the reason, |
| 3945 | // later ops with the post-abort message) and RPC dispatch to the |
| 3946 | // scope rejects with the reason. Direct host-dispatched DO events |
| 3947 | // keep the uncatchable terminate_execution path. |
| 3948 | const __brokenActors = new Map(); |
| 3949 | const __actorBreak = (scope, reason) => { |
| 3950 | if (__brokenActors.has(scope)) return; |
| 3951 | __brokenActors.set(scope, reason); |
| 3952 | for (const entry of __stubEntries.values()) |
| 3953 | if (entry.scope === scope) |
| 3954 | __ctxAbort(entry.ctx, new __ActorAbort(reason)); |
| 3955 | }; |
| 3956 | // Everything this isolate holds for one cell scope that belongs to the |
| 3957 | // cell's residency rather than to the isolate, so a fresh instance |
| 3958 | // inherits none of it. `adopt_cell` calls this on both edges: the |
| 3959 | // give-back frees it, the take-in guarantees that no epoch spans. |
| 3960 | // Storage is not here -- `stop_cell` closes it host-side -- and sockets |
| 3961 | // live in the host registry, so a hibernated cell keeps them. |
| 3962 | const __cellRelease = (scope) => { |
| 3963 | __cell.instances[scope]?.ctx?.facets?._release(); |
| 3964 | delete __cell.instances[scope]; |
| 3965 | delete __cell.idNames[scope]; |
| 3966 | delete __cell.facetConfigs[scope]; |
| 3967 | __brokenActors.delete(scope); |
| 3968 | // An abandoned block can never run `__blockLeave`. A normal eviction |
| 3969 | // cannot abandon a block because its event keeps the cell in flight. A |
| 3970 | // stop that waits for nobody can, so the release drops every block record |
| 3971 | // together with the other state for this residency. |
| 3972 | __cellBlocks.delete(scope); |
| 3973 | // An entry holds `target`, which can be an object the released |
| 3974 | // instance owns. Dropping it ends that reachability; `released` is |
| 3975 | // what an already-revived handle reads, since it holds its entry |
| 3976 | // directly and never looks in this map again. |
| 3977 | for (const entry of __stubEntries.values()) { |
| 3978 | if (entry.scope !== scope) continue; |
| 3979 | entry.released = true; |
| 3980 | __stubEntries.delete(entry.id); |
| 3981 | // Break in-flight ops as an abort would, but not through |
| 3982 | // `__actorBreak`: that records the scope broken for the life of the |
| 3983 | // isolate, which is the state this function drops. |
| 3984 | __ctxAbort(entry.ctx, new __ActorAbort(__releasedStubError())); |
| 3985 | } |
| 3986 | }; |
| 3987 | const __releasedStubError = () => new Error( |
| 3988 | "The Durable Object that returned this RPC stub no longer runs on " + |
| 3989 | "this node."); |
| 3990 | const __disposeStub = (meta) => { |
| 3991 | if (meta.disposed) return; |
| 3992 | meta.disposed = true; |
| 3993 | __ctxUnregister(meta); |
| 3994 | const entry = meta.entry; |
| 3995 | if (--entry.refs > 0) return; |
| 3996 | __stubEntries.delete(entry.id); |
| 3997 | const disposer = entry.target?.[Symbol.dispose]; |
| 3998 | if (typeof disposer === "function") |
| 3999 | Promise.resolve().then(() => disposer.call(entry.target)); |
| 4000 | }; |
| 4001 | const __stubDisposedError = () => |
| 4002 | new Error("RPC stub used after being disposed."); |
| 4003 | // Shared brand value for RpcTarget instances; see the RpcTarget |
| 4004 | // constructor. |
| 4005 | const __rpcNoClone = () => {}; |
| 4006 | // Workerd method-visibility rules by target kind: an RpcTarget |
| 4007 | // exposes inherited methods/accessors (never own instance state, |
| 4008 | // never Object.prototype); a plain object or function exposes own |
| 4009 | // properties only. Property reads go through normal [[Get]] so |
| 4010 | // Proxy handlers participate, as in Workerd. |
| 4011 | const __rpcNoSuchMethod = (prop) => new TypeError( |
| 4012 | 'The RPC receiver does not implement the method "' + prop + '".'); |
| 4013 | // Bind through the intrinsic because a callable proxy can implement `.bind` |
| 4014 | // as a remote property. Reading that property can turn a valid named RPC |
| 4015 | // method into a non-function. Keep this rule shared by every RPC binding site. |
| 4016 | const __rpcBindMethod = (value, receiver) => |
| 4017 | Reflect.apply(Function.prototype.bind, value, [receiver]); |
| 4018 | const __stubResolve = (target, prop) => { |
| 4019 | if (target instanceof __cf.RpcTarget) { |
| 4020 | if (Object.hasOwn(target, prop) || !(prop in target) || |
| 4021 | prop in Object.prototype) throw __rpcNoSuchMethod(prop); |
| 4022 | } else if (!Object.hasOwn(target, prop)) { |
| 4023 | throw __rpcNoSuchMethod(prop); |
| 4024 | } |
| 4025 | const value = target[prop]; |
| 4026 | // Keep celld's own stubs and pipeline nodes unwrapped because the wrapper |
| 4027 | // would lose their metadata. |
| 4028 | return typeof value === "function" && !__stubMeta.has(value) && |
| 4029 | !(value instanceof __cf.RpcPromise) && |
| 4030 | !(value instanceof __cf.RpcProperty) |
| 4031 | ? __rpcBindMethod(value, target) : value; |
| 4032 | }; |
| 4033 | // ---- streams over RPC ------------------------------------------ |
| 4034 | // A live stream crosses as a handle in the caps table: the sender |
| 4035 | // locks the origin (reader/writer acquired at lift) behind a |
| 4036 | // bridge entry, and the receiver's endpoint is an ordinary |
| 4037 | // ReadableStream/WritableStream whose pulls and writes are stub |
| 4038 | // ops against the bridge -- one bounded reverse call per chunk, |
| 4039 | // the clone being the one wire copy. Backpressure is the op in |
| 4040 | // flight: hwm 0 pulls only on demand, and the writable carries |
| 4041 | // one chunk per op. EOF, close, and errors cross as op results; |
| 4042 | // teardown (param disposal, context end, context abort) runs the |
| 4043 | // bridge disposer, which cancels or aborts an unfinished origin |
| 4044 | // with Workerd's generic disconnect errors -- reasons do not |
| 4045 | // propagate, matching Workerd's own TODOs (and its verbatim |
| 4046 | // "endeded" typo). |
| 4047 | const __wsDisconnect = () => new Error( |
| 4048 | "WritableStream received over RPC was disconnected because " + |
| 4049 | "the remote execution context has endeded."); |
| 4050 | const __rsDisconnect = () => new Error( |
| 4051 | "ReadableStream received over RPC disconnected prematurely."); |
| 4052 | // Receiver wrapper stream -> its handle meta, for forwarding. |
| 4053 | const __rpcStreamMeta = new WeakMap(); |
| 4054 | const __readableBridge = (reader) => { |
| 4055 | const bridge = { |
| 4056 | done: false, |
| 4057 | async read() { |
| 4058 | let result; |
| 4059 | try { |
| 4060 | result = await reader.read(); |
| 4061 | } catch (error) { |
| 4062 | bridge.done = true; |
| 4063 | throw error; |
| 4064 | } |
| 4065 | if (result.done) bridge.done = true; |
| 4066 | return result; |
| 4067 | }, |
| 4068 | cancel() { |
| 4069 | if (bridge.done) return; |
| 4070 | bridge.done = true; |
| 4071 | reader.cancel(__rsDisconnect()).catch(() => {}); |
| 4072 | }, |
| 4073 | [Symbol.dispose]() { bridge.cancel(); }, |
| 4074 | }; |
| 4075 | return bridge; |
| 4076 | }; |
| 4077 | const __writableBridge = (writer) => { |
| 4078 | const bridge = { |
| 4079 | done: false, |
| 4080 | write: (chunk) => writer.write(chunk), |
| 4081 | close() { |
| 4082 | bridge.done = true; |
| 4083 | return writer.close(); |
| 4084 | }, |
| 4085 | abort() { |
| 4086 | bridge.done = true; |
| 4087 | return writer.abort(__wsDisconnect()); |
| 4088 | }, |
| 4089 | [Symbol.dispose]() { |
| 4090 | if (!bridge.done) bridge.abort().catch(() => {}); |
| 4091 | }, |
| 4092 | }; |
| 4093 | return bridge; |
| 4094 | }; |
| 4095 | const __liftStream = (v) => { |
| 4096 | const readable = v instanceof ReadableStream; |
| 4097 | const key = readable ? "__celld$rs" : "__celld$ws"; |
| 4098 | const meta = __rpcStreamMeta.get(v); |
| 4099 | if (meta !== undefined && !meta.disposed && !v.locked) { |
| 4100 | // Re-serializing a received, untouched stream forwards the |
| 4101 | // original handle: the reference moves (like a stub) and |
| 4102 | // the local wrapper is dead -- a round trip stays one hop. |
| 4103 | meta.disposed = true; |
| 4104 | __ctxUnregister(meta); |
| 4105 | return { [key]: meta.entry.id, t: __stubIsolate }; |
| 4106 | } |
| 4107 | if (v.locked) |
| 4108 | throw new TypeError(readable |
| 4109 | ? "The ReadableStream has been locked to a reader." |
| 4110 | : "The WritableStream has been locked to a writer."); |
| 4111 | const bridge = readable |
| 4112 | ? __readableBridge(v.getReader()) |
| 4113 | : __writableBridge(v.getWriter()); |
| 4114 | return { [key]: __newEntry(bridge).id, t: __stubIsolate }; |
| 4115 | }; |
| 4116 | // A signal is not a snapshot on the RPC wire. The marker carries a |
| 4117 | // process-wide identity, and the host forwards the source's single state |
| 4118 | // transition to every receiving isolate. A received signal keeps that |
| 4119 | // identity when an RPC forwards it again, so a chain does not add relays. |
| 4120 | const __rpcSignalMeta = new WeakMap(); |
| 4121 | const __rpcSignalReceivers = new Map(); |
| 4122 | const __rpcSignalSourceFinalizer = new FinalizationRegistry( |
| 4123 | (id) => __rpc_signal_release(id)); |
| 4124 | const __rpcSignalReceiverFinalizer = new FinalizationRegistry( |
| 4125 | ({ id, subscription }) => |
| 4126 | __rpc_signal_unsubscribe(id, subscription)); |
| 4127 | const __rpcSignalReasonOut = (reason) => { |
| 4128 | if (reason instanceof DOMException) |
| 4129 | return __sc_encode({ d: true, n: reason.name, m: reason.message }); |
| 4130 | try { |
| 4131 | return __sc_encode({ v: reason }); |
| 4132 | } catch { |
| 4133 | return __sc_encode({ v: new Error(String(reason)) }); |
| 4134 | } |
| 4135 | }; |
| 4136 | const __rpcSignalReasonIn = (bytes) => { |
| 4137 | const reason = __sc_decode(bytes); |
| 4138 | return reason.d |
| 4139 | ? new DOMException(reason.m, reason.n) |
| 4140 | : reason.v; |
| 4141 | }; |
| 4142 | const __rpcSignalSubscribe = (receiver) => { |
| 4143 | const signal = receiver.signal.deref(); |
| 4144 | if (signal === undefined) return false; |
| 4145 | const pending = __rpc_signal_wait(receiver.id); |
| 4146 | receiver.subscription = pending.__celldRpcSignalSubscription; |
| 4147 | pending.then((reason) => { |
| 4148 | const target = receiver.signal.deref(); |
| 4149 | if (target !== undefined && reason.byteLength !== 0) |
| 4150 | __abortSignal(target, __rpcSignalReasonIn(reason)); |
| 4151 | }); |
| 4152 | // A wait belongs to the request that installed it. A retained signal needs |
| 4153 | // a fresh wait in each later request, and its finalizer must unsubscribe the |
| 4154 | // newest one rather than the dead request's subscription. |
| 4155 | __rpcSignalReceiverFinalizer.unregister(receiver); |
| 4156 | __rpcSignalReceiverFinalizer.register(signal, receiver, receiver); |
| 4157 | return true; |
| 4158 | }; |
| 4159 | const __liftSignal = (signal) => { |
| 4160 | let meta = __rpcSignalMeta.get(signal); |
| 4161 | if (meta === undefined) { |
| 4162 | const id = __rpc_signal_new(); |
| 4163 | meta = { id }; |
| 4164 | __rpcSignalMeta.set(signal, meta); |
| 4165 | __rpcSignalSourceFinalizer.register(signal, id); |
| 4166 | if (signal.aborted) { |
| 4167 | __rpc_signal_abort(id, __rpcSignalReasonOut(signal.reason)); |
| 4168 | } else { |
| 4169 | signal.addEventListener("abort", (event) => { |
| 4170 | __rpc_signal_abort(id, |
| 4171 | __rpcSignalReasonOut(event.target.reason)); |
| 4172 | }, { once: true }); |
| 4173 | } |
| 4174 | } |
| 4175 | const marker = { "__celld$sig": meta.id, a: signal.aborted }; |
| 4176 | if (signal.aborted) marker.r = __rpcSignalReasonOut(signal.reason); |
| 4177 | return marker; |
| 4178 | }; |
| 4179 | const __rpcSignalRefresh = () => { |
| 4180 | for (const [id, receivers] of __rpcSignalReceivers) { |
| 4181 | const state = __rpc_signal_poll(id); |
| 4182 | const live = new Set(); |
| 4183 | for (const receiver of receivers) { |
| 4184 | const signal = receiver.signal.deref(); |
| 4185 | if (signal === undefined) continue; |
| 4186 | if (state instanceof Uint8Array) |
| 4187 | __abortSignal(signal, __rpcSignalReasonIn(state)); |
| 4188 | else if (state !== null && __rpcSignalSubscribe(receiver)) |
| 4189 | live.add(receiver); |
| 4190 | } |
| 4191 | if (live.size === 0 || state === null || state instanceof Uint8Array) |
| 4192 | __rpcSignalReceivers.delete(id); |
| 4193 | else |
| 4194 | __rpcSignalReceivers.set(id, live); |
| 4195 | } |
| 4196 | }; |
| 4197 | // Replace stub-able values with wire markers. Runs only after a |
| 4198 | // plain clone failed, so plain-data serialization never pays for |
| 4199 | // it. Passing an existing stub transfers its reference: the |
| 4200 | // sender's handle is disposed (dup() first to keep one) and the |
| 4201 | // receiver adopts it. Returns null when nothing was liftable. |
| 4202 | const __stubLift = (value, allowCapabilities = true, originals) => { |
| 4203 | let lifted = false; |
| 4204 | // Capabilities (stubs, disposers) root the callee context; |
| 4205 | // by-value host types do not -- they pick the 0x02 envelope. |
| 4206 | let caps = false; |
| 4207 | const seen = new Map(); |
| 4208 | const ctx = __ctxNow(); |
| 4209 | // A buffered body crosses as its bytes; a live-stream body |
| 4210 | // crosses as a stream handle (a capability, so the reply |
| 4211 | // roots its callee context and the pulls keep working). |
| 4212 | const liftBody = (v) => { |
| 4213 | if (v._bodyBytes !== null) return v._bodyBytes; |
| 4214 | caps = true; |
| 4215 | return __liftStream(v.body); |
| 4216 | }; |
| 4217 | const lift = (v) => { |
| 4218 | if (v === null || |
| 4219 | (typeof v !== "object" && typeof v !== "function")) return v; |
| 4220 | const cached = seen.get(v); |
| 4221 | if (cached !== undefined) return cached; |
| 4222 | const meta = __stubMeta.get(v); |
| 4223 | if (meta) { |
| 4224 | if (!allowCapabilities) return v; |
| 4225 | lifted = true; |
| 4226 | caps = true; |
| 4227 | if (meta.disposed) throw __stubDisposedError(); |
| 4228 | // A stub belongs to the request that received it; another |
| 4229 | // request cannot serialize it (Workerd's IoContext rule). |
| 4230 | if (meta.ctx !== ctx) throw __ctxError("Client"); |
| 4231 | meta.disposed = true; // the ref moves to the receiver |
| 4232 | __ctxUnregister(meta); |
| 4233 | const marker = { "__celld$stub": meta.entry.id, |
| 4234 | t: __stubIsolate, c: meta.callable }; |
| 4235 | seen.set(v, marker); |
| 4236 | return marker; |
| 4237 | } |
| 4238 | const svc = __svcMeta.get(v); |
| 4239 | if (svc !== undefined) { |
| 4240 | if (!allowCapabilities) return v; |
| 4241 | // A loopback service stub (ctx.exports): name + props cross |
| 4242 | // as plain data and revive as a fresh loopback stub. Props |
| 4243 | // are lifted too -- they may nest further stubs (Workerd's |
| 4244 | // nested channel tokens). |
| 4245 | lifted = true; |
| 4246 | caps = true; |
| 4247 | const marker = { "__celld$svc": svc.name, t: __stubIsolate }; |
| 4248 | seen.set(v, marker); |
| 4249 | if (svc.props !== undefined) marker.p = lift(svc.props); |
| 4250 | return marker; |
| 4251 | } |
| 4252 | // Workerd refuses to serialize its promise/property handles. |
| 4253 | if (v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty) |
| 4254 | throw new DOMException( |
| 4255 | 'Could not serialize object of type "' + |
| 4256 | (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + |
| 4257 | '". This type does not support serialization.', |
| 4258 | "DataCloneError"); |
| 4259 | if (typeof v === "function" || v instanceof __cf.RpcTarget) { |
| 4260 | if (!allowCapabilities) return v; |
| 4261 | lifted = true; |
| 4262 | caps = true; |
| 4263 | const marker = { "__celld$stub": __newEntry(v).id, |
| 4264 | t: __stubIsolate, |
| 4265 | c: typeof v === "function" }; |
| 4266 | seen.set(v, marker); |
| 4267 | return marker; |
| 4268 | } |
| 4269 | const doId = __doStubMeta.get(v); |
| 4270 | if (doId !== undefined) { |
| 4271 | if (!allowCapabilities) return v; |
| 4272 | lifted = true; |
| 4273 | caps = true; |
| 4274 | const marker = { "__celld$do": doId._className, |
| 4275 | v: doId._value, n: v.name ?? null }; |
| 4276 | seen.set(v, marker); |
| 4277 | return marker; |
| 4278 | } |
| 4279 | // HTTP host types cross by value, as in Workerd's RPC |
| 4280 | // serialization: entry lists for Headers, the buffered bytes |
| 4281 | // for bodies (the marker aliases the live buffer; the clone |
| 4282 | // is the one wire copy), and no signal -- the receiver mints |
| 4283 | // a fresh one. A live stream body cannot cross yet. |
| 4284 | let marker; |
| 4285 | if (v instanceof Headers) { |
| 4286 | if (!allowCapabilities) return v; |
| 4287 | marker = { "__celld$hdr": [...v] }; |
| 4288 | } else if (v instanceof Blob) { |
| 4289 | if (!allowCapabilities) return v; |
| 4290 | marker = { "__celld$blob": v._bytes, y: v.type }; |
| 4291 | if (v instanceof File) { |
| 4292 | marker.n = v.name; |
| 4293 | marker.m = v.lastModified; |
| 4294 | } |
| 4295 | } else if (v instanceof Request) { |
| 4296 | if (!allowCapabilities) return v; |
| 4297 | marker = { "__celld$req": v.url, m: v.method, |
| 4298 | h: [...v.headers], r: v.redirect, c: v.cf, |
| 4299 | b: liftBody(v) }; |
| 4300 | } else if (v instanceof Response) { |
| 4301 | if (!allowCapabilities) return v; |
| 4302 | marker = { "__celld$res": v.status, |
| 4303 | t: v.statusText || |
| 4304 | __STATUS_TEXT[v.status] || "", |
| 4305 | h: [...v.headers], c: v.cf, |
| 4306 | e: v.type === "error", |
| 4307 | b: v.body === null ? null : liftBody(v) }; |
| 4308 | } else if (v instanceof ReadableStream || |
| 4309 | v instanceof WritableStream) { |
| 4310 | if (!allowCapabilities) return v; |
| 4311 | caps = true; |
| 4312 | marker = __liftStream(v); |
| 4313 | } else if (v instanceof AbortSignal) { |
| 4314 | marker = __liftSignal(v); |
| 4315 | } |
| 4316 | if (marker !== undefined) { |
| 4317 | lifted = true; |
| 4318 | seen.set(v, marker); |
| 4319 | return marker; |
| 4320 | } |
| 4321 | const proto = Object.getPrototypeOf(v); |
| 4322 | if (!Array.isArray(v) && |
| 4323 | proto !== Object.prototype && proto !== null) { |
| 4324 | // A Proxy emulating neither a plain object nor an RpcTarget |
| 4325 | // is Workerd's canonical proxy serialization error. |
| 4326 | if (__util_proxy_details(v) !== undefined) |
| 4327 | throw new DOMException( |
| 4328 | "Proxy could not be serialized because it is not a " + |
| 4329 | "valid RPC receiver type. The Proxy must emulate either " + |
| 4330 | "a plain object or an RpcTarget, as indicated by the " + |
| 4331 | "Proxy's prototype chain.", "DataCloneError"); |
| 4332 | return v; // host/other: leave to the clone |
| 4333 | } |
| 4334 | const out = Array.isArray(v) ? [] : {}; |
| 4335 | seen.set(v, out); |
| 4336 | for (const key of Object.keys(v)) out[key] = lift(v[key]); |
| 4337 | const disposerSource = originals?.get(v) ?? v; |
| 4338 | const disposer = disposerSource[Symbol.dispose]; |
| 4339 | if (allowCapabilities && !Array.isArray(v) && |
| 4340 | typeof disposer === "function") { |
| 4341 | lifted = true; |
| 4342 | caps = true; |
| 4343 | out["__celld$disp"] = |
| 4344 | __newEntry(__rpcBindMethod(disposer, disposerSource)).id; |
| 4345 | } |
| 4346 | return out; |
| 4347 | }; |
| 4348 | const tree = lift(value); |
| 4349 | return lifted ? { tree, caps } : null; |
| 4350 | }; |
| 4351 | // Revive host-type markers into real instances, adopting the wire |
| 4352 | // bytes directly -- no copy beyond the clone's own. |
| 4353 | const __reviveBlob = (marker, bytes) => { |
| 4354 | const blob = marker.n !== undefined |
| 4355 | ? new File([], marker.n, |
| 4356 | { type: marker.y, lastModified: marker.m }) |
| 4357 | : new Blob([], { type: marker.y }); |
| 4358 | blob._bytes = bytes; |
| 4359 | blob.size = bytes.byteLength; |
| 4360 | return blob; |
| 4361 | }; |
| 4362 | const __adoptBody = (target, bytes) => { |
| 4363 | target._bodyBytes = bytes; |
| 4364 | target._body = undefined; // decoded lazily on the first text()/json() |
| 4365 | const body = target.body; |
| 4366 | if (body !== null) { |
| 4367 | body._st.bytes = bytes; |
| 4368 | body.__celldBodyBytes = bytes; |
| 4369 | body._expectedLength = bytes.byteLength; |
| 4370 | } |
| 4371 | }; |
| 4372 | // A non-bytes `b` is a live-stream body marker: revive it and |
| 4373 | // let the constructor adopt it as a streaming body. |
| 4374 | const __reviveRequest = (marker, url, revive) => { |
| 4375 | if (!(marker.b instanceof Uint8Array)) |
| 4376 | return new Request(url, { method: marker.m, |
| 4377 | headers: marker.h, redirect: marker.r, cf: marker.c, |
| 4378 | body: revive(marker.b) }); |
| 4379 | const req = new Request(url, { method: marker.m, |
| 4380 | headers: marker.h, redirect: marker.r, cf: marker.c }); |
| 4381 | __adoptBody(req, marker.b); |
| 4382 | return req; |
| 4383 | }; |
| 4384 | const __reviveResponse = (marker, revive) => { |
| 4385 | const bytes = marker.b instanceof Uint8Array; |
| 4386 | const res = new Response( |
| 4387 | marker.b === null ? null : bytes ? "" : revive(marker.b), { |
| 4388 | status: marker["__celld$res"], statusText: marker.t, |
| 4389 | headers: marker.h, cf: marker.c }); |
| 4390 | if (bytes) __adoptBody(res, marker.b); |
| 4391 | if (marker.e) res.type = "error"; |
| 4392 | return res; |
| 4393 | }; |
| 4394 | // Wire a received stream handle to a local endpoint built with |
| 4395 | // the ordinary constructors -- nothing new threads through the |
| 4396 | // stream hot paths. Read errors surface as Workerd's generic |
| 4397 | // premature-disconnect; write errors propagate (Workerd sends |
| 4398 | // real errors back through the write loop). |
| 4399 | const __foreignStreamOp = () => Promise.reject(new Error( |
| 4400 | "RPC streams cannot cross isolate boundaries yet.")); |
| 4401 | const __reviveStream = (marker, id, readable, handles) => { |
| 4402 | const entry = marker.t === __stubIsolate |
| 4403 | ? __stubEntries.get(id) : undefined; |
| 4404 | if (entry === undefined) |
| 4405 | return readable |
| 4406 | ? new ReadableStream({ pull: __foreignStreamOp }) |
| 4407 | : new WritableStream({ write: __foreignStreamOp, |
| 4408 | close: __foreignStreamOp, abort: __foreignStreamOp }); |
| 4409 | const meta = { entry, disposed: false, ctx: __ctxNow() }; |
| 4410 | __ctxRegister(meta); |
| 4411 | handles.push(meta); |
| 4412 | const stream = readable |
| 4413 | ? new ReadableStream({ |
| 4414 | async pull(controller) { |
| 4415 | let result; |
| 4416 | try { |
| 4417 | result = await __stubOp(meta, ["read"], []); |
| 4418 | } catch { |
| 4419 | throw __rsDisconnect(); |
| 4420 | } |
| 4421 | if (result.done) controller.close(); |
| 4422 | else controller.enqueue(result.value); |
| 4423 | }, |
| 4424 | cancel: () => |
| 4425 | __stubOp(meta, ["cancel"], []).catch(() => {}), |
| 4426 | }, { highWaterMark: 0 }) |
| 4427 | : new WritableStream({ |
| 4428 | write: (chunk) => __stubOp(meta, ["write"], [chunk]), |
| 4429 | close: () => __stubOp(meta, ["close"], []), |
| 4430 | abort: () => |
| 4431 | __stubOp(meta, ["abort"], []).catch(() => {}), |
| 4432 | }); |
| 4433 | __rpcStreamMeta.set(stream, meta); |
| 4434 | return stream; |
| 4435 | }; |
| 4436 | const __reviveSignal = (marker, id) => { |
| 4437 | const controller = new AbortController(); |
| 4438 | const signal = controller.signal; |
| 4439 | __rpcSignalMeta.set(signal, { id }); |
| 4440 | if (marker.a) { |
| 4441 | controller.abort(__rpcSignalReasonIn(marker.r)); |
| 4442 | return controller.signal; |
| 4443 | } |
| 4444 | let receivers = __rpcSignalReceivers.get(id); |
| 4445 | if (receivers === undefined) { |
| 4446 | receivers = new Set(); |
| 4447 | __rpcSignalReceivers.set(id, receivers); |
| 4448 | } |
| 4449 | const receiver = { id, signal: new WeakRef(signal), subscription: null }; |
| 4450 | receivers.add(receiver); |
| 4451 | __rpcSignalSubscribe(receiver); |
| 4452 | return signal; |
| 4453 | }; |
| 4454 | // The inverse: markers become live handles. `handles` collects the |
| 4455 | // revived stubs (for call-end param disposal or result-tree |
| 4456 | // disposal); `disposers` collects remote Symbol.dispose entries. |
| 4457 | const __stubRevive = (value) => { |
| 4458 | const handles = []; |
| 4459 | const disposers = []; |
| 4460 | const seen = new Set(); |
| 4461 | const revive = (v) => { |
| 4462 | if (v === null || typeof v !== "object") return v; |
| 4463 | const stubId = v["__celld$stub"]; |
| 4464 | if (stubId !== undefined) { |
| 4465 | const entry = v.t === __stubIsolate |
| 4466 | ? __stubEntries.get(stubId) : undefined; |
| 4467 | const stub = entry === undefined |
| 4468 | ? __foreignStub() |
| 4469 | : __makeStub(entry, v.c); |
| 4470 | const meta = __stubMeta.get(stub); |
| 4471 | if (meta) handles.push(meta); |
| 4472 | return stub; |
| 4473 | } |
| 4474 | const svcName = v["__celld$svc"]; |
| 4475 | if (svcName !== undefined) |
| 4476 | return v.t === __stubIsolate |
| 4477 | ? __entrypointStub(svcName, revive(v.p)) |
| 4478 | : __foreignStub(); |
| 4479 | const doClass = v["__celld$do"]; |
| 4480 | if (doClass !== undefined) { |
| 4481 | const namespace = __cell.makeNamespace(doClass); |
| 4482 | return namespace.get( |
| 4483 | new DurableObjectId(doClass, v.v, v.n ?? undefined)); |
| 4484 | } |
| 4485 | const hdr = v["__celld$hdr"]; |
| 4486 | if (hdr !== undefined) return new Headers(hdr); |
| 4487 | const blobBytes = v["__celld$blob"]; |
| 4488 | if (blobBytes !== undefined) return __reviveBlob(v, blobBytes); |
| 4489 | const reqUrl = v["__celld$req"]; |
| 4490 | if (reqUrl !== undefined) |
| 4491 | return __reviveRequest(v, reqUrl, revive); |
| 4492 | if (v["__celld$res"] !== undefined) |
| 4493 | return __reviveResponse(v, revive); |
| 4494 | const rsId = v["__celld$rs"]; |
| 4495 | if (rsId !== undefined) |
| 4496 | return __reviveStream(v, rsId, true, handles); |
| 4497 | const wsId = v["__celld$ws"]; |
| 4498 | if (wsId !== undefined) |
| 4499 | return __reviveStream(v, wsId, false, handles); |
| 4500 | const sigId = v["__celld$sig"]; |
| 4501 | if (sigId !== undefined) return __reviveSignal(v, sigId); |
| 4502 | if (seen.has(v)) return v; |
| 4503 | seen.add(v); |
| 4504 | if (Array.isArray(v)) { |
| 4505 | for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); |
| 4506 | return v; |
| 4507 | } |
| 4508 | const proto = Object.getPrototypeOf(v); |
| 4509 | if (proto !== Object.prototype && proto !== null) return v; |
| 4510 | for (const key of Object.keys(v)) { |
| 4511 | if (key === "__celld$disp") { |
| 4512 | const entry = __stubEntries.get(v[key]); |
| 4513 | if (entry) disposers.push(entry); |
| 4514 | delete v[key]; |
| 4515 | continue; |
| 4516 | } |
| 4517 | v[key] = revive(v[key]); |
| 4518 | } |
| 4519 | return v; |
| 4520 | }; |
| 4521 | return { value: revive(value), handles, disposers }; |
| 4522 | }; |
| 4523 | // A marker that crossed an isolate boundary: fail on use, loudly. |
| 4524 | const __foreignStub = () => new Proxy(function () {}, { |
| 4525 | get: (_b, prop) => { |
| 4526 | if (prop === "then" || typeof prop !== "string") return undefined; |
| 4527 | return () => Promise.reject(new Error( |
| 4528 | "RPC stubs cannot cross isolate boundaries yet.")); |
| 4529 | }, |
| 4530 | apply: () => Promise.reject(new Error( |
| 4531 | "RPC stubs cannot cross isolate boundaries yet.")), |
| 4532 | }); |
| 4533 | // Workerd's entrypoint method-visibility rules (worker-rpc.c++): |
| 4534 | // reserved lifecycle names are refused outright; only prototype |
| 4535 | // methods and accessors are visible -- never own instance state |
| 4536 | // (env/ctx live there) and never Object.prototype. |
| 4537 | const __entrypointReserved = new Set([ |
| 4538 | "constructor", "fetch", "connect", "alarm", "scheduled", |
| 4539 | "webSocketMessage", "webSocketClose", "webSocketError", "dup", |
| 4540 | ]); |
| 4541 | const __entrypointResolve = (inst, prop) => { |
| 4542 | if (__entrypointReserved.has(prop)) |
| 4543 | throw new TypeError("'" + prop + |
| 4544 | "' is a reserved method and cannot be called over RPC."); |
| 4545 | if (Object.hasOwn(inst, prop) || !(prop in inst) || |
| 4546 | prop in Object.prototype) |
| 4547 | throw __rpcNoSuchMethod(prop); |
| 4548 | const value = inst[prop]; |
| 4549 | return typeof value === "function" && !__stubMeta.has(value) && |
| 4550 | !(value instanceof __cf.RpcPromise) && |
| 4551 | !(value instanceof __cf.RpcProperty) |
| 4552 | ? __rpcBindMethod(value, inst) : value; |
| 4553 | }; |
| 4554 | // A pipeline hop may continue only through plain data, functions, |
| 4555 | // RpcTargets, and stubs -- never through an RPC promise/property |
| 4556 | // handle or a class instance (Workerd's receiver rules). |
| 4557 | const __walkable = (v) => |
| 4558 | v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty |
| 4559 | ? false |
| 4560 | : typeof v === "function" || v instanceof __cf.RpcTarget || |
| 4561 | (typeof v === "object" && v !== null && |
| 4562 | (Object.getPrototypeOf(v) === Object.prototype || |
| 4563 | Array.isArray(v))); |
| 4564 | // Receiver-side pipeline walk: resolve `path` from `root`, then |
| 4565 | // GET the final member (`args` null) or CALL it. Errors name the |
| 4566 | // path walked so far, as Workerd's do. A stub mid-walk continues |
| 4567 | // against its own target, in the stub's owning context. |
| 4568 | const __rpcWalk = async (root, path, args, entrypointRoot) => { |
| 4569 | let value = root; |
| 4570 | for (let i = 0; i < path.length; i++) { |
| 4571 | const meta = __stubMeta.get(value); |
| 4572 | if (meta) { |
| 4573 | if (meta.disposed) throw __stubDisposedError(); |
| 4574 | const rest = path.slice(i); |
| 4575 | return await __ctxRun(meta.entry.ctx, |
| 4576 | () => __rpcWalk(meta.entry.target, rest, args, false)); |
| 4577 | } |
| 4578 | if (i > 0 && !__walkable(value)) |
| 4579 | throw __rpcNoSuchMethod(path[i - 1]); |
| 4580 | const prop = path[i]; |
| 4581 | const next = entrypointRoot && i === 0 |
| 4582 | ? __entrypointResolve(value, prop) |
| 4583 | : __stubResolve(value, prop); |
| 4584 | if (i === path.length - 1) { |
| 4585 | if (args === null) return next; |
| 4586 | if (typeof next !== "function") |
| 4587 | throw new TypeError( |
| 4588 | '"' + path.join(".") + '" is not a function.'); |
| 4589 | return next(...args); |
| 4590 | } |
| 4591 | if (next instanceof __cf.RpcPromise || |
| 4592 | next instanceof __cf.RpcProperty) |
| 4593 | throw __rpcNoSuchMethod(prop); |
| 4594 | value = next; |
| 4595 | } |
| 4596 | // An empty path applies the root itself (a callable stub). |
| 4597 | if (args === null) return value; |
| 4598 | if (typeof value !== "function") |
| 4599 | throw new TypeError("The RPC stub is not callable."); |
| 4600 | return value(...args); |
| 4601 | }; |
| 4602 | // One stub-mediated op: clone through the RPC envelope both ways, |
| 4603 | // so nested stubs, errors, and uncloneables behave exactly as a |
| 4604 | // dispatched call. Args serialize in the caller's context (its |
| 4605 | // stubs must be its own to transfer); the decode, the walk, and |
| 4606 | // the reply serialization run in the stub's owning context, so |
| 4607 | // stubs minted by the target belong to the target's context. |
| 4608 | // Params received by the target are disposed when the op ends |
| 4609 | // (Workerd's param-disposal rule). |
| 4610 | const __stubOp = (meta, path, args) => { |
| 4611 | if (meta.disposed) return Promise.reject(__stubDisposedError()); |
| 4612 | const entry = meta.entry; |
| 4613 | // The cell that minted this stub left residency, so `entry.target` |
| 4614 | // belongs to an instance this node released. The stub fails here |
| 4615 | // rather than calling into it. |
| 4616 | if (entry.released) return Promise.reject(__releasedStubError()); |
| 4617 | // A stub rooted in an aborted context is broken: reject with the |
| 4618 | // abort reason, before and after the dispatch (the target may |
| 4619 | // abort its own context mid-call). Gated on one field read. |
| 4620 | if (__abortedCtxs.size !== 0) { |
| 4621 | const aborted = __abortedCtxs.get(entry.ctx); |
| 4622 | if (aborted !== undefined) |
| 4623 | return Promise.reject(__postAbortError(aborted)); |
| 4624 | } |
| 4625 | const argsSc = args === null ? null : __rpcOut(args, true); |
| 4626 | const dispatch = (async () => { |
| 4627 | // Workerd delivers RPC asynchronously: the callee must not run |
| 4628 | // before the caller's synchronous code. A call made just after |
| 4629 | // a not-yet-delivered ctx.abort counts as in flight (rejects |
| 4630 | // with the reason, not the post-abort message). Bodies queue |
| 4631 | // in call order, so e-order holds. |
| 4632 | await null; |
| 4633 | // The cell that minted this stub gates it like any other event. |
| 4634 | // The op is dispatched inside the isolate and never becomes a |
| 4635 | // drive, so it is the one delivery point that has to ask here |
| 4636 | // rather than in Rust. A stub carrying the running critical |
| 4637 | // section re-enters it; everything else queues, and a section |
| 4638 | // that failed refuses what queued. |
| 4639 | const cell = entry.scope; |
| 4640 | if (cell !== undefined) { |
| 4641 | const block = __cellBlocks.get(cell); |
| 4642 | if (block !== undefined && (entry.section === null || |
| 4643 | entry.section !== block.holder)) |
| 4644 | await __gate_wait(cell); |
| 4645 | } |
| 4646 | const reply = await __ctxRun(entry.ctx, |
| 4647 | () => __rpcRun(async () => { |
| 4648 | const decoded = |
| 4649 | argsSc === null ? null : __rpcDesArgs(argsSc); |
| 4650 | try { |
| 4651 | return await __rpcWalk(entry.target, path, |
| 4652 | decoded === null ? null : decoded.args, false); |
| 4653 | } finally { |
| 4654 | if (decoded !== null) |
| 4655 | for (const handle of decoded.received) |
| 4656 | __disposeStub(handle); |
| 4657 | } |
| 4658 | }, true)); |
| 4659 | if (__abortedCtxs.size !== 0) { |
| 4660 | const aborted = __abortedCtxs.get(entry.ctx); |
| 4661 | if (aborted !== undefined) |
| 4662 | throw aborted instanceof __ActorAbort |
| 4663 | ? aborted.reason : aborted; |
| 4664 | } |
| 4665 | return __rpcDes(reply); |
| 4666 | })(); |
| 4667 | if (entry.ctx === undefined) return dispatch; |
| 4668 | // Race the op against its hosting context's abort: a hung callee |
| 4669 | // never settles, so the settlement check above cannot reach it. |
| 4670 | // A late settlement lands on an already-settled promise (no-op). |
| 4671 | return new Promise((resolve, reject) => { |
| 4672 | const untrack = __opTrack(entry.ctx, reject); |
| 4673 | dispatch.then( |
| 4674 | (value) => { untrack(); resolve(value); }, |
| 4675 | (error) => { untrack(); reject(error); }); |
| 4676 | }); |
| 4677 | }; |
| 4678 | // Resolve a path against a local, already-revived value. A hop |
| 4679 | // landing on a same-isolate stub delegates the rest of the path |
| 4680 | // to the stub's target; everything else is a plain [[Get]] so |
| 4681 | // Durable Object stubs and Proxies participate. |
| 4682 | const __walkLocal = (parent, path, args) => { |
| 4683 | for (let i = 0; i < path.length; i++) { |
| 4684 | const meta = __stubMeta.get(parent); |
| 4685 | if (meta) return __stubOp(meta, path.slice(i), args); |
| 4686 | const prop = path[i]; |
| 4687 | const member = parent == null ? undefined : parent[prop]; |
| 4688 | if (i < path.length - 1) { |
| 4689 | parent = member; |
| 4690 | continue; |
| 4691 | } |
| 4692 | if (args === null) return member; |
| 4693 | if (typeof member !== "function") { |
| 4694 | if (member === undefined) throw __rpcNoSuchMethod(prop); |
| 4695 | throw new TypeError('"' + prop + '" is not a function.'); |
| 4696 | } |
| 4697 | // [[Call]] directly: `.apply` on a stub proxy would be a |
| 4698 | // remote property access, not an invocation. |
| 4699 | return Reflect.apply(member, parent, args); |
| 4700 | } |
| 4701 | if (args === null) return parent; |
| 4702 | const meta = __stubMeta.get(parent); |
| 4703 | if (meta) return __stubOp(meta, [], args); |
| 4704 | if (typeof parent !== "function") |
| 4705 | throw new TypeError("The RPC value is not callable."); |
| 4706 | return parent(...args); |
| 4707 | }; |
| 4708 | // A session is one place pipeline ops resolve: the local value a |
| 4709 | // call returned, a same-isolate stub's target, or a named |
| 4710 | // entrypoint (whose paths resolve receiver-side in one op). |
| 4711 | const __valueSession = (promise) => ({ |
| 4712 | root: () => promise, |
| 4713 | get: (path) => promise.then((v) => __walkLocal(v, path, null)), |
| 4714 | call: (path, args) => |
| 4715 | promise.then((v) => __walkLocal(v, path, args)), |
| 4716 | }); |
| 4717 | const __stubSession = (meta) => ({ |
| 4718 | get: (path) => __stubOp(meta, path, null), |
| 4719 | call: (path, args) => __stubOp(meta, path, args), |
| 4720 | }); |
| 4721 | const __entrypointSession = (name, local, script, makeInst, propsSc) => ({ |
| 4722 | get: (path) => local |
| 4723 | ? (async () => __rpcDes( |
| 4724 | await __entrypointOp(name, path, null, true, makeInst)))() |
| 4725 | : (async () => __rpcDes( |
| 4726 | await __svc_rpc( |
| 4727 | script, name, JSON.stringify(path), null, propsSc)))(), |
| 4728 | call: (path, args) => (async () => { |
| 4729 | const argsSc = __rpcOut(args, local); |
| 4730 | if (local) |
| 4731 | return __rpcDes(await __entrypointOp( |
| 4732 | name, path, argsSc, true, makeInst)); |
| 4733 | return __rpcDes( |
| 4734 | await __svc_rpc( |
| 4735 | script, name, JSON.stringify(path), argsSc, propsSc)); |
| 4736 | })(), |
| 4737 | }); |
| 4738 | // Workerd's JsRpcPromise/JsRpcProperty: awaitable, callable, and |
| 4739 | // property access extends a path resolved at the far end, so |
| 4740 | // intermediates obey Workerd's receiver rules. `ctx` is the node's |
| 4741 | // owning request context -- null marks a context-free node (a |
| 4742 | // property path rooted directly at a service binding, which |
| 4743 | // starts a fresh session per await); a foreign context awaiting a |
| 4744 | // property or calling through the node gets Workerd's |
| 4745 | // cross-context error. Depth is capped like Workerd's |
| 4746 | // MAX_PROPERTY_DEPTH. |
| 4747 | const __makeNode = (session, path, ctx) => { |
| 4748 | let promise; |
| 4749 | const value = () => promise ??= (() => { |
| 4750 | if (path.length === 0) return session.root(); |
| 4751 | if (ctx !== null && ctx !== __ctxNow()) |
| 4752 | return Promise.reject(__ctxError("Pipeline")); |
| 4753 | return session.get(path); |
| 4754 | })(); |
| 4755 | const brand = |
| 4756 | path.length === 0 ? __cf.RpcPromise : __cf.RpcProperty; |
| 4757 | return new Proxy(function () {}, { |
| 4758 | getPrototypeOf: () => brand.prototype, |
| 4759 | get: (_b, p) => { |
| 4760 | if (p === "then") |
| 4761 | return (onOk, onErr) => value().then(onOk, onErr); |
| 4762 | if (p === "catch") return (onErr) => value().catch(onErr); |
| 4763 | if (p === "finally") |
| 4764 | return (onDone) => value().finally(onDone); |
| 4765 | if (typeof p !== "string") return undefined; |
| 4766 | if (path.length >= 5120) |
| 4767 | throw new TypeError( |
| 4768 | "RPC pipelined property chain is too deep."); |
| 4769 | return __makeNode(session, [...path, p], ctx); |
| 4770 | }, |
| 4771 | apply: (_b, _this, args) => { |
| 4772 | let call; |
| 4773 | if (ctx !== null && ctx !== __ctxNow()) { |
| 4774 | call = Promise.reject(__ctxError("JsRpcPromise")); |
| 4775 | call.catch(() => {}); |
| 4776 | } else { |
| 4777 | // Eager, so concurrent calls keep e-order. |
| 4778 | call = session.call(path, args); |
| 4779 | } |
| 4780 | return __makeNode( |
| 4781 | __valueSession(call), [], ctx ?? __ctxNow()); |
| 4782 | }, |
| 4783 | }); |
| 4784 | }; |
| 4785 | const __makeStub = (entry, callable) => { |
| 4786 | const meta = |
| 4787 | { entry, callable, disposed: false, ctx: __ctxNow() }; |
| 4788 | __ctxRegister(meta); |
| 4789 | const stub = new Proxy(function () {}, { |
| 4790 | getPrototypeOf: () => __cf.RpcStub.prototype, |
| 4791 | get: (_b, prop) => { |
| 4792 | if (prop === "then") return undefined; |
| 4793 | if (prop === Symbol.dispose) return () => __disposeStub(meta); |
| 4794 | if (prop === "dup") return () => { |
| 4795 | if (meta.disposed) throw __stubDisposedError(); |
| 4796 | entry.refs++; |
| 4797 | return __makeStub(entry, callable); |
| 4798 | }; |
| 4799 | if (typeof prop !== "string") return undefined; |
| 4800 | return __makeNode(__stubSession(meta), [prop], __ctxNow()); |
| 4801 | }, |
| 4802 | apply: (_b, _this, args) => __makeNode( |
| 4803 | __valueSession(__stubOp(meta, [], args)), [], __ctxNow()), |
| 4804 | }); |
| 4805 | __stubMeta.set(stub, meta); |
| 4806 | return stub; |
| 4807 | }; |
| 4808 | // A loopback service stub for one of this worker's own |
| 4809 | // entrypoints -- the ctx.exports surface. Calling the stub itself |
| 4810 | // returns a new stub carrying per-instance props, delivered to |
| 4811 | // the class constructor as ctx.props (Workerd's |
| 4812 | // ctx.exports.Name({ props })). |
| 4813 | const __svcMeta = new WeakMap(); |
| 4814 | const __entrypointStub = (name, props) => { |
| 4815 | let inst; |
| 4816 | const makeInst = props === undefined ? undefined : () => { |
| 4817 | if (inst !== undefined) return inst; |
| 4818 | const cls = __cell.entrypoints[name]; |
| 4819 | if (typeof cls !== "function") |
| 4820 | throw new TypeError( |
| 4821 | "The entrypoint " + name + " cannot carry props."); |
| 4822 | // Construction gets its own event, like a top-level invocation, and hands |
| 4823 | // that event's drain to the enclosing one. This runs inside the event of |
| 4824 | // the first method call on the stub, so a ctx.waitUntil() call in the |
| 4825 | // constructor drains before that call replies. |
| 4826 | inst = __constructEntrypoint(cls, props); |
| 4827 | return inst; |
| 4828 | }; |
| 4829 | const session = __entrypointSession(name, true, null, makeInst); |
| 4830 | const stub = new Proxy(function () {}, { |
| 4831 | getPrototypeOf: () => __cf.ServiceStub.prototype, |
| 4832 | get: (_b, prop) => { |
| 4833 | if (prop === "then") return undefined; |
| 4834 | if (typeof prop !== "string") return undefined; |
| 4835 | if (prop === "getRpcMethodForTestOnly") |
| 4836 | return (n) => __makeNode(session, [String(n)], null); |
| 4837 | // A Fetcher's fetch() is an HTTP request, as a service binding's is. |
| 4838 | if (prop === "fetch") |
| 4839 | return (input, init) => __makeServiceBinding( |
| 4840 | __cell.script, name === "default" ? null : name, |
| 4841 | props === undefined ? undefined : __rpcOut(props, false), |
| 4842 | ).fetch(input, init); |
| 4843 | return __makeNode(session, [prop], null); |
| 4844 | }, |
| 4845 | apply: (_b, _this, args) => |
| 4846 | __entrypointStub(name, args[0]?.props), |
| 4847 | }); |
| 4848 | __svcMeta.set(stub, { name, props }); |
| 4849 | __outboundMeta.set(stub, { |
| 4850 | script: __cell.script, |
| 4851 | entrypoint: name, |
| 4852 | props, |
| 4853 | }); |
| 4854 | return stub; |
| 4855 | }; |
| 4856 | // ---- stored stubs ---------------------------------------------- |
| 4857 | // Durable Object storage accepts only stubs with durable identity: |
| 4858 | // loopback service stubs (entrypoint name + props re-mint a fresh |
| 4859 | // stub on read) and Durable Object stubs (HMAC'd id + class revive |
| 4860 | // in any isolate). A transient handle -- a received RPC stub, a |
| 4861 | // function, an RpcTarget -- dies with its isolate; persisting its |
| 4862 | // entry id would revive garbage after a restart, so it is refused. |
| 4863 | // A stub-bearing row is written as 0x01 + clone(marker tree), off |
| 4864 | // the plain-clone fast path (the lift runs only after the plain |
| 4865 | // clone already threw, exactly like the RPC envelope). Reads hand |
| 4866 | // tagged rows to JS as [sentinel, tree]; the sentinel never leaves |
| 4867 | // this script and no user value can decode to it, so revival |
| 4868 | // cannot be spoofed by data shaped like a marker. |
| 4869 | const __storedSentinel = {}; |
| 4870 | const __storedLift = (value) => { |
| 4871 | let lifted = false; |
| 4872 | const seen = new Map(); |
| 4873 | const lift = (v) => { |
| 4874 | if (v === null || |
| 4875 | (typeof v !== "object" && typeof v !== "function")) return v; |
| 4876 | const cached = seen.get(v); |
| 4877 | if (cached !== undefined) return cached; |
| 4878 | // Ordering mirrors __stubLift: identify proxies by their |
| 4879 | // side tables and brands before touching any property -- a |
| 4880 | // stub or pipeline proxy answers every property read with a |
| 4881 | // fresh RpcProperty node. |
| 4882 | if (__stubMeta.has(v) || v instanceof __cf.RpcTarget) |
| 4883 | throw new DOMException( |
| 4884 | "Durable Object storage can only store stubs with " + |
| 4885 | "durable identity: service stubs from ctx.exports and " + |
| 4886 | "Durable Object stubs. This value is a transient RPC " + |
| 4887 | "handle that would not survive a restart.", |
| 4888 | "DataCloneError"); |
| 4889 | const svc = __svcMeta.get(v); |
| 4890 | if (svc !== undefined) { |
| 4891 | lifted = true; |
| 4892 | const marker = { "__celld$svc": svc.name }; |
| 4893 | seen.set(v, marker); |
| 4894 | if (svc.props !== undefined) marker.p = lift(svc.props); |
| 4895 | return marker; |
| 4896 | } |
| 4897 | if (v instanceof __cf.RpcPromise || |
| 4898 | v instanceof __cf.RpcProperty) |
| 4899 | throw new DOMException( |
| 4900 | 'Could not serialize object of type "' + |
| 4901 | (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + |
| 4902 | '". This type does not support serialization.', |
| 4903 | "DataCloneError"); |
| 4904 | if (typeof v === "function") return v; // leave to the clone |
| 4905 | const doId = __doStubMeta.get(v); |
| 4906 | if (doId !== undefined) { |
| 4907 | lifted = true; |
| 4908 | const marker = { "__celld$do": doId._className, |
| 4909 | v: doId._value, n: v.name ?? null }; |
| 4910 | seen.set(v, marker); |
| 4911 | return marker; |
| 4912 | } |
| 4913 | if (Array.isArray(v)) { |
| 4914 | const out = []; |
| 4915 | seen.set(v, out); |
| 4916 | for (let i = 0; i < v.length; i++) out[i] = lift(v[i]); |
| 4917 | return out; |
| 4918 | } |
| 4919 | const proto = Object.getPrototypeOf(v); |
| 4920 | if (proto !== Object.prototype && proto !== null) |
| 4921 | return v; // host/other: leave to the clone |
| 4922 | const out = {}; |
| 4923 | seen.set(v, out); |
| 4924 | for (const key of Object.keys(v)) out[key] = lift(v[key]); |
| 4925 | return out; |
| 4926 | }; |
| 4927 | const tree = lift(value); |
| 4928 | return lifted ? tree : null; |
| 4929 | }; |
| 4930 | // Encode one stub-bearing value for storage. Rethrows the original |
| 4931 | // clone error when nothing was liftable, so plain uncloneables |
| 4932 | // fail exactly as they always did. |
| 4933 | const __storedBytes = (value, error) => { |
| 4934 | const tree = __storedLift(value); |
| 4935 | if (tree === null) throw error; |
| 4936 | return __tagged(1, __sc_encode(tree)); |
| 4937 | }; |
| 4938 | const __storedRevive = (value) => { |
| 4939 | const seen = new Set(); |
| 4940 | const revive = (v) => { |
| 4941 | if (v === null || typeof v !== "object") return v; |
| 4942 | const svcName = v["__celld$svc"]; |
| 4943 | if (svcName !== undefined) |
| 4944 | return __entrypointStub(svcName, revive(v.p)); |
| 4945 | const doClass = v["__celld$do"]; |
| 4946 | if (doClass !== undefined) |
| 4947 | return __cell.makeNamespace(doClass).get( |
| 4948 | new DurableObjectId(doClass, v.v, v.n ?? undefined)); |
| 4949 | if (seen.has(v)) return v; |
| 4950 | seen.add(v); |
| 4951 | if (Array.isArray(v)) { |
| 4952 | for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); |
| 4953 | return v; |
| 4954 | } |
| 4955 | const proto = Object.getPrototypeOf(v); |
| 4956 | if (proto !== Object.prototype && proto !== null) return v; |
| 4957 | for (const key of Object.keys(v)) v[key] = revive(v[key]); |
| 4958 | return v; |
| 4959 | }; |
| 4960 | return revive(value); |
| 4961 | }; |
| 4962 | const __unwrapStored = (v) => |
| 4963 | Array.isArray(v) && v[0] === __storedSentinel |
| 4964 | ? __storedRevive(v[1]) : v; |
| 4965 | // A map result is wrapped as a whole only when it holds at least |
| 4966 | // one tagged row, so the per-entry walk never runs on plain data. |
| 4967 | const __unwrapStoredMap = (v) => { |
| 4968 | if (!Array.isArray(v) || v[0] !== __storedSentinel) return v; |
| 4969 | const map = v[1]; |
| 4970 | for (const [key, value] of map) |
| 4971 | map.set(key, __unwrapStored(value)); |
| 4972 | return map; |
| 4973 | }; |
| 4974 | // ctx.exports, as workerd's server builds it: a loopback stub for |
| 4975 | // `default` and each other entrypoint, a namespace for each exported |
| 4976 | // Durable Object class with storage, and a class, for facets, for |
| 4977 | // each other exported one. Built once, on first access -- ctx |
| 4978 | // construction itself only carries the getter. |
| 4979 | let __ctxExportsCache; |
| 4980 | const __ctxExports = () => __ctxExportsCache ??= (() => { |
| 4981 | const out = {}; |
| 4982 | for (const name of Object.keys(__cell.entrypoints)) |
| 4983 | out[name] = __entrypointStub(name, undefined); |
| 4984 | for (const name of Object.keys(__cell.objectEntrypoints)) |
| 4985 | out[name] = __entrypointStub(name, undefined); |
| 4986 | // Loader 0 is the script's own isolate: a facet of such a class runs |
| 4987 | // beside the object that holds it. |
| 4988 | for (const name of Object.keys(__cell.doExports)) { |
| 4989 | if (__runtimeClasses.has(name)) continue; |
| 4990 | out[name] = Object.hasOwn(__cell.namespaceKeys, name) |
| 4991 | ? __cell.makeNamespace(name) |
| 4992 | : __makeLoopbackDurableObjectClass(name); |
| 4993 | } |
| 4994 | return out; |
| 4995 | })(); |
| 4996 | // ---- RPC envelope ---------------------------------------------- |
| 4997 | // Serialize one payload. `lift` marks a same-isolate transport, |
| 4998 | // where stub-able values may cross as markers; elsewhere they stay |
| 4999 | // a DataCloneError, exactly as before stubs existed. |
| 5000 | const __rpcOut = (value, lift) => { |
| 5001 | const projected = __rpcProject(value); |
| 5002 | try { |
| 5003 | return __sc_encode(projected.tree); |
| 5004 | } catch (error) { |
| 5005 | // A cross-isolate call lifts only a live signal. A same-isolate call can |
| 5006 | // also transfer the existing host values and JS capability handles. |
| 5007 | const lifted = __stubLift(projected.tree, lift, projected.originals); |
| 5008 | if (lifted === null) throw __dataCloneError(error); |
| 5009 | try { |
| 5010 | return __tagged( |
| 5011 | lifted.caps ? 1 : 2, __sc_encode(lifted.tree)); |
| 5012 | } catch (error_) { |
| 5013 | throw __dataCloneError(error_); |
| 5014 | } |
| 5015 | } |
| 5016 | }; |
| 5017 | // A callee exception as tagged bytes: the Error crosses by value |
| 5018 | // (V8 serializes Error natively), custom own properties beside it. |
| 5019 | const __rpcErrOut = (error) => { |
| 5020 | // `name` rides in the props: V8 only round-trips the standard |
| 5021 | // Error subclass names, and e.g. DataCloneError must survive. |
| 5022 | const props = error instanceof Error |
| 5023 | ? { ...error, name: error.name } : {}; |
| 5024 | let sc; |
| 5025 | try { |
| 5026 | sc = __sc_encode([error, props]); |
| 5027 | } catch { |
| 5028 | const error_ = new Error(String(error?.message ?? error)); |
| 5029 | sc = __sc_encode([error_, { name: String(error?.name ?? "Error") }]); |
| 5030 | } |
| 5031 | return __tagged(0, sc); |
| 5032 | }; |
| 5033 | // The callee half of one RPC: run `body`, answer tagged bytes. |
| 5034 | const __rpcRun = async (body, lift) => { |
| 5035 | try { |
| 5036 | return __rpcOut(await body(), lift); |
| 5037 | } catch (error) { |
| 5038 | return __rpcErrOut(error); |
| 5039 | } |
| 5040 | }; |
| 5041 | const __rpcDesArgs = (bytes) => { |
| 5042 | if (bytes[0] === 0xff) |
| 5043 | return { args: __sc_decode(bytes), received: [] }; |
| 5044 | const revived = __stubRevive(__sc_decode(bytes.subarray(1))); |
| 5045 | return { args: revived.value, received: revived.handles }; |
| 5046 | }; |
| 5047 | // The caller half: decode a reply, rebuilding stubs and rethrowing |
| 5048 | // callee exceptions as real Errors with the callee's own |
| 5049 | // properties, `.remote`, and a local (caller-side) stack. |
| 5050 | const __rpcDes = (bytes) => { |
| 5051 | if (bytes[0] === 0xff) return __sc_decode(bytes); |
| 5052 | if (bytes[0] === 1 || bytes[0] === 2) { |
| 5053 | const { value, handles, disposers } = |
| 5054 | __stubRevive(__sc_decode(bytes.subarray(1))); |
| 5055 | if (value !== null && typeof value === "object" && |
| 5056 | !__stubMeta.has(value) && |
| 5057 | (handles.length > 0 || disposers.length > 0)) { |
| 5058 | Object.defineProperty(value, Symbol.dispose, { |
| 5059 | configurable: true, |
| 5060 | value: () => { |
| 5061 | for (const handle of handles) __disposeStub(handle); |
| 5062 | for (const entry of disposers) { |
| 5063 | __stubEntries.delete(entry.id); |
| 5064 | Promise.resolve().then(() => entry.target()); |
| 5065 | } |
| 5066 | }, |
| 5067 | }); |
| 5068 | } |
| 5069 | return value; |
| 5070 | } |
| 5071 | const [error, props] = __sc_decode(bytes.subarray(1)); |
| 5072 | if (error instanceof Error) { |
| 5073 | Object.assign(error, props); |
| 5074 | error.remote = true; |
| 5075 | const local = new Error().stack; |
| 5076 | error.stack = error.name + ": " + error.message + |
| 5077 | local.slice(local.indexOf("\n")); |
| 5078 | } |
| 5079 | throw error; |
| 5080 | }; |
| 5081 | // Deprecated Fetcher `get()`/`put()`/`delete()` HTTP helpers, kept by |
| 5082 | // the fetcher_has_get_put_delete compat flag (Workerd http.c++): |
| 5083 | // shortcuts for fetch() with the corresponding method. |
| 5084 | const __fetcherStatus = (res, method) => { |
| 5085 | if (res.status >= 200 && res.status < 300) return; |
| 5086 | throw new Error("HTTP " + method + " request failed: " + res.status + |
| 5087 | " " + (res.statusText || __STATUS_TEXT[res.status] || "")); |
| 5088 | }; |
| 5089 | const __fetcherHelper = (fetch, prop) => { |
| 5090 | if (prop === "get") return async (url, type) => { |
| 5091 | const res = await fetch(url, { method: "GET" }); |
| 5092 | if (res.status === 404 || res.status === 410) return null; |
| 5093 | __fetcherStatus(res, "GET"); |
| 5094 | if (type === "stream") |
| 5095 | return res.body ?? new ReadableStream({ start(c) { c.close(); } }); |
| 5096 | if (type === "arrayBuffer") return res.arrayBuffer(); |
| 5097 | if (type === "json") return res.json(); |
| 5098 | return res.text(); |
| 5099 | }; |
| 5100 | if (prop === "put") return async (url, body, options) => { |
| 5101 | const { expiration, expirationTtl } = options ?? {}; |
| 5102 | if (expiration !== undefined || expirationTtl !== undefined) { |
| 5103 | const url_ = new URL(url); |
| 5104 | if (expiration !== undefined) |
| 5105 | url_.searchParams.append("expiration", expiration); |
| 5106 | if (expirationTtl !== undefined) |
| 5107 | url_.searchParams.append("expiration_ttl", expirationTtl); |
| 5108 | url = url_.toString(); |
| 5109 | } |
| 5110 | __fetcherStatus(await fetch(url, { method: "PUT", body }), "PUT"); |
| 5111 | }; |
| 5112 | return async (url) => { |
| 5113 | __fetcherStatus(await fetch(url, { method: "DELETE" }), "DELETE"); |
| 5114 | }; |
| 5115 | }; |
| 5116 | function makeNamespace(className) { |
| 5117 | const namespaceKey = __cell.namespaceKeys[className]; |
| 5118 | if (typeof namespaceKey !== "string") |
| 5119 | throw new Error("no Durable Object namespace key for " + className); |
| 5120 | return new DurableObjectNamespace(className, namespaceKey); |
| 5121 | } |
| 5122 | // A named class: SDKs sniff bindings by constructor name (workers-rs |
| 5123 | // EnvBinding requires `constructor.name === "DurableObjectNamespace"`). |
| 5124 | class DurableObjectNamespace { |
| 5125 | constructor(className, namespaceKey) { |
| 5126 | Object.defineProperty(this, "_className", { value: className }); |
| 5127 | Object.defineProperty(this, "_namespaceKey", { value: namespaceKey }); |
| 5128 | } |
| 5129 | idFromName(name) { |
| 5130 | name = String(name); |
| 5131 | return new DurableObjectId( |
| 5132 | this._className, __do_id(this._namespaceKey, "name", name), name, |
| 5133 | ); |
| 5134 | } |
| 5135 | idFromString(value) { |
| 5136 | return new DurableObjectId( |
| 5137 | this._className, __do_id(this._namespaceKey, "validate", String(value)), |
| 5138 | ); |
| 5139 | } |
| 5140 | newUniqueId(options = {}) { |
| 5141 | const jurisdiction = options == null ? undefined : options.jurisdiction; |
| 5142 | if (jurisdiction != null) |
| 5143 | throw new Error("Jurisdiction restrictions are not implemented"); |
| 5144 | return new DurableObjectId( |
| 5145 | this._className, __do_id(this._namespaceKey, "unique", ""), |
| 5146 | ); |
| 5147 | } |
| 5148 | jurisdiction(value) { |
| 5149 | if (value == null) return this; |
| 5150 | throw new Error("Jurisdiction restrictions are not implemented"); |
| 5151 | } |
| 5152 | getByName(name, options) { |
| 5153 | return this.get(this.idFromName(name), options); |
| 5154 | } |
| 5155 | get(id) { |
| 5156 | const className = this._className; |
| 5157 | if (!(id instanceof DurableObjectId) || id._className !== className) |
| 5158 | throw new TypeError("Durable Object ID is not valid for this namespace"); |
| 5159 | const scope = id._scope(); |
| 5160 | // Emulate production: the actor recovers its name only when it is |
| 5161 | // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is |
| 5162 | // undefined. The full name still seeds the routing hash, so |
| 5163 | // dispatch is unchanged. Short names skip the byte count (< 256 |
| 5164 | // chars is always <= 1020 bytes) to keep the hot path alloc-free. |
| 5165 | const nm = id.name; |
| 5166 | const dispatchName = nm === undefined ? undefined |
| 5167 | : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024 |
| 5168 | ? nm : undefined; |
| 5169 | if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName; |
| 5170 | // Fetch and native RPC use the same host routing/activation seam. |
| 5171 | // Never expose `.then`: a DO stub is not itself a promise. |
| 5172 | const target = { id, name: dispatchName }; |
| 5173 | const abortMarker = "__CELLD_ACTOR_ABORT__:"; |
| 5174 | const processExitMarker = "__CELLD_PROCESS_EXIT__:"; |
| 5175 | let brokenReason = null; |
| 5176 | const invoke = async (operation) => { |
| 5177 | if (brokenReason !== null) throw new Error(brokenReason); |
| 5178 | try { |
| 5179 | return await operation(); |
| 5180 | } catch (error) { |
| 5181 | const routingError = __durableObjectRoutingError(error); |
| 5182 | if (routingError !== null) throw routingError; |
| 5183 | const message = String(error && error.message || error); |
| 5184 | const marker = [abortMarker, processExitMarker] |
| 5185 | .find((candidate) => message.includes(candidate)); |
| 5186 | if (!marker) throw error; |
| 5187 | brokenReason = message.slice(message.indexOf(marker) + marker.length); |
| 5188 | throw new Error(brokenReason); |
| 5189 | } |
| 5190 | }; |
| 5191 | const doFetch = async (input, init) => { |
| 5192 | const req = new Request(input, init); |
| 5193 | const signal = req._signalForSubrequests; |
| 5194 | if (signal?.aborted) throw signal.reason; |
| 5195 | // A body already backed by a host stream forwards to the cell as its |
| 5196 | // stream id, so a proxied upload to a cell on this node costs a chunk |
| 5197 | // rather than the whole body (#156). The host keeps it a stream for a |
| 5198 | // local cell and collects it only to sign a cross-node frame. A held |
| 5199 | // body -- or a stream with no host id -- crosses as its bytes. |
| 5200 | const bodyStreamId = |
| 5201 | req._bodyBytes === null && req.body && req.body.__celldStreamId !== undefined |
| 5202 | ? req.body.__celldStreamId |
| 5203 | : undefined; |
| 5204 | const body_ = bodyStreamId !== undefined |
| 5205 | ? new Uint8Array() |
| 5206 | : req._bodyBytes === null |
| 5207 | ? await req._consume() |
| 5208 | : req._bodyBytes; |
| 5209 | if (bodyStreamId !== undefined) { |
| 5210 | // The cell reads this upload through the same host stream id, so the |
| 5211 | // Worker's wrapper must not also read it: lock it (a late read throws |
| 5212 | // instead of racing the cell over one host stream) and mark it used, |
| 5213 | // which is what awaiting the old _consume() did and what workerd |
| 5214 | // reports as request.bodyUsed after the forward. |
| 5215 | req.bodyUsed = true; |
| 5216 | req.body.getReader(); |
| 5217 | } |
| 5218 | // Forward the request's headers to the cell as JSON. When they were |
| 5219 | // never materialized -- a Worker that only routes to a cell reads |
| 5220 | // none -- pass the raw header string straight through, so the whole |
| 5221 | // dispatch never builds a Headers object on either side. |
| 5222 | // |
| 5223 | // Both branches now carry the same shape. The raw string is the |
| 5224 | // wire list the host handed in, so the materialized branch must send |
| 5225 | // the header list too, not the iterator; see the note on the |
| 5226 | // outbound `fetch`. Reading `.headers` on a forwarded request used |
| 5227 | // to change what the cell received. |
| 5228 | const headersJson = req._headersJson !== undefined |
| 5229 | ? req._headersJson |
| 5230 | : JSON.stringify(req.headers.__celldHeaderList); |
| 5231 | const r = JSON.parse(await invoke(() => { |
| 5232 | if (!signal) return __do_call( |
| 5233 | scope, dispatchName ?? null, req.url, req.method, body_, |
| 5234 | headersJson, bodyStreamId, |
| 5235 | ); |
| 5236 | return __awaitCancellableDoCall( |
| 5237 | __do_call_cancellable( |
| 5238 | scope, dispatchName ?? null, req.url, req.method, body_, |
| 5239 | headersJson, bodyStreamId, |
| 5240 | ), |
| 5241 | signal, |
| 5242 | ); |
| 5243 | })); |
| 5244 | const body = r.streamId !== undefined |
| 5245 | ? new CelldHttpBodyStream(r.streamId) |
| 5246 | : r.body !== undefined |
| 5247 | ? r.body |
| 5248 | : Uint8Array.from(r.bodyBytes || []); |
| 5249 | // An upgrade the cell answered with. The pair straddles two isolates, |
| 5250 | // so the client end cannot be the peer object itself -- it is a new |
| 5251 | // socket the host joins to the cell's on `accept()`. A caller that |
| 5252 | // returns this response instead of accepting keeps the direct route |
| 5253 | // `__wsTarget` already describes, and binds nothing. |
| 5254 | return new Response(body, { |
| 5255 | status: r.status, |
| 5256 | headers: r.headers, |
| 5257 | __wsTarget: r.wsTarget, |
| 5258 | webSocket: r.status === 101 && r.wsTarget |
| 5259 | ? new WebSocket(undefined, [], r.wsTarget) |
| 5260 | : undefined, |
| 5261 | }); |
| 5262 | }; |
| 5263 | const stub = new Proxy(target, { get: (_target, prop) => { |
| 5264 | if (prop === "then") return undefined; |
| 5265 | if (Reflect.has(_target, prop)) return Reflect.get(_target, prop); |
| 5266 | if (prop === "fetch") return doFetch; |
| 5267 | if (typeof prop !== "string") return undefined; |
| 5268 | if (__cell.compat.fetcherGetPutDelete && |
| 5269 | (prop === "get" || prop === "put" || prop === "delete")) |
| 5270 | return __fetcherHelper(doFetch, prop); |
| 5271 | // Every cell RPC goes out through the host, whichever node owns the |
| 5272 | // target. Same-process dispatch re-enters this isolate, where the |
| 5273 | // abort and exit markers revive; bytes that land elsewhere revive as |
| 5274 | // loud foreign stubs. |
| 5275 | return async (...args) => invoke( |
| 5276 | async () => __rpcDes(await __rpc_call( |
| 5277 | scope, dispatchName ?? null, prop, __rpcOut(args, true), |
| 5278 | )), |
| 5279 | ); |
| 5280 | }}); |
| 5281 | __doStubMeta.set(stub, id); |
| 5282 | return stub; |
| 5283 | } |
| 5284 | } |
| 5285 | const __attachResponseRequestCancellation = ( |
| 5286 | response, |
| 5287 | requestController, |
| 5288 | wrapBody, |
| 5289 | ) => { |
| 5290 | if (!(response instanceof Response) || |
| 5291 | response._bodyBytes !== null || |
| 5292 | response.body === null) { |
| 5293 | return; |
| 5294 | } |
| 5295 | const requestControllers = Array.isArray( |
| 5296 | response.__celldRequestControllers, |
| 5297 | ) |
| 5298 | ? response.__celldRequestControllers |
| 5299 | : [requestController]; |
| 5300 | if (requestControllers !== response.__celldRequestControllers) { |
| 5301 | Object.defineProperty(response, "__celldRequestControllers", { |
| 5302 | value: requestControllers, |
| 5303 | }); |
| 5304 | } else { |
| 5305 | requestControllers.push(requestController); |
| 5306 | } |
| 5307 | if (!wrapBody || response.__celldCancellationWrapped) return; |
| 5308 | const reader = response.body.getReader(); |
| 5309 | response.body = new ReadableStream({ |
| 5310 | async pull(controller) { |
| 5311 | const result = await reader.read(); |
| 5312 | if (result.done) controller.close(); |
| 5313 | else controller.enqueue(result.value); |
| 5314 | }, |
| 5315 | async cancel() { |
| 5316 | const reason = new Error("The client has disconnected"); |
| 5317 | for (const controller of requestControllers) { |
| 5318 | if (!controller.signal.aborted) controller.abort(reason); |
| 5319 | } |
| 5320 | try { |
| 5321 | await reader.cancel(reason); |
| 5322 | } catch {} |
| 5323 | }, |
| 5324 | }, { highWaterMark: 0 }); |
| 5325 | Object.defineProperty(response, "__celldCancellationWrapped", { |
| 5326 | value: true, |
| 5327 | }); |
| 5328 | }; |
| 5329 | // called on the owner node by the /__do/<scope> endpoint: run one object. |
| 5330 | // Returns the Response; Rust's read_response unwraps it (don't double-wrap). |
| 5331 | // A top-level (non-actor) request whose signal can be aborted by id, so a |
| 5332 | // disconnected HTTP or service-binding caller reaches the target's |
| 5333 | // `request.signal`. |
| 5334 | // A large body, or a body of unknown length, arrives as a stream id and |
| 5335 | // not as bytes. The handler then pulls the body off the socket as it |
| 5336 | // reads, so the whole body is never resident. `request.body` is a stream |
| 5337 | // in both cases. |
| 5338 | __celld.__makeIncomingRequest = ( |
| 5339 | url, method, body, headersJson, streamId, |
| 5340 | ) => __makeRequest( |
| 5341 | url, method, |
| 5342 | streamId === undefined ? body : new CelldHttpBodyStream(streamId), |
| 5343 | headersJson, undefined, true); |
| 5344 | const __dispatchTo = __celld.__dispatchTo = async ( |
| 5345 | scope, url, method, body, headersJson, requestId = null, bodyStreamId = null, |
| 5346 | ) => { |
| 5347 | // A routed body that must not be collected crosses as a host stream id; the |
| 5348 | // handler here reads it in parts. A held body arrives as its bytes. |
| 5349 | if (bodyStreamId !== null) body = new CelldHttpBodyStream(bodyStreamId); |
| 5350 | // Request already allocates a default controller for an absent signal. |
| 5351 | // Retain that same allocation so a streamed response can report reader |
| 5352 | // cancellation after the handler has returned. |
| 5353 | const requestController = new AbortController(); |
| 5354 | if (requestId !== null) |
| 5355 | __incomingRequestSignals.set( |
| 5356 | String(requestId), requestController.signal); |
| 5357 | const actorEvent = __beginActorEvent(scope); |
| 5358 | try { |
| 5359 | const dispatch = (async () => { |
| 5360 | const inst = await _readyInstance(scope); |
| 5361 | return await __ctxRun(undefined, () => inst.fetch( |
| 5362 | __makeRequest( |
| 5363 | url, |
| 5364 | method, |
| 5365 | body, |
| 5366 | headersJson, |
| 5367 | requestController.signal, |
| 5368 | true, |
| 5369 | ))); |
| 5370 | })(); |
| 5371 | // The caller's abandonment reaches the target through |
| 5372 | // __do_call_cancel/__abortIncomingRequest, which aborts the fresh incoming |
| 5373 | // signal made above; the host dispatcher passes no caller signal here. |
| 5374 | const response = await dispatch; |
| 5375 | // Not wrapped: the host holds this response and gates it, and the caller |
| 5376 | // that would cancel the body reaches it through the routed channel's own |
| 5377 | // controller rather than this one. |
| 5378 | __attachResponseRequestCancellation(response, requestController, false); |
| 5379 | if (response instanceof Response && response.status === 101 && |
| 5380 | response.webSocket && !response.webSocket._target) { |
| 5381 | const socket = response.webSocket._peer; |
| 5382 | const target = { id: response.webSocket._id, scope }; |
| 5383 | response.webSocket._target = target; |
| 5384 | if (socket) { |
| 5385 | socket._target = target; |
| 5386 | if (!socket._hibernatable) |
| 5387 | __ws_accept_regular(socket._id, scope); |
| 5388 | __sockets.set(socket._id, socket); |
| 5389 | socket._flushPending(); |
| 5390 | } |
| 5391 | } |
| 5392 | return response; |
| 5393 | } finally { |
| 5394 | if (requestId !== null) |
| 5395 | __incomingRequestSignals.delete(String(requestId)); |
| 5396 | __endActorEvent(actorEvent); |
| 5397 | } |
| 5398 | }; |
| 5399 | const __rpcTargetMethod = async (scope, method) => { |
| 5400 | const inst = await _readyInstance(scope); |
| 5401 | if (!inst.__celldState._rpcOk) |
| 5402 | throw new TypeError( |
| 5403 | "The receiving Durable Object does not support RPC, because " + |
| 5404 | "its class was not declared with `extends DurableObject`. In " + |
| 5405 | "order to enable RPC, make sure your class extends the " + |
| 5406 | "special class `DurableObject`, which can be imported from " + |
| 5407 | "the module \"cloudflare:workers\"."); |
| 5408 | const fn = inst[method]; |
| 5409 | if (typeof fn !== "function") |
| 5410 | throw new TypeError(method + " is not a function"); |
| 5411 | return [inst, fn]; |
| 5412 | }; |
| 5413 | // The byte path always lifts stub-able values into the reply: the |
| 5414 | // markers carry the isolate token, so they revive only back in this |
| 5415 | // isolate (same-process routed dispatch re-enters it) and fail loudly |
| 5416 | // on use anywhere else. Callee exceptions cross in |
| 5417 | // the error envelope on every flavor. |
| 5418 | __celld.__dispatchRpc = async (scope, method, args) => { |
| 5419 | const actorEvent = __beginActorEvent(scope); |
| 5420 | try { |
| 5421 | // A string is the legacy JSON flavor; bytes are V8 structured clone. |
| 5422 | // Answer in kind. |
| 5423 | if (typeof args === "string") { |
| 5424 | const [inst, fn] = await __rpcTargetMethod(scope, method); |
| 5425 | const result = await fn.apply(inst, JSON.parse(args)); |
| 5426 | return JSON.stringify(result) ?? "null"; |
| 5427 | } |
| 5428 | return await __ctxRun(undefined, () => (async () => { |
| 5429 | const decoded = __rpcDesArgs(args); |
| 5430 | try { |
| 5431 | return await __rpcRun(async () => { |
| 5432 | // A broken actor (JS-flavored ctx.abort) rejects every |
| 5433 | // later call with the reason. One gated field read. |
| 5434 | if (__brokenActors.size !== 0) { |
| 5435 | const broken = __brokenActors.get(scope); |
| 5436 | if (broken !== undefined) throw broken; |
| 5437 | } |
| 5438 | const [inst, fn] = await __rpcTargetMethod(scope, method); |
| 5439 | return fn.apply(inst, decoded.args); |
| 5440 | }, true); |
| 5441 | } finally { |
| 5442 | for (const handle of decoded.received) __disposeStub(handle); |
| 5443 | } |
| 5444 | })()); |
| 5445 | } finally { |
| 5446 | __endActorEvent(actorEvent); |
| 5447 | } |
| 5448 | }; |
| 5449 | const __entrypointClass = (name) => { |
| 5450 | const cls = __cell.entrypoints[name]; |
| 5451 | if (typeof cls !== "function") { |
| 5452 | // Workerd getExportedHandler(): distinguish a Durable Object class |
| 5453 | // misused as a stateless entrypoint from a name that resolves to |
| 5454 | // nothing. Error path only; both lookups are O(1). |
| 5455 | if (__cell.classes[name] !== undefined || __cell.doExports[name]) |
| 5456 | throw new TypeError( |
| 5457 | `The entrypoint name ${name} refers to a Durable Object ` + |
| 5458 | "class, but the incoming request is trying to invoke it as " + |
| 5459 | "a stateless worker."); |
| 5460 | throw new TypeError( |
| 5461 | `The entrypoint name ${name} was not found in this worker. ` + |
| 5462 | "Ensure the worker exports an entrypoint with that name."); |
| 5463 | } |
| 5464 | return cls; |
| 5465 | }; |
| 5466 | // End the construction event immediately: ctx.waitUntil registers into |
| 5467 | // whichever event is current at call time, so leaving this event on the |
| 5468 | // stack would swallow every later registration in the isolate. The drain that |
| 5469 | // the event yields moves to the enclosing event, because a ctx.waitUntil() |
| 5470 | // call inside a constructor is otherwise fire-and-forget: the RPC reply can |
| 5471 | // answer and the request context can tear down before that work runs. |
| 5472 | // __wait_until drops the drain when no event encloses this one, which is the |
| 5473 | // isolate-startup case and matches the older behavior. |
| 5474 | const __constructEntrypoint = (cls, props) => { |
| 5475 | const ctx = __beginEvent(props); |
| 5476 | try { |
| 5477 | return new cls(ctx, __cell.env); |
| 5478 | } finally { |
| 5479 | const drain = __endEvent(); |
| 5480 | if (drain !== null) __wait_until(drain); |
| 5481 | } |
| 5482 | }; |
| 5483 | // A stateless Worker invocation owns one class instance and its constructor |
| 5484 | // context. Reusing either across invocations leaks class fields and request |
| 5485 | // authority, while constructing more than once inside one invocation splits |
| 5486 | // work that Cloudflare delivers to one receiver. |
| 5487 | const __newEntrypointInstance = (name, props) => |
| 5488 | __constructEntrypoint(__entrypointClass(name), props); |
| 5489 | // `env.NAME.fetch()` where NAME is bound with `entrypoint = "..."` goes |
| 5490 | // to that class's fetch, not the module's default export. A plain |
| 5491 | // object export (Workerd's non-class entrypoint) dispatches its |
| 5492 | // handler functions as fn(arg, env, ctx). |
| 5493 | // A missing fetch reports workerd's own text, the same one the loader |
| 5494 | // installs for a Worker with no default export, so the two paths agree. |
| 5495 | const __noHandler = (name, method) => |
| 5496 | method === "fetch" && name === "default" |
| 5497 | ? new Error("Handler does not export a fetch() function.") |
| 5498 | : new TypeError( |
| 5499 | `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); |
| 5500 | |
| 5501 | const __dispatchEntrypointMethod = async (name, method, arg, props) => { |
| 5502 | const handler = __cell.objectEntrypoints[name]; |
| 5503 | if (handler !== undefined) { |
| 5504 | if (typeof handler[method] !== "function") |
| 5505 | throw __noHandler(name, method); |
| 5506 | const ctx = __beginEvent(props); |
| 5507 | try { |
| 5508 | return await __ctxRun(undefined, |
| 5509 | () => handler[method](arg, __cell.env, ctx)); |
| 5510 | } finally { |
| 5511 | __endEvent(); |
| 5512 | } |
| 5513 | } |
| 5514 | // A class entrypoint's methods get env and ctx from its constructor, |
| 5515 | // not as arguments. |
| 5516 | const inst = __newEntrypointInstance(name, props); |
| 5517 | if (typeof inst[method] !== "function") |
| 5518 | throw __noHandler(name, method); |
| 5519 | return await __ctxRun(undefined, () => inst[method](arg)); |
| 5520 | }; |
| 5521 | // Invoke a handler inside the event frame that the host already opened. A |
| 5522 | // Queue dispatch uses this form because its host driver must receive and keep |
| 5523 | // driving the handler's waitUntil aggregate after the settlement is returned. |
| 5524 | const __dispatchEntrypointMethodInCurrentEvent = async (name, method, arg) => { |
| 5525 | const handler = __cell.objectEntrypoints[name]; |
| 5526 | if (handler !== undefined) { |
| 5527 | if (typeof handler[method] !== "function") |
| 5528 | throw __noHandler(name, method); |
| 5529 | return await __ctxRun(undefined, |
| 5530 | () => handler[method](arg, __cell.env, __entrypointContext())); |
| 5531 | } |
| 5532 | const inst = __newEntrypointInstance(name, undefined); |
| 5533 | if (typeof inst[method] !== "function") |
| 5534 | throw __noHandler(name, method); |
| 5535 | return await __ctxRun(undefined, () => inst[method](arg)); |
| 5536 | }; |
| 5537 | const __dispatchEntrypointFetch = __celld.__dispatchEntrypointFetch = |
| 5538 | (name, request, propsSc = null) => |
| 5539 | __dispatchEntrypointMethod( |
| 5540 | name, "fetch", request, |
| 5541 | propsSc === null || propsSc.length === 0 |
| 5542 | ? undefined : __sc_decode(propsSc)); |
| 5543 | __celld.__dispatchEntrypointScheduled = (name, ctrl) => |
| 5544 | __dispatchEntrypointMethod(name, "scheduled", ctrl); |
| 5545 | // A queue batch owns mutable settlement state only while its handler runs. |
| 5546 | // Keeping a batch alive after dispatch must not keep authority to settle its |
| 5547 | // lease, because that lease can have expired and been handed out again. |
| 5548 | __celld.__dispatchEntrypointQueue = async (name, incoming) => { |
| 5549 | let active = true; |
| 5550 | let ackAll = false; |
| 5551 | const explicitAcks = new Set(); |
| 5552 | const retries = new Map(); |
| 5553 | const retryBatch = { retry: false, delaySeconds: undefined }; |
| 5554 | const checkActive = () => { |
| 5555 | if (!active) |
| 5556 | throw new Error("Queue event methods cannot be called after the handler returns."); |
| 5557 | }; |
| 5558 | const retryDelay = (options) => { |
| 5559 | const value = options?.delaySeconds; |
| 5560 | if (value === undefined) return undefined; |
| 5561 | if (!Number.isInteger(value) || value < -0x8000_0000 || value > 0x7fff_ffff) |
| 5562 | throw new TypeError("delaySeconds must be a 32-bit integer"); |
| 5563 | return value; |
| 5564 | }; |
| 5565 | const decode = (message) => { |
| 5566 | switch (message.contentType) { |
| 5567 | case "text": return new TextDecoder().decode(message.body); |
| 5568 | case "bytes": return message.body; |
| 5569 | case "json": return JSON.parse(new TextDecoder().decode(message.body)); |
| 5570 | case "v8": return __sc_decode(message.body); |
| 5571 | default: throw new TypeError(`Unknown queue content type: ${message.contentType}`); |
| 5572 | } |
| 5573 | }; |
| 5574 | const messages = incoming.messages.map((message) => ({ |
| 5575 | id: message.id, |
| 5576 | timestamp: new Date(message.timestamp), |
| 5577 | body: decode(message), |
| 5578 | attempts: message.attempts, |
| 5579 | ack() { |
| 5580 | checkActive(); |
| 5581 | if (ackAll || retryBatch.retry || retries.has(message.id)) return; |
| 5582 | explicitAcks.add(message.id); |
| 5583 | }, |
| 5584 | retry(options) { |
| 5585 | checkActive(); |
| 5586 | if (ackAll || explicitAcks.has(message.id)) return; |
| 5587 | const delaySeconds = retryDelay(options); |
| 5588 | if (delaySeconds !== undefined || !retries.has(message.id)) |
| 5589 | retries.set(message.id, delaySeconds); |
| 5590 | }, |
| 5591 | })); |
| 5592 | const oldest = incoming.metrics.oldestMessageTimestamp; |
| 5593 | const batch = { |
| 5594 | queue: incoming.queue, |
| 5595 | messages, |
| 5596 | metadata: { |
| 5597 | metrics: { |
| 5598 | backlogCount: incoming.metrics.backlogCount, |
| 5599 | backlogBytes: incoming.metrics.backlogBytes, |
| 5600 | oldestMessageTimestamp: oldest === undefined ? undefined : new Date(oldest), |
| 5601 | }, |
| 5602 | }, |
| 5603 | ackAll() { |
| 5604 | checkActive(); |
| 5605 | if (!retryBatch.retry) ackAll = true; |
| 5606 | }, |
| 5607 | retryAll(options) { |
| 5608 | checkActive(); |
| 5609 | if (ackAll) return; |
| 5610 | retryBatch.retry = true; |
| 5611 | const delaySeconds = retryDelay(options); |
| 5612 | if (delaySeconds !== undefined) retryBatch.delaySeconds = delaySeconds; |
| 5613 | }, |
| 5614 | }; |
| 5615 | let outcome = "ok"; |
| 5616 | let errorText; |
| 5617 | try { |
| 5618 | await __dispatchEntrypointMethodInCurrentEvent(name, "queue", batch); |
| 5619 | } catch (error) { |
| 5620 | // A handler exception retries the batch but keeps explicit acks that the |
| 5621 | // handler made before it threw. The caller needs both facts together. |
| 5622 | outcome = "exception"; |
| 5623 | try { |
| 5624 | errorText = String(error); |
| 5625 | } catch { |
| 5626 | errorText = "queue handler rejected"; |
| 5627 | } |
| 5628 | } finally { |
| 5629 | active = false; |
| 5630 | } |
| 5631 | return { |
| 5632 | outcome, |
| 5633 | error: errorText, |
| 5634 | ackAll, |
| 5635 | retryBatch, |
| 5636 | explicitAcks: [...explicitAcks], |
| 5637 | retryMessages: [...retries].map(([msgId, delaySeconds]) => ({ |
| 5638 | msgId, |
| 5639 | delaySeconds, |
| 5640 | })), |
| 5641 | }; |
| 5642 | }; |
| 5643 | // Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class |
| 5644 | // handler method is called as fn(arg, env, ctx), the client must send |
| 5645 | // exactly one argument, and the handler must not declare more than |
| 5646 | // (arg, env, ctx). The messages are Workerd's, verbatim. |
| 5647 | const __callObjectEntrypoint = (handler, method, args, props) => { |
| 5648 | const fn = handler[method]; |
| 5649 | if (typeof fn !== "function") |
| 5650 | throw new TypeError( |
| 5651 | 'The RPC receiver does not implement the method "' + method + |
| 5652 | '".'); |
| 5653 | if (fn.length > 3) |
| 5654 | throw new TypeError( |
| 5655 | 'Cannot call handler function "' + method + '" over RPC ' + |
| 5656 | "because it has the wrong number of arguments. A simple " + |
| 5657 | "function handler can only be called over RPC if it has " + |
| 5658 | "exactly the arguments (arg, env, ctx), where only the first " + |
| 5659 | "argument comes from the client. To support multi-argument " + |
| 5660 | "RPC functions, use class-based syntax (extending " + |
| 5661 | "WorkerEntrypoint) instead."); |
| 5662 | if (args.length !== 1) |
| 5663 | throw new TypeError( |
| 5664 | 'Attempted to call RPC function "' + method + '" with the ' + |
| 5665 | "wrong number of arguments. When calling a top-level handler " + |
| 5666 | "function that is not declared as part of a class, you must " + |
| 5667 | "always send exactly one argument. In order to support " + |
| 5668 | "variable numbers of arguments, the server must use " + |
| 5669 | "class-based syntax (extending WorkerEntrypoint) instead."); |
| 5670 | return fn.call(handler, args[0], __cell.env, __entrypointContext(props)); |
| 5671 | }; |
| 5672 | let __nextPendingEventId = 1; |
| 5673 | const __pendingEvents = new Map(); |
| 5674 | const __pendingEventError = () => new Error( |
| 5675 | "The Workers runtime canceled this request because it detected that " + |
| 5676 | "your Worker's code had hung and would never generate a response. " + |
| 5677 | "Refer to: https://developers.cloudflare.com/workers/observability/errors/"); |
| 5678 | // The host calls this only when the request has no native operation that can |
| 5679 | // resume JavaScript. Reject the entrypoint call itself, so its caller can |
| 5680 | // catch the cancellation and continue the enclosing event. |
| 5681 | __celld.__cancelPendingEvents = (ids) => { |
| 5682 | for (const id of ids) __pendingEvents.get(id)?.(__pendingEventError()); |
| 5683 | }; |
| 5684 | // One entrypoint op (a call, or a property GET when argsSc is |
| 5685 | // null), inside a fresh request context -- the callee owns stubs |
| 5686 | // revived from its params, and stubs it mints belong to it. |
| 5687 | // `props` is the caller's per-stub props (Workerd's |
| 5688 | // getEntrypoint(name, { props })); undefined leaves the entrypoint's |
| 5689 | // default empty props. |
| 5690 | const __entrypointOp = (name, path, argsSc, local, makeInst, props) => { |
| 5691 | const id = __nextCtxId++; |
| 5692 | return __ctxRun(id, () => { |
| 5693 | const pendingId = __nextPendingEventId++; |
| 5694 | let cancel; |
| 5695 | const cancellation = new Promise((_, reject) => { cancel = reject; }); |
| 5696 | __pendingEvents.set(pendingId, cancel); |
| 5697 | __pending_event_begin(pendingId); |
| 5698 | const running = (async () => { |
| 5699 | const decoded = argsSc === null ? null : __rpcDesArgs(argsSc); |
| 5700 | let drain = null; |
| 5701 | try { |
| 5702 | const reply = await __rpcRun(async () => { |
| 5703 | // The handler's synchronous part runs inside its own event so |
| 5704 | // ctx.waitUntil and the imported waitUntil have a target. The |
| 5705 | // event pops before the first await -- the event stack is |
| 5706 | // strictly LIFO and an event held across an await would be |
| 5707 | // popped by whichever event settles next -- and its registered |
| 5708 | // work drains before a plain reply (below). |
| 5709 | __beginEvent(); |
| 5710 | let result; |
| 5711 | try { |
| 5712 | const handler = __cell.objectEntrypoints[name]; |
| 5713 | if (handler !== undefined && makeInst === undefined) { |
| 5714 | // Simple-handler entrypoints expose single-method calls |
| 5715 | // only; property GETs and deeper paths are refused. |
| 5716 | if (argsSc === null || path.length !== 1) |
| 5717 | throw __rpcNoSuchMethod(path[0]); |
| 5718 | result = __callObjectEntrypoint( |
| 5719 | handler, path[0], decoded.args, props); |
| 5720 | } else { |
| 5721 | // A loopback stub with props retains one instance for that RPC |
| 5722 | // session. Each ordinary top-level operation constructs once here, |
| 5723 | // so neither its fields nor its constructor context reach the next |
| 5724 | // invocation. |
| 5725 | const inst = makeInst !== undefined ? makeInst() |
| 5726 | : __newEntrypointInstance(name, props); |
| 5727 | result = __rpcWalk(inst, path, |
| 5728 | decoded === null ? null : decoded.args, true); |
| 5729 | } |
| 5730 | } finally { |
| 5731 | drain = __endEvent(); |
| 5732 | } |
| 5733 | return await result; |
| 5734 | }, local); |
| 5735 | // Registered work drains before a plain reply. A |
| 5736 | // capability-bearing reply (tag 1) must not wait: a returned |
| 5737 | // stream's chunks may be produced by that very work, which |
| 5738 | // cannot finish until the caller pulls (returnReadableStream's |
| 5739 | // waitUntil writer would deadlock behind its own reply). |
| 5740 | if (reply[0] !== 1 && drain !== null) await drain; |
| 5741 | // ctx.abort() during the call supersedes its result; the raw |
| 5742 | // reason rejects the caller (same isolate -- identity holds). |
| 5743 | if (__abortedCtxs.size !== 0) { |
| 5744 | const reason = __abortedCtxs.get(id); |
| 5745 | if (reason !== undefined) throw reason; |
| 5746 | } |
| 5747 | // A reply that exports no stubs (tag 0xff plain, tag 0 error) |
| 5748 | // leaves nothing rooting this context: tear it down now, so a |
| 5749 | // dup() the callee leaked reaches its disposal callback |
| 5750 | // promptly (Workerd tears the IoContext down at call end |
| 5751 | // unless returned capabilities hold it open). |
| 5752 | if (reply[0] !== 1) __ctxEnd(id); |
| 5753 | return reply; |
| 5754 | } finally { |
| 5755 | if (decoded !== null) |
| 5756 | for (const handle of decoded.received) __disposeStub(handle); |
| 5757 | } |
| 5758 | })(); |
| 5759 | return Promise.race([running, cancellation]).finally(() => { |
| 5760 | __pendingEvents.delete(pendingId); |
| 5761 | __pending_event_end(pendingId); |
| 5762 | }); |
| 5763 | }); |
| 5764 | }; |
| 5765 | // Cross-isolate service callers pass a complete property path. Older host |
| 5766 | // callers can still pass one method name, which becomes a one-part path. |
| 5767 | // `propsSc` carries getEntrypoint(name, {props}) as structured-clone bytes, |
| 5768 | // the same encoding as `argsSc`. It is empty when the caller sent no props, |
| 5769 | // which no encoded value can be, so an empty buffer is an unambiguous absent. |
| 5770 | __celld.__dispatchEntrypointRpc = |
| 5771 | (name, path, argsSc, local = false, propsSc = null) => __entrypointOp( |
| 5772 | name, typeof path === "string" ? [path] : path, argsSc, local, |
| 5773 | undefined, |
| 5774 | propsSc === null || propsSc.length === 0 |
| 5775 | ? undefined : __sc_decode(propsSc)); |
| 5776 | // WebSocket: the host holds the socket; these deliver events into the DO. |
| 5777 | // `ws` is a lightweight stub whose send/close route back to the host task |
| 5778 | // by wsId -- so the isolate can be hibernated between messages. |
| 5779 | const __wsStub = __celld.__wsStub = (wsId) => ({ |
| 5780 | _hibernatable: true, |
| 5781 | send: (data) => { |
| 5782 | if (data instanceof ArrayBuffer) |
| 5783 | __ws_send_binary(wsId, new Uint8Array(data)); |
| 5784 | else if (ArrayBuffer.isView(data)) |
| 5785 | __ws_send_binary(wsId, |
| 5786 | new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); |
| 5787 | else |
| 5788 | __ws_send(wsId, String(data)); |
| 5789 | }, |
| 5790 | close: (code = 1000, reason = "") => __ws_close(wsId, code, reason), |
| 5791 | }); |
| 5792 | __celld.__wsOpen = async (scope, wsId, protocol) => { |
| 5793 | const actorEvent = __beginActorEvent(scope); |
| 5794 | try { |
| 5795 | const inst = await _readyInstance(scope); |
| 5796 | const socket = inst.__celldState._socket(wsId); |
| 5797 | if (socket.readyState !== WebSocket.READY_STATE_CONNECTING) return; |
| 5798 | socket.protocol = protocol; |
| 5799 | socket.readyState = WebSocket.READY_STATE_OPEN; |
| 5800 | socket.dispatchEvent(new Event("open")); |
| 5801 | } finally { |
| 5802 | __endActorEvent(actorEvent); |
| 5803 | } |
| 5804 | }; |
| 5805 | __celld.__wsMessage = async (scope, wsId, msg) => { |
| 5806 | const actorEvent = __beginActorEvent(scope); |
| 5807 | try { |
| 5808 | const inst = await _readyInstance(scope); |
| 5809 | const socket = inst.__celldState._socket(wsId); |
| 5810 | if (!socket._hibernatable && typeof socket._dispatchMessage === "function") |
| 5811 | socket._dispatchMessage(msg); |
| 5812 | else if (typeof inst.webSocketMessage === "function") |
| 5813 | await inst.webSocketMessage(socket, msg); |
| 5814 | } finally { |
| 5815 | __endActorEvent(actorEvent); |
| 5816 | } |
| 5817 | }; |
| 5818 | __celld.__wsBinary = async (scope, wsId, data) => { |
| 5819 | const actorEvent = __beginActorEvent(scope); |
| 5820 | try { |
| 5821 | const inst = await _readyInstance(scope); |
| 5822 | const socket = inst.__celldState._socket(wsId); |
| 5823 | const bytes = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); |
| 5824 | if (!socket._hibernatable && typeof socket._dispatchMessage === "function") |
| 5825 | socket._dispatchMessage(bytes); |
| 5826 | else if (typeof inst.webSocketMessage === "function") |
| 5827 | await inst.webSocketMessage(socket, bytes); |
| 5828 | } finally { |
| 5829 | __endActorEvent(actorEvent); |
| 5830 | } |
| 5831 | }; |
| 5832 | __celld.__wsClosed = async (scope, wsId, code, reason, wasClean) => { |
| 5833 | const actorEvent = __beginActorEvent(scope); |
| 5834 | try { |
| 5835 | const inst = await _readyInstance(scope); |
| 5836 | const socket = inst.__celldState._socket(wsId); |
| 5837 | if (!socket._hibernatable && typeof socket._dispatchClose === "function") |
| 5838 | socket._dispatchClose(code, reason, wasClean); |
| 5839 | else if (!wasClean && typeof inst.webSocketError === "function") |
| 5840 | // A hibernatable socket reports an abnormal closure through |
| 5841 | // webSocketError, which celld listed as a handler name and never |
| 5842 | // called. |
| 5843 | await inst.webSocketError( |
| 5844 | socket, |
| 5845 | new Error(reason ? `WebSocket closed abnormally: ${reason}` : "WebSocket closed abnormally"), |
| 5846 | ); |
| 5847 | else if (typeof inst.webSocketClose === "function") |
| 5848 | await inst.webSocketClose(socket, code, reason, wasClean); |
| 5849 | } finally { |
| 5850 | __endActorEvent(actorEvent); |
| 5851 | } |
| 5852 | }; |
| 5853 | // called by celld's scheduler when an alarm is due. Returns a promise. |
| 5854 | __celld.__fireAlarm = async (scope, scheduledTime, retryCount) => { |
| 5855 | const actorEvent = __beginActorEvent(scope); |
| 5856 | try { |
| 5857 | const inst = await _readyInstance(scope); |
| 5858 | if (typeof inst.alarm !== "function") return; |
| 5859 | await inst.alarm({ scheduledTime, retryCount, isRetry: retryCount > 0 }); |
| 5860 | } finally { |
| 5861 | __endActorEvent(actorEvent); |
| 5862 | } |
| 5863 | }; |
| 5864 | // The reserved cron cell. It is not a user class: celld registers it under |
| 5865 | // `.cron` for every deployment that declares `triggers.crons`, and one cell |
| 5866 | // per script carries that script's whole schedule. Ownership CAS on that one |
| 5867 | // name is what makes a cron trigger fire once per fleet rather than once per |
| 5868 | // node -- the same arbiter an alarm already relies on, with nothing added. |
| 5869 | // |
| 5870 | // The schedule itself is never stored here. `__cell.crons` comes from the |
| 5871 | // deployment the cell is running under, so changing a cron expression takes |
| 5872 | // effect on the next activation and needs no migration of an armed alarm. |
| 5873 | class CelldCronSchedule { |
| 5874 | constructor(state) { |
| 5875 | this._state = state; |
| 5876 | // Failures within one occurrence. Held in memory on purpose: losing the |
| 5877 | // count to an eviction only makes the next retry sooner, and every retry |
| 5878 | // is capped at the next occurrence anyway, so it need not be durable. |
| 5879 | this._retry = 0; |
| 5880 | // What a pending retry owes: the occurrence, the expressions of it that |
| 5881 | // failed, and the deadline the retry was armed for. A retry deadline is a |
| 5882 | // backoff instant and not an occurrence, so nothing about it can be |
| 5883 | // recovered from the deadline itself -- without this record the wake |
| 5884 | // matches no expression, runs nothing, and drops the failed tick in |
| 5885 | // silence. Held in memory beside `_retry` and for the same reason: an |
| 5886 | // eviction costs the retry, never the next occurrence. |
| 5887 | this._owed = null; |
| 5888 | } |
| 5889 | // celld calls this once per node after a deployment loads, because a cron |
| 5890 | // cell has no client to wake it. Arming is idempotent -- the same schedule |
| 5891 | // and the same clock give the same answer -- so it does not matter which |
| 5892 | // node wins the cell. |
| 5893 | async fetch() { |
| 5894 | // A pending retry is a deadline this cell already owes, and re-arming |
| 5895 | // would move it to the next occurrence and lose the tick it owes with it. |
| 5896 | if (this._owed !== null) return new Response(null, { status: 204 }); |
| 5897 | const armed = await this._state.storage.getAlarm(); |
| 5898 | // An alarm already due is a tick that is late, not one that is wrong. |
| 5899 | // Leaving it alone is what makes a fleet that was down fire the missed |
| 5900 | // occurrence once, instead of skipping it by re-arming into the future. |
| 5901 | if (armed === null || armed > Date.now()) await this._arm(null, [], false); |
| 5902 | return new Response(null, { status: 204 }); |
| 5903 | } |
| 5904 | async alarm(info) { |
| 5905 | const crons = __cell.crons || []; |
| 5906 | // A retry wake carries the backoff instant as its deadline, so what to run |
| 5907 | // and what time to report both come from the record the failure left. Only |
| 5908 | // a deadline that is not a retry is an occurrence to match against. |
| 5909 | const owed = this._owed !== null && this._owed.armedFor === info.scheduledTime |
| 5910 | ? this._owed |
| 5911 | : null; |
| 5912 | const occurrence = owed === null ? info.scheduledTime : owed.at; |
| 5913 | // One deadline can belong to several expressions, and each is its own |
| 5914 | // invocation with its own controller.cron, as on Cloudflare. A retry |
| 5915 | // repeats only the expressions that failed, because the ones that |
| 5916 | // succeeded already ran for this occurrence. |
| 5917 | const due = owed === null |
| 5918 | ? __cron_plan(crons, info.scheduledTime, Date.now(), 0, false).matching |
| 5919 | : owed.indices; |
| 5920 | const failed = []; |
| 5921 | for (const index of due) { |
| 5922 | let noRetry = false; |
| 5923 | const controller = { |
| 5924 | // The occurrence, never the instant this attempt started, so a late |
| 5925 | // run and a retry both report the minute they were scheduled for. |
| 5926 | scheduledTime: occurrence, |
| 5927 | cron: crons[index], |
| 5928 | noRetry() { noRetry = true; }, |
| 5929 | }; |
| 5930 | const ctx = __beginEvent(); |
| 5931 | try { |
| 5932 | if (typeof __cell.selfScheduled !== "function") |
| 5933 | throw new Error( |
| 5934 | "a cron trigger needs the Worker to export a `scheduled` handler"); |
| 5935 | await __cell.selfScheduled(controller, __cell.env, ctx); |
| 5936 | } catch (error) { |
| 5937 | // Swallowed on purpose: this handler owns the re-arm below, so |
| 5938 | // throwing would hand the deadline to the generic alarm retry and |
| 5939 | // lose the next occurrence with it. |
| 5940 | console.error( |
| 5941 | `scheduled handler for cron ${JSON.stringify(crons[index])} failed:`, |
| 5942 | error); |
| 5943 | if (!noRetry) failed.push(index); |
| 5944 | } finally { |
| 5945 | const drain = __endEvent(); |
| 5946 | // The alarm turn is the only host owner for this scheduled event. |
| 5947 | // Dropping its drain lets the actor turn end with waitUntil work still |
| 5948 | // pending, so an I/O promise can remain unresolved forever. |
| 5949 | if (drain !== null) await drain; |
| 5950 | } |
| 5951 | } |
| 5952 | await this._arm(occurrence, failed, owed !== null); |
| 5953 | } |
| 5954 | // `occurrence` is the tick just handled, or null when the cell is only |
| 5955 | // arming, `failed` holds the expressions of it still owed, and `retried` |
| 5956 | // says the deadline just handled was a backoff rather than an occurrence. |
| 5957 | async _arm(occurrence, failed, retried) { |
| 5958 | const crons = __cell.crons || []; |
| 5959 | // The count is failures within one occurrence, so a fresh occurrence |
| 5960 | // starts at one however the last one ended. Carrying it across would |
| 5961 | // spend `alarm_retry`'s ceiling once and leave every later occurrence |
| 5962 | // with no retry at all, which is a budget for the schedule and not for |
| 5963 | // the tick. |
| 5964 | this._retry = failed.length ? (retried ? this._retry + 1 : 1) : 0; |
| 5965 | // A negative first argument means "arming only, nothing fired". |
| 5966 | const plan = __cron_plan(crons, -1, Date.now(), this._retry, failed.length > 0); |
| 5967 | // The next occurrence beats the backoff whenever it is sooner, and it then |
| 5968 | // cancels the retry rather than queueing behind it, so the record the |
| 5969 | // retry needed goes when the retry does. |
| 5970 | this._owed = plan.armIsRetry |
| 5971 | ? { at: occurrence, indices: failed, armedFor: plan.armAt } |
| 5972 | : null; |
| 5973 | // No expression matches again and nothing is owed: the deployment dropped |
| 5974 | // its crons, so the cell retires rather than waking forever. |
| 5975 | if (plan.armAt === null) await this._state.storage.deleteAlarm(); |
| 5976 | else await this._state.storage.setAlarm(plan.armAt); |
| 5977 | } |
| 5978 | } |
| 5979 | const __cell = __celld.__cell = { |
| 5980 | entrypoints: {}, |
| 5981 | objectEntrypoints: {}, |
| 5982 | doExports: {}, |
| 5983 | classes: { ".cron": CelldCronSchedule }, |
| 5984 | crons: [], |
| 5985 | workflows: {}, |
| 5986 | containers: {}, |
| 5987 | instances: {}, |
| 5988 | facetConfigs: {}, |
| 5989 | env: {}, |
| 5990 | idNames: {}, |
| 5991 | namespaceKeys: {}, |
| 5992 | node: "", |
| 5993 | deleteAllDeletesAlarm: false, |
| 5994 | compat: { jsRpc: false, fetcherGetPutDelete: false, queueJsonMessages: false }, |
| 5995 | makeNamespace, |
| 5996 | release: __cellRelease, |
| 5997 | }; |
| 5998 | // A class the runtime supplies. RPC on a stub needs `extends DurableObject` |
| 5999 | // or the js_rpc flag; the class is the runtime's own, so grant it here rather |
| 6000 | // than make every user set a flag. It is not the application's export, so it |
| 6001 | // stays out of ctx.exports. |
| 6002 | const __runtimeClasses = new Set(); |
| 6003 | const __runtimeClass = (name, cls) => { |
| 6004 | __cell.classes[name] = cls; |
| 6005 | __cell.doExports[name] = true; |
| 6006 | __runtimeClasses.add(name); |
| 6007 | }; |
| 6008 | // ---- KV ------------------------------------------------------------------ |
| 6009 | // The namespace cell and the binding's client are `services/kv.js`, which the |
| 6010 | // workerd engine runs too; this is the host they run against here. |
| 6011 | const { |
| 6012 | KvNamespaceCell: __KvNamespaceCell, |
| 6013 | KvNamespace: __KvNamespace, |
| 6014 | cellSweepBatch: __cellSweepBatch, |
| 6015 | } = kvService({ |
| 6016 | // RPC on a runtime class is granted by `__runtimeClass` below. |
| 6017 | DurableObject: class { |
| 6018 | constructor(ctx) { |
| 6019 | this.ctx = ctx; |
| 6020 | } |
| 6021 | }, |
| 6022 | limits: () => __cell.kvLimits, |
| 6023 | // One op for the whole large-value path, following `__d1_run`. |
| 6024 | blob: async (_cell, request, value) => { |
| 6025 | const reply = await __kv_blob(JSON.stringify(request), value); |
| 6026 | return reply instanceof Uint8Array |
| 6027 | ? { found: true, value: reply } |
| 6028 | : JSON.parse(reply); |
| 6029 | }, |
| 6030 | // The raw base64 ops accept typed views for this internal wire form; the |
| 6031 | // public atob() and btoa() wrappers keep their standard string-only |
| 6032 | // behaviour. |
| 6033 | btoa: (bytes) => $$btoa(bytes), |
| 6034 | atob: (text) => $$atob(text, true), |
| 6035 | }); |
| 6036 | |
| 6037 | __runtimeClass("__KvNamespace", __KvNamespaceCell); |
| 6038 | |
| 6039 | const __makeKvNamespace = __celld.__makeKvNamespace = (id, cellName) => |
| 6040 | new __KvNamespace(() => __cell.makeNamespace("__KvNamespace"), cellName); |
| 6041 | |
| 6042 | // ---- Queues -------------------------------------------------------------- |
| 6043 | // A Queue is one runtime-supplied Durable Object. The producer binding writes |
| 6044 | // bytes and a content tag through RPC, and the cell owns the durable order, |
| 6045 | // deadlines, leases, and alarms. `celld_logic::queue` owns every transition |
| 6046 | // that can invalidate a lease or choose a deadline; this code supplies SQL and |
| 6047 | // the Cloudflare-compatible presentation. |
| 6048 | |
| 6049 | const __QUEUE_MESSAGES = "__queue_messages"; |
| 6050 | const __QUEUE_META = "__queue_meta"; |
| 6051 | const __QUEUE_STATS = "__queue_stats"; |
| 6052 | const __QUEUE_TRANSFER_RECEIPTS = "__queue_transfer_receipts"; |
| 6053 | const __queueEncoder = new TextEncoder(); |
| 6054 | |
| 6055 | // Independent send() calls share the same economics as sendBatch() without |
| 6056 | // changing the public promise boundary. The first call opens a four-millisecond |
| 6057 | // owner-local group by default; later cell events append their already-copied |
| 6058 | // entries, and park on their own promise. One event commits the bounded group, |
| 6059 | // and every response still trails that commit through the ordinary output |
| 6060 | // gate. The three caps bound heap retention and keep the persisted transaction |
| 6061 | // inside the public sendBatch limits. |
| 6062 | const __QUEUE_PRODUCER_GROUP_CALLS = 64; |
| 6063 | const __QUEUE_PRODUCER_GROUP_MESSAGES = 100; |
| 6064 | const __QUEUE_PRODUCER_GROUP_BYTES = 256_000; |
| 6065 | |
| 6066 | const __queueError = (message) => new Error("QUEUE_ERROR: " + String(message)); |
| 6067 | // A Queue message id is a UUIDv7 (RFC 9562): 48 bits of enqueue time, a |
| 6068 | // 12-bit sequence inside that millisecond, and 62 random bits. It keeps the |
| 6069 | // UUID shape a consumer can parse, and it sorts in enqueue order, so the |
| 6070 | // UNIQUE index on `id` appends. A random v4 id made every grouped send |
| 6071 | // transaction dirty one index leaf per message (about 1.6 WAL frames per |
| 6072 | // 64-byte message) and turned every passive checkpoint into a random write |
| 6073 | // across the whole backlog, which is what made a deep Queue's checkpoint |
| 6074 | // cost grow with its backlog. The sequence never moves backwards inside one |
| 6075 | // process, so a clock step only widens the gap between consecutive ids. |
| 6076 | let __queueIdMs = 0; |
| 6077 | let __queueIdSeq = 0; |
| 6078 | function __queueMessageId(now) { |
| 6079 | if (now > __queueIdMs) { |
| 6080 | __queueIdMs = now; |
| 6081 | __queueIdSeq = 0; |
| 6082 | } else { |
| 6083 | __queueIdSeq += 1; |
| 6084 | if (__queueIdSeq > 0xfff) { |
| 6085 | __queueIdMs += 1; |
| 6086 | __queueIdSeq = 0; |
| 6087 | } |
| 6088 | } |
| 6089 | const bytes = new Uint8Array(16); |
| 6090 | crypto.getRandomValues(bytes); |
| 6091 | const ms = __queueIdMs; |
| 6092 | bytes[0] = Math.floor(ms / 0x10000000000) & 0xff; |
| 6093 | bytes[1] = Math.floor(ms / 0x100000000) & 0xff; |
| 6094 | bytes[2] = (ms >>> 24) & 0xff; |
| 6095 | bytes[3] = (ms >>> 16) & 0xff; |
| 6096 | bytes[4] = (ms >>> 8) & 0xff; |
| 6097 | bytes[5] = ms & 0xff; |
| 6098 | bytes[6] = 0x70 | (__queueIdSeq >> 8); |
| 6099 | bytes[7] = __queueIdSeq & 0xff; |
| 6100 | bytes[8] = (bytes[8] & 0x3f) | 0x80; |
| 6101 | let hex = ""; |
| 6102 | for (let i = 0; i < 16; i++) hex += bytes[i].toString(16).padStart(2, "0"); |
| 6103 | return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${ |
| 6104 | hex.slice(16, 20) |
| 6105 | }-${hex.slice(20)}`; |
| 6106 | } |
| 6107 | const __queueLimits = () => __cell.queueLimits; |
| 6108 | const __queuePolicy = (request) => |
| 6109 | JSON.parse(__queue_policy(JSON.stringify(request))); |
| 6110 | |
| 6111 | const __queueDelay = (value, fallback = 0) => { |
| 6112 | if (value === undefined || value === null) return fallback; |
| 6113 | const seconds = Number(value); |
| 6114 | if (!Number.isInteger(seconds) || seconds < 0 || |
| 6115 | seconds > __queueLimits().maxDelaySeconds) { |
| 6116 | throw __queueError( |
| 6117 | `delaySeconds must be an integer from 0 to ${__queueLimits().maxDelaySeconds}`, |
| 6118 | ); |
| 6119 | } |
| 6120 | return seconds; |
| 6121 | }; |
| 6122 | |
| 6123 | const __queueBytes = (value) => { |
| 6124 | if (value instanceof ArrayBuffer) { |
| 6125 | return new Uint8Array(value.slice(0)); |
| 6126 | } |
| 6127 | if (ArrayBuffer.isView(value)) { |
| 6128 | return new Uint8Array( |
| 6129 | value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), |
| 6130 | ); |
| 6131 | } |
| 6132 | throw __queueError("a bytes message must be an ArrayBuffer or a typed array"); |
| 6133 | }; |
| 6134 | |
| 6135 | // Encode before entering the cell. The copy makes `sendBatch()` immune to a |
| 6136 | // caller resizing or reusing a backing buffer while the durable write awaits. |
| 6137 | const __queueEncode = (body, requestedType) => { |
| 6138 | const contentType = requestedType ?? |
| 6139 | (__cell.compat.queueJsonMessages ? "json" : "v8"); |
| 6140 | let bytes; |
| 6141 | switch (contentType) { |
| 6142 | case "text": |
| 6143 | bytes = __queueEncoder.encode(String(body)); |
| 6144 | break; |
| 6145 | case "bytes": |
| 6146 | bytes = __queueBytes(body); |
| 6147 | break; |
| 6148 | case "json": { |
| 6149 | let json; |
| 6150 | try { |
| 6151 | json = JSON.stringify(body); |
| 6152 | } catch (error) { |
| 6153 | throw __queueError("the JSON message body cannot be serialized", error); |
| 6154 | } |
| 6155 | if (json === undefined) { |
| 6156 | throw __queueError("the JSON message body cannot be undefined"); |
| 6157 | } |
| 6158 | bytes = __queueEncoder.encode(json); |
| 6159 | break; |
| 6160 | } |
| 6161 | case "v8": |
| 6162 | try { |
| 6163 | bytes = __sc_encode(body); |
| 6164 | } catch (error) { |
| 6165 | throw __queueError("the message body cannot be cloned", error); |
| 6166 | } |
| 6167 | break; |
| 6168 | default: |
| 6169 | throw __queueError( |
| 6170 | `contentType must be "text", "bytes", "json", or "v8", got ${JSON.stringify(contentType)}`, |
| 6171 | ); |
| 6172 | } |
| 6173 | if (bytes.byteLength > __queueLimits().maxMessageBytes) { |
| 6174 | throw __queueError( |
| 6175 | `a message is at most ${__queueLimits().maxMessageBytes} bytes, got ${bytes.byteLength}`, |
| 6176 | ); |
| 6177 | } |
| 6178 | return { body: bytes, contentType, size: bytes.byteLength }; |
| 6179 | }; |
| 6180 | |
| 6181 | // A lease-scoped read must seek, not walk the backlog. The plan is the only |
| 6182 | // evidence that says which, and it is cheap to ask for, so a gated test seam |
| 6183 | // reads it from the shipped query rather than from a copy that can drift. |
| 6184 | const __queueReportLeaseLookupPlan = (sql, query, leaseId) => { |
| 6185 | if (typeof __test_queue_lease_lookup_plan !== "function") return; |
| 6186 | const plan = sql.exec(`EXPLAIN QUERY PLAN ${query}`, leaseId) |
| 6187 | .toArray() |
| 6188 | .map((row) => row.detail) |
| 6189 | .join("; "); |
| 6190 | __test_queue_lease_lookup_plan(plan); |
| 6191 | }; |
| 6192 | |
| 6193 | const __queueMetricsView = (metrics) => ({ |
| 6194 | backlogCount: metrics.backlogCount, |
| 6195 | backlogBytes: metrics.backlogBytes, |
| 6196 | oldestMessageTimestamp: metrics.oldestMessageTimestamp === null || |
| 6197 | metrics.oldestMessageTimestamp === undefined |
| 6198 | ? undefined |
| 6199 | : new Date(metrics.oldestMessageTimestamp), |
| 6200 | }); |
| 6201 | |
| 6202 | class __QueueCell { |
| 6203 | constructor(ctx) { |
| 6204 | this.ctx = ctx; |
| 6205 | this.queue = ctx.id.name; |
| 6206 | this._ready = false; |
| 6207 | this._producerGroup = null; |
| 6208 | } |
| 6209 | |
| 6210 | _open() { |
| 6211 | if (this._ready) return this.ctx.storage.sql; |
| 6212 | const sql = this.ctx.storage.sql; |
| 6213 | sql.exec( |
| 6214 | `CREATE TABLE IF NOT EXISTS ${__QUEUE_MESSAGES} ( |
| 6215 | seq INTEGER PRIMARY KEY AUTOINCREMENT, |
| 6216 | id TEXT NOT NULL UNIQUE, |
| 6217 | body BLOB NOT NULL, |
| 6218 | content_type TEXT NOT NULL, |
| 6219 | size INTEGER NOT NULL, |
| 6220 | enqueued_at INTEGER NOT NULL, |
| 6221 | visible_at INTEGER NOT NULL, |
| 6222 | attempts INTEGER NOT NULL DEFAULT 0, |
| 6223 | lease_id TEXT, |
| 6224 | lease_generation INTEGER NOT NULL DEFAULT 0, |
| 6225 | leased_until INTEGER, |
| 6226 | purge_on_settle INTEGER NOT NULL DEFAULT 0, |
| 6227 | dlq_target TEXT, |
| 6228 | dlq_transfer_id TEXT, |
| 6229 | transfer_kind TEXT, |
| 6230 | dead_letter_source TEXT, |
| 6231 | CHECK ((dlq_target IS NULL AND transfer_kind IS NULL) |
| 6232 | OR (dlq_target IS NOT NULL |
| 6233 | AND transfer_kind IN ('dead-letter', 'redrive'))) |
| 6234 | )`, |
| 6235 | ); |
| 6236 | sql.exec( |
| 6237 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_visible |
| 6238 | ON ${__QUEUE_MESSAGES} (visible_at, seq)`, |
| 6239 | ); |
| 6240 | // Rearming is on every producer acknowledgement and settlement. Each |
| 6241 | // scheduling lookup must therefore stop at one deadline or one batch; |
| 6242 | // an aggregate over the backlog makes a large Queue quadratic to fill. |
| 6243 | sql.exec( |
| 6244 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_ready |
| 6245 | ON ${__QUEUE_MESSAGES} (visible_at, seq) |
| 6246 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6247 | AND lease_id IS NULL`, |
| 6248 | ); |
| 6249 | sql.exec( |
| 6250 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_enqueued |
| 6251 | ON ${__QUEUE_MESSAGES} (enqueued_at, seq)`, |
| 6252 | ); |
| 6253 | sql.exec( |
| 6254 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_retained |
| 6255 | ON ${__QUEUE_MESSAGES} (enqueued_at, seq) |
| 6256 | WHERE purge_on_settle = 0 AND dlq_target IS NULL`, |
| 6257 | ); |
| 6258 | sql.exec( |
| 6259 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease |
| 6260 | ON ${__QUEUE_MESSAGES} (leased_until, seq) |
| 6261 | WHERE lease_id IS NOT NULL`, |
| 6262 | ); |
| 6263 | sql.exec( |
| 6264 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_moving |
| 6265 | ON ${__QUEUE_MESSAGES} (seq) |
| 6266 | WHERE dlq_target IS NOT NULL`, |
| 6267 | ); |
| 6268 | // Dispatch and settlement both select a whole batch by its lease. Without |
| 6269 | // this index SQLite answers them by walking every row: the dispatch |
| 6270 | // readback scans `_visible` and the settlement scan walks the table, so |
| 6271 | // each delivered batch costs two passes over the backlog. The `_lease` |
| 6272 | // index cannot serve them because it is keyed on `leased_until`. |
| 6273 | // The partial predicate keeps only leased rows, which `max_concurrency` |
| 6274 | // times `max_batch_size` bounds, and an inserted message has a null |
| 6275 | // `lease_id`, so `send` pays nothing for it. |
| 6276 | sql.exec( |
| 6277 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease_batch |
| 6278 | ON ${__QUEUE_MESSAGES} (lease_id, visible_at, seq) |
| 6279 | WHERE lease_id IS NOT NULL`, |
| 6280 | ); |
| 6281 | // The live-row index catches an impossible duplicate while a received |
| 6282 | // message remains queued. The receipt below is the durable deduplication |
| 6283 | // record after a consumer or purge removes that message. |
| 6284 | sql.exec( |
| 6285 | `CREATE UNIQUE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_dlq_transfer |
| 6286 | ON ${__QUEUE_MESSAGES} (dlq_transfer_id) |
| 6287 | WHERE dlq_transfer_id IS NOT NULL AND dlq_target IS NULL`, |
| 6288 | ); |
| 6289 | sql.exec( |
| 6290 | `CREATE TABLE IF NOT EXISTS ${__QUEUE_META} ( |
| 6291 | name TEXT PRIMARY KEY, |
| 6292 | value TEXT NOT NULL |
| 6293 | ) WITHOUT ROWID`, |
| 6294 | ); |
| 6295 | // The producer result and operator metrics are on hot paths. SQLite |
| 6296 | // triggers keep the three values in the same transaction as every row |
| 6297 | // transition, so a caller cannot observe a new message with old totals. |
| 6298 | sql.exec( |
| 6299 | `CREATE TABLE IF NOT EXISTS ${__QUEUE_STATS} ( |
| 6300 | id INTEGER PRIMARY KEY CHECK (id = 1), |
| 6301 | stored_count INTEGER NOT NULL, |
| 6302 | backlog_count INTEGER NOT NULL, |
| 6303 | backlog_bytes INTEGER NOT NULL, |
| 6304 | oldest_message_timestamp INTEGER |
| 6305 | )`, |
| 6306 | ); |
| 6307 | sql.exec( |
| 6308 | `INSERT INTO ${__QUEUE_STATS} |
| 6309 | (id, stored_count, backlog_count, backlog_bytes, |
| 6310 | oldest_message_timestamp) |
| 6311 | SELECT 1, |
| 6312 | COUNT(*), |
| 6313 | COALESCE(SUM(purge_on_settle = 0), 0), |
| 6314 | COALESCE(SUM(CASE WHEN purge_on_settle = 0 THEN size ELSE 0 END), 0), |
| 6315 | MIN(CASE WHEN purge_on_settle = 0 THEN enqueued_at END) |
| 6316 | FROM ${__QUEUE_MESSAGES} |
| 6317 | WHERE true |
| 6318 | ON CONFLICT(id) DO NOTHING`, |
| 6319 | ); |
| 6320 | sql.exec( |
| 6321 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_insert |
| 6322 | AFTER INSERT ON ${__QUEUE_MESSAGES} |
| 6323 | BEGIN |
| 6324 | UPDATE ${__QUEUE_STATS} |
| 6325 | SET stored_count = stored_count + 1 |
| 6326 | WHERE id = 1; |
| 6327 | END`, |
| 6328 | ); |
| 6329 | sql.exec( |
| 6330 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_delete |
| 6331 | AFTER DELETE ON ${__QUEUE_MESSAGES} |
| 6332 | BEGIN |
| 6333 | UPDATE ${__QUEUE_STATS} |
| 6334 | SET stored_count = stored_count - 1 |
| 6335 | WHERE id = 1; |
| 6336 | END`, |
| 6337 | ); |
| 6338 | sql.exec( |
| 6339 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_insert |
| 6340 | AFTER INSERT ON ${__QUEUE_MESSAGES} |
| 6341 | WHEN new.purge_on_settle = 0 |
| 6342 | BEGIN |
| 6343 | UPDATE ${__QUEUE_STATS} |
| 6344 | SET backlog_count = backlog_count + 1, |
| 6345 | backlog_bytes = backlog_bytes + new.size, |
| 6346 | oldest_message_timestamp = CASE |
| 6347 | WHEN oldest_message_timestamp IS NULL |
| 6348 | OR new.enqueued_at < oldest_message_timestamp |
| 6349 | THEN new.enqueued_at ELSE oldest_message_timestamp END |
| 6350 | WHERE id = 1; |
| 6351 | END`, |
| 6352 | ); |
| 6353 | sql.exec( |
| 6354 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_delete |
| 6355 | AFTER DELETE ON ${__QUEUE_MESSAGES} |
| 6356 | WHEN old.purge_on_settle = 0 |
| 6357 | BEGIN |
| 6358 | UPDATE ${__QUEUE_STATS} |
| 6359 | SET backlog_count = backlog_count - 1, |
| 6360 | backlog_bytes = backlog_bytes - old.size, |
| 6361 | oldest_message_timestamp = CASE |
| 6362 | WHEN backlog_count <= 1 THEN NULL |
| 6363 | WHEN oldest_message_timestamp = old.enqueued_at |
| 6364 | THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} |
| 6365 | WHERE purge_on_settle = 0) |
| 6366 | ELSE oldest_message_timestamp END |
| 6367 | WHERE id = 1; |
| 6368 | END`, |
| 6369 | ); |
| 6370 | sql.exec( |
| 6371 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_exclude |
| 6372 | AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} |
| 6373 | WHEN old.purge_on_settle = 0 AND new.purge_on_settle != 0 |
| 6374 | BEGIN |
| 6375 | UPDATE ${__QUEUE_STATS} |
| 6376 | SET backlog_count = backlog_count - 1, |
| 6377 | backlog_bytes = backlog_bytes - old.size, |
| 6378 | oldest_message_timestamp = CASE |
| 6379 | WHEN backlog_count <= 1 THEN NULL |
| 6380 | WHEN oldest_message_timestamp = old.enqueued_at |
| 6381 | THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} |
| 6382 | WHERE purge_on_settle = 0) |
| 6383 | ELSE oldest_message_timestamp END |
| 6384 | WHERE id = 1; |
| 6385 | END`, |
| 6386 | ); |
| 6387 | sql.exec( |
| 6388 | `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_include |
| 6389 | AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} |
| 6390 | WHEN old.purge_on_settle != 0 AND new.purge_on_settle = 0 |
| 6391 | BEGIN |
| 6392 | UPDATE ${__QUEUE_STATS} |
| 6393 | SET backlog_count = backlog_count + 1, |
| 6394 | backlog_bytes = backlog_bytes + new.size, |
| 6395 | oldest_message_timestamp = CASE |
| 6396 | WHEN oldest_message_timestamp IS NULL |
| 6397 | OR new.enqueued_at < oldest_message_timestamp |
| 6398 | THEN new.enqueued_at ELSE oldest_message_timestamp END |
| 6399 | WHERE id = 1; |
| 6400 | END`, |
| 6401 | ); |
| 6402 | sql.exec( |
| 6403 | `CREATE TABLE IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS} ( |
| 6404 | transfer_id TEXT PRIMARY KEY, |
| 6405 | message_id TEXT NOT NULL, |
| 6406 | dead_letter_source TEXT, |
| 6407 | expires_at INTEGER NOT NULL |
| 6408 | ) WITHOUT ROWID`, |
| 6409 | ); |
| 6410 | sql.exec( |
| 6411 | `CREATE INDEX IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS}_expires |
| 6412 | ON ${__QUEUE_TRANSFER_RECEIPTS} (expires_at, transfer_id)`, |
| 6413 | ); |
| 6414 | this._ready = true; |
| 6415 | return sql; |
| 6416 | } |
| 6417 | |
| 6418 | _meta(name) { |
| 6419 | return this._open().exec( |
| 6420 | `SELECT value FROM ${__QUEUE_META} WHERE name = ?`, name, |
| 6421 | ).toArray()[0]?.value; |
| 6422 | } |
| 6423 | |
| 6424 | _setMeta(name, value) { |
| 6425 | if (value === null || value === undefined) { |
| 6426 | this._open().exec(`DELETE FROM ${__QUEUE_META} WHERE name = ?`, name); |
| 6427 | return; |
| 6428 | } |
| 6429 | this._open().exec( |
| 6430 | `INSERT INTO ${__QUEUE_META} (name, value) VALUES (?, ?) |
| 6431 | ON CONFLICT(name) DO UPDATE SET value = excluded.value`, |
| 6432 | name, |
| 6433 | String(value), |
| 6434 | ); |
| 6435 | } |
| 6436 | |
| 6437 | _paused() { |
| 6438 | return this._meta("paused") === "1"; |
| 6439 | } |
| 6440 | |
| 6441 | _metrics(now = Date.now(), waitingOnly = false) { |
| 6442 | const expiresBefore = now - __queueLimits().retentionMs; |
| 6443 | const sql = this._open(); |
| 6444 | const stats = sql.exec( |
| 6445 | `SELECT backlog_count, backlog_bytes, oldest_message_timestamp |
| 6446 | FROM ${__QUEUE_STATS} WHERE id = 1`, |
| 6447 | ).toArray()[0]; |
| 6448 | // Retention is a clock transition, not a row transition. Until the |
| 6449 | // bounded sweep catches up, use the exact query only at that boundary; |
| 6450 | // the normal hot path remains one materialized row at every depth. |
| 6451 | if (stats.oldest_message_timestamp !== null && |
| 6452 | stats.oldest_message_timestamp <= expiresBefore) { |
| 6453 | const row = sql.exec( |
| 6454 | `SELECT COUNT(*) AS backlog_count, |
| 6455 | COALESCE(SUM(size), 0) AS backlog_bytes, |
| 6456 | MIN(enqueued_at) AS oldest_message_timestamp |
| 6457 | FROM ${__QUEUE_MESSAGES} |
| 6458 | WHERE purge_on_settle = 0 AND enqueued_at > ? |
| 6459 | AND (? = 0 OR (lease_id IS NULL AND dlq_target IS NULL |
| 6460 | AND visible_at <= ?))`, |
| 6461 | expiresBefore, |
| 6462 | waitingOnly ? 1 : 0, |
| 6463 | now, |
| 6464 | ).toArray()[0]; |
| 6465 | return { |
| 6466 | backlogCount: row.backlog_count, |
| 6467 | backlogBytes: row.backlog_bytes, |
| 6468 | oldestMessageTimestamp: row.oldest_message_timestamp ?? null, |
| 6469 | }; |
| 6470 | } |
| 6471 | if (!waitingOnly) { |
| 6472 | if (typeof __test_queue_metrics_materialized === "function") { |
| 6473 | __test_queue_metrics_materialized(); |
| 6474 | } |
| 6475 | return { |
| 6476 | backlogCount: stats.backlog_count, |
| 6477 | backlogBytes: stats.backlog_bytes, |
| 6478 | oldestMessageTimestamp: stats.oldest_message_timestamp ?? null, |
| 6479 | }; |
| 6480 | } |
| 6481 | const blocked = sql.exec( |
| 6482 | `SELECT COALESCE(SUM(blocked_count), 0) AS blocked_count, |
| 6483 | COALESCE(SUM(blocked_bytes), 0) AS blocked_bytes |
| 6484 | FROM ( |
| 6485 | SELECT COUNT(*) AS blocked_count, |
| 6486 | COALESCE(SUM(size), 0) AS blocked_bytes |
| 6487 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease |
| 6488 | WHERE purge_on_settle = 0 AND lease_id IS NOT NULL |
| 6489 | UNION ALL |
| 6490 | SELECT COUNT(*) AS blocked_count, |
| 6491 | COALESCE(SUM(size), 0) AS blocked_bytes |
| 6492 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving |
| 6493 | WHERE purge_on_settle = 0 AND dlq_target IS NOT NULL |
| 6494 | UNION ALL |
| 6495 | SELECT COUNT(*) AS blocked_count, |
| 6496 | COALESCE(SUM(size), 0) AS blocked_bytes |
| 6497 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready |
| 6498 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6499 | AND lease_id IS NULL AND visible_at > ? |
| 6500 | )`, |
| 6501 | now, |
| 6502 | ).toArray()[0]; |
| 6503 | const unleasedOldest = sql.exec( |
| 6504 | `SELECT enqueued_at |
| 6505 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained |
| 6506 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6507 | AND lease_id IS NULL AND visible_at <= ? |
| 6508 | ORDER BY enqueued_at, seq |
| 6509 | LIMIT 1`, |
| 6510 | now, |
| 6511 | ).toArray()[0]?.enqueued_at ?? null; |
| 6512 | return { |
| 6513 | backlogCount: stats.backlog_count - blocked.blocked_count, |
| 6514 | backlogBytes: stats.backlog_bytes - blocked.blocked_bytes, |
| 6515 | oldestMessageTimestamp: unleasedOldest, |
| 6516 | }; |
| 6517 | } |
| 6518 | |
| 6519 | async _rearm(now = Date.now(), waitForWake = false) { |
| 6520 | const sql = this._open(); |
| 6521 | const consumer = __cell.queueConsumers?.[this.queue]; |
| 6522 | const paused = this._paused(); |
| 6523 | const active = sql.exec( |
| 6524 | `SELECT COUNT(DISTINCT lease_id) AS count |
| 6525 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease |
| 6526 | WHERE lease_id IS NOT NULL AND leased_until > ?`, |
| 6527 | now, |
| 6528 | ).toArray()[0].count; |
| 6529 | const concurrency = consumer |
| 6530 | ? consumer.maxConcurrency ?? __queueLimits().maxConcurrency |
| 6531 | : 0; |
| 6532 | const hasCapacity = !paused && consumer !== undefined && __queuePolicy({ |
| 6533 | op: "capacity", |
| 6534 | active, |
| 6535 | maximum: concurrency, |
| 6536 | }); |
| 6537 | // We need only enough ready rows to distinguish a partial batch from a |
| 6538 | // full one. The two indexed arms cover a new row and an expired lease, |
| 6539 | // and the outer LIMIT keeps the work independent of backlog depth. |
| 6540 | let ready = []; |
| 6541 | if (hasCapacity) { |
| 6542 | const visibleReady = sql.exec( |
| 6543 | `SELECT visible_at AS ready_at, seq |
| 6544 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready |
| 6545 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6546 | AND lease_id IS NULL AND visible_at <= ? |
| 6547 | ORDER BY visible_at, seq |
| 6548 | LIMIT ?`, |
| 6549 | now, |
| 6550 | consumer.maxBatchSize, |
| 6551 | ).toArray(); |
| 6552 | const expiredReady = sql.exec( |
| 6553 | `SELECT leased_until AS ready_at, seq |
| 6554 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease |
| 6555 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6556 | AND lease_id IS NOT NULL AND leased_until <= ? |
| 6557 | ORDER BY leased_until, seq |
| 6558 | LIMIT ?`, |
| 6559 | now, |
| 6560 | consumer.maxBatchSize, |
| 6561 | ).toArray(); |
| 6562 | ready = [...visibleReady, ...expiredReady] |
| 6563 | .sort((left, right) => left.ready_at - right.ready_at || left.seq - right.seq) |
| 6564 | .slice(0, consumer.maxBatchSize); |
| 6565 | } |
| 6566 | if (typeof __test_queue_rearm_bounded === "function") { |
| 6567 | __test_queue_rearm_bounded( |
| 6568 | ready.length <= (consumer?.maxBatchSize ?? 0), |
| 6569 | ready.length > 0, |
| 6570 | ); |
| 6571 | } |
| 6572 | const earliestVisible = hasCapacity |
| 6573 | ? sql.exec( |
| 6574 | `SELECT visible_at |
| 6575 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready |
| 6576 | WHERE purge_on_settle = 0 AND dlq_target IS NULL |
| 6577 | AND lease_id IS NULL AND visible_at > ? |
| 6578 | ORDER BY visible_at, seq |
| 6579 | LIMIT 1`, |
| 6580 | now, |
| 6581 | ).toArray()[0]?.visible_at ?? null |
| 6582 | : null; |
| 6583 | const earliestLeaseExpiry = paused |
| 6584 | ? null |
| 6585 | : sql.exec( |
| 6586 | `SELECT leased_until |
| 6587 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease |
| 6588 | WHERE lease_id IS NOT NULL |
| 6589 | ORDER BY leased_until |
| 6590 | LIMIT 1`, |
| 6591 | ).toArray()[0]?.leased_until ?? null; |
| 6592 | const nextSweep = sql.exec( |
| 6593 | `SELECT enqueued_at + ? AS next_sweep |
| 6594 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained |
| 6595 | WHERE dlq_target IS NULL AND purge_on_settle = 0 |
| 6596 | ORDER BY enqueued_at, seq |
| 6597 | LIMIT 1`, |
| 6598 | __queueLimits().retentionMs, |
| 6599 | ).toArray()[0]?.next_sweep ?? null; |
| 6600 | const dlqPending = sql.exec( |
| 6601 | `SELECT 1 AS pending |
| 6602 | FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving |
| 6603 | WHERE dlq_target IS NOT NULL |
| 6604 | LIMIT 1`, |
| 6605 | ).toArray().length !== 0; |
| 6606 | const receiptSweep = sql.exec( |
| 6607 | `SELECT expires_at AS next_sweep |
| 6608 | FROM ${__QUEUE_TRANSFER_RECEIPTS} |
| 6609 | ORDER BY expires_at, transfer_id |
| 6610 | LIMIT 1`, |
| 6611 | ).toArray()[0]?.next_sweep ?? null; |
| 6612 | // A queue without an attached consumer only wakes to reclaim retention. |
| 6613 | // Consumer attachment will nudge the cell when the fleet catalog gains a |
| 6614 | // registration; spinning on an already-visible row cannot make progress. |
| 6615 | let batchDeadline = null; |
| 6616 | if (ready.length > 0) { |
| 6617 | batchDeadline = ready.length >= consumer.maxBatchSize |
| 6618 | ? now |
| 6619 | : ready[0].ready_at + consumer.maxBatchTimeoutMs; |
| 6620 | } |
| 6621 | if (dlqPending) { |
| 6622 | batchDeadline = batchDeadline === null ? now : Math.min(batchDeadline, now); |
| 6623 | } |
| 6624 | const sweepDeadlines = [nextSweep, receiptSweep] |
| 6625 | .filter((deadline) => deadline !== null && deadline !== undefined); |
| 6626 | const armAt = __queuePolicy({ |
| 6627 | op: "rearm", |
| 6628 | now, |
| 6629 | batchDeadline, |
| 6630 | earliestVisible, |
| 6631 | // A live handler can settle after delivery pauses. Do not reclaim its |
| 6632 | // lease while paused; resume re-arms the expired deadline immediately |
| 6633 | // and only then can a new generation replace it. |
| 6634 | earliestLeaseExpiry, |
| 6635 | nextSweep: sweepDeadlines.length === 0 ? null : Math.min(...sweepDeadlines), |
| 6636 | }); |
| 6637 | if (armAt !== null && !Number.isFinite(armAt)) { |
| 6638 | throw __queueError("the Queue sweep deadline is invalid"); |
| 6639 | } |
| 6640 | if (armAt === null) await this.ctx.storage.deleteAlarm(); |
| 6641 | else if (waitForWake) { |
| 6642 | await __queue_alarm_set_wait(this.ctx.storage._scope, armAt); |
| 6643 | } else await this.ctx.storage.setAlarm(armAt); |
| 6644 | } |
| 6645 | |
| 6646 | _newProducerGroup() { |
| 6647 | const group = { |
| 6648 | calls: [], |
| 6649 | entries: [], |
| 6650 | bytes: 0, |
| 6651 | flushing: false, |
| 6652 | timer: null, |
| 6653 | }; |
| 6654 | this._producerGroup = group; |
| 6655 | group.timer = setTimeout(() => { |
| 6656 | void this._flushProducerGroup(group); |
| 6657 | }, __queueLimits().producerGroupMs); |
| 6658 | return group; |
| 6659 | } |
| 6660 | |
| 6661 | async _flushProducerGroup(group) { |
| 6662 | if (group.flushing) return; |
| 6663 | group.flushing = true; |
| 6664 | if (this._producerGroup === group) this._producerGroup = null; |
| 6665 | if (group.timer !== null) { |
| 6666 | clearTimeout(group.timer); |
| 6667 | group.timer = null; |
| 6668 | } |
| 6669 | |
| 6670 | const now = Date.now(); |
| 6671 | try { |
| 6672 | const sql = this._open(); |
| 6673 | this.ctx.storage.transactionSync(() => { |
| 6674 | for (const entry of group.entries) { |
| 6675 | sql.exec( |
| 6676 | `INSERT INTO ${__QUEUE_MESSAGES} |
| 6677 | (id, body, content_type, size, enqueued_at, visible_at) |
| 6678 | VALUES (?, ?, ?, ?, ?, ?)`, |
| 6679 | __queueMessageId(now), |
| 6680 | entry.body, |
| 6681 | entry.contentType, |
| 6682 | entry.size, |
| 6683 | now, |
| 6684 | now + entry.delaySeconds * 1000, |
| 6685 | ); |
| 6686 | } |
| 6687 | }); |
| 6688 | await this._rearm(now, true); |
| 6689 | const metrics = this._metrics(now); |
| 6690 | if (typeof __test_queue_producer_group === "function") { |
| 6691 | __test_queue_producer_group(group.calls.length, group.entries.length); |
| 6692 | } |
| 6693 | for (const call of group.calls) call.resolve(metrics); |
| 6694 | } catch (error) { |
| 6695 | for (const call of group.calls) call.reject(error); |
| 6696 | } |
| 6697 | } |
| 6698 | |
| 6699 | __queueSend({ entries }) { |
| 6700 | const bytes = entries.reduce((total, entry) => total + entry.size, 0); |
| 6701 | return new Promise((resolve, reject) => { |
| 6702 | let group = this._producerGroup; |
| 6703 | if (group !== null && |
| 6704 | (group.calls.length + 1 > __QUEUE_PRODUCER_GROUP_CALLS || |
| 6705 | group.entries.length + entries.length > __QUEUE_PRODUCER_GROUP_MESSAGES || |
| 6706 | group.bytes + bytes > __QUEUE_PRODUCER_GROUP_BYTES)) { |
| 6707 | void this._flushProducerGroup(group); |
| 6708 | group = null; |
| 6709 | } |
| 6710 | if (group === null) group = this._newProducerGroup(); |
| 6711 | group.calls.push({ resolve, reject }); |
| 6712 | group.entries.push(...entries); |
| 6713 | group.bytes += bytes; |
| 6714 | if (group.calls.length === __QUEUE_PRODUCER_GROUP_CALLS || |
| 6715 | group.entries.length === __QUEUE_PRODUCER_GROUP_MESSAGES || |
| 6716 | group.bytes === __QUEUE_PRODUCER_GROUP_BYTES) { |
| 6717 | void this._flushProducerGroup(group); |
| 6718 | } |
| 6719 | }); |
| 6720 | } |
| 6721 | |
| 6722 | __queueMetrics() { |
| 6723 | return this._metrics(); |
| 6724 | } |
| 6725 | |
| 6726 | // Retention decides visibility through `_metrics` immediately, while this |
| 6727 | // bounded sweep only reclaims space. A live lease is marked instead of |
| 6728 | // deleted, so its handler can finish but settlement or expiry removes it |
| 6729 | // without a redelivery. |
| 6730 | _sweep(now) { |
| 6731 | const sql = this._open(); |
| 6732 | const cutoff = now - __queueLimits().retentionMs; |
| 6733 | const messages = __cellSweepBatch( |
| 6734 | this.ctx.storage, |
| 6735 | (limit) => sql.exec( |
| 6736 | `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} |
| 6737 | WHERE enqueued_at <= ? |
| 6738 | AND (purge_on_settle = 0 |
| 6739 | OR lease_id IS NULL OR leased_until <= ?) |
| 6740 | ORDER BY enqueued_at, seq |
| 6741 | LIMIT ?`, |
| 6742 | cutoff, |
| 6743 | now, |
| 6744 | limit, |
| 6745 | ).toArray(), |
| 6746 | (row) => { |
| 6747 | if (row.lease_id !== null && row.leased_until > now) { |
| 6748 | sql.exec( |
| 6749 | `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 WHERE seq = ?`, |
| 6750 | row.seq, |
| 6751 | ); |
| 6752 | } else { |
| 6753 | sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); |
| 6754 | } |
| 6755 | }, |
| 6756 | __queueLimits().sweepBatchRows, |
| 6757 | ); |
| 6758 | const remaining = __queueLimits().sweepBatchRows - messages; |
| 6759 | if (remaining === 0) return messages; |
| 6760 | const receipts = __cellSweepBatch( |
| 6761 | this.ctx.storage, |
| 6762 | (limit) => sql.exec( |
| 6763 | `SELECT transfer_id FROM ${__QUEUE_TRANSFER_RECEIPTS} |
| 6764 | WHERE expires_at <= ? |
| 6765 | ORDER BY expires_at, transfer_id |
| 6766 | LIMIT ?`, |
| 6767 | now, |
| 6768 | limit, |
| 6769 | ).toArray(), |
| 6770 | (row) => { |
| 6771 | sql.exec( |
| 6772 | `DELETE FROM ${__QUEUE_TRANSFER_RECEIPTS} WHERE transfer_id = ?`, |
| 6773 | row.transfer_id, |
| 6774 | ); |
| 6775 | }, |
| 6776 | remaining, |
| 6777 | ); |
| 6778 | return messages + receipts; |
| 6779 | } |
| 6780 | |
| 6781 | _candidateRows(now, limit) { |
| 6782 | return this._open().exec( |
| 6783 | `SELECT seq, id, body, content_type, size, enqueued_at, visible_at, |
| 6784 | attempts, lease_id, lease_generation, leased_until, |
| 6785 | purge_on_settle |
| 6786 | FROM ${__QUEUE_MESSAGES} |
| 6787 | WHERE dlq_target IS NULL AND ((purge_on_settle = 1 |
| 6788 | AND (lease_id IS NULL OR leased_until <= ?)) |
| 6789 | OR (purge_on_settle = 0 AND visible_at <= ? |
| 6790 | AND (lease_id IS NULL OR leased_until <= ?))) |
| 6791 | ORDER BY visible_at, seq |
| 6792 | LIMIT ?`, |
| 6793 | now, |
| 6794 | now, |
| 6795 | now, |
| 6796 | limit, |
| 6797 | ).toArray(); |
| 6798 | } |
| 6799 | |
| 6800 | async _leaseBatch(now, consumer) { |
| 6801 | const sql = this._open(); |
| 6802 | const active = sql.exec( |
| 6803 | `SELECT COUNT(DISTINCT lease_id) AS count |
| 6804 | FROM ${__QUEUE_MESSAGES} |
| 6805 | WHERE lease_id IS NOT NULL AND leased_until > ?`, |
| 6806 | now, |
| 6807 | ).toArray()[0].count; |
| 6808 | const concurrency = consumer.maxConcurrency ?? __queueLimits().maxConcurrency; |
| 6809 | if (!__queuePolicy({ op: "capacity", active, maximum: concurrency })) return null; |
| 6810 | |
| 6811 | // Read extra rows so expired purge markers cannot hide a deliverable |
| 6812 | // batch. Policy chooses at most `maxBatchSize` rows and returns every |
| 6813 | // purge deletion that precedes them in this bounded scan. |
| 6814 | const rows = this._candidateRows(now, consumer.maxBatchSize + 256); |
| 6815 | const deliverable = rows.filter((row) => row.purge_on_settle === 0); |
| 6816 | if (deliverable.length === 0) { |
| 6817 | if (rows.length > 0) { |
| 6818 | this.ctx.storage.transactionSync(() => { |
| 6819 | for (const row of rows) { |
| 6820 | sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); |
| 6821 | } |
| 6822 | }); |
| 6823 | } |
| 6824 | return null; |
| 6825 | } |
| 6826 | const readySince = Math.min(...deliverable.map((row) => |
| 6827 | row.lease_id === null ? row.visible_at : row.leased_until |
| 6828 | )); |
| 6829 | if (deliverable.length < consumer.maxBatchSize && |
| 6830 | readySince + consumer.maxBatchTimeoutMs > now) { |
| 6831 | return null; |
| 6832 | } |
| 6833 | |
| 6834 | const plan = __queuePolicy({ |
| 6835 | op: "batch", |
| 6836 | now, |
| 6837 | maxBatchSize: consumer.maxBatchSize, |
| 6838 | rows: rows.map((row) => ({ |
| 6839 | seq: row.seq, |
| 6840 | visibleAt: row.visible_at, |
| 6841 | leaseGeneration: String(row.lease_generation), |
| 6842 | leasedUntil: row.leased_until, |
| 6843 | purgeOnSettle: row.purge_on_settle !== 0, |
| 6844 | })), |
| 6845 | }); |
| 6846 | if (plan.leases.length === 0 && plan.deletePurged.length === 0) return null; |
| 6847 | const rowBySeq = new Map(rows.map((row) => [row.seq, row])); |
| 6848 | const reclaimed = plan.leases.filter((lease) => lease.reclaimed); |
| 6849 | const expiryPolicy = __queuePolicy({ |
| 6850 | op: "expiry", |
| 6851 | now, |
| 6852 | entries: reclaimed.map((lease) => { |
| 6853 | const row = rowBySeq.get(lease.seq); |
| 6854 | return { |
| 6855 | priorFailures: row.attempts, |
| 6856 | maxRetries: consumer.maxRetries, |
| 6857 | configuredSeconds: consumer.retryDelaySeconds ?? null, |
| 6858 | purgeOnSettle: row.purge_on_settle !== 0, |
| 6859 | }; |
| 6860 | }), |
| 6861 | }); |
| 6862 | const expiryBySeq = new Map( |
| 6863 | reclaimed.map((lease, index) => [lease.seq, expiryPolicy[index]]), |
| 6864 | ); |
| 6865 | const installs = plan.leases.filter((lease) => { |
| 6866 | const expiry = expiryBySeq.get(lease.seq); |
| 6867 | return expiry === undefined || |
| 6868 | (expiry.action.kind === "retry" && expiry.action.at <= now); |
| 6869 | }); |
| 6870 | const exhaustedTransfers = new Map( |
| 6871 | reclaimed |
| 6872 | .filter((lease) => |
| 6873 | expiryBySeq.get(lease.seq).action.kind === "exhausted" && |
| 6874 | consumer.deadLetterQueue !== undefined |
| 6875 | ) |
| 6876 | .map((lease) => [lease.seq, crypto.randomUUID()]), |
| 6877 | ); |
| 6878 | const leaseId = crypto.randomUUID(); |
| 6879 | const leasedUntil = Math.min( |
| 6880 | Number.MAX_SAFE_INTEGER, |
| 6881 | now + __cell.queueLeaseDurationMs, |
| 6882 | ); |
| 6883 | this.ctx.storage.transactionSync(() => { |
| 6884 | for (const seq of plan.deletePurged) { |
| 6885 | sql.exec( |
| 6886 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 6887 | WHERE seq = ? AND purge_on_settle = 1 |
| 6888 | AND (lease_id IS NULL OR leased_until <= ?)`, |
| 6889 | seq, |
| 6890 | now, |
| 6891 | ); |
| 6892 | } |
| 6893 | for (const lease of reclaimed) { |
| 6894 | const expiry = expiryBySeq.get(lease.seq); |
| 6895 | if (expiry.action.kind === "delete-purged") { |
| 6896 | sql.exec( |
| 6897 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 6898 | WHERE seq = ? AND leased_until <= ?`, |
| 6899 | lease.seq, |
| 6900 | now, |
| 6901 | ); |
| 6902 | } else if (expiry.action.kind === "exhausted") { |
| 6903 | if (consumer.deadLetterQueue === undefined) { |
| 6904 | sql.exec( |
| 6905 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 6906 | WHERE seq = ? AND leased_until <= ?`, |
| 6907 | lease.seq, |
| 6908 | now, |
| 6909 | ); |
| 6910 | } else { |
| 6911 | sql.exec( |
| 6912 | `UPDATE ${__QUEUE_MESSAGES} |
| 6913 | SET attempts = ?, lease_id = NULL, leased_until = NULL, |
| 6914 | dlq_target = ?, dlq_transfer_id = ?, |
| 6915 | transfer_kind = 'dead-letter' |
| 6916 | WHERE seq = ? AND leased_until <= ?`, |
| 6917 | expiry.attempt, |
| 6918 | consumer.deadLetterQueue, |
| 6919 | exhaustedTransfers.get(lease.seq), |
| 6920 | lease.seq, |
| 6921 | now, |
| 6922 | ); |
| 6923 | } |
| 6924 | } else if (expiry.action.at > now) { |
| 6925 | sql.exec( |
| 6926 | `UPDATE ${__QUEUE_MESSAGES} |
| 6927 | SET attempts = ?, visible_at = ?, lease_id = NULL, |
| 6928 | leased_until = NULL |
| 6929 | WHERE seq = ? AND leased_until <= ?`, |
| 6930 | expiry.attempt, |
| 6931 | expiry.action.at, |
| 6932 | lease.seq, |
| 6933 | now, |
| 6934 | ); |
| 6935 | } |
| 6936 | } |
| 6937 | for (const lease of installs) { |
| 6938 | const generation = Number(lease.generation); |
| 6939 | if (!Number.isSafeInteger(generation)) { |
| 6940 | throw __queueError(`message ${lease.seq} exhausted its safe lease generation`); |
| 6941 | } |
| 6942 | sql.exec( |
| 6943 | `UPDATE ${__QUEUE_MESSAGES} |
| 6944 | SET lease_id = ?, lease_generation = ?, leased_until = ?, |
| 6945 | attempts = attempts + ? |
| 6946 | WHERE seq = ? AND lease_generation = ? |
| 6947 | AND (lease_id IS NULL OR leased_until <= ?)`, |
| 6948 | leaseId, |
| 6949 | generation, |
| 6950 | leasedUntil, |
| 6951 | lease.reclaimed ? 1 : 0, |
| 6952 | lease.seq, |
| 6953 | generation - 1, |
| 6954 | now, |
| 6955 | ); |
| 6956 | } |
| 6957 | }); |
| 6958 | if (installs.length === 0) return null; |
| 6959 | const leasedQuery = |
| 6960 | `SELECT seq, id, body, content_type, enqueued_at, attempts, |
| 6961 | lease_generation |
| 6962 | FROM ${__QUEUE_MESSAGES} |
| 6963 | WHERE lease_id = ? |
| 6964 | ORDER BY visible_at, seq`; |
| 6965 | __queueReportLeaseLookupPlan(sql, leasedQuery, leaseId); |
| 6966 | const leased = sql.exec(leasedQuery, leaseId).toArray(); |
| 6967 | if (leased.length !== installs.length) { |
| 6968 | throw __queueError("the Queue lease transaction changed fewer rows than its plan"); |
| 6969 | } |
| 6970 | return { |
| 6971 | leaseId, |
| 6972 | leases: leased.map((row) => ({ |
| 6973 | message_id: row.id, |
| 6974 | seq: row.seq, |
| 6975 | generation: row.lease_generation, |
| 6976 | })), |
| 6977 | messages: leased.map((row) => ({ |
| 6978 | id: row.id, |
| 6979 | timestampMs: row.enqueued_at, |
| 6980 | // SQLite answers a BLOB as an ArrayBuffer. The raw base64 op accepts |
| 6981 | // typed views, so normalize here; otherwise it encodes the text |
| 6982 | // "[object ArrayBuffer]" and every consumer decoder sees corrupt data. |
| 6983 | bodyBase64: $$btoa( |
| 6984 | row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), |
| 6985 | ), |
| 6986 | contentType: row.content_type, |
| 6987 | attempts: row.attempts + 1, |
| 6988 | })), |
| 6989 | // Miniflare removes every dispatched batch from its backlog before it |
| 6990 | // invokes the consumer. Exclude every lease here for the same contract; |
| 6991 | // the operator aggregate still includes durable in-flight messages. |
| 6992 | metrics: this._metrics(now, true), |
| 6993 | }; |
| 6994 | } |
| 6995 | |
| 6996 | // The target deduplicates the stable transfer identity. The source can |
| 6997 | // therefore repeat this call after a stop between the target commit and the |
| 6998 | // source delete without creating a second message. |
| 6999 | async __queueDlqAcceptBatch({ transfers }) { |
| 7000 | if (!Array.isArray(transfers) || transfers.length === 0 || |
| 7001 | transfers.length > __queueLimits().maxBatchMessages) { |
| 7002 | throw __queueError("a Queue transfer batch has an invalid size"); |
| 7003 | } |
| 7004 | for (const transfer of transfers) { |
| 7005 | if (transfer.deadLetterSource !== null && |
| 7006 | typeof transfer.deadLetterSource !== "string") { |
| 7007 | throw __queueError("a Queue transfer has an invalid dead-letter source"); |
| 7008 | } |
| 7009 | } |
| 7010 | const now = Date.now(); |
| 7011 | const sql = this._open(); |
| 7012 | this.ctx.storage.transactionSync(() => { |
| 7013 | for (const { transferId, entry, deadLetterSource } of transfers) { |
| 7014 | const accepted = sql.exec( |
| 7015 | `SELECT message_id, dead_letter_source |
| 7016 | FROM ${__QUEUE_TRANSFER_RECEIPTS} |
| 7017 | WHERE transfer_id = ?`, |
| 7018 | transferId, |
| 7019 | ).toArray()[0]; |
| 7020 | if (accepted !== undefined && (accepted.message_id !== entry.id || |
| 7021 | accepted.dead_letter_source !== deadLetterSource)) { |
| 7022 | throw __queueError("a DLQ transfer collided with another message identity"); |
| 7023 | } |
| 7024 | if (accepted !== undefined) continue; |
| 7025 | sql.exec( |
| 7026 | `INSERT INTO ${__QUEUE_TRANSFER_RECEIPTS} |
| 7027 | (transfer_id, message_id, dead_letter_source, expires_at) |
| 7028 | VALUES (?, ?, ?, ?)`, |
| 7029 | transferId, |
| 7030 | entry.id, |
| 7031 | deadLetterSource, |
| 7032 | now + __queueLimits().retentionMs, |
| 7033 | ); |
| 7034 | sql.exec( |
| 7035 | `INSERT INTO ${__QUEUE_MESSAGES} |
| 7036 | (id, body, content_type, size, enqueued_at, visible_at, |
| 7037 | attempts, dlq_transfer_id, dead_letter_source) |
| 7038 | VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)`, |
| 7039 | entry.id, |
| 7040 | entry.body, |
| 7041 | entry.contentType, |
| 7042 | entry.size, |
| 7043 | now, |
| 7044 | now, |
| 7045 | transferId, |
| 7046 | deadLetterSource, |
| 7047 | ); |
| 7048 | } |
| 7049 | }); |
| 7050 | await this._rearm(now); |
| 7051 | return this._metrics(now); |
| 7052 | } |
| 7053 | |
| 7054 | async _driveDlq(limit = 100) { |
| 7055 | const now = Date.now(); |
| 7056 | const pending = this._open().exec( |
| 7057 | `SELECT seq, id, body, content_type, size, dlq_target, dlq_transfer_id, |
| 7058 | transfer_kind |
| 7059 | FROM ${__QUEUE_MESSAGES} |
| 7060 | WHERE dlq_target IS NOT NULL |
| 7061 | AND enqueued_at > ? |
| 7062 | ORDER BY seq |
| 7063 | LIMIT ?`, |
| 7064 | now - __queueLimits().retentionMs, |
| 7065 | limit, |
| 7066 | ).toArray(); |
| 7067 | const groups = new Map(); |
| 7068 | for (const row of pending) { |
| 7069 | let group = groups.get(row.dlq_target); |
| 7070 | if (group === undefined) groups.set(row.dlq_target, group = []); |
| 7071 | group.push(row); |
| 7072 | } |
| 7073 | for (const [targetName, rows] of groups) { |
| 7074 | const target = __cell.makeNamespace("__Queue").getByName(targetName); |
| 7075 | await target.__queueDlqAcceptBatch({ |
| 7076 | transfers: rows.map((row) => ({ |
| 7077 | transferId: row.dlq_transfer_id, |
| 7078 | // A dead-letter transfer records where redrive returns the message. |
| 7079 | // A redrive returns it to ordinary queue state, so the source marker |
| 7080 | // must not follow it and make a later redrive bounce it backwards. |
| 7081 | deadLetterSource: row.transfer_kind === "dead-letter" ? this.queue : null, |
| 7082 | entry: { |
| 7083 | id: row.id, |
| 7084 | body: row.body, |
| 7085 | contentType: row.content_type, |
| 7086 | size: row.size, |
| 7087 | }, |
| 7088 | })), |
| 7089 | }); |
| 7090 | if (typeof __test_queue_dlq_accepted === "function") { |
| 7091 | __test_queue_dlq_accepted(); |
| 7092 | } |
| 7093 | // The target committed every receipt before this reply. Delete the |
| 7094 | // corresponding source marks together; a stop before this transaction |
| 7095 | // leaves the whole group replayable through those stable receipts. |
| 7096 | this.ctx.storage.transactionSync(() => { |
| 7097 | for (const row of rows) { |
| 7098 | this._open().exec( |
| 7099 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7100 | WHERE seq = ? AND dlq_target = ? AND dlq_transfer_id = ? |
| 7101 | AND transfer_kind = ?`, |
| 7102 | row.seq, |
| 7103 | row.dlq_target, |
| 7104 | row.dlq_transfer_id, |
| 7105 | row.transfer_kind, |
| 7106 | ); |
| 7107 | } |
| 7108 | }); |
| 7109 | } |
| 7110 | return pending.length; |
| 7111 | } |
| 7112 | |
| 7113 | async alarm() { |
| 7114 | const now = Date.now(); |
| 7115 | try { |
| 7116 | await this._driveDlq(); |
| 7117 | } catch (error) { |
| 7118 | // The durable source mark is the retry record. An alarm stays armed at |
| 7119 | // `now`, and the target's transfer identity makes a replay idempotent. |
| 7120 | console.error("Queue DLQ transfer failed:", error); |
| 7121 | } |
| 7122 | const swept = this._sweep(now); |
| 7123 | const consumer = this._paused() |
| 7124 | ? undefined |
| 7125 | : __cell.queueConsumers?.[this.queue]; |
| 7126 | // Install every lease that the configured concurrency admits before the |
| 7127 | // first consumer can settle. One lease per alarm serialized full batches |
| 7128 | // because the next alarm depended on a later scheduler turn, so a queue |
| 7129 | // with maxConcurrency > 1 still used only one handler under backlog. |
| 7130 | // `_leaseBatch` counts the durable lease IDs on every iteration, which |
| 7131 | // makes the configured concurrency the structural bound for this loop. |
| 7132 | const batches = []; |
| 7133 | if (consumer !== undefined) { |
| 7134 | while (true) { |
| 7135 | const batch = await this._leaseBatch(now, consumer); |
| 7136 | if (batch === null) break; |
| 7137 | batches.push(batch); |
| 7138 | } |
| 7139 | } |
| 7140 | try { |
| 7141 | // `_leaseBatch` can exhaust an expired lease and create a new durable |
| 7142 | // DLQ mark. Drive that mark in the same wake; the first call above is |
| 7143 | // for a mark recovered from an earlier stopped process. |
| 7144 | await this._driveDlq(); |
| 7145 | } catch (error) { |
| 7146 | console.error("Queue DLQ transfer failed:", error); |
| 7147 | } |
| 7148 | await this._rearm(now); |
| 7149 | if (swept >= __queueLimits().sweepBatchRows && batches.length === 0) { |
| 7150 | await this.ctx.storage.setAlarm(now + 1); |
| 7151 | return; |
| 7152 | } |
| 7153 | for (const batch of batches) { |
| 7154 | // This await covers only the output-gated handoff to the host. The |
| 7155 | // consumer runs after this alarm returns, and settlement comes back as |
| 7156 | // an independent cell event. All admitted leases are durable before the |
| 7157 | // first handoff, so a fast settlement cannot make this turn exceed the |
| 7158 | // configured concurrency. |
| 7159 | await __queue_dispatch( |
| 7160 | consumer.script, |
| 7161 | this.queue, |
| 7162 | JSON.stringify(batch), |
| 7163 | ); |
| 7164 | } |
| 7165 | } |
| 7166 | |
| 7167 | _matchingLease(body) { |
| 7168 | if (typeof body.leaseId !== "string" || !Array.isArray(body.leases)) return null; |
| 7169 | const matchQuery = |
| 7170 | `SELECT seq, id, attempts, lease_generation, purge_on_settle |
| 7171 | FROM ${__QUEUE_MESSAGES} |
| 7172 | WHERE lease_id = ? |
| 7173 | ORDER BY seq`; |
| 7174 | __queueReportLeaseLookupPlan(this._open(), matchQuery, body.leaseId); |
| 7175 | const rows = this._open().exec(matchQuery, body.leaseId).toArray(); |
| 7176 | for (const lease of body.leases) { |
| 7177 | if (typeof lease?.message_id !== "string" || |
| 7178 | !Number.isSafeInteger(lease.seq) || |
| 7179 | !Number.isSafeInteger(lease.generation)) return null; |
| 7180 | } |
| 7181 | const matches = __queuePolicy({ |
| 7182 | op: "settlement", |
| 7183 | current: rows.map((row) => ({ |
| 7184 | seq: String(row.seq), |
| 7185 | messageId: row.id, |
| 7186 | generation: String(row.lease_generation), |
| 7187 | })), |
| 7188 | submitted: body.leases.map((lease) => ({ |
| 7189 | seq: String(lease.seq), |
| 7190 | messageId: lease.message_id, |
| 7191 | generation: String(lease.generation), |
| 7192 | })), |
| 7193 | }); |
| 7194 | return matches ? rows : null; |
| 7195 | } |
| 7196 | |
| 7197 | async _settle(body) { |
| 7198 | const rows = this._matchingLease(body); |
| 7199 | if (rows === null) return false; |
| 7200 | const consumer = __cell.queueConsumers?.[this.queue]; |
| 7201 | if (consumer === undefined) return false; |
| 7202 | const explicitAcks = new Set(body.explicitAcks ?? []); |
| 7203 | const retryMessages = new Map( |
| 7204 | (body.retryMessages ?? []).map((retry) => [retry.msgId, retry.delaySeconds]), |
| 7205 | ); |
| 7206 | const retryBatch = body.retryBatch?.retry === true; |
| 7207 | const batchDelay = body.retryBatch?.delaySeconds; |
| 7208 | const exception = body.outcome === "exception"; |
| 7209 | // An explicit ack-all survives a later handler exception, so it must |
| 7210 | // override every batch-level and message-level retry signal. |
| 7211 | const ackAll = body.ackAll === true; |
| 7212 | const decisions = rows.map((row) => { |
| 7213 | const retry = !ackAll && !explicitAcks.has(row.id) && ( |
| 7214 | retryMessages.has(row.id) || retryBatch || exception |
| 7215 | ); |
| 7216 | return { row, retry }; |
| 7217 | }); |
| 7218 | const retrying = decisions.filter((decision) => |
| 7219 | decision.retry && decision.row.purge_on_settle === 0 |
| 7220 | ); |
| 7221 | const retryPolicy = __queuePolicy({ |
| 7222 | op: "retries", |
| 7223 | now: Date.now(), |
| 7224 | entries: retrying.map(({ row }) => ({ |
| 7225 | attempt: row.attempts + 1, |
| 7226 | maxRetries: consumer.maxRetries, |
| 7227 | explicitSeconds: retryMessages.has(row.id) |
| 7228 | ? retryMessages.get(row.id) |
| 7229 | : retryBatch ? batchDelay : null, |
| 7230 | configuredSeconds: consumer.retryDelaySeconds ?? null, |
| 7231 | })), |
| 7232 | }); |
| 7233 | const retryById = new Map( |
| 7234 | retrying.map(({ row }, index) => [row.id, retryPolicy[index]]), |
| 7235 | ); |
| 7236 | const dlqTransferById = new Map( |
| 7237 | retrying |
| 7238 | .filter(({ row }) => |
| 7239 | retryById.get(row.id).exhausted && consumer.deadLetterQueue !== undefined |
| 7240 | ) |
| 7241 | .map(({ row }) => [row.id, crypto.randomUUID()]), |
| 7242 | ); |
| 7243 | const sql = this._open(); |
| 7244 | this.ctx.storage.transactionSync(() => { |
| 7245 | for (const { row, retry } of decisions) { |
| 7246 | const policy = retryById.get(row.id); |
| 7247 | if (row.purge_on_settle !== 0 || !retry || |
| 7248 | (policy.exhausted && consumer.deadLetterQueue === undefined)) { |
| 7249 | sql.exec( |
| 7250 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7251 | WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, |
| 7252 | row.seq, |
| 7253 | body.leaseId, |
| 7254 | row.lease_generation, |
| 7255 | ); |
| 7256 | continue; |
| 7257 | } |
| 7258 | if (policy.exhausted) { |
| 7259 | sql.exec( |
| 7260 | `UPDATE ${__QUEUE_MESSAGES} |
| 7261 | SET attempts = attempts + 1, lease_id = NULL, |
| 7262 | leased_until = NULL, dlq_target = ?, dlq_transfer_id = ?, |
| 7263 | transfer_kind = 'dead-letter' |
| 7264 | WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, |
| 7265 | consumer.deadLetterQueue, |
| 7266 | dlqTransferById.get(row.id), |
| 7267 | row.seq, |
| 7268 | body.leaseId, |
| 7269 | row.lease_generation, |
| 7270 | ); |
| 7271 | continue; |
| 7272 | } |
| 7273 | sql.exec( |
| 7274 | `UPDATE ${__QUEUE_MESSAGES} |
| 7275 | SET attempts = attempts + 1, visible_at = ?, |
| 7276 | lease_id = NULL, leased_until = NULL |
| 7277 | WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, |
| 7278 | policy.at, |
| 7279 | row.seq, |
| 7280 | body.leaseId, |
| 7281 | row.lease_generation, |
| 7282 | ); |
| 7283 | } |
| 7284 | }); |
| 7285 | try { |
| 7286 | await this._driveDlq(); |
| 7287 | } catch (error) { |
| 7288 | // Settlement is durable once the source mark commits. A failed transfer |
| 7289 | // is alarm work now, not a reason to put the message back in delivery. |
| 7290 | console.error("Queue DLQ transfer deferred:", error); |
| 7291 | } |
| 7292 | await this._rearm(); |
| 7293 | return true; |
| 7294 | } |
| 7295 | |
| 7296 | async _purge() { |
| 7297 | const now = Date.now(); |
| 7298 | const sql = this._open(); |
| 7299 | let deleted = 0; |
| 7300 | let leased = 0; |
| 7301 | this.ctx.storage.transactionSync(() => { |
| 7302 | let after = 0; |
| 7303 | while (true) { |
| 7304 | // Purge is necessarily proportional to the stored backlog, but its |
| 7305 | // policy envelope stays bounded instead of materializing the Queue in |
| 7306 | // V8 or Rust. One SQLite transaction keeps the visibility change |
| 7307 | // atomic across all chunks. |
| 7308 | const rows = sql.exec( |
| 7309 | `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} |
| 7310 | WHERE seq > ? |
| 7311 | ORDER BY seq |
| 7312 | LIMIT 256`, |
| 7313 | after, |
| 7314 | ).toArray(); |
| 7315 | if (rows.length === 0) break; |
| 7316 | after = rows[rows.length - 1].seq; |
| 7317 | const plan = __queuePolicy({ |
| 7318 | op: "purge", |
| 7319 | now, |
| 7320 | rows: rows.map((row) => ({ |
| 7321 | seq: String(row.seq), |
| 7322 | leaseIdPresent: row.lease_id !== null, |
| 7323 | leasedUntil: row.leased_until, |
| 7324 | })), |
| 7325 | }); |
| 7326 | for (const seq of plan.delete) { |
| 7327 | sql.exec( |
| 7328 | `DELETE FROM ${__QUEUE_MESSAGES} |
| 7329 | WHERE seq = ? |
| 7330 | AND (lease_id IS NULL OR leased_until IS NULL OR leased_until <= ?)`, |
| 7331 | Number(seq), |
| 7332 | now, |
| 7333 | ); |
| 7334 | deleted += 1; |
| 7335 | } |
| 7336 | for (const seq of plan.markForSettle) { |
| 7337 | sql.exec( |
| 7338 | `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 |
| 7339 | WHERE seq = ? AND lease_id IS NOT NULL AND leased_until > ?`, |
| 7340 | Number(seq), |
| 7341 | now, |
| 7342 | ); |
| 7343 | leased += 1; |
| 7344 | } |
| 7345 | } |
| 7346 | }); |
| 7347 | await this._rearm(now); |
| 7348 | return { deleted, leased, metrics: this._metrics(now) }; |
| 7349 | } |
| 7350 | |
| 7351 | async _setPaused(paused) { |
| 7352 | this._setMeta("paused", paused ? "1" : null); |
| 7353 | await this._rearm(); |
| 7354 | return { paused, ...this._metrics() }; |
| 7355 | } |
| 7356 | |
| 7357 | _operatorLimit(value, fallback) { |
| 7358 | const limit = value ?? fallback; |
| 7359 | if (!Number.isInteger(limit) || limit < 1 || limit > 100) { |
| 7360 | throw __queueError("limit must be an integer from 1 through 100"); |
| 7361 | } |
| 7362 | return limit; |
| 7363 | } |
| 7364 | |
| 7365 | _peek(limit) { |
| 7366 | const now = Date.now(); |
| 7367 | const cutoff = now - __queueLimits().retentionMs; |
| 7368 | const rows = this._open().exec( |
| 7369 | `SELECT id, body, content_type, size, enqueued_at, visible_at, attempts, |
| 7370 | lease_id, leased_until, purge_on_settle, dlq_target, |
| 7371 | dead_letter_source |
| 7372 | FROM ${__QUEUE_MESSAGES} |
| 7373 | WHERE enqueued_at > ? |
| 7374 | ORDER BY visible_at, seq |
| 7375 | LIMIT ?`, |
| 7376 | cutoff, |
| 7377 | limit, |
| 7378 | ).toArray(); |
| 7379 | return { |
| 7380 | messages: rows.map((row) => ({ |
| 7381 | id: row.id, |
| 7382 | bodyBase64: $$btoa( |
| 7383 | row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), |
| 7384 | ), |
| 7385 | contentType: row.content_type, |
| 7386 | size: row.size, |
| 7387 | enqueuedAt: row.enqueued_at, |
| 7388 | visibleAt: row.visible_at, |
| 7389 | attempts: row.attempts, |
| 7390 | state: row.dlq_target !== null |
| 7391 | ? "moving" |
| 7392 | : row.purge_on_settle !== 0 |
| 7393 | ? "purging" |
| 7394 | : row.lease_id !== null && row.leased_until > now |
| 7395 | ? "leased" |
| 7396 | : row.visible_at <= now |
| 7397 | ? "visible" |
| 7398 | : "delayed", |
| 7399 | leasedUntil: row.lease_id !== null && row.leased_until > now |
| 7400 | ? row.leased_until |
| 7401 | : null, |
| 7402 | transferTarget: row.dlq_target, |
| 7403 | deadLetterSource: row.dead_letter_source, |
| 7404 | })), |
| 7405 | }; |
| 7406 | } |
| 7407 | |
| 7408 | async _redrive(limit) { |
| 7409 | // Finish an interrupted move before selecting more work. A transfer mark |
| 7410 | // is durable, so selecting it a second time would invent another identity |
| 7411 | // where replaying the existing identity is sufficient. |
| 7412 | await this._driveDlq(100); |
| 7413 | const now = Date.now(); |
| 7414 | const cutoff = now - __queueLimits().retentionMs; |
| 7415 | const candidates = this._open().exec( |
| 7416 | `SELECT seq, dead_letter_source |
| 7417 | FROM ${__QUEUE_MESSAGES} |
| 7418 | WHERE dead_letter_source IS NOT NULL |
| 7419 | AND dlq_target IS NULL |
| 7420 | AND purge_on_settle = 0 |
| 7421 | AND enqueued_at > ? |
| 7422 | AND (lease_id IS NULL OR leased_until <= ?) |
| 7423 | ORDER BY visible_at, seq |
| 7424 | LIMIT ?`, |
| 7425 | cutoff, |
| 7426 | now, |
| 7427 | limit, |
| 7428 | ).toArray(); |
| 7429 | const transfers = candidates.map((row) => ({ |
| 7430 | ...row, |
| 7431 | transferId: crypto.randomUUID(), |
| 7432 | })); |
| 7433 | this.ctx.storage.transactionSync(() => { |
| 7434 | for (const transfer of transfers) { |
| 7435 | this._open().exec( |
| 7436 | `UPDATE ${__QUEUE_MESSAGES} |
| 7437 | SET dlq_target = ?, dlq_transfer_id = ?, transfer_kind = 'redrive', |
| 7438 | lease_id = NULL, leased_until = NULL |
| 7439 | WHERE seq = ? AND dead_letter_source = ? AND dlq_target IS NULL |
| 7440 | AND purge_on_settle = 0 |
| 7441 | AND (lease_id IS NULL OR leased_until <= ?)`, |
| 7442 | transfer.dead_letter_source, |
| 7443 | transfer.transferId, |
| 7444 | transfer.seq, |
| 7445 | transfer.dead_letter_source, |
| 7446 | now, |
| 7447 | ); |
| 7448 | } |
| 7449 | }); |
| 7450 | // Arm before the cross-cell call. If the process stops after the durable |
| 7451 | // mark, the alarm replays the same transfer identity. |
| 7452 | await this._rearm(now); |
| 7453 | await this._driveDlq(100); |
| 7454 | await this._rearm(); |
| 7455 | return { redriven: transfers.length, metrics: this._metrics() }; |
| 7456 | } |
| 7457 | |
| 7458 | async fetch(request) { |
| 7459 | const path = new URL(request.url).pathname; |
| 7460 | if (request.method !== "POST") { |
| 7461 | return new Response("Queue route not found", { status: 404 }); |
| 7462 | } |
| 7463 | let body; |
| 7464 | try { |
| 7465 | body = await request.json(); |
| 7466 | } catch { |
| 7467 | return new Response("invalid Queue request", { status: 400 }); |
| 7468 | } |
| 7469 | try { |
| 7470 | if (path === "/__qSettle") { |
| 7471 | return await this._settle(body) |
| 7472 | ? new Response(null, { status: 204 }) |
| 7473 | : new Response("stale Queue settlement", { status: 409 }); |
| 7474 | } |
| 7475 | if (body.op === "info") { |
| 7476 | const metrics = this._metrics(); |
| 7477 | const stored = this._open().exec( |
| 7478 | `SELECT stored_count FROM ${__QUEUE_STATS} WHERE id = 1`, |
| 7479 | ).toArray()[0].stored_count; |
| 7480 | return Response.json({ result: { ...metrics, stored, paused: this._paused() } }); |
| 7481 | } |
| 7482 | if (body.op === "purge") { |
| 7483 | return Response.json({ result: await this._purge() }); |
| 7484 | } |
| 7485 | if (body.op === "pause") { |
| 7486 | return Response.json({ result: await this._setPaused(true) }); |
| 7487 | } |
| 7488 | if (body.op === "resume") { |
| 7489 | return Response.json({ result: await this._setPaused(false) }); |
| 7490 | } |
| 7491 | if (body.op === "peek") { |
| 7492 | return Response.json({ |
| 7493 | result: this._peek(this._operatorLimit(body.limit, 10)), |
| 7494 | }); |
| 7495 | } |
| 7496 | if (body.op === "redrive") { |
| 7497 | return Response.json({ |
| 7498 | result: await this._redrive(this._operatorLimit(body.limit, 100)), |
| 7499 | }); |
| 7500 | } |
| 7501 | return Response.json( |
| 7502 | { error: `QUEUE_ERROR: unknown operation ${JSON.stringify(body.op)}` }, |
| 7503 | { status: 400 }, |
| 7504 | ); |
| 7505 | } catch (error) { |
| 7506 | return Response.json( |
| 7507 | { error: String(error?.message ?? error) }, |
| 7508 | { status: 400 }, |
| 7509 | ); |
| 7510 | } |
| 7511 | } |
| 7512 | } |
| 7513 | |
| 7514 | __runtimeClass("__Queue", __QueueCell); |
| 7515 | |
| 7516 | class Queue { |
| 7517 | constructor(queue, cellName, deliveryDelay) { |
| 7518 | Object.defineProperties(this, { |
| 7519 | _queue: { value: queue }, |
| 7520 | _cellName: { value: cellName }, |
| 7521 | _deliveryDelay: { value: deliveryDelay }, |
| 7522 | }); |
| 7523 | } |
| 7524 | |
| 7525 | get _stub() { |
| 7526 | return __cell.makeNamespace("__Queue").getByName(this._cellName); |
| 7527 | } |
| 7528 | |
| 7529 | async _send(entries) { |
| 7530 | const metrics = await this._stub.__queueSend({ entries }); |
| 7531 | return { metadata: { metrics: __queueMetricsView(metrics) } }; |
| 7532 | } |
| 7533 | |
| 7534 | send(body, options = {}) { |
| 7535 | const encoded = __queueEncode(body, options.contentType); |
| 7536 | return this._send([{ |
| 7537 | ...encoded, |
| 7538 | delaySeconds: __queueDelay(options.delaySeconds, this._deliveryDelay), |
| 7539 | }]); |
| 7540 | } |
| 7541 | |
| 7542 | sendBatch(messages, options = {}) { |
| 7543 | if (messages === null || messages === undefined || |
| 7544 | typeof messages[Symbol.iterator] !== "function") { |
| 7545 | throw __queueError("sendBatch() needs an iterable of messages"); |
| 7546 | } |
| 7547 | const entries = []; |
| 7548 | let bytes = 0; |
| 7549 | const batchDelay = __queueDelay(options.delaySeconds, this._deliveryDelay); |
| 7550 | for (const message of messages) { |
| 7551 | if (entries.length >= __queueLimits().maxBatchMessages) { |
| 7552 | throw __queueError( |
| 7553 | `a batch has at most ${__queueLimits().maxBatchMessages} messages`, |
| 7554 | ); |
| 7555 | } |
| 7556 | if (message === null || typeof message !== "object" || !("body" in message)) { |
| 7557 | throw __queueError("each batch entry needs a body"); |
| 7558 | } |
| 7559 | const encoded = __queueEncode(message.body, message.contentType); |
| 7560 | bytes += encoded.size; |
| 7561 | if (bytes > __queueLimits().maxBatchBytes) { |
| 7562 | throw __queueError( |
| 7563 | `a batch is at most ${__queueLimits().maxBatchBytes} bytes, got ${bytes}`, |
| 7564 | ); |
| 7565 | } |
| 7566 | entries.push({ |
| 7567 | ...encoded, |
| 7568 | delaySeconds: __queueDelay(message.delaySeconds, batchDelay), |
| 7569 | }); |
| 7570 | } |
| 7571 | if (entries.length === 0) { |
| 7572 | throw __queueError("sendBatch() needs at least one message"); |
| 7573 | } |
| 7574 | return this._send(entries); |
| 7575 | } |
| 7576 | |
| 7577 | async metrics() { |
| 7578 | return __queueMetricsView(await this._stub.__queueMetrics()); |
| 7579 | } |
| 7580 | } |
| 7581 | |
| 7582 | __celld.__makeQueue = (queue, cellName, deliveryDelay) => |
| 7583 | new Queue(queue, cellName, deliveryDelay); |
| 7584 | |
| 7585 | // ---- D1 ----------------------------------------------------------------- |
| 7586 | // A D1 database is a cell of a runtime-supplied Durable Object class, so it |
| 7587 | // inherits ownership, fencing, LTX replication, RPO=0 acknowledgement and |
| 7588 | // pressure shedding from the cell it already is. This half is the server; |
| 7589 | // `__makeD1Database` below is the client the binding hands to a Worker. |
| 7590 | // |
| 7591 | // Everything SQL goes through the one `__d1_run` op. The engine owns the |
| 7592 | // statement walk, the row and byte caps, and the meta snapshot, all inside |
| 7593 | // one execution -- the previous shape assembled these from the general |
| 7594 | // SqlStorage ops, and every seam between them was a contract only convention |
| 7595 | // enforced. |
| 7596 | |
| 7597 | // The error families applications match on. A message that already carries |
| 7598 | // one must pass through unwrapped: wrapping again would bury the family the |
| 7599 | // application is matching under a second D1_ERROR prefix. |
| 7600 | const __d1IsFamilyError = (message) => |
| 7601 | /^D1_([A-Z]+_)*(ERROR|NOTFOUND): /.test(String(message)); |
| 7602 | |
| 7603 | const __d1Error = (message, cause) => { |
| 7604 | const error = new Error("D1_ERROR: " + String(message)); |
| 7605 | error.cause = cause !== undefined ? cause : new Error(String(message)); |
| 7606 | return error; |
| 7607 | }; |
| 7608 | |
| 7609 | // A typed refusal from the engine: `{family, message}` becomes the Error the |
| 7610 | // application sees, with `.cause` carrying the bare message as upstream does. |
| 7611 | const __d1Failure = (failure) => { |
| 7612 | const error = new Error(failure.family + ": " + failure.message); |
| 7613 | error.cause = new Error(failure.message); |
| 7614 | return error; |
| 7615 | }; |
| 7616 | |
| 7617 | const __d1Run = (scope, request) => { |
| 7618 | const response = JSON.parse(__d1_run(scope, JSON.stringify(request))); |
| 7619 | if (response.error) throw __d1Failure(response.error); |
| 7620 | return response.ok; |
| 7621 | }; |
| 7622 | |
| 7623 | class __D1DatabaseCell { |
| 7624 | constructor(ctx) { |
| 7625 | this.ctx = ctx; |
| 7626 | } |
| 7627 | // Takes an array so that `batch()` can ride this same method, and the |
| 7628 | // same turn, when it lands. |
| 7629 | __d1Query(statements) { |
| 7630 | const scope = this.ctx.storage.sql._scope; |
| 7631 | return statements.map((statement) => |
| 7632 | __d1Run(scope, { |
| 7633 | mode: "prepared", |
| 7634 | sql: String(statement.sql), |
| 7635 | params: statement.params || [], |
| 7636 | first: !!statement.first, |
| 7637 | }) |
| 7638 | ); |
| 7639 | } |
| 7640 | __d1Batch(statements) { |
| 7641 | return __d1Run(this.ctx.storage.sql._scope, { |
| 7642 | mode: "batch", |
| 7643 | statements: statements.map((statement) => ({ |
| 7644 | sql: String(statement.sql), |
| 7645 | params: statement.params || [], |
| 7646 | })), |
| 7647 | }); |
| 7648 | } |
| 7649 | // The CLI's way in. `celld d1` signs each request with the fleet secret |
| 7650 | // and sends it to a live node's `/runtime/<scope>` route, which verifies the |
| 7651 | // signature and then forwards to the owner over the same dispatch `/do/` |
| 7652 | // uses -- so the CLI needs no ownership logic and the database is reached |
| 7653 | // the way a Worker reaches it. The unauthenticated `/do/` route refuses a |
| 7654 | // D1 scope outright: this cell answers arbitrary SQL, and its scope is an |
| 7655 | // HMAC over names that sit in the project's config, so the scope itself |
| 7656 | // is no secret. |
| 7657 | async fetch(request) { |
| 7658 | let body; |
| 7659 | try { |
| 7660 | body = await request.json(); |
| 7661 | } catch { |
| 7662 | return Response.json({ error: "D1_ERROR: invalid request body" }, { status: 400 }); |
| 7663 | } |
| 7664 | try { |
| 7665 | let result; |
| 7666 | if (body.migrate !== undefined) { |
| 7667 | result = this.__d1Migrate( |
| 7668 | String(body.migrate.name), |
| 7669 | String(body.migrate.sql), |
| 7670 | String(body.migrate.table || "d1_migrations"), |
| 7671 | ); |
| 7672 | } else if (body.exec !== undefined) { |
| 7673 | // The CLI asks for rows; the Worker binding's exec() never does. |
| 7674 | result = __d1Run(this.ctx.storage.sql._scope, { |
| 7675 | mode: "exec", |
| 7676 | sql: String(body.exec.sql), |
| 7677 | rows: !!body.exec.rows, |
| 7678 | }); |
| 7679 | } else { |
| 7680 | result = this.__d1Query(body.statements || []); |
| 7681 | } |
| 7682 | return Response.json({ result }); |
| 7683 | } catch (error) { |
| 7684 | return Response.json({ error: String(error && error.message || error) }, { status: 400 }); |
| 7685 | } |
| 7686 | } |
| 7687 | __d1Exec(source) { |
| 7688 | const result = __d1Run(this.ctx.storage.sql._scope, { |
| 7689 | mode: "exec", |
| 7690 | sql: String(source), |
| 7691 | rows: false, |
| 7692 | }); |
| 7693 | return { count: result.count, duration: result.duration }; |
| 7694 | } |
| 7695 | // Apply one migration and record it. The engine runs the file, the |
| 7696 | // bookkeeping insert (the name is a bound parameter, so a file name never |
| 7697 | // reaches SQL text) and the BEGIN IMMEDIATE .. COMMIT bracket in one |
| 7698 | // request, so a migration that fails part-way rolls back whole and the |
| 7699 | // operator fixes the file and re-runs. Without the transaction the |
| 7700 | // statements that DID land are exactly the ones a re-run trips over. |
| 7701 | __d1Migrate(name, source, table) { |
| 7702 | return __d1Run(this.ctx.storage.sql._scope, { |
| 7703 | mode: "migrate", |
| 7704 | name, |
| 7705 | sql: source, |
| 7706 | table, |
| 7707 | }); |
| 7708 | } |
| 7709 | } |
| 7710 | |
| 7711 | __runtimeClass("__D1Database", __D1DatabaseCell); |
| 7712 | |
| 7713 | // Validate and encode bind values once, at the public boundary, exactly as |
| 7714 | // upstream does (workerd d1-api.ts). Byte-shaped values become byte arrays -- |
| 7715 | // the wire format for a BLOB bind -- and anything unsupported throws |
| 7716 | // D1_TYPE_ERROR here, before any SQL runs. The first version deferred this |
| 7717 | // to a JSON round-trip whose fallthrough was SQL NULL, so a Uint8Array bind |
| 7718 | // stored NULL and nothing said so. |
| 7719 | const __d1BindValue = (value) => { |
| 7720 | const kind = typeof value; |
| 7721 | if (kind === "number") { |
| 7722 | // A non-finite number has no JSON form, so it crosses as null and |
| 7723 | // stores SQL NULL. Upstream does the same (bind(NaN) selects typeof |
| 7724 | // "null"); making it explicit here turns the conversion from an |
| 7725 | // accident of JSON.stringify into a pinned decision. |
| 7726 | return Number.isFinite(value) ? value : null; |
| 7727 | } |
| 7728 | if (kind === "string") return value; |
| 7729 | if (kind === "boolean") return value ? 1 : 0; |
| 7730 | if (kind === "object") { |
| 7731 | if (value === null) return value; |
| 7732 | if ( |
| 7733 | Array.isArray(value) && |
| 7734 | value.every((byte) => typeof byte === "number" && byte >= 0 && byte < 256) |
| 7735 | ) { |
| 7736 | return value; |
| 7737 | } |
| 7738 | if (value instanceof ArrayBuffer) { |
| 7739 | return Array.from(new Uint8Array(value)); |
| 7740 | } |
| 7741 | // A typed view binds its ELEMENT values, each truncated to a byte -- |
| 7742 | // Int8Array([-1]) stores 0xff, Float32Array([1.5]) stores 0x01 -- not |
| 7743 | // its underlying byte window, so Uint16Array([65, 66]) stores 2 bytes |
| 7744 | // and not 4. Upstream behaves this way (verified against workerd's D1; |
| 7745 | // the differential suite pins it), and the bare Array.from that |
| 7746 | // preceded this produced elements the engine then refused as bytes. |
| 7747 | if (ArrayBuffer.isView(value)) return Array.from(Uint8Array.from(value)); |
| 7748 | } |
| 7749 | const error = new Error( |
| 7750 | `D1_TYPE_ERROR: Type '${kind}' not supported for value '${value}'`, |
| 7751 | ); |
| 7752 | error.cause = new Error(`Type '${kind}' not supported for value '${value}'`); |
| 7753 | throw error; |
| 7754 | }; |
| 7755 | |
| 7756 | class D1PreparedStatement { |
| 7757 | constructor(database, sql, params) { |
| 7758 | Object.defineProperty(this, "_database", { value: database }); |
| 7759 | Object.defineProperty(this, "_sql", { value: sql }); |
| 7760 | Object.defineProperty(this, "_params", { value: params }); |
| 7761 | } |
| 7762 | bind(...values) { |
| 7763 | return new D1PreparedStatement( |
| 7764 | this._database, |
| 7765 | this._sql, |
| 7766 | values.map(__d1BindValue), |
| 7767 | ); |
| 7768 | } |
| 7769 | async _run(first) { |
| 7770 | const results = await this._database._query([ |
| 7771 | { sql: this._sql, params: this._params, first }, |
| 7772 | ]); |
| 7773 | return results[0]; |
| 7774 | } |
| 7775 | async all() { |
| 7776 | const result = await this._run(); |
| 7777 | return { |
| 7778 | success: true, |
| 7779 | meta: result.meta, |
| 7780 | results: result.rows.map((row) => __d1Shape(result.columns, row)), |
| 7781 | }; |
| 7782 | } |
| 7783 | async run() { |
| 7784 | return await this.all(); |
| 7785 | } |
| 7786 | async first(column) { |
| 7787 | // `first: true` keeps one row on the cell side, so only that row crosses |
| 7788 | // the isolate boundary and the row cap cannot fire for a first(). |
| 7789 | const result = await this._run(true); |
| 7790 | if (result.rows.length === 0) return null; |
| 7791 | const row = __d1Shape(result.columns, result.rows[0]); |
| 7792 | if (column === undefined) return row; |
| 7793 | // The check runs on the shaped object, as upstream's does, so a column |
| 7794 | // named like an Object.prototype member behaves the same here as there. |
| 7795 | if (row[column] === undefined) { |
| 7796 | const error = new Error( |
| 7797 | `D1_COLUMN_NOTFOUND: Column not found (${column})`, |
| 7798 | ); |
| 7799 | error.cause = new Error("Column not found"); |
| 7800 | throw error; |
| 7801 | } |
| 7802 | return row[column]; |
| 7803 | } |
| 7804 | async raw(options) { |
| 7805 | const result = await this._run(); |
| 7806 | return options && options.columnNames |
| 7807 | ? [result.columns, ...result.rows] |
| 7808 | : result.rows; |
| 7809 | } |
| 7810 | } |
| 7811 | |
| 7812 | // Object.fromEntries, not property assignment: assigning to a column named |
| 7813 | // `__proto__` would walk the prototype chain and silently drop the value, |
| 7814 | // while fromEntries defines an own property whatever the name. |
| 7815 | const __d1Shape = (columns, row) => |
| 7816 | Object.fromEntries(row.map((value, index) => [columns[index], value])); |
| 7817 | |
| 7818 | const __d1PublicResult = (result) => ({ |
| 7819 | success: true, |
| 7820 | meta: result.meta, |
| 7821 | results: result.rows.map((row) => __d1Shape(result.columns, row)), |
| 7822 | }); |
| 7823 | |
| 7824 | // celld has one primary and no replicas, so every completed query satisfies |
| 7825 | // every earlier session constraint. One stable opaque token states that fact |
| 7826 | // without pretending an isolate-local counter is a durable database position. |
| 7827 | const __d1PrimaryBookmark = "celld:primary"; |
| 7828 | |
| 7829 | class D1DatabaseSession { |
| 7830 | constructor(database, constraintOrBookmark) { |
| 7831 | Object.defineProperty(this, "_database", { value: database }); |
| 7832 | const value = constraintOrBookmark == null |
| 7833 | ? "first-unconstrained" |
| 7834 | : String(constraintOrBookmark).trim(); |
| 7835 | if (!value) { |
| 7836 | throw new Error("D1_SESSION_ERROR: invalid bookmark or constraint"); |
| 7837 | } |
| 7838 | Object.defineProperty(this, "_bookmark", { |
| 7839 | value: value === "first-primary" || value === "first-unconstrained" ? null : value, |
| 7840 | writable: true, |
| 7841 | }); |
| 7842 | } |
| 7843 | _advanceBookmark() { |
| 7844 | this._bookmark = __d1PrimaryBookmark; |
| 7845 | } |
| 7846 | async _query(statements) { |
| 7847 | const results = await this._database._query(statements); |
| 7848 | this._advanceBookmark(); |
| 7849 | return results; |
| 7850 | } |
| 7851 | prepare(sql) { |
| 7852 | return new D1PreparedStatement(this, String(sql), []); |
| 7853 | } |
| 7854 | async batch(statements) { |
| 7855 | const results = await this._database._batch(statements); |
| 7856 | this._advanceBookmark(); |
| 7857 | return results; |
| 7858 | } |
| 7859 | getBookmark() { |
| 7860 | return this._bookmark; |
| 7861 | } |
| 7862 | } |
| 7863 | |
| 7864 | // Named so SDKs that sniff a binding by `constructor.name` recognise it. |
| 7865 | class D1Database { |
| 7866 | constructor(databaseName) { |
| 7867 | Object.defineProperty(this, "_databaseName", { value: databaseName }); |
| 7868 | } |
| 7869 | // Resolved per call rather than cached: a cell can move between calls, and |
| 7870 | // `getByName` is the same cost the Durable Object path already pays. |
| 7871 | get _stub() { |
| 7872 | return __cell.makeNamespace("__D1Database").getByName(this._databaseName); |
| 7873 | } |
| 7874 | async _query(statements) { |
| 7875 | try { |
| 7876 | return await this._stub.__d1Query(statements); |
| 7877 | } catch (error) { |
| 7878 | if (__d1IsFamilyError(error && error.message)) throw error; |
| 7879 | throw __d1Error(String(error && error.message || error), error); |
| 7880 | } |
| 7881 | } |
| 7882 | async _batch(statements) { |
| 7883 | try { |
| 7884 | const encoded = statements.map((statement) => ({ |
| 7885 | sql: statement._sql, |
| 7886 | params: statement._params, |
| 7887 | })); |
| 7888 | const results = await this._stub.__d1Batch(encoded); |
| 7889 | return results.map(__d1PublicResult); |
| 7890 | } catch (error) { |
| 7891 | if (__d1IsFamilyError(error && error.message)) throw error; |
| 7892 | throw __d1Error(String(error && error.message || error), error); |
| 7893 | } |
| 7894 | } |
| 7895 | prepare(sql) { |
| 7896 | return new D1PreparedStatement(this, String(sql), []); |
| 7897 | } |
| 7898 | async exec(sql) { |
| 7899 | try { |
| 7900 | return await this._stub.__d1Exec(String(sql)); |
| 7901 | } catch (error) { |
| 7902 | if (__d1IsFamilyError(error && error.message)) throw error; |
| 7903 | throw __d1Error(String(error && error.message || error), error); |
| 7904 | } |
| 7905 | } |
| 7906 | async batch(statements) { |
| 7907 | return await this._batch(statements); |
| 7908 | } |
| 7909 | withSession(constraintOrBookmark) { |
| 7910 | return new D1DatabaseSession(this, constraintOrBookmark); |
| 7911 | } |
| 7912 | async dump() { |
| 7913 | throw __d1Error( |
| 7914 | "dump() is not implemented in celld; the database is a SQLite file in " + |
| 7915 | "your own bucket", |
| 7916 | ); |
| 7917 | } |
| 7918 | } |
| 7919 | |
| 7920 | const __makeD1Database = __celld.__makeD1Database = |
| 7921 | (databaseName) => new D1Database(databaseName); |
| 7922 | // ---- Workflows ---------------------------------------------------------- |
| 7923 | // A workflow instance is one cell of the runtime-supplied `__Workflow` class, |
| 7924 | // named `<workflow_name>/<instance_id>` through getByName, so it inherits |
| 7925 | // ownership, fencing, LTX replication and the output gate from the cell it |
| 7926 | // already is. Execution is replay: `run()` re-executes from the top on every |
| 7927 | // resume and only steps are memoized, in `ctx.storage` KV under `__wf.*`. |
| 7928 | // This half is the server; `__makeWorkflow` below is the client the binding |
| 7929 | // hands to a Worker. The public contract is in docs/cloudflare-compat.md. |
| 7930 | |
| 7931 | // Upstream's limit for a step return, an event payload, and the params. The |
| 7932 | // error is distinct and names the step, because "too large" and "the isolate |
| 7933 | // died" must not read the same (the D1 row-cap precedent). |
| 7934 | const __WF_VALUE_CAP = 1 << 20; |
| 7935 | // Workflow names, instance ids, and event types all share this charset. |
| 7936 | // `/` is outside it, which is what makes the `<name>/<id>` cell-name join |
| 7937 | // unambiguous. |
| 7938 | const __WF_NAME_RE = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/; |
| 7939 | const __wfError = (message) => new Error("WORKFLOW_ERROR: " + message); |
| 7940 | // The suspension primitive: a blocked step returns a promise that never |
| 7941 | // settles in this invocation, so user code simply stops progressing. A |
| 7942 | // sentinel thrown through user code was rejected because `Promise.all` in |
| 7943 | // `run()` would observe it as a rejection and user try/catch would eat it. |
| 7944 | const __wfNever = new Promise(() => {}); |
| 7945 | const __wfTerminal = (status) => |
| 7946 | status === "complete" || status === "errored" || status === "terminated"; |
| 7947 | // Upstream's hard bounds: 10,000 retries per step, 365 days for any sleep or |
| 7948 | // event wait, one second under a waitForEvent timeout. Enforced loudly at the |
| 7949 | // call site -- a config outside them would otherwise misbehave only after |
| 7950 | // the instance is minutes or days into its run. |
| 7951 | const __WF_RETRY_LIMIT_CAP = 10000; |
| 7952 | const __WF_STEP_NAME_LIMIT = 256; |
| 7953 | const __WF_MAX_WAIT_MS = 365 * 86400000; |
| 7954 | const __WF_MIN_EVENT_TIMEOUT_MS = 1000; |
| 7955 | // celld has no account plans, so it exposes the larger published retention |
| 7956 | // ceiling as one stable application limit. Both an omitted policy and an |
| 7957 | // omitted member of a partial policy use this value. |
| 7958 | const __WF_RETENTION_MAX_MS = 30 * 86400000; |
| 7959 | const __WF_LOCATION_HINTS = new Set([ |
| 7960 | "wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", |
| 7961 | "oc", "afr", "me", |
| 7962 | ]); |
| 7963 | // How long run() can stay pending on non-step work while no step runs and |
| 7964 | // none is blocked before the instance fails. Upstream permits un-stepped |
| 7965 | // awaits between steps (they are merely non-durable), so erroring at the |
| 7966 | // first quiescent macrotask would kill any run() whose external await |
| 7967 | // outlives one turn of the loop. Sixty seconds is long enough for any |
| 7968 | // sane un-stepped await and short enough that a truly never-settling |
| 7969 | // promise fails the instance instead of wedging the alarm handler. |
| 7970 | const __WF_STALL_GRACE_MS = 60000; |
| 7971 | const __WF_UNITS = { |
| 7972 | second: 1000, |
| 7973 | minute: 60000, |
| 7974 | hour: 3600000, |
| 7975 | day: 86400000, |
| 7976 | week: 604800000, |
| 7977 | // Upstream does not document its month/year arithmetic; fixed 30/365-day |
| 7978 | // units are used so one expression cannot mean two durations depending on |
| 7979 | // when it runs. |
| 7980 | month: 30 * 86400000, |
| 7981 | year: 365 * 86400000, |
| 7982 | }; |
| 7983 | const __wfDuration = (value, what) => { |
| 7984 | if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value; |
| 7985 | if (typeof value !== "string") { |
| 7986 | throw __wfError( |
| 7987 | `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + |
| 7988 | 'or "<n> <second|minute|hour|day|week|month|year>[s]"', |
| 7989 | ); |
| 7990 | } |
| 7991 | const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week|month|year)s?\s*$/ |
| 7992 | .exec(value); |
| 7993 | if (!match) { |
| 7994 | throw __wfError( |
| 7995 | `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + |
| 7996 | 'or "<n> <second|minute|hour|day|week|month|year>[s]"', |
| 7997 | ); |
| 7998 | } |
| 7999 | return Number(match[1]) * __WF_UNITS[match[2]]; |
| 8000 | }; |
| 8001 | const __wfRetentionDuration = (value, what) => { |
| 8002 | const durationMs = __wfDuration(value, what); |
| 8003 | if (durationMs > __WF_RETENTION_MAX_MS) { |
| 8004 | throw __wfError( |
| 8005 | `${what} is ${durationMs} ms, above celld's 30-day retention limit`, |
| 8006 | ); |
| 8007 | } |
| 8008 | return durationMs; |
| 8009 | }; |
| 8010 | const __wfOwnObject = (value) => |
| 8011 | value !== null && typeof value === "object" && !Array.isArray(value); |
| 8012 | const __wfUnknownKey = (value, allowed) => |
| 8013 | Object.keys(value).find((key) => !allowed.includes(key)); |
| 8014 | const __wfStepName = (name) => { |
| 8015 | // The pinned workers-sdk validator has no minimum length. An empty name is |
| 8016 | // therefore valid, although rejecting it looks safer at first glance. A |
| 8017 | // non-empty check made celld reject Worker code that the upstream runtime |
| 8018 | // accepts, so keep only the upstream length and control-character bounds. |
| 8019 | if ( |
| 8020 | typeof name !== "string" || name.length > __WF_STEP_NAME_LIMIT || |
| 8021 | /[\x00-\x1f]/.test(name) |
| 8022 | ) { |
| 8023 | throw __wfError( |
| 8024 | `invalid step name ${JSON.stringify(name)}: use at most ` + |
| 8025 | `${__WF_STEP_NAME_LIMIT} characters and no control characters`, |
| 8026 | ); |
| 8027 | } |
| 8028 | }; |
| 8029 | const __wfEventType = (type) => { |
| 8030 | if (typeof type !== "string" || type.length > 100 || !__WF_NAME_RE.test(type)) { |
| 8031 | throw __wfError( |
| 8032 | `invalid event type ${JSON.stringify(type)}: use at most 100 letters, ` + |
| 8033 | "digits, hyphens, or underscores", |
| 8034 | ); |
| 8035 | } |
| 8036 | }; |
| 8037 | const __wfSleepDuration = (duration, name) => { |
| 8038 | const durationMs = __wfDuration( |
| 8039 | duration, |
| 8040 | `the duration of sleep ${JSON.stringify(name)}`, |
| 8041 | ); |
| 8042 | if (durationMs > __WF_MAX_WAIT_MS) { |
| 8043 | throw __wfError( |
| 8044 | `sleep ${JSON.stringify(name)} is ${durationMs} ms, above the upstream ` + |
| 8045 | "limit of 365 days", |
| 8046 | ); |
| 8047 | } |
| 8048 | return durationMs; |
| 8049 | }; |
| 8050 | const __wfSleepUntil = (timestamp, name) => { |
| 8051 | const at = timestamp instanceof Date ? timestamp.getTime() : timestamp; |
| 8052 | if (typeof at !== "number" || !Number.isFinite(at)) { |
| 8053 | throw __wfError( |
| 8054 | `invalid sleepUntil timestamp for ${JSON.stringify(name)}: use a Date ` + |
| 8055 | "or a UNIX timestamp in milliseconds", |
| 8056 | ); |
| 8057 | } |
| 8058 | const delay = at - Date.now(); |
| 8059 | if (delay > __WF_MAX_WAIT_MS) { |
| 8060 | throw __wfError( |
| 8061 | `sleepUntil ${JSON.stringify(name)} is ${delay} ms away, above the ` + |
| 8062 | "upstream limit of 365 days", |
| 8063 | ); |
| 8064 | } |
| 8065 | return at; |
| 8066 | }; |
| 8067 | const __wfWaitOptions = (options, name) => { |
| 8068 | if (!__wfOwnObject(options)) { |
| 8069 | throw __wfError(`invalid waitForEvent options for ${JSON.stringify(name)}`); |
| 8070 | } |
| 8071 | __wfEventType(options.type); |
| 8072 | const timeout = options.timeout ?? "24 hours"; |
| 8073 | const timeoutMs = __wfDuration( |
| 8074 | timeout, |
| 8075 | `the timeout of waitForEvent ${JSON.stringify(name)}`, |
| 8076 | ); |
| 8077 | if (timeoutMs < __WF_MIN_EVENT_TIMEOUT_MS || timeoutMs > __WF_MAX_WAIT_MS) { |
| 8078 | throw __wfError( |
| 8079 | `the timeout of waitForEvent ${JSON.stringify(name)} is ${timeoutMs} ms; ` + |
| 8080 | "upstream allows 1 second to 365 days", |
| 8081 | ); |
| 8082 | } |
| 8083 | return { type: options.type, timeout, timeoutMs }; |
| 8084 | }; |
| 8085 | const __wfEventOptions = (options) => { |
| 8086 | if (!__wfOwnObject(options)) { |
| 8087 | throw __wfError("sendEvent() needs an event object"); |
| 8088 | } |
| 8089 | __wfEventType(options.type); |
| 8090 | if (options.payload !== undefined) __wfCheckValue(options.payload, "the event payload"); |
| 8091 | return { type: options.type, payload: options.payload }; |
| 8092 | }; |
| 8093 | const __wfRetentionOptions = (retention, what) => { |
| 8094 | if (retention === undefined) { |
| 8095 | return { |
| 8096 | successMs: __WF_RETENTION_MAX_MS, |
| 8097 | errorMs: __WF_RETENTION_MAX_MS, |
| 8098 | }; |
| 8099 | } |
| 8100 | if (!__wfOwnObject(retention)) { |
| 8101 | throw __wfError(`${what} option retention must be an object`); |
| 8102 | } |
| 8103 | const unknown = __wfUnknownKey(retention, ["successRetention", "errorRetention"]); |
| 8104 | if (unknown !== undefined) { |
| 8105 | throw __wfError( |
| 8106 | `${what} option retention has an unknown field ${JSON.stringify(unknown)}`, |
| 8107 | ); |
| 8108 | } |
| 8109 | return { |
| 8110 | successMs: retention.successRetention === undefined |
| 8111 | ? __WF_RETENTION_MAX_MS |
| 8112 | : __wfRetentionDuration( |
| 8113 | retention.successRetention, |
| 8114 | `${what} successRetention`, |
| 8115 | ), |
| 8116 | errorMs: retention.errorRetention === undefined |
| 8117 | ? __WF_RETENTION_MAX_MS |
| 8118 | : __wfRetentionDuration(retention.errorRetention, `${what} errorRetention`), |
| 8119 | }; |
| 8120 | }; |
| 8121 | const __wfLocationHint = (hint, what) => { |
| 8122 | if (hint !== undefined && !__WF_LOCATION_HINTS.has(hint)) { |
| 8123 | throw __wfError( |
| 8124 | `${what} has invalid locationHint ${JSON.stringify(hint)}`, |
| 8125 | ); |
| 8126 | } |
| 8127 | return hint; |
| 8128 | }; |
| 8129 | const __wfRestartOptions = (options) => { |
| 8130 | if (options === undefined) return {}; |
| 8131 | if (!__wfOwnObject(options)) { |
| 8132 | throw __wfError("restart() options must be an object"); |
| 8133 | } |
| 8134 | const unknown = __wfUnknownKey(options, ["from"]); |
| 8135 | if (unknown !== undefined) { |
| 8136 | throw __wfError(`restart() has an unknown option ${JSON.stringify(unknown)}`); |
| 8137 | } |
| 8138 | if (options.from === undefined) return {}; |
| 8139 | const from = options.from; |
| 8140 | if (!__wfOwnObject(from)) { |
| 8141 | throw __wfError("restart() option from must be an object"); |
| 8142 | } |
| 8143 | const fromUnknown = __wfUnknownKey(from, ["name", "count", "type"]); |
| 8144 | if (fromUnknown !== undefined) { |
| 8145 | throw __wfError( |
| 8146 | `restart() option from has an unknown field ${JSON.stringify(fromUnknown)}`, |
| 8147 | ); |
| 8148 | } |
| 8149 | __wfStepName(from.name); |
| 8150 | const count = from.count ?? 1; |
| 8151 | if (!Number.isInteger(count) || count < 1) { |
| 8152 | throw __wfError("restart() option from.count must be a positive integer"); |
| 8153 | } |
| 8154 | const type = from.type ?? "do"; |
| 8155 | if (!["do", "sleep", "waitForEvent"].includes(type)) { |
| 8156 | throw __wfError( |
| 8157 | 'restart() option from.type must be "do", "sleep", or "waitForEvent"', |
| 8158 | ); |
| 8159 | } |
| 8160 | return { from: { name: from.name, count, type } }; |
| 8161 | }; |
| 8162 | const __wfStepConfig = (config, name) => { |
| 8163 | if (!__wfOwnObject(config)) { |
| 8164 | throw __wfError(`invalid config for step ${JSON.stringify(name)}: use an object`); |
| 8165 | } |
| 8166 | let unknown = __wfUnknownKey(config, ["retries", "timeout", "sensitive"]); |
| 8167 | if (unknown !== undefined) { |
| 8168 | throw __wfError( |
| 8169 | `invalid config for step ${JSON.stringify(name)}: unknown option ` + |
| 8170 | JSON.stringify(unknown), |
| 8171 | ); |
| 8172 | } |
| 8173 | const retries = config.retries; |
| 8174 | if (retries !== undefined) { |
| 8175 | if (!__wfOwnObject(retries)) { |
| 8176 | throw __wfError(`invalid retries config for step ${JSON.stringify(name)}`); |
| 8177 | } |
| 8178 | unknown = __wfUnknownKey(retries, ["limit", "delay", "backoff"]); |
| 8179 | if (unknown !== undefined) { |
| 8180 | throw __wfError( |
| 8181 | `invalid retries config for step ${JSON.stringify(name)}: unknown option ` + |
| 8182 | JSON.stringify(unknown), |
| 8183 | ); |
| 8184 | } |
| 8185 | if ( |
| 8186 | typeof retries.limit !== "number" || !Number.isFinite(retries.limit) || |
| 8187 | retries.limit < 0 |
| 8188 | ) { |
| 8189 | throw __wfError( |
| 8190 | `invalid retries config for step ${JSON.stringify(name)}: ` + |
| 8191 | "limit must be a non-negative number", |
| 8192 | ); |
| 8193 | } |
| 8194 | if (retries.limit > __WF_RETRY_LIMIT_CAP) { |
| 8195 | throw __wfError( |
| 8196 | `invalid retries config for step ${JSON.stringify(name)}: limit is above ` + |
| 8197 | String(__WF_RETRY_LIMIT_CAP), |
| 8198 | ); |
| 8199 | } |
| 8200 | if (typeof retries.delay !== "function") { |
| 8201 | __wfDuration(retries.delay, `the retries config delay of step ${JSON.stringify(name)}`); |
| 8202 | } |
| 8203 | if ( |
| 8204 | retries.backoff !== undefined && |
| 8205 | !["constant", "linear", "exponential"].includes(retries.backoff) |
| 8206 | ) { |
| 8207 | throw __wfError( |
| 8208 | `invalid retries config for step ${JSON.stringify(name)}: ` + |
| 8209 | "backoff must be constant, linear, or exponential", |
| 8210 | ); |
| 8211 | } |
| 8212 | } |
| 8213 | if (config.timeout !== undefined) { |
| 8214 | const timeout = __wfDuration( |
| 8215 | config.timeout, |
| 8216 | `the config timeout of step ${JSON.stringify(name)}`, |
| 8217 | ); |
| 8218 | if (timeout === 0) { |
| 8219 | throw __wfError( |
| 8220 | `invalid config timeout for step ${JSON.stringify(name)}: use a value above zero`, |
| 8221 | ); |
| 8222 | } |
| 8223 | } |
| 8224 | if (config.sensitive !== undefined && config.sensitive !== "output") { |
| 8225 | throw __wfError( |
| 8226 | `invalid config sensitive value for step ${JSON.stringify(name)}: use "output"`, |
| 8227 | ); |
| 8228 | } |
| 8229 | return { |
| 8230 | ...config, |
| 8231 | ...(retries === undefined ? {} : { retries: { ...retries } }), |
| 8232 | }; |
| 8233 | }; |
| 8234 | // Serialization is checked with the same encoder storage and RPC use, so a |
| 8235 | // value that passes here cannot fail later at the isolate boundary. The |
| 8236 | // thrown errors are permanent: retrying cannot make a value cloneable or |
| 8237 | // shrink it. |
| 8238 | const __wfEncodeValue = (value, what) => { |
| 8239 | try { |
| 8240 | return __sc_encode(value); |
| 8241 | } catch (error) { |
| 8242 | const failure = __wfError( |
| 8243 | `${what} is not serializable: ${String(error && error.message || error)}. ` + |
| 8244 | "It must survive structured clone; a ReadableStream return is not implemented in celld.", |
| 8245 | ); |
| 8246 | failure.__wfPermanent = true; |
| 8247 | throw failure; |
| 8248 | } |
| 8249 | }; |
| 8250 | const __wfCheckEncodedValue = (bytes, what) => { |
| 8251 | if (bytes.byteLength > __WF_VALUE_CAP) { |
| 8252 | const failure = __wfError( |
| 8253 | `${what} is ${bytes.byteLength} bytes, above the 1 MiB limit; ` + |
| 8254 | "store large output externally and return a reference", |
| 8255 | ); |
| 8256 | failure.__wfPermanent = true; |
| 8257 | throw failure; |
| 8258 | } |
| 8259 | }; |
| 8260 | const __wfCheckValue = (value, what) => |
| 8261 | __wfCheckEncodedValue(__wfEncodeValue(value, what), what); |
| 8262 | const __wfErrorRecord = (error) => ({ |
| 8263 | name: String(error && error.name || "Error"), |
| 8264 | message: String(error && error.message || error), |
| 8265 | }); |
| 8266 | // A permanently failed step rejects on every replay, so user try/catch |
| 8267 | // around step.do keeps working after a resume, not only on the attempt that |
| 8268 | // failed live. |
| 8269 | const __wfReviveError = (record) => { |
| 8270 | const error = new Error(record.message); |
| 8271 | error.name = record.name; |
| 8272 | return error; |
| 8273 | }; |
| 8274 | const __wfLedgerPrefix = (generation) => `__wf.${generation}.`; |
| 8275 | const __wfEventPrefix = (generation) => |
| 8276 | __wfLedgerPrefix(generation) + "event."; |
| 8277 | const __wfEventKey = (generation, sequence) => |
| 8278 | __wfEventPrefix(generation) + String(sequence).padStart(9, "0"); |
| 8279 | const __wfRetentionMs = (meta, status) => |
| 8280 | status === "complete" |
| 8281 | ? (meta.retention?.successMs ?? __WF_RETENTION_MAX_MS) |
| 8282 | : (meta.retention?.errorMs ?? __WF_RETENTION_MAX_MS); |
| 8283 | const __wfFinishRetention = (meta, transaction) => { |
| 8284 | meta.endedMs = Date.now(); |
| 8285 | meta.expiresMs = meta.endedMs + __wfRetentionMs(meta, meta.status); |
| 8286 | transaction.setAlarm(meta.expiresMs); |
| 8287 | }; |
| 8288 | // A ledger record replays only through the kind of call that wrote it. A |
| 8289 | // `do` renamed into a `sleep`, or two calls reordered under one name, would |
| 8290 | // otherwise read fields the other kind never wrote and continue on |
| 8291 | // undefined -- a deadline of NaN, a value of nothing -- instead of failing. |
| 8292 | const __wfKindCheck = (record, kind, name) => { |
| 8293 | if (record === undefined || record.kind === kind) return record; |
| 8294 | const failure = __wfError( |
| 8295 | `step ${JSON.stringify(name)} replays as ${kind} but its ledger record ` + |
| 8296 | `was written by ${record.kind}; a step keeps one kind across replays`, |
| 8297 | ); |
| 8298 | failure.__wfPermanent = true; |
| 8299 | throw failure; |
| 8300 | }; |
| 8301 | // Each step callback runs under an async-context frame naming its step (the |
| 8302 | // same CPED-backed frame __ctxRun uses, so it survives the callback's |
| 8303 | // awaits). A step started inside another step's callback would wedge |
| 8304 | // quiescence: the outer callback cannot settle while it awaits the blocked |
| 8305 | // inner step, so `running` never reaches zero and the instance can neither |
| 8306 | // suspend nor finish. The frame is what lets the inner call refuse loudly |
| 8307 | // at the nesting site instead. |
| 8308 | const __wfStepKey = Symbol("celld.wfStep"); |
| 8309 | const __wfEnclosingStep = () => { |
| 8310 | const frame = __als_get(); |
| 8311 | return frame === undefined ? undefined : frame.get(__wfStepKey); |
| 8312 | }; |
| 8313 | const __wfEnterStep = (name, fn) => { |
| 8314 | const prior = __als_get(); |
| 8315 | const frame = new Map(prior); |
| 8316 | frame.set(__wfStepKey, name); |
| 8317 | __als_set(frame); |
| 8318 | try { |
| 8319 | return fn(); |
| 8320 | } finally { |
| 8321 | __als_set(prior); |
| 8322 | } |
| 8323 | }; |
| 8324 | |
| 8325 | // Race an attempt against its deadline. The abandoned callback keeps |
| 8326 | // running -- there is no cancellation to send it -- but its result is |
| 8327 | // discarded and the timeout counts as a failed attempt, as upstream. |
| 8328 | const __wfTimeout = (promise, ms, name, attempt) => |
| 8329 | new Promise((resolve, reject) => { |
| 8330 | const timer = setTimeout( |
| 8331 | () => |
| 8332 | reject(new Error( |
| 8333 | `step ${JSON.stringify(name)} timed out after ${ms} ms (attempt ${attempt})`, |
| 8334 | )), |
| 8335 | ms, |
| 8336 | ); |
| 8337 | promise.then( |
| 8338 | (value) => { clearTimeout(timer); resolve(value); }, |
| 8339 | (error) => { clearTimeout(timer); reject(error); }, |
| 8340 | ); |
| 8341 | }); |
| 8342 | |
| 8343 | // Storage failures belong to the engine even when workflow code catches the |
| 8344 | // rejected step promise. Record them outside the Error object, so user code |
| 8345 | // cannot suppress a retry or forge one by returning a marked exception. |
| 8346 | const __wfTrackStorageFailures = (storage, driver) => { |
| 8347 | const tracked = Object.create(storage); |
| 8348 | for (const name of ["get", "put", "transactionSync"]) { |
| 8349 | Object.defineProperty(tracked, name, { |
| 8350 | value(...args) { |
| 8351 | try { |
| 8352 | const result = storage[name](...args); |
| 8353 | if (result !== null && typeof result === "object" && |
| 8354 | typeof result.then === "function") { |
| 8355 | return result.catch((error) => { |
| 8356 | driver.storageFailure ??= error; |
| 8357 | throw error; |
| 8358 | }); |
| 8359 | } |
| 8360 | return result; |
| 8361 | } catch (error) { |
| 8362 | driver.storageFailure ??= error; |
| 8363 | throw error; |
| 8364 | } |
| 8365 | }, |
| 8366 | }); |
| 8367 | } |
| 8368 | return tracked; |
| 8369 | }; |
| 8370 | |
| 8371 | // The WorkflowStep the driver hands to run(). Each method resolves its step |
| 8372 | // record by (name, occurrence count) -- the count is assigned synchronously |
| 8373 | // at call time, so `Promise.all` of two same-named steps gets deterministic |
| 8374 | // distinct keys in call order, and a repeated name in a loop cannot collide. |
| 8375 | const __wfMakeStep = (driver) => { |
| 8376 | const storage = driver.storage; |
| 8377 | // The shared step frame. `body` resolves to {value} or {block: at, kind}; |
| 8378 | // a blocked step leaves its promise unsettled forever in this invocation. |
| 8379 | // The running counter covers the whole body, ledger reads included, so |
| 8380 | // quiescence cannot fire between a step's read and its decision. |
| 8381 | const frame = (name, body) => { |
| 8382 | // A stale replay -- one whose invocation already suspended -- can wake |
| 8383 | // later if user code raced a step against an un-stepped await. It goes |
| 8384 | // quiet instead of executing an attempt beside the fresh replay. |
| 8385 | if (driver.finished) return __wfNever; |
| 8386 | const enclosing = __wfEnclosingStep(); |
| 8387 | if (enclosing !== undefined) { |
| 8388 | const failure = __wfError( |
| 8389 | `step ${JSON.stringify(name)} cannot start inside the callback of ` + |
| 8390 | `step ${JSON.stringify(enclosing)}; a step callback must not use ` + |
| 8391 | "the step API", |
| 8392 | ); |
| 8393 | failure.__wfPermanent = true; |
| 8394 | return Promise.reject(failure); |
| 8395 | } |
| 8396 | const count = (driver.counts.get(name) ?? 0) + 1; |
| 8397 | driver.counts.set(name, count); |
| 8398 | const ordinal = ++driver.ordinal; |
| 8399 | const key = driver.ledgerPrefix + `step.${count}.${name}`; |
| 8400 | // Step activity restarts the stall clock: a pending grace timer was |
| 8401 | // armed against a run() that looked stuck, and this call is progress. |
| 8402 | driver.clearStall(); |
| 8403 | driver.running += 1; |
| 8404 | return new Promise((resolve, reject) => { |
| 8405 | (async () => { |
| 8406 | const meta = await storage.get("__wf.meta"); |
| 8407 | if ( |
| 8408 | meta === undefined || meta.generation !== driver.generation || |
| 8409 | __wfTerminal(meta.status) || meta.status === "paused" || |
| 8410 | meta.status === "waitingForPause" |
| 8411 | ) { |
| 8412 | return { pause: true }; |
| 8413 | } |
| 8414 | return await body(key, count, ordinal); |
| 8415 | })().then( |
| 8416 | (result) => { |
| 8417 | driver.running -= 1; |
| 8418 | driver.clearStall(); |
| 8419 | if (result.pause === true) { |
| 8420 | driver.pauseRequested = true; |
| 8421 | driver.check(); |
| 8422 | return; |
| 8423 | } |
| 8424 | if (result.block !== undefined) { |
| 8425 | if (!driver.finished) { |
| 8426 | driver.blocked.push({ at: result.block, kind: result.kind }); |
| 8427 | } |
| 8428 | driver.check(); |
| 8429 | return; |
| 8430 | } |
| 8431 | driver.check(); |
| 8432 | resolve(result.value); |
| 8433 | }, |
| 8434 | (error) => { |
| 8435 | driver.running -= 1; |
| 8436 | driver.clearStall(); |
| 8437 | driver.check(); |
| 8438 | reject(error); |
| 8439 | }, |
| 8440 | ); |
| 8441 | }); |
| 8442 | }; |
| 8443 | const doStep = (name, configOrCallback, callbackOrRollback, maybeRollback) => { |
| 8444 | const hasConfig = typeof configOrCallback !== "function"; |
| 8445 | let config = hasConfig ? (configOrCallback ?? {}) : {}; |
| 8446 | const callback = hasConfig ? callbackOrRollback : configOrCallback; |
| 8447 | const rollback = hasConfig ? maybeRollback : callbackOrRollback; |
| 8448 | try { |
| 8449 | __wfStepName(name); |
| 8450 | config = __wfStepConfig(config, name); |
| 8451 | } catch (error) { |
| 8452 | return Promise.reject(error); |
| 8453 | } |
| 8454 | if (rollback !== undefined) { |
| 8455 | return Promise.reject(__wfError( |
| 8456 | "step rollbackOptions are not implemented in celld; remove the rollback handler", |
| 8457 | )); |
| 8458 | } |
| 8459 | if (config.sensitive !== undefined) { |
| 8460 | return Promise.reject(__wfError( |
| 8461 | "sensitive step output is not implemented in celld; remove `sensitive`", |
| 8462 | )); |
| 8463 | } |
| 8464 | if (typeof callback !== "function") { |
| 8465 | return Promise.reject(__wfError("step.do needs a callback function")); |
| 8466 | } |
| 8467 | return frame(name, async (key, count, ordinal) => { |
| 8468 | const record = __wfKindCheck(await storage.get(key), "do", name); |
| 8469 | if (record !== undefined && record.status === "completed") { |
| 8470 | return { value: record.value }; |
| 8471 | } |
| 8472 | if (record !== undefined && record.status === "failed") { |
| 8473 | throw __wfReviveError(record.error); |
| 8474 | } |
| 8475 | // A pending retry whose backoff has not elapsed blocks without |
| 8476 | // executing; the deadline was persisted when the attempt failed, so a |
| 8477 | // replay cannot reset the backoff. |
| 8478 | if (record !== undefined && record.nextAt > Date.now()) { |
| 8479 | return { block: record.nextAt, kind: "retry" }; |
| 8480 | } |
| 8481 | const attempt = (record === undefined ? 0 : record.attempt) + 1; |
| 8482 | const historyOrdinal = record?.ordinal ?? ordinal; |
| 8483 | const retries = config.retries ?? |
| 8484 | { limit: 5, delay: 10000, backoff: "exponential" }; |
| 8485 | const timeout = config.timeout ?? "10 minutes"; |
| 8486 | const timeoutMs = __wfDuration( |
| 8487 | timeout, |
| 8488 | `the timeout of step ${JSON.stringify(name)}`, |
| 8489 | ); |
| 8490 | // Upstream omits a dynamic delay from the step context. Copying the |
| 8491 | // config verbatim would expose the callback to itself as retry policy, |
| 8492 | // while callers expect only the serializable limit and backoff fields. |
| 8493 | const contextRetries = typeof retries.delay === "function" |
| 8494 | ? { limit: retries.limit, ...(retries.backoff === undefined |
| 8495 | ? {} |
| 8496 | : { backoff: retries.backoff }) } |
| 8497 | : retries; |
| 8498 | const context = { |
| 8499 | step: { name, count }, |
| 8500 | attempt, |
| 8501 | config: { retries: contextRetries, timeout }, |
| 8502 | }; |
| 8503 | try { |
| 8504 | // Persist the history entry before the callback starts. A concurrent |
| 8505 | // selected restart can therefore name an in-flight occurrence, and |
| 8506 | // its new generation fences the callback's eventual old-ledger write. |
| 8507 | await storage.put(key, { |
| 8508 | kind: "do", |
| 8509 | status: "running", |
| 8510 | attempt: attempt - 1, |
| 8511 | ordinal: historyOrdinal, |
| 8512 | }); |
| 8513 | const value = await __wfTimeout( |
| 8514 | __wfEnterStep(name, async () => callback(context)), |
| 8515 | timeoutMs, |
| 8516 | name, |
| 8517 | attempt, |
| 8518 | ); |
| 8519 | if (value !== undefined) { |
| 8520 | __wfCheckValue(value, `the return value of step ${JSON.stringify(name)}`); |
| 8521 | } |
| 8522 | await storage.put(key, { |
| 8523 | kind: "do", |
| 8524 | status: "completed", |
| 8525 | value, |
| 8526 | ordinal: historyOrdinal, |
| 8527 | }); |
| 8528 | return { value }; |
| 8529 | } catch (error) { |
| 8530 | // NonRetryableError skips retries by contract; a value-cap or |
| 8531 | // serialization failure is marked permanent above because another |
| 8532 | // attempt returns the same value. |
| 8533 | const permanent = error instanceof NonRetryableError || |
| 8534 | (error !== null && typeof error === "object" && |
| 8535 | (error.name === "NonRetryableError" || error.__wfPermanent === true)) || |
| 8536 | attempt > retries.limit; |
| 8537 | if (permanent) { |
| 8538 | await storage.put(key, { |
| 8539 | kind: "do", |
| 8540 | status: "failed", |
| 8541 | error: __wfErrorRecord(error), |
| 8542 | ordinal: historyOrdinal, |
| 8543 | }); |
| 8544 | throw error; |
| 8545 | } |
| 8546 | // Upstream documents the backoff names, not the arithmetic; the |
| 8547 | // simplest reading is used and recorded in the design page. When |
| 8548 | // `retries` is given without `backoff`, celld uses constant -- the |
| 8549 | // documented exponential default is the whole-config-omitted case. |
| 8550 | const dynamic = typeof retries.delay === "function"; |
| 8551 | const delay = dynamic |
| 8552 | ? await __wfEnterStep(name, () => retries.delay({ ctx: context, error })) |
| 8553 | : retries.delay; |
| 8554 | const base = __wfDuration( |
| 8555 | delay, |
| 8556 | `the retry delay of step ${JSON.stringify(name)}`, |
| 8557 | ); |
| 8558 | // A delay callback replaces the fixed base duration, not the backoff |
| 8559 | // policy. Skipping this factor makes a dynamic exponential or linear |
| 8560 | // policy retry earlier than the same policy with a fixed base. |
| 8561 | const factor = retries.backoff === "exponential" |
| 8562 | ? 2 ** (attempt - 1) |
| 8563 | : retries.backoff === "linear" |
| 8564 | ? attempt |
| 8565 | : 1; |
| 8566 | const nextAt = Date.now() + base * factor; |
| 8567 | await storage.put(key, { |
| 8568 | kind: "do", |
| 8569 | status: "retrying", |
| 8570 | attempt, |
| 8571 | nextAt, |
| 8572 | ordinal: historyOrdinal, |
| 8573 | }); |
| 8574 | return { block: nextAt, kind: "retry" }; |
| 8575 | } |
| 8576 | }); |
| 8577 | }; |
| 8578 | const sleepUntilDeadline = (name, key, ordinal, deadline) => (async () => { |
| 8579 | const record = __wfKindCheck(await storage.get(key), "sleep", name); |
| 8580 | if (record !== undefined && record.status === "completed") { |
| 8581 | return { value: undefined }; |
| 8582 | } |
| 8583 | const historyOrdinal = record?.ordinal ?? ordinal; |
| 8584 | let at = record === undefined ? undefined : record.deadline; |
| 8585 | if (at === undefined) { |
| 8586 | // The absolute deadline is computed once and persisted. Recomputing |
| 8587 | // from "now" on replay would extend the sleep by however long the |
| 8588 | // instance was down, so a crash could postpone a deadline forever. |
| 8589 | at = deadline(); |
| 8590 | if (at - Date.now() > __WF_MAX_WAIT_MS) { |
| 8591 | throw __wfError( |
| 8592 | `sleep ${JSON.stringify(name)} ends ${at - Date.now()} ms from now, ` + |
| 8593 | "above the upstream limit of 365 days", |
| 8594 | ); |
| 8595 | } |
| 8596 | await storage.put(key, { |
| 8597 | kind: "sleep", |
| 8598 | status: "sleeping", |
| 8599 | deadline: at, |
| 8600 | ordinal: historyOrdinal, |
| 8601 | }); |
| 8602 | } |
| 8603 | if (at <= Date.now()) { |
| 8604 | await storage.put(key, { |
| 8605 | kind: "sleep", |
| 8606 | status: "completed", |
| 8607 | ordinal: historyOrdinal, |
| 8608 | }); |
| 8609 | return { value: undefined }; |
| 8610 | } |
| 8611 | return { block: at, kind: "sleep" }; |
| 8612 | })(); |
| 8613 | return { |
| 8614 | do: doStep, |
| 8615 | sleep: (name, duration) => { |
| 8616 | let durationMs; |
| 8617 | try { |
| 8618 | __wfStepName(name); |
| 8619 | durationMs = __wfSleepDuration(duration, name); |
| 8620 | } catch (error) { |
| 8621 | return Promise.reject(error); |
| 8622 | } |
| 8623 | return frame(name, (key, _count, ordinal) => |
| 8624 | sleepUntilDeadline( |
| 8625 | name, |
| 8626 | key, |
| 8627 | ordinal, |
| 8628 | () => Date.now() + durationMs, |
| 8629 | )); |
| 8630 | }, |
| 8631 | sleepUntil: (name, timestamp) => { |
| 8632 | let at; |
| 8633 | try { |
| 8634 | __wfStepName(name); |
| 8635 | at = __wfSleepUntil(timestamp, name); |
| 8636 | } catch (error) { |
| 8637 | return Promise.reject(error); |
| 8638 | } |
| 8639 | return frame(name, (key, _count, ordinal) => |
| 8640 | sleepUntilDeadline(name, key, ordinal, () => { |
| 8641 | // A replay uses the persisted deadline after it has passed. Check |
| 8642 | // the moving future bound only while the deadline is first installed, |
| 8643 | // or every successful sleep would fail on the resume that completes it. |
| 8644 | if (at - Date.now() < 0) { |
| 8645 | throw __wfError( |
| 8646 | `sleepUntil ${JSON.stringify(name)} needs a future timestamp`, |
| 8647 | ); |
| 8648 | } |
| 8649 | return at; |
| 8650 | })); |
| 8651 | }, |
| 8652 | waitForEvent: (name, options) => { |
| 8653 | let checked; |
| 8654 | try { |
| 8655 | __wfStepName(name); |
| 8656 | checked = __wfWaitOptions(options, name); |
| 8657 | } catch (error) { |
| 8658 | return Promise.reject(error); |
| 8659 | } |
| 8660 | return frame(name, async (key, _count, ordinal) => { |
| 8661 | let record = __wfKindCheck(await storage.get(key), "event", name); |
| 8662 | if (record !== undefined && record.status === "completed") { |
| 8663 | return { value: record.value }; |
| 8664 | } |
| 8665 | if (record !== undefined && record.status === "failed") { |
| 8666 | throw __wfReviveError(record.error); |
| 8667 | } |
| 8668 | if (record === undefined) { |
| 8669 | record = { |
| 8670 | kind: "event", |
| 8671 | status: "waiting", |
| 8672 | type: checked.type, |
| 8673 | deadline: Date.now() + checked.timeoutMs, |
| 8674 | ordinal, |
| 8675 | }; |
| 8676 | await storage.put(key, record); |
| 8677 | } |
| 8678 | // The deadline is checked before the buffer: an event that arrived |
| 8679 | // after the persisted deadline must time the step out, not succeed |
| 8680 | // because the replay that noticed it ran late. |
| 8681 | if (record.deadline <= Date.now()) { |
| 8682 | const error = new Error( |
| 8683 | `waitForEvent ${JSON.stringify(name)} timed out waiting for an event ` + |
| 8684 | `of type ${JSON.stringify(record.type)}`, |
| 8685 | ); |
| 8686 | await storage.put(key, { |
| 8687 | kind: "event", |
| 8688 | status: "failed", |
| 8689 | error: __wfErrorRecord(error), |
| 8690 | ordinal: record.ordinal, |
| 8691 | }); |
| 8692 | throw error; |
| 8693 | } |
| 8694 | // Delivered events persist until a matching step consumes one, in |
| 8695 | // arrival order -- the zero-padded sequence key makes list order |
| 8696 | // arrival order -- so an event sent before the step is reached is |
| 8697 | // buffered, not lost. |
| 8698 | const consumed = storage.transactionSync(() => { |
| 8699 | const current = __wfKindCheck(storage.kv.get(key), "event", name); |
| 8700 | if (current !== undefined && current.status === "completed") { |
| 8701 | return { value: current.value }; |
| 8702 | } |
| 8703 | if (current !== undefined && current.status === "failed") { |
| 8704 | throw __wfReviveError(current.error); |
| 8705 | } |
| 8706 | for (const [eventKey, event] of storage.kv.list({ |
| 8707 | prefix: __wfEventPrefix(driver.generation), |
| 8708 | })) { |
| 8709 | if (event.type !== current.type) continue; |
| 8710 | const value = { |
| 8711 | payload: event.payload, |
| 8712 | timestamp: new Date(event.timestampMs), |
| 8713 | type: event.type, |
| 8714 | }; |
| 8715 | // The delete and completed ledger record are one SQLite commit. |
| 8716 | // A crash can therefore expose both or neither, so an |
| 8717 | // acknowledged event cannot disappear between them. |
| 8718 | storage.kv.delete(eventKey); |
| 8719 | /*__CELLD_TEST_WORKFLOW_EVENT_CONSUMED__*/ |
| 8720 | storage.kv.put(key, { |
| 8721 | kind: "event", |
| 8722 | status: "completed", |
| 8723 | value, |
| 8724 | ordinal: current.ordinal, |
| 8725 | }); |
| 8726 | return { value }; |
| 8727 | } |
| 8728 | }); |
| 8729 | if (consumed !== undefined) return consumed; |
| 8730 | return { block: record.deadline, kind: "event" }; |
| 8731 | }); |
| 8732 | }, |
| 8733 | }; |
| 8734 | }; |
| 8735 | |
| 8736 | const __WorkflowCell = (() => { |
| 8737 | class StorageTransaction { |
| 8738 | constructor(storage) { |
| 8739 | this.kv = storage.kv; |
| 8740 | this._scope = storage._scope; |
| 8741 | } |
| 8742 | setAlarm(t) { |
| 8743 | __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); |
| 8744 | } |
| 8745 | deleteAlarm() { |
| 8746 | __alarm_delete(this._scope); |
| 8747 | } |
| 8748 | } |
| 8749 | const transactionSync = (storage, callback) => |
| 8750 | storage.transactionSync(() => callback(new StorageTransaction(storage))); |
| 8751 | const clearInstance = (transaction) => { |
| 8752 | for (const [key] of transaction.kv.list({ prefix: "__wf." })) { |
| 8753 | transaction.kv.delete(key); |
| 8754 | } |
| 8755 | transaction.deleteAlarm(); |
| 8756 | }; |
| 8757 | const expireTerminal = (transaction, meta, now) => { |
| 8758 | if (!__wfTerminal(meta.status)) return false; |
| 8759 | if (meta.expiresMs === undefined) { |
| 8760 | meta.endedMs = now; |
| 8761 | meta.expiresMs = now + __wfRetentionMs(meta, meta.status); |
| 8762 | transaction.kv.put("__wf.meta", meta); |
| 8763 | } |
| 8764 | if (meta.expiresMs > now) return false; |
| 8765 | clearInstance(transaction); |
| 8766 | return true; |
| 8767 | }; |
| 8768 | |
| 8769 | // The adapter stays in this closure because Workflow needs synchronous |
| 8770 | // alarm writes inside transactionSync(). The public async alarm API runs |
| 8771 | // after that commit, while a global helper would let application code |
| 8772 | // split metadata from its wake or invoke the raw operation after commit. |
| 8773 | return class __WorkflowCell { |
| 8774 | constructor(state) { |
| 8775 | this._state = state; |
| 8776 | } |
| 8777 | async __wfCreate({ |
| 8778 | workflowName, |
| 8779 | instanceId, |
| 8780 | params, |
| 8781 | retention, |
| 8782 | locationHint, |
| 8783 | skipExisting = false, |
| 8784 | }) { |
| 8785 | const storage = this._state.storage; |
| 8786 | if (params !== undefined) __wfCheckValue(params, "the workflow params"); |
| 8787 | const result = transactionSync(storage, (transaction) => { |
| 8788 | let meta = transaction.kv.get("__wf.meta"); |
| 8789 | if (meta !== undefined && expireTerminal(transaction, meta, Date.now())) { |
| 8790 | meta = undefined; |
| 8791 | } |
| 8792 | if (meta !== undefined && skipExisting) return { id: instanceId, created: false }; |
| 8793 | if (meta !== undefined) { |
| 8794 | throw __wfError( |
| 8795 | `instance ${JSON.stringify(instanceId)} already exists with status ` + |
| 8796 | JSON.stringify(meta.status), |
| 8797 | ); |
| 8798 | } |
| 8799 | const generation = crypto.randomUUID(); |
| 8800 | transaction.kv.put("__wf.meta", { |
| 8801 | workflowName, |
| 8802 | instanceId, |
| 8803 | params, |
| 8804 | retention, |
| 8805 | ...(locationHint === undefined ? {} : { locationHint }), |
| 8806 | generation, |
| 8807 | createdMs: Date.now(), |
| 8808 | status: "queued", |
| 8809 | }); |
| 8810 | // The metadata and alarm are one SQLite commit. A committed creation |
| 8811 | // therefore always has the wake that can start or recover its drive. |
| 8812 | transaction.setAlarm(Date.now()); |
| 8813 | /*__CELLD_TEST_WORKFLOW_META_CREATED__*/ |
| 8814 | return { id: instanceId, created: true }; |
| 8815 | }); |
| 8816 | return result; |
| 8817 | } |
| 8818 | async __wfStatus() { |
| 8819 | const meta = transactionSync(this._state.storage, (transaction) => { |
| 8820 | const current = transaction.kv.get("__wf.meta"); |
| 8821 | if (current === undefined) return undefined; |
| 8822 | return expireTerminal(transaction, current, Date.now()) ? undefined : current; |
| 8823 | }); |
| 8824 | // A cell exists on first address like any cell, so an absent ledger is |
| 8825 | // the only honest "no such instance" signal. Inventing an instance here |
| 8826 | // would turn every typo into an empty workflow. |
| 8827 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8828 | const status = { status: meta.status, rollback: null }; |
| 8829 | if (meta.error !== undefined) status.error = meta.error; |
| 8830 | if (meta.output !== undefined) status.output = meta.output; |
| 8831 | return status; |
| 8832 | } |
| 8833 | async __wfDelete() { |
| 8834 | const storage = this._state.storage; |
| 8835 | const deleted = transactionSync(storage, (transaction) => { |
| 8836 | const meta = transaction.kv.get("__wf.meta"); |
| 8837 | if (meta === undefined) return false; |
| 8838 | if (expireTerminal(transaction, meta, Date.now())) return false; |
| 8839 | clearInstance(transaction); |
| 8840 | return true; |
| 8841 | }); |
| 8842 | // Throw after the transaction commits. An expiry discovered here must |
| 8843 | // keep its cleanup even though delete() reports that the instance is gone. |
| 8844 | if (!deleted) throw __wfError("instance does not exist"); |
| 8845 | // A callback can still be awaiting application I/O when deletion lands. |
| 8846 | // Reset the object after the deletion commit so that callback cannot |
| 8847 | // recreate an old-generation ledger entry after delete() reports success. |
| 8848 | this._state.abort(new Error("WORKFLOW_INSTANCE_DELETED")); |
| 8849 | } |
| 8850 | async __wfPause() { |
| 8851 | const storage = this._state.storage; |
| 8852 | transactionSync(storage, (transaction) => { |
| 8853 | const meta = transaction.kv.get("__wf.meta"); |
| 8854 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8855 | if (__wfTerminal(meta.status) || meta.status === "paused" || |
| 8856 | meta.status === "waitingForPause") return; |
| 8857 | if (meta.status === "running") { |
| 8858 | meta.status = "waitingForPause"; |
| 8859 | // A drive lost after this commit must re-enter and finish the pause. |
| 8860 | transaction.setAlarm(Date.now()); |
| 8861 | } else { |
| 8862 | meta.status = "paused"; |
| 8863 | meta.pausedMs = Date.now(); |
| 8864 | transaction.deleteAlarm(); |
| 8865 | } |
| 8866 | transaction.kv.put("__wf.meta", meta); |
| 8867 | }); |
| 8868 | } |
| 8869 | async __wfResume() { |
| 8870 | const storage = this._state.storage; |
| 8871 | transactionSync(storage, (transaction) => { |
| 8872 | const meta = transaction.kv.get("__wf.meta"); |
| 8873 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8874 | if (meta.status === "waitingForPause") { |
| 8875 | meta.status = "running"; |
| 8876 | transaction.kv.put("__wf.meta", meta); |
| 8877 | transaction.setAlarm(Date.now()); |
| 8878 | return; |
| 8879 | } |
| 8880 | if (meta.status !== "paused") { |
| 8881 | throw __wfError( |
| 8882 | `cannot resume an instance with status ${JSON.stringify(meta.status)}`, |
| 8883 | ); |
| 8884 | } |
| 8885 | const offset = Math.max(0, Date.now() - (meta.pausedMs ?? Date.now())); |
| 8886 | for (const [key, record] of transaction.kv.list({ |
| 8887 | prefix: __wfLedgerPrefix(meta.generation) + "step.", |
| 8888 | })) { |
| 8889 | if (record.status === "retrying") record.nextAt += offset; |
| 8890 | if (record.status === "sleeping" || record.status === "waiting") { |
| 8891 | record.deadline += offset; |
| 8892 | } |
| 8893 | transaction.kv.put(key, record); |
| 8894 | } |
| 8895 | delete meta.pausedMs; |
| 8896 | meta.status = "queued"; |
| 8897 | transaction.kv.put("__wf.meta", meta); |
| 8898 | transaction.setAlarm(Date.now()); |
| 8899 | }); |
| 8900 | } |
| 8901 | async __wfRestart(options) { |
| 8902 | const checked = __wfRestartOptions(options); |
| 8903 | const storage = this._state.storage; |
| 8904 | transactionSync(storage, (transaction) => { |
| 8905 | const meta = transaction.kv.get("__wf.meta"); |
| 8906 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8907 | const oldPrefix = __wfLedgerPrefix(meta.generation); |
| 8908 | let targetOrdinal; |
| 8909 | if (checked.from !== undefined) { |
| 8910 | const expectedKind = checked.from.type === "waitForEvent" |
| 8911 | ? "event" |
| 8912 | : checked.from.type; |
| 8913 | let occurrence = 0; |
| 8914 | const history = [...transaction.kv.list({ prefix: oldPrefix + "step." })] |
| 8915 | .filter(([, record]) => Number.isInteger(record.ordinal)) |
| 8916 | .sort((left, right) => left[1].ordinal - right[1].ordinal); |
| 8917 | // The ledger key is `<prefix>step.<per-name-count>.<name>`. Derive |
| 8918 | // the name from it because a record stores replay state, not identity. |
| 8919 | for (const [key, record] of history) { |
| 8920 | const marker = oldPrefix + "step."; |
| 8921 | const suffix = key.slice(marker.length); |
| 8922 | const dot = suffix.indexOf("."); |
| 8923 | const name = dot < 0 ? "" : suffix.slice(dot + 1); |
| 8924 | if (record.kind !== expectedKind || name !== checked.from.name) continue; |
| 8925 | occurrence += 1; |
| 8926 | if (occurrence === checked.from.count) { |
| 8927 | targetOrdinal = record.ordinal; |
| 8928 | break; |
| 8929 | } |
| 8930 | } |
| 8931 | if (targetOrdinal === undefined) { |
| 8932 | throw __wfError( |
| 8933 | `restart() could not find ${checked.from.type} step ` + |
| 8934 | `${JSON.stringify(checked.from.name)} occurrence ${checked.from.count}`, |
| 8935 | ); |
| 8936 | } |
| 8937 | } |
| 8938 | const generation = crypto.randomUUID(); |
| 8939 | const newPrefix = __wfLedgerPrefix(generation); |
| 8940 | if (targetOrdinal !== undefined) { |
| 8941 | for (const [key, record] of transaction.kv.list({ prefix: oldPrefix + "step." })) { |
| 8942 | if (Number.isInteger(record.ordinal) && record.ordinal < targetOrdinal) { |
| 8943 | transaction.kv.put(newPrefix + key.slice(oldPrefix.length), record); |
| 8944 | } |
| 8945 | } |
| 8946 | } |
| 8947 | for (const [key] of transaction.kv.list({ prefix: oldPrefix })) { |
| 8948 | transaction.kv.delete(key); |
| 8949 | } |
| 8950 | meta.generation = generation; |
| 8951 | meta.status = "queued"; |
| 8952 | delete meta.pausedMs; |
| 8953 | delete meta.output; |
| 8954 | delete meta.error; |
| 8955 | transaction.kv.put("__wf.meta", meta); |
| 8956 | transaction.setAlarm(Date.now()); |
| 8957 | }); |
| 8958 | } |
| 8959 | async __wfTerminate() { |
| 8960 | const storage = this._state.storage; |
| 8961 | transactionSync(storage, (transaction) => { |
| 8962 | const meta = transaction.kv.get("__wf.meta"); |
| 8963 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8964 | if (__wfTerminal(meta.status)) { |
| 8965 | throw __wfError( |
| 8966 | `cannot terminate an instance with status ${JSON.stringify(meta.status)}`, |
| 8967 | ); |
| 8968 | } |
| 8969 | meta.status = "terminated"; |
| 8970 | __wfFinishRetention(meta, transaction); |
| 8971 | transaction.kv.put("__wf.meta", meta); |
| 8972 | /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ |
| 8973 | }); |
| 8974 | } |
| 8975 | async __wfSendEvent(options) { |
| 8976 | const storage = this._state.storage; |
| 8977 | // The binding validates first to avoid an unnecessary cell call. Repeat |
| 8978 | // the check here because this RPC owns the durable event invariant: no |
| 8979 | // current or future internal caller can bypass validation before storage. |
| 8980 | const { type, payload } = __wfEventOptions(options); |
| 8981 | transactionSync(storage, (transaction) => { |
| 8982 | const meta = transaction.kv.get("__wf.meta"); |
| 8983 | if (meta === undefined) throw __wfError("instance does not exist"); |
| 8984 | if (__wfTerminal(meta.status)) { |
| 8985 | throw __wfError( |
| 8986 | `cannot send an event to an instance with status ${JSON.stringify(meta.status)}`, |
| 8987 | ); |
| 8988 | } |
| 8989 | const sequenceKey = __wfLedgerPrefix(meta.generation) + "eventSeq"; |
| 8990 | const sequence = transaction.kv.get(sequenceKey) ?? 0; |
| 8991 | transaction.kv.put(sequenceKey, sequence + 1); |
| 8992 | transaction.kv.put(__wfEventKey(meta.generation, sequence), { |
| 8993 | type, |
| 8994 | payload, |
| 8995 | timestampMs: Date.now(), |
| 8996 | }); |
| 8997 | // Allocation, the event body, and the nudge are one commit. Parallel |
| 8998 | // writers cannot reuse a sequence and a crash cannot expose a partial |
| 8999 | // acknowledged send. |
| 9000 | if (meta.status !== "paused" && meta.status !== "waitingForPause") { |
| 9001 | transaction.setAlarm(Date.now()); |
| 9002 | } |
| 9003 | }); |
| 9004 | } |
| 9005 | async alarm() { |
| 9006 | const storage = this._state.storage; |
| 9007 | // One drive at a time. A sendEvent nudge (setAlarm(now)) landing |
| 9008 | // mid-fire replaces the firing alarm in the core, and the replacement |
| 9009 | // can dispatch a second alarm() into this isolate while the first drive |
| 9010 | // still awaits user code. Two concurrent replays would both see the |
| 9011 | // same incomplete steps and double-execute their callbacks. The guard |
| 9012 | // is isolate-local and that is sufficient: every drive for a cell runs |
| 9013 | // in its owner's isolate, and a takeover starts a fresh isolate with no |
| 9014 | // drive in flight. The nudge is not lost -- the in-flight drive folds |
| 9015 | // `_wfNudge` into the minimum it re-arms, and if it suspended before |
| 9016 | // seeing the flag, the re-arm below starts a fresh drive immediately. |
| 9017 | // A failed drive is not re-raised here: the engine already retries the |
| 9018 | // alarm that fired it. |
| 9019 | if (this._wfDriving !== undefined) { |
| 9020 | this._wfNudge = Date.now(); |
| 9021 | await this._wfDriving.catch(() => {}); |
| 9022 | if (this._wfNudge !== undefined) { |
| 9023 | this._wfNudge = undefined; |
| 9024 | const meta = await storage.get("__wf.meta"); |
| 9025 | if ( |
| 9026 | meta !== undefined && !__wfTerminal(meta.status) && |
| 9027 | meta.status !== "paused" && meta.status !== "waitingForPause" |
| 9028 | ) { |
| 9029 | await storage.setAlarm(Date.now()); |
| 9030 | } |
| 9031 | } |
| 9032 | return; |
| 9033 | } |
| 9034 | const meta = await storage.get("__wf.meta"); |
| 9035 | // A terminal instance's pending alarm can still fire. It owns retention: |
| 9036 | // remove expired state, or restore the expiry wake after a stale nudge. |
| 9037 | if (meta === undefined) { |
| 9038 | await storage.deleteAlarm(); |
| 9039 | return; |
| 9040 | } |
| 9041 | if (__wfTerminal(meta.status)) { |
| 9042 | transactionSync(storage, (transaction) => { |
| 9043 | const current = transaction.kv.get("__wf.meta"); |
| 9044 | if (current === undefined) { |
| 9045 | transaction.deleteAlarm(); |
| 9046 | return; |
| 9047 | } |
| 9048 | if (!expireTerminal(transaction, current, Date.now())) { |
| 9049 | transaction.setAlarm(current.expiresMs); |
| 9050 | } |
| 9051 | }); |
| 9052 | return; |
| 9053 | } |
| 9054 | if (meta.status === "paused") { |
| 9055 | await storage.deleteAlarm(); |
| 9056 | return; |
| 9057 | } |
| 9058 | if (meta.status === "waitingForPause") { |
| 9059 | transactionSync(storage, (transaction) => { |
| 9060 | const current = transaction.kv.get("__wf.meta"); |
| 9061 | if (current === undefined || current.generation !== meta.generation || |
| 9062 | current.status !== "waitingForPause") return; |
| 9063 | current.status = "paused"; |
| 9064 | current.pausedMs = Date.now(); |
| 9065 | transaction.kv.put("__wf.meta", current); |
| 9066 | transaction.deleteAlarm(); |
| 9067 | }); |
| 9068 | return; |
| 9069 | } |
| 9070 | // The fired alarm stays armed while the drive runs. The engine consumes |
| 9071 | // it only when this handler returns cleanly, and retries it when the |
| 9072 | // handler fails -- that retry is the crash safety net. Deleting it here |
| 9073 | // would commit the deletion durably mid-drive (durability is per SQLite |
| 9074 | // commit, and replication ships frames per commit), so a SIGKILL before |
| 9075 | // the suspend-time re-arm would strand a "running" instance with no |
| 9076 | // alarm and no wake entry. The suspend path re-arms explicitly, and a |
| 9077 | // terminal drive deletes. |
| 9078 | const driving = this._drive(meta); |
| 9079 | this._wfDriving = driving; |
| 9080 | try { |
| 9081 | await driving; |
| 9082 | } finally { |
| 9083 | this._wfDriving = undefined; |
| 9084 | } |
| 9085 | } |
| 9086 | async _drive(meta) { |
| 9087 | const storage = this._state.storage; |
| 9088 | // The drive owns `status`, `output`, and `error`; every other piece of |
| 9089 | // instance state belongs to the RPCs (sendEvent's sequence lives in its |
| 9090 | // own key for the same reason). The gate is open at every await, so a |
| 9091 | // terminate can land mid-drive: re-reading before each write, and |
| 9092 | // writing nothing once the status is terminal, is what makes "terminate |
| 9093 | // wins the race" true rather than asserted. Writing back the meta this |
| 9094 | // drive entered with would resurrect a terminated instance as "waiting" |
| 9095 | // and re-arm the alarm its terminate deleted. |
| 9096 | const settle = (mutate) => transactionSync(storage, (transaction) => { |
| 9097 | const current = transaction.kv.get("__wf.meta"); |
| 9098 | if (current === undefined || __wfTerminal(current.status) || |
| 9099 | current.generation !== meta.generation) return false; |
| 9100 | mutate(current, transaction); |
| 9101 | transaction.kv.put("__wf.meta", current); |
| 9102 | return true; |
| 9103 | }); |
| 9104 | const className = __cell.workflows[meta.workflowName]; |
| 9105 | const cls = className === undefined ? undefined : __cf.exports[className]; |
| 9106 | if (typeof cls !== "function" || |
| 9107 | typeof (cls.prototype && cls.prototype.run) !== "function") { |
| 9108 | // Deploy cannot see inside the bundle, so a missing export fails |
| 9109 | // here, loudly, with the class and the config key named. |
| 9110 | settle((current, transaction) => { |
| 9111 | current.status = "errored"; |
| 9112 | current.error = { |
| 9113 | name: "Error", |
| 9114 | message: className === undefined |
| 9115 | ? `workflow ${JSON.stringify(meta.workflowName)} is not declared ` + |
| 9116 | "in this deployment's `workflows`" |
| 9117 | : `workflow class ${JSON.stringify(className)} is not a module ` + |
| 9118 | "export with a run() method; export it and extend " + |
| 9119 | "WorkflowEntrypoint", |
| 9120 | }; |
| 9121 | __wfFinishRetention(current, transaction); |
| 9122 | /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ |
| 9123 | }); |
| 9124 | return; |
| 9125 | } |
| 9126 | const driver = { |
| 9127 | storage: undefined, |
| 9128 | storageFailure: undefined, |
| 9129 | generation: meta.generation, |
| 9130 | ledgerPrefix: __wfLedgerPrefix(meta.generation), |
| 9131 | counts: new Map(), |
| 9132 | ordinal: 0, |
| 9133 | running: 0, |
| 9134 | blocked: [], |
| 9135 | pauseRequested: false, |
| 9136 | finished: false, |
| 9137 | checkQueued: false, |
| 9138 | stallTimer: undefined, |
| 9139 | clearStall() { |
| 9140 | if (this.stallTimer !== undefined) { |
| 9141 | clearTimeout(this.stallTimer); |
| 9142 | this.stallTimer = undefined; |
| 9143 | } |
| 9144 | }, |
| 9145 | }; |
| 9146 | driver.storage = __wfTrackStorageFailures(storage, driver); |
| 9147 | const outcome = new Promise((resolve) => { |
| 9148 | driver.finish = (result) => { |
| 9149 | if (driver.finished) return; |
| 9150 | driver.finished = true; |
| 9151 | driver.clearStall(); |
| 9152 | resolve(result); |
| 9153 | }; |
| 9154 | }); |
| 9155 | // Quiescence: when a step is blocked, no step callback is executing, |
| 9156 | // and a macrotask has passed, nothing can progress, so the invocation |
| 9157 | // suspends. The macrotask lets every microtask chain a completed step |
| 9158 | // unblocked drain first; checking on the spot would suspend an instance |
| 9159 | // whose next step is one `await` away from starting. |
| 9160 | driver.check = () => { |
| 9161 | if (driver.checkQueued || driver.finished) return; |
| 9162 | driver.checkQueued = true; |
| 9163 | setTimeout(() => { |
| 9164 | driver.checkQueued = false; |
| 9165 | if (driver.finished || driver.running !== 0) return; |
| 9166 | if (driver.pauseRequested) { |
| 9167 | driver.finish({ kind: "pause" }); |
| 9168 | return; |
| 9169 | } |
| 9170 | if (driver.blocked.length > 0) { |
| 9171 | driver.finish({ kind: "suspend" }); |
| 9172 | return; |
| 9173 | } |
| 9174 | // No step runs, none is blocked, and run() has not settled: it |
| 9175 | // awaits something that is not a step. Upstream permits that -- an |
| 9176 | // un-stepped `await fetch()` between steps is legal, merely |
| 9177 | // non-durable -- so this is not yet an error; but a promise that |
| 9178 | // never settles would wedge the alarm handler in silence, with the |
| 9179 | // instance "running" forever. A grace timer splits the two: if the |
| 9180 | // same nothing-can-progress state still holds when it fires, the |
| 9181 | // instance fails loudly. The timer is a plain in-isolate timeout, |
| 9182 | // not a durable alarm, on purpose: an eviction or a restart replays |
| 9183 | // run() from the top anyway, so losing the timer loses nothing -- |
| 9184 | // the replay re-enters the same stall and re-arms its own grace. |
| 9185 | if (driver.stallTimer !== undefined) return; |
| 9186 | driver.stallTimer = setTimeout(() => { |
| 9187 | driver.stallTimer = undefined; |
| 9188 | if (driver.finished || driver.running !== 0 || driver.blocked.length > 0) { |
| 9189 | return; |
| 9190 | } |
| 9191 | driver.finish({ |
| 9192 | kind: "error", |
| 9193 | error: __wfError( |
| 9194 | "run() has been awaiting something that is not a step for " + |
| 9195 | (__WF_STALL_GRACE_MS / 1000) + " seconds while no step is " + |
| 9196 | "running or blocked; a replay cannot resume this wait, so " + |
| 9197 | "wrap long async work in step.do", |
| 9198 | ), |
| 9199 | }); |
| 9200 | }, __WF_STALL_GRACE_MS); |
| 9201 | }, 0); |
| 9202 | }; |
| 9203 | if ( |
| 9204 | meta.status !== "running" && |
| 9205 | !(await settle((current) => { |
| 9206 | current.status = "running"; |
| 9207 | })) |
| 9208 | ) { |
| 9209 | return; |
| 9210 | } |
| 9211 | const step = __wfMakeStep(driver); |
| 9212 | const event = { |
| 9213 | payload: meta.params, |
| 9214 | timestamp: new Date(meta.createdMs), |
| 9215 | instanceId: meta.instanceId, |
| 9216 | workflowName: meta.workflowName, |
| 9217 | }; |
| 9218 | // ExecutionContext-shaped, as the WorkflowEntrypoint constructor |
| 9219 | // documents upstream. |
| 9220 | const ctx = { |
| 9221 | waitUntil: __registerWaitUntil, |
| 9222 | passThroughOnException() {}, |
| 9223 | }; |
| 9224 | (async () => new cls(ctx, __cell.env).run(event, step))().then( |
| 9225 | (value) => driver.finish({ kind: "complete", value }), |
| 9226 | (error) => driver.finish({ kind: "error", error }), |
| 9227 | ); |
| 9228 | /*__CELLD_TEST_WORKFLOW_AFTER_RUN_STARTED__*/ |
| 9229 | let result = await outcome; |
| 9230 | // The workflow can catch a rejected step promise, but it cannot turn an |
| 9231 | // engine storage failure into a successful run. Preserve the alarm so |
| 9232 | // the runtime retries over the last committed ledger prefix. |
| 9233 | if (driver.storageFailure !== undefined) { |
| 9234 | throw driver.storageFailure; |
| 9235 | } |
| 9236 | const currentMeta = await storage.get("__wf.meta"); |
| 9237 | if ( |
| 9238 | result.kind === "pause" || |
| 9239 | (currentMeta !== undefined && |
| 9240 | currentMeta.generation === meta.generation && |
| 9241 | currentMeta.status === "waitingForPause") |
| 9242 | ) { |
| 9243 | /*__CELLD_TEST_WORKFLOW_BEFORE_PAUSE_SETTLE__*/ |
| 9244 | settle((current, transaction) => { |
| 9245 | // A resume can cancel waitingForPause after this drive selected its |
| 9246 | // pause result. Preserve that newer running state and its alarm, or |
| 9247 | // this stale settlement strands an acknowledged resume as paused. |
| 9248 | if (current.status !== "waitingForPause") return; |
| 9249 | current.status = "paused"; |
| 9250 | current.pausedMs = Date.now(); |
| 9251 | transaction.deleteAlarm(); |
| 9252 | }); |
| 9253 | return; |
| 9254 | } |
| 9255 | if (result.kind === "suspend") { |
| 9256 | let at = Math.min(...driver.blocked.map((entry) => entry.at)); |
| 9257 | // A nudge that landed mid-drive must not wait out the pending |
| 9258 | // deadline. It is visible in one of two places: getAlarm(), when the |
| 9259 | // nudge re-armed and no second alarm dispatched yet, or `_wfNudge`, |
| 9260 | // when a second alarm() already entered and parked on the drive |
| 9261 | // guard -- its dispatch consumed the armed alarm, so getAlarm() |
| 9262 | // alone would miss it. |
| 9263 | const nudge = await storage.getAlarm(); |
| 9264 | if (nudge !== null) at = Math.min(at, nudge); |
| 9265 | if (this._wfNudge !== undefined) { |
| 9266 | at = Math.min(at, this._wfNudge); |
| 9267 | this._wfNudge = undefined; |
| 9268 | } |
| 9269 | settle((current, transaction) => { |
| 9270 | current.status = "waiting"; |
| 9271 | transaction.setAlarm(at); |
| 9272 | }); |
| 9273 | // The explicit re-arm replaces the alarm that fired this drive. |
| 9274 | // Durability is per SQLite commit, not per turn: a crash can persist |
| 9275 | // any prefix of this invocation's ledger writes, and the unconsumed |
| 9276 | // fired alarm is what re-drives the replay over whatever prefix |
| 9277 | // survived. A terminated instance re-arms nothing; its leftover |
| 9278 | // alarm fires once, sees the terminal status, and retires itself. |
| 9279 | return; |
| 9280 | } |
| 9281 | if (result.kind === "complete") { |
| 9282 | try { |
| 9283 | if (result.value !== undefined) { |
| 9284 | __wfCheckValue(result.value, "the run() return value"); |
| 9285 | } |
| 9286 | } catch (error) { |
| 9287 | result = { kind: "error", error }; |
| 9288 | } |
| 9289 | if (result.kind === "complete") { |
| 9290 | // Keep settlement outside the value-validation catch. A storage |
| 9291 | // failure must escape the alarm handler so the engine retries the |
| 9292 | // still-armed drive; converting it to a user error would consume the |
| 9293 | // alarm and make a transient commit failure terminal. |
| 9294 | settle((current, transaction) => { |
| 9295 | current.status = "complete"; |
| 9296 | if (result.value !== undefined) current.output = result.value; |
| 9297 | // The terminal commit installs the expiry wake with the retained |
| 9298 | // state, so a crash can expose neither without the other. |
| 9299 | __wfFinishRetention(current, transaction); |
| 9300 | /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ |
| 9301 | }); |
| 9302 | return; |
| 9303 | } |
| 9304 | } |
| 9305 | settle((current, transaction) => { |
| 9306 | current.status = "errored"; |
| 9307 | current.error = __wfErrorRecord(result.error); |
| 9308 | __wfFinishRetention(current, transaction); |
| 9309 | /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ |
| 9310 | }); |
| 9311 | } |
| 9312 | }; |
| 9313 | })(); |
| 9314 | __runtimeClass("__Workflow", __WorkflowCell); |
| 9315 | |
| 9316 | class NonRetryableError extends Error { |
| 9317 | constructor(message, name = "NonRetryableError") { |
| 9318 | super(message); |
| 9319 | this.name = name; |
| 9320 | } |
| 9321 | } |
| 9322 | // Backing object for the `cloudflare:workflows` builtin module. |
| 9323 | __celld.__cfWorkflows = { NonRetryableError }; |
| 9324 | // `celld:python`, imported only by the Python Worker bundle. |
| 9325 | __celld.__pythonHost = { |
| 9326 | condemnIsolate: (reason) => __isolate_condemn(String(reason)), |
| 9327 | }; |
| 9328 | |
| 9329 | const __wfValidInstanceId = (id) => |
| 9330 | typeof id === "string" && id.length >= 1 && id.length <= 100 && |
| 9331 | __WF_NAME_RE.test(id); |
| 9332 | const __wfCreateOptions = (options, what, validateParams = true) => { |
| 9333 | if (!__wfOwnObject(options)) { |
| 9334 | throw __wfError(`${what} needs an object`); |
| 9335 | } |
| 9336 | const retention = __wfRetentionOptions(options.retention, what); |
| 9337 | const locationHint = __wfLocationHint(options.locationHint, what); |
| 9338 | const id = options.id === undefined ? crypto.randomUUID() : options.id; |
| 9339 | if (!__wfValidInstanceId(id)) { |
| 9340 | throw __wfError( |
| 9341 | `invalid instance id ${JSON.stringify(id)}: use letters, digits, ` + |
| 9342 | "\"-\" and \"_\" (not starting with \"-\"), at most 100 characters", |
| 9343 | ); |
| 9344 | } |
| 9345 | if (validateParams && options.params !== undefined) { |
| 9346 | // The cell repeats this serialization check because it owns the durable |
| 9347 | // create invariant. A single create rejects before it addresses the cell. |
| 9348 | __wfCheckValue(options.params, "the workflow params"); |
| 9349 | } |
| 9350 | return { id, params: options.params, retention, locationHint }; |
| 9351 | }; |
| 9352 | |
| 9353 | // Named so SDKs that sniff a binding by `constructor.name` recognise it. |
| 9354 | class WorkflowInstance { |
| 9355 | constructor(workflowName, id) { |
| 9356 | Object.defineProperty(this, "_workflowName", { value: workflowName }); |
| 9357 | this.id = id; |
| 9358 | } |
| 9359 | // Resolved per call rather than cached: a cell can move between calls. |
| 9360 | get _stub() { |
| 9361 | // The reserved class is script-scoped (`deploy::workflow_class`), because |
| 9362 | // a workflow instance is: two co-hosted scripts must not share one entry |
| 9363 | // in the deployment's flat class registry. `__cell.script` is injected |
| 9364 | // before any binding runs, so this resolves at call time. |
| 9365 | return __cell.makeNamespace("__Workflow." + __cell.script) |
| 9366 | .getByName(this._workflowName + "/" + this.id); |
| 9367 | } |
| 9368 | async status() { |
| 9369 | return await this._stub.__wfStatus(); |
| 9370 | } |
| 9371 | async terminate(options) { |
| 9372 | if (options && options.rollback) { |
| 9373 | throw __wfError( |
| 9374 | "terminate({rollback: true}) is not implemented in celld; step " + |
| 9375 | "rollbackOptions are not implemented, so no handler could run", |
| 9376 | ); |
| 9377 | } |
| 9378 | await this._stub.__wfTerminate(); |
| 9379 | } |
| 9380 | async sendEvent(options) { |
| 9381 | await this._stub.__wfSendEvent(__wfEventOptions(options)); |
| 9382 | } |
| 9383 | async pause() { |
| 9384 | await this._stub.__wfPause(); |
| 9385 | } |
| 9386 | async resume() { |
| 9387 | await this._stub.__wfResume(); |
| 9388 | } |
| 9389 | async restart(options) { |
| 9390 | await this._stub.__wfRestart(__wfRestartOptions(options)); |
| 9391 | } |
| 9392 | async delete() { |
| 9393 | try { |
| 9394 | await this._stub.__wfDelete(); |
| 9395 | } catch (error) { |
| 9396 | // The deletion commit resets an active Workflow cell so an in-flight |
| 9397 | // callback cannot put old ledger state back. That reset rejects this |
| 9398 | // RPC with its private completion marker; it is the successful path. |
| 9399 | if (!String(error && error.message || error).includes("WORKFLOW_INSTANCE_DELETED")) { |
| 9400 | throw error; |
| 9401 | } |
| 9402 | } |
| 9403 | } |
| 9404 | } |
| 9405 | |
| 9406 | class Workflow { |
| 9407 | constructor(workflowName) { |
| 9408 | Object.defineProperty(this, "_workflowName", { value: workflowName }); |
| 9409 | } |
| 9410 | async _create(options, skipExisting) { |
| 9411 | const { id, params, retention, locationHint } = options; |
| 9412 | const instance = new WorkflowInstance(this._workflowName, id); |
| 9413 | const result = await instance._stub.__wfCreate({ |
| 9414 | workflowName: this._workflowName, |
| 9415 | instanceId: id, |
| 9416 | params, |
| 9417 | retention, |
| 9418 | locationHint, |
| 9419 | skipExisting, |
| 9420 | }); |
| 9421 | return result.created ? instance : undefined; |
| 9422 | } |
| 9423 | async create(options = {}) { |
| 9424 | return await this._create(__wfCreateOptions(options, "create()"), false); |
| 9425 | } |
| 9426 | async createBatch(batch) { |
| 9427 | if (!Array.isArray(batch)) { |
| 9428 | throw __wfError("createBatch() needs an array of create options"); |
| 9429 | } |
| 9430 | if (batch.length > 100) { |
| 9431 | throw __wfError( |
| 9432 | `createBatch() accepts at most 100 instances, got ${batch.length}`, |
| 9433 | ); |
| 9434 | } |
| 9435 | if (batch.length === 0) { |
| 9436 | throw __wfError("createBatch() needs at least one instance"); |
| 9437 | } |
| 9438 | // Cloudflare rejects a structural error in any item before it creates the |
| 9439 | // first instance, but it filters a params clone failure per item. Keep |
| 9440 | // these two gates separate so a bad ID stays atomic while a clone failure |
| 9441 | // does not suppress the valid items around it. |
| 9442 | const optionsList = batch.map((options, index) => |
| 9443 | __wfCreateOptions(options, `createBatch() item ${index}`, false)); |
| 9444 | const creatable = []; |
| 9445 | for (const options of optionsList) { |
| 9446 | let encoded; |
| 9447 | try { |
| 9448 | if (options.params !== undefined) { |
| 9449 | encoded = __wfEncodeValue(options.params, "the workflow params"); |
| 9450 | } |
| 9451 | } catch { |
| 9452 | continue; |
| 9453 | } |
| 9454 | if (encoded !== undefined) { |
| 9455 | __wfCheckEncodedValue(encoded, "the workflow params"); |
| 9456 | } |
| 9457 | creatable.push(options); |
| 9458 | } |
| 9459 | const created = []; |
| 9460 | for (const options of creatable) { |
| 9461 | const instance = await this._create(options, true); |
| 9462 | if (instance !== undefined) created.push(instance); |
| 9463 | } |
| 9464 | return created; |
| 9465 | } |
| 9466 | async get(id) { |
| 9467 | if (!__wfValidInstanceId(id)) { |
| 9468 | throw __wfError(`invalid instance id ${JSON.stringify(id)}`); |
| 9469 | } |
| 9470 | const instance = new WorkflowInstance(this._workflowName, id); |
| 9471 | // The cell exists on first address like any cell, but get() must not |
| 9472 | // mint an instance for a typo: an id with no ledger rejects here. |
| 9473 | await instance._stub.__wfStatus(); |
| 9474 | return instance; |
| 9475 | } |
| 9476 | async deleteBatch(instanceIds) { |
| 9477 | if (!Array.isArray(instanceIds)) { |
| 9478 | throw __wfError("deleteBatch() needs an array of instance ids"); |
| 9479 | } |
| 9480 | if (instanceIds.length < 1 || instanceIds.length > 100) { |
| 9481 | throw __wfError( |
| 9482 | `deleteBatch() accepts 1 to 100 instance ids, got ${instanceIds.length}`, |
| 9483 | ); |
| 9484 | } |
| 9485 | for (const id of instanceIds) { |
| 9486 | if (!__wfValidInstanceId(id)) { |
| 9487 | throw __wfError(`invalid instance id ${JSON.stringify(id)}`); |
| 9488 | } |
| 9489 | } |
| 9490 | const uniqueIds = [...new Set(instanceIds)]; |
| 9491 | const settled = await Promise.allSettled(uniqueIds.map(async (id) => { |
| 9492 | const instance = new WorkflowInstance(this._workflowName, id); |
| 9493 | await instance.delete(); |
| 9494 | })); |
| 9495 | const results = new Map(uniqueIds.map((id, index) => [id, settled[index]])); |
| 9496 | const output = { deleted: [], errors: [] }; |
| 9497 | for (const id of instanceIds) { |
| 9498 | const result = results.get(id); |
| 9499 | if (result.status === "fulfilled") { |
| 9500 | output.deleted.push({ id }); |
| 9501 | continue; |
| 9502 | } |
| 9503 | const notFound = String(result.reason && result.reason.message || result.reason) |
| 9504 | .includes("instance does not exist"); |
| 9505 | output.errors.push({ |
| 9506 | id, |
| 9507 | code: notFound ? 10400 : 10001, |
| 9508 | message: notFound |
| 9509 | ? "workflows.api.error.instance.not_found" |
| 9510 | : "workflows.api.error.internal_server", |
| 9511 | }); |
| 9512 | } |
| 9513 | return output; |
| 9514 | } |
| 9515 | } |
| 9516 | |
| 9517 | const __makeWorkflow = __celld.__makeWorkflow = |
| 9518 | (workflowName) => new Workflow(workflowName); |
| 9519 | // `cloudflare:workers` module surface. The DO base class sets ctx/env the |
| 9520 | // way `class X extends DurableObject` expects; env aliases the cell env. |
| 9521 | const __cf = __celld.__cf = { |
| 9522 | DurableObject: class DurableObject { |
| 9523 | constructor(ctx, env) { this.ctx = ctx; this.env = env; } |
| 9524 | }, |
| 9525 | // The enumerable function-valued brand makes V8's structured clone |
| 9526 | // fail on every RpcTarget instance, forcing it off the silent |
| 9527 | // plain-clone path and into the stub lift (Workerd rejects these |
| 9528 | // from plain serialization outright). |
| 9529 | RpcTarget: class RpcTarget { |
| 9530 | constructor() { |
| 9531 | Object.defineProperty(this, "__celldRpcTarget", { |
| 9532 | value: __rpcNoClone, enumerable: true, |
| 9533 | }); |
| 9534 | } |
| 9535 | }, |
| 9536 | // Named entrypoint for `[[services]]` with `entrypoint = "Name"`. |
| 9537 | WorkerEntrypoint: class WorkerEntrypoint { |
| 9538 | constructor(ctx, env) { this.ctx = ctx; this.env = env; } |
| 9539 | }, |
| 9540 | // Base class for `workflows` classes. The reserved workflow cell |
| 9541 | // instantiates a subclass on every replay with an ExecutionContext-shaped |
| 9542 | // ctx -- never the cell's own DurableObjectState, which would hand user |
| 9543 | // code the ledger that replays it. |
| 9544 | WorkflowEntrypoint: class WorkflowEntrypoint { |
| 9545 | constructor(ctx, env) { this.ctx = ctx; this.env = env; } |
| 9546 | }, |
| 9547 | // `new RpcStub(target)` wraps any local object or function in a |
| 9548 | // loopback stub; the constructor returns the proxy, so instanceof |
| 9549 | // works through __makeStub's getPrototypeOf trap. |
| 9550 | RpcStub: class RpcStub { |
| 9551 | constructor(target) { |
| 9552 | if (target === null || |
| 9553 | (typeof target !== "object" && typeof target !== "function")) |
| 9554 | throw new TypeError( |
| 9555 | "RpcStub requires an object or function."); |
| 9556 | return __makeStub( |
| 9557 | __newEntry(target), typeof target === "function"); |
| 9558 | } |
| 9559 | }, |
| 9560 | RpcPromise: class RpcPromise extends Promise {}, |
| 9561 | RpcProperty: class RpcProperty {}, |
| 9562 | ServiceStub: class ServiceStub {}, |
| 9563 | // `import { waitUntil } from "cloudflare:workers"`: register into |
| 9564 | // the current event or extend its active background work. Outside either |
| 9565 | // lifetime this is Workerd's global-scope error. |
| 9566 | waitUntil(promise) { |
| 9567 | if (!__wait_until_active()) |
| 9568 | throw new Error( |
| 9569 | "Disallowed operation called within global scope."); |
| 9570 | __registerWaitUntil(promise); |
| 9571 | }, |
| 9572 | exports: {}, |
| 9573 | get env() { return __cell.env; }, |
| 9574 | }; |
| 9575 | // Proxy standing in for unsupported node:*/cloudflare:* builtins. Property |
| 9576 | // walks stay inert -- real bundles reference these at module scope, and |
| 9577 | // evaluation must not crash on a builtin the fetch path never exercises -- |
| 9578 | // but a call or construct throws: the compat contract is "reject at first |
| 9579 | // use", and the old silent pass-through turned a missing builtin into a |
| 9580 | // wrong result far from the cause. Memoized by dotted path so repeated |
| 9581 | // reads keep identity (`mod.foo === mod.foo`). |
| 9582 | const __stubCache = new Map(); |
| 9583 | const __nodeStubFor = __celld.__nodeStubFor = (path) => { |
| 9584 | let stub = __stubCache.get(path); |
| 9585 | if (stub) return stub; |
| 9586 | stub = new Proxy(function () {}, { |
| 9587 | get: (_t, p) => { |
| 9588 | // Never masquerade as a thenable. `await` probes `.then`; returning |
| 9589 | // a callable here creates a promise that can never settle. |
| 9590 | if (p === "then") return undefined; |
| 9591 | // coerce cleanly in string/number contexts so evaluation never throws |
| 9592 | if (p === Symbol.toPrimitive || p === "toString" || p === "valueOf") |
| 9593 | return () => ""; |
| 9594 | if (p === Symbol.toStringTag) return "NodeStub"; |
| 9595 | if (p === Symbol.iterator) return function* () {}; |
| 9596 | if (typeof p !== "string") return undefined; |
| 9597 | return __nodeStubFor(path + "." + p); |
| 9598 | }, |
| 9599 | apply() { throw new Error(path + " is not implemented in celld"); }, |
| 9600 | construct() { throw new Error(path + " is not implemented in celld"); }, |
| 9601 | }); |
| 9602 | __stubCache.set(path, stub); |
| 9603 | return stub; |
| 9604 | }; |
| 9605 | __celld.__nodeStub = __nodeStubFor("node builtin"); |
| 9606 | if (!globalThis.Event) { |
| 9607 | globalThis.Event = class Event { |
| 9608 | // Private fields: stored in the object itself, so an Event costs no |
| 9609 | // side allocation and no defineProperty call at construction. The |
| 9610 | // public members are accessors because the DOM standard makes them |
| 9611 | // read-only; EventTarget drives them through _begin/_end. |
| 9612 | #type; #bubbles; #cancelable; #composed; |
| 9613 | #defaultPrevented = false; |
| 9614 | #eventPhase = 0; |
| 9615 | #target; #currentTarget; #path; |
| 9616 | #stop = false; #stopImmediate = false; #dispatching = false; |
| 9617 | // Workerd: events the runtime delivers are trusted; events a |
| 9618 | // script constructs and dispatches itself are not. |
| 9619 | #trusted = false; |
| 9620 | constructor(type, init = {}) { |
| 9621 | if (arguments.length === 0) |
| 9622 | throw new TypeError( |
| 9623 | "Failed to construct 'Event': 1 argument required, but only " + |
| 9624 | "0 present."); |
| 9625 | if (init !== undefined && init !== null && |
| 9626 | typeof init !== "object") |
| 9627 | throw new TypeError( |
| 9628 | "Failed to construct 'Event': The provided value is not of " + |
| 9629 | "type 'EventInit'."); |
| 9630 | const options = init || {}; |
| 9631 | // Template interpolation, not String(): it must throw for a |
| 9632 | // Symbol, which String() would happily format. |
| 9633 | this.#type = `${type}`; |
| 9634 | this.#bubbles = !!options.bubbles; |
| 9635 | this.#cancelable = !!options.cancelable; |
| 9636 | this.#composed = !!options.composed; |
| 9637 | } |
| 9638 | get type() { return this.#type; } |
| 9639 | get bubbles() { return this.#bubbles; } |
| 9640 | get cancelable() { return this.#cancelable; } |
| 9641 | get composed() { return this.#composed; } |
| 9642 | get defaultPrevented() { return this.#defaultPrevented; } |
| 9643 | get eventPhase() { return this.#eventPhase; } |
| 9644 | get target() { return this.#target; } |
| 9645 | get currentTarget() { return this.#currentTarget; } |
| 9646 | get isTrusted() { return this.#trusted; } |
| 9647 | get timeStamp() { return 0; } |
| 9648 | get returnValue() { return !this.#defaultPrevented; } |
| 9649 | // The one writable member, per the DOM standard. |
| 9650 | get cancelBubble() { return this.#stop; } |
| 9651 | set cancelBubble(value) { if (value) this.#stop = true; } |
| 9652 | composedPath() { return this.#path ? this.#path.slice() : []; } |
| 9653 | preventDefault() { |
| 9654 | if (this.#cancelable) this.#defaultPrevented = true; |
| 9655 | } |
| 9656 | stopPropagation() { this.#stop = true; } |
| 9657 | stopImmediatePropagation() { |
| 9658 | this.#stop = true; |
| 9659 | this.#stopImmediate = true; |
| 9660 | } |
| 9661 | // Internal dispatch hooks used by EventTarget. |
| 9662 | get _dispatching() { return this.#dispatching; } |
| 9663 | get _stopImmediate() { return this.#stopImmediate; } |
| 9664 | _trust() { this.#trusted = true; } |
| 9665 | _begin(target) { |
| 9666 | this.#dispatching = true; |
| 9667 | this.#target = target; |
| 9668 | this.#currentTarget = target; |
| 9669 | this.#eventPhase = 2; // AT_TARGET |
| 9670 | this.#path = [target]; |
| 9671 | this.#stop = false; |
| 9672 | this.#stopImmediate = false; |
| 9673 | } |
| 9674 | // Workerd leaves currentTarget set after dispatch (the DOM standard |
| 9675 | // nulls it); only the phase is reset. |
| 9676 | _end() { |
| 9677 | this.#eventPhase = 0; |
| 9678 | this.#dispatching = false; |
| 9679 | } |
| 9680 | }; |
| 9681 | { |
| 9682 | const phases = { |
| 9683 | NONE: 0, CAPTURING_PHASE: 1, AT_TARGET: 2, BUBBLING_PHASE: 3, |
| 9684 | }; |
| 9685 | for (const [name, value] of Object.entries(phases)) { |
| 9686 | const d = { value, writable: false, enumerable: true, |
| 9687 | configurable: false }; |
| 9688 | Object.defineProperty(globalThis.Event, name, d); |
| 9689 | Object.defineProperty(globalThis.Event.prototype, name, d); |
| 9690 | } |
| 9691 | } |
| 9692 | } |
| 9693 | if (!globalThis.CustomEvent) { |
| 9694 | globalThis.CustomEvent = class CustomEvent extends Event { |
| 9695 | constructor(type, init = {}) { |
| 9696 | super(type, init); |
| 9697 | this.detail = init.detail === undefined ? null : init.detail; |
| 9698 | } |
| 9699 | }; |
| 9700 | } |
| 9701 | if (!globalThis.ExtendableEvent) { |
| 9702 | // Exists as a type but is not constructable from user code. |
| 9703 | globalThis.ExtendableEvent = class ExtendableEvent extends Event { |
| 9704 | constructor() { |
| 9705 | throw new TypeError("Illegal constructor"); |
| 9706 | } |
| 9707 | }; |
| 9708 | } |
| 9709 | // An event-handler IDL attribute occupies one listener-list position. Replacing |
| 9710 | // its callback must retain that position, or listeners added after `onabort` |
| 9711 | // run before it and observe an order that differs from the web platform. |
| 9712 | const __eventHandlerEntry = Symbol("eventHandlerEntry"); |
| 9713 | const __getEventHandler = (target, type) => |
| 9714 | (target._listeners.get(type) || []) |
| 9715 | .find((entry) => entry[__eventHandlerEntry])?.callback ?? null; |
| 9716 | const __setEventHandler = (target, type, callback) => { |
| 9717 | const list = target._listeners.get(type) || []; |
| 9718 | const entry = list.find((item) => item[__eventHandlerEntry]); |
| 9719 | if (typeof callback !== "function") { |
| 9720 | if (entry) list.splice(list.indexOf(entry), 1); |
| 9721 | return; |
| 9722 | } |
| 9723 | if (entry) { |
| 9724 | entry.callback = callback; |
| 9725 | } else { |
| 9726 | list.push({ callback, once: false, [__eventHandlerEntry]: true }); |
| 9727 | target._listeners.set(type, list); |
| 9728 | } |
| 9729 | }; |
| 9730 | if (!globalThis.EventTarget) { |
| 9731 | globalThis.EventTarget = class EventTarget { |
| 9732 | constructor() { this._listeners = new Map(); } |
| 9733 | addEventListener(type, callback, options = {}) { |
| 9734 | if (callback === null || callback === undefined) return; |
| 9735 | if (typeof callback !== "function" && |
| 9736 | typeof callback.handleEvent !== "function") |
| 9737 | throw new TypeError( |
| 9738 | "Failed to execute 'addEventListener' on 'EventTarget': " + |
| 9739 | "parameter 2 is not of type 'EventListener'."); |
| 9740 | const object = typeof options === "object" && options !== null; |
| 9741 | // Capture and passive are accepted for portability but must be |
| 9742 | // false: Cells dispatches only at the target, so honouring them |
| 9743 | // would silently change ordering. |
| 9744 | if (object ? options.capture || options.passive : !!options) |
| 9745 | throw new TypeError( |
| 9746 | "Cells does not support the 'capture' or 'passive' options " + |
| 9747 | "on addEventListener()."); |
| 9748 | const signal = object ? options.signal : undefined; |
| 9749 | if (signal && signal.aborted) return; |
| 9750 | const key = String(type); |
| 9751 | const list = this._listeners.get(key) || []; |
| 9752 | if (list.some((e) => e.callback === callback)) return; |
| 9753 | list.push({ callback, once: object && !!options.once }); |
| 9754 | this._listeners.set(key, list); |
| 9755 | if (signal) |
| 9756 | signal.addEventListener("abort", () => |
| 9757 | this.removeEventListener(key, callback), { once: true }); |
| 9758 | } |
| 9759 | removeEventListener(type, callback, options = {}) { |
| 9760 | const object = typeof options === "object" && options !== null; |
| 9761 | if (object ? options.capture : !!options) |
| 9762 | throw new TypeError( |
| 9763 | "Cells does not support the 'capture' option on " + |
| 9764 | "removeEventListener()."); |
| 9765 | const list = this._listeners.get(String(type)); |
| 9766 | if (!list) return; |
| 9767 | const index = list.findIndex((e) => e.callback === callback); |
| 9768 | if (index >= 0) list.splice(index, 1); |
| 9769 | } |
| 9770 | dispatchEvent(event) { |
| 9771 | if (!(event instanceof Event)) |
| 9772 | throw new TypeError("argument is not an Event"); |
| 9773 | if (event._dispatching) |
| 9774 | throw new DOMException( |
| 9775 | "The event is already being dispatched.", |
| 9776 | "InvalidStateError"); |
| 9777 | event._begin(this); |
| 9778 | // Copy: a listener may add or remove listeners mid-dispatch. |
| 9779 | for (const item of (this._listeners.get(event.type) || []).slice()) { |
| 9780 | if (event._stopImmediate) break; |
| 9781 | if (item.once) |
| 9782 | this.removeEventListener(event.type, item.callback); |
| 9783 | if (typeof item.callback === "function") |
| 9784 | item.callback.call(this, event); |
| 9785 | else item.callback.handleEvent(event); |
| 9786 | } |
| 9787 | const handler = this["on" + event.type]; |
| 9788 | const hasEventHandler = (this._listeners.get(event.type) || []) |
| 9789 | .some((item) => item[__eventHandlerEntry]); |
| 9790 | if (!hasEventHandler && !event._stopImmediate && |
| 9791 | typeof handler === "function") |
| 9792 | handler.call(this, event); |
| 9793 | event._end(); |
| 9794 | return !event.defaultPrevented; |
| 9795 | } |
| 9796 | }; |
| 9797 | } |
| 9798 | // The global scope is itself an EventTarget. |
| 9799 | if (typeof globalThis.addEventListener !== "function") { |
| 9800 | const globalTarget = new EventTarget(); |
| 9801 | for (const name of |
| 9802 | ["addEventListener", "removeEventListener", "dispatchEvent"]) |
| 9803 | globalThis[name] = globalTarget[name].bind(globalTarget); |
| 9804 | } |
| 9805 | if (!globalThis.MessageEvent) { |
| 9806 | globalThis.MessageEvent = class MessageEvent extends Event { |
| 9807 | constructor(type, init = {}) { |
| 9808 | super(type, init); |
| 9809 | this.data = init.data; |
| 9810 | this.origin = String(init.origin || ""); |
| 9811 | this.lastEventId = String(init.lastEventId || ""); |
| 9812 | } |
| 9813 | }; |
| 9814 | } |
| 9815 | if (!globalThis.CloseEvent) { |
| 9816 | globalThis.CloseEvent = class CloseEvent extends Event { |
| 9817 | constructor(type, init = {}) { |
| 9818 | super(type, init); |
| 9819 | this.code = Number(init.code || 0); |
| 9820 | // `reason` is a USVString: a lone surrogate becomes U+FFFD rather than |
| 9821 | // travelling as an unpaired code unit. |
| 9822 | this.reason = String(init.reason || "").toWellFormed |
| 9823 | ? String(init.reason || "").toWellFormed() |
| 9824 | : String(init.reason || "").replace( |
| 9825 | /[\uD800-\uDFFF]/g, |
| 9826 | (unit, index, whole) => { |
| 9827 | const code = unit.charCodeAt(0); |
| 9828 | const next = whole.charCodeAt(index + 1); |
| 9829 | const prev = whole.charCodeAt(index - 1); |
| 9830 | const paired = code <= 0xDBFF |
| 9831 | ? next >= 0xDC00 && next <= 0xDFFF |
| 9832 | : prev >= 0xD800 && prev <= 0xDBFF; |
| 9833 | return paired ? unit : "\uFFFD"; |
| 9834 | }, |
| 9835 | ); |
| 9836 | this.wasClean = !!init.wasClean; |
| 9837 | } |
| 9838 | }; |
| 9839 | } |
| 9840 | if (!globalThis.DOMException) { |
| 9841 | globalThis.DOMException = class DOMException extends Error { |
| 9842 | constructor(message = "", name = "Error") { super(message); this.name = name; } |
| 9843 | }; |
| 9844 | // WebIDL legacy code constants, enumerable on both the interface |
| 9845 | // object and its prototype, in spec order. |
| 9846 | { |
| 9847 | const codes = [ |
| 9848 | ["INDEX_SIZE_ERR", 1], ["DOMSTRING_SIZE_ERR", 2], |
| 9849 | ["HIERARCHY_REQUEST_ERR", 3], ["WRONG_DOCUMENT_ERR", 4], |
| 9850 | ["INVALID_CHARACTER_ERR", 5], ["NO_DATA_ALLOWED_ERR", 6], |
| 9851 | ["NO_MODIFICATION_ALLOWED_ERR", 7], ["NOT_FOUND_ERR", 8], |
| 9852 | ["NOT_SUPPORTED_ERR", 9], ["INUSE_ATTRIBUTE_ERR", 10], |
| 9853 | ["INVALID_STATE_ERR", 11], ["SYNTAX_ERR", 12], |
| 9854 | ["INVALID_MODIFICATION_ERR", 13], ["NAMESPACE_ERR", 14], |
| 9855 | ["INVALID_ACCESS_ERR", 15], ["VALIDATION_ERR", 16], |
| 9856 | ["TYPE_MISMATCH_ERR", 17], ["SECURITY_ERR", 18], |
| 9857 | ["NETWORK_ERR", 19], ["ABORT_ERR", 20], |
| 9858 | ["URL_MISMATCH_ERR", 21], ["QUOTA_EXCEEDED_ERR", 22], |
| 9859 | ["TIMEOUT_ERR", 23], ["INVALID_NODE_TYPE_ERR", 24], |
| 9860 | ["DATA_CLONE_ERR", 25], |
| 9861 | ]; |
| 9862 | for (const [name, value] of codes) { |
| 9863 | const d = { value, writable: false, enumerable: true, |
| 9864 | configurable: false }; |
| 9865 | Object.defineProperty(globalThis.DOMException, name, d); |
| 9866 | Object.defineProperty(globalThis.DOMException.prototype, name, d); |
| 9867 | } |
| 9868 | // The legacy `code` member maps the error name to its constant, per |
| 9869 | // WebIDL; names outside the table (and every modern name) are 0. |
| 9870 | const legacy = { |
| 9871 | IndexSizeError: 1, HierarchyRequestError: 3, WrongDocumentError: 4, |
| 9872 | InvalidCharacterError: 5, NoModificationAllowedError: 7, |
| 9873 | NotFoundError: 8, NotSupportedError: 9, InUseAttributeError: 10, |
| 9874 | InvalidStateError: 11, SyntaxError: 12, InvalidModificationError: 13, |
| 9875 | NamespaceError: 14, InvalidAccessError: 15, TypeMismatchError: 17, |
| 9876 | SecurityError: 18, NetworkError: 19, AbortError: 20, |
| 9877 | URLMismatchError: 21, QuotaExceededError: 22, TimeoutError: 23, |
| 9878 | InvalidNodeTypeError: 24, DataCloneError: 25, |
| 9879 | }; |
| 9880 | Object.defineProperty(globalThis.DOMException.prototype, "code", { |
| 9881 | get() { return legacy[this.name] ?? 0; }, |
| 9882 | enumerable: true, configurable: true, |
| 9883 | }); |
| 9884 | } |
| 9885 | } |
| 9886 | if (!globalThis.AbortSignal) { |
| 9887 | const __abortBrand = Symbol("abortSignal"); |
| 9888 | globalThis.AbortSignal = class AbortSignal extends EventTarget { |
| 9889 | // The Headers/Blob clone-poisoning brand: V8's structured |
| 9890 | // clone throws on functions, so a live signal reaches the |
| 9891 | // RPC lift instead of silently flattening to plain data. |
| 9892 | constructor() { |
| 9893 | // Per spec AbortSignal has no constructor: it is only reachable |
| 9894 | // through AbortController, AbortSignal.abort/timeout/any. The internal |
| 9895 | // paths pass the brand to get past this. |
| 9896 | if (arguments[0] !== __abortBrand) { |
| 9897 | throw new TypeError("Illegal constructor"); |
| 9898 | } |
| 9899 | super(); |
| 9900 | this.aborted = false; |
| 9901 | this.reason = undefined; |
| 9902 | this.__celldHost = __rpcNoClone; |
| 9903 | } |
| 9904 | throwIfAborted() { if (this.aborted) throw this.reason; } |
| 9905 | static abort(reason = new DOMException("This operation was aborted", "AbortError")) { |
| 9906 | const c = new AbortController(); c.abort(reason); return c.signal; |
| 9907 | } |
| 9908 | static timeout(ms) { |
| 9909 | const c = new AbortController(); |
| 9910 | setTimeout(() => c.abort(new DOMException( |
| 9911 | "The operation was aborted due to timeout", "TimeoutError", |
| 9912 | )), ms); |
| 9913 | return c.signal; |
| 9914 | } |
| 9915 | static any(signals) { |
| 9916 | const c = new AbortController(); |
| 9917 | for (const signal of signals) { |
| 9918 | if (signal.aborted) { c.abort(signal.reason); break; } |
| 9919 | signal.addEventListener("abort", () => c.abort(signal.reason), { once: true }); |
| 9920 | } |
| 9921 | return c.signal; |
| 9922 | } |
| 9923 | }; |
| 9924 | Object.defineProperty(globalThis.AbortSignal.prototype, "onabort", { |
| 9925 | configurable: true, |
| 9926 | enumerable: true, |
| 9927 | get() { |
| 9928 | if (!(this instanceof globalThis.AbortSignal)) |
| 9929 | throw new TypeError("Illegal invocation"); |
| 9930 | return __getEventHandler(this, "abort"); |
| 9931 | }, |
| 9932 | set(value) { |
| 9933 | if (!(this instanceof globalThis.AbortSignal)) |
| 9934 | throw new TypeError("Illegal invocation"); |
| 9935 | __setEventHandler(this, "abort", value); |
| 9936 | }, |
| 9937 | }); |
| 9938 | globalThis.AbortController = class AbortController { |
| 9939 | constructor() { this.signal = new AbortSignal(__abortBrand); } |
| 9940 | abort(reason = new DOMException("This operation was aborted", "AbortError")) { |
| 9941 | __abortSignal(this.signal, reason); |
| 9942 | } |
| 9943 | }; |
| 9944 | } |
| 9945 | if (!globalThis.Blob) { |
| 9946 | // Same clone-poisoning brand as Headers: an enumerable |
| 9947 | // function-valued property makes V8's structured clone throw, so |
| 9948 | // a Blob reaches the RPC lift instead of silently flattening. |
| 9949 | const __blobNoClone = () => {}; |
| 9950 | globalThis.Blob = class Blob { |
| 9951 | constructor(parts = [], options = {}) { |
| 9952 | // size is assigned before type so both land in the order the |
| 9953 | // inspect output below reports them. |
| 9954 | if (options && options.endings !== undefined) |
| 9955 | throw new Error( |
| 9956 | "The 'endings' field on 'Options' is not implemented."); |
| 9957 | this.size = 0; |
| 9958 | // A type outside U+0020..U+007E is not a valid MIME type and is |
| 9959 | // dropped rather than stored. |
| 9960 | const rawType = String(options.type || ""); |
| 9961 | this.type = /^[\u0020-\u007e]*$/.test(rawType) |
| 9962 | ? rawType.toLowerCase() : ""; |
| 9963 | this.__celldHost = __blobNoClone; |
| 9964 | // Two passes. First convert every part in order -- string |
| 9965 | // conversion runs user code (Symbol.toPrimitive), which may |
| 9966 | // resize a backing buffer. Buffers and views are carried through |
| 9967 | // as-is so a length-tracking view is measured *after* those side |
| 9968 | // effects, matching Workerd. Then allocate once and copy. |
| 9969 | // |
| 9970 | // The previous shape pushed every byte into a plain array with a |
| 9971 | // spread, costing roughly 8x the memory and exceeding the |
| 9972 | // argument limit on multi-megabyte parts. |
| 9973 | const sources = []; |
| 9974 | for (const part of parts) { |
| 9975 | if (part instanceof Blob) sources.push(part._bytes); |
| 9976 | else if (part instanceof ArrayBuffer || |
| 9977 | ArrayBuffer.isView(part)) sources.push(part); |
| 9978 | else sources.push(new TextEncoder().encode(String(part))); |
| 9979 | } |
| 9980 | const chunks = sources.map((source) => |
| 9981 | source instanceof Uint8Array ? source |
| 9982 | : source instanceof ArrayBuffer ? new Uint8Array(source) |
| 9983 | : new Uint8Array( |
| 9984 | source.buffer, source.byteOffset, source.byteLength)); |
| 9985 | let total = 0; |
| 9986 | for (const chunk of chunks) total += chunk.byteLength; |
| 9987 | const LIMIT = 134217728; |
| 9988 | if (total > LIMIT) |
| 9989 | throw new RangeError( |
| 9990 | `Blob size ${total} exceeds limit ${LIMIT}`); |
| 9991 | const bytes = new Uint8Array(total); |
| 9992 | let offset = 0; |
| 9993 | for (const chunk of chunks) { |
| 9994 | bytes.set(chunk, offset); |
| 9995 | offset += chunk.byteLength; |
| 9996 | } |
| 9997 | // Non-enumerable: the backing store is not part of the object's |
| 9998 | // observable shape (inspect, JSON, spread). |
| 9999 | Object.defineProperty(this, "_bytes", { |
| 10000 | value: bytes, writable: true, configurable: true, |
| 10001 | }); |
| 10002 | this.size = total; |
| 10003 | } |
| 10004 | async arrayBuffer() { return this._bytes.slice().buffer; } |
| 10005 | async bytes() { return this._bytes.slice(); } |
| 10006 | async text() { return new TextDecoder().decode(this._bytes); } |
| 10007 | stream() { |
| 10008 | const bytes = this._bytes; |
| 10009 | return new ReadableStream({ |
| 10010 | start(controller) { |
| 10011 | if (bytes.byteLength) controller.enqueue(bytes.slice()); |
| 10012 | controller.close(); |
| 10013 | }, |
| 10014 | }); |
| 10015 | } |
| 10016 | [Symbol.for("nodejs.util.inspect.custom")]() { |
| 10017 | return `Blob { size: ${this.size}, type: '${this.type}' }`; |
| 10018 | } |
| 10019 | slice(start = 0, end = this.size, type = "") { |
| 10020 | const norm = (n, fallback) => { |
| 10021 | n = n === undefined ? fallback : Number(n); |
| 10022 | return n < 0 ? Math.max(this.size + n, 0) : Math.min(n, this.size); |
| 10023 | }; |
| 10024 | const a = norm(start, 0), b = norm(end, this.size); |
| 10025 | return new Blob( |
| 10026 | [this._bytes.subarray(a, Math.max(a, b))], { type }); |
| 10027 | } |
| 10028 | get [Symbol.toStringTag]() { return "Blob"; } |
| 10029 | }; |
| 10030 | } |
| 10031 | if (!globalThis.File) { |
| 10032 | // WebIDL-ish per Workerd: name is required, name/lastModified are |
| 10033 | // brand-checked prototype getters (enumerable, matching the |
| 10034 | // workers_api_getters_setters_on_prototype flag), and lastModified |
| 10035 | // coerces via ToNumber (throws for BigInt), NaN becoming 0. |
| 10036 | globalThis.File = class File extends Blob { |
| 10037 | #name; |
| 10038 | #lastModified; |
| 10039 | constructor(parts, name, options = {}) { |
| 10040 | if (arguments.length < 2) |
| 10041 | throw new TypeError( |
| 10042 | "Failed to construct 'File': 2 arguments required, but " + |
| 10043 | `only ${arguments.length} present.`); |
| 10044 | super(parts, options); |
| 10045 | this.#name = String(name); |
| 10046 | const lm = options == null ? undefined : options.lastModified; |
| 10047 | if (lm === undefined) this.#lastModified = Date.now(); |
| 10048 | else { |
| 10049 | const n = +lm; // ToNumber: throws for BigInt, like WebIDL |
| 10050 | this.#lastModified = Number.isFinite(n) ? Math.trunc(n) : 0; |
| 10051 | } |
| 10052 | } |
| 10053 | get name() { return this.#name; } |
| 10054 | get lastModified() { return this.#lastModified; } |
| 10055 | get [Symbol.toStringTag]() { return "File"; } |
| 10056 | [Symbol.for("nodejs.util.inspect.custom")]() { |
| 10057 | return `File { name: '${this.name}', ` + |
| 10058 | `lastModified: ${this.lastModified}, size: ${this.size}, ` + |
| 10059 | `type: '${this.type}' }`; |
| 10060 | } |
| 10061 | }; |
| 10062 | for (const key of ["name", "lastModified"]) { |
| 10063 | const desc = |
| 10064 | Object.getOwnPropertyDescriptor(File.prototype, key); |
| 10065 | desc.enumerable = true; |
| 10066 | Object.defineProperty(File.prototype, key, desc); |
| 10067 | } |
| 10068 | } |
| 10069 | if (!globalThis.FormData) { |
| 10070 | // Byte offsets the multipart scanner compares against. A part body is |
| 10071 | // arbitrary bytes, so every framing decision below is made on bytes. |
| 10072 | const __CR = 13, __LF = 10, __DASH = 45; |
| 10073 | const __bytesIndexOf = (haystack, needle, from) => { |
| 10074 | const last = haystack.length - needle.length; |
| 10075 | outer: for (let i = from; i <= last; i++) { |
| 10076 | for (let j = 0; j < needle.length; j++) |
| 10077 | if (haystack[i + j] !== needle[j]) continue outer; |
| 10078 | return i; |
| 10079 | } |
| 10080 | return -1; |
| 10081 | }; |
| 10082 | // A boundary delimiter is a delimiter only at the start of a line (RFC 2046 |
| 10083 | // section 5.1.1). Searching for the bytes anywhere would let a binary part |
| 10084 | // that happens to contain `--<boundary>` split itself, which is a corrupt |
| 10085 | // upload rather than a parse error, so the caller never learns of it. |
| 10086 | const __delimiterIndex = (bytes, delimiter, from) => { |
| 10087 | for (let at = from;;) { |
| 10088 | const found = __bytesIndexOf(bytes, delimiter, at); |
| 10089 | if (found < 0) return -1; |
| 10090 | if (found === 0 || bytes[found - 1] === __LF) return found; |
| 10091 | at = found + 1; |
| 10092 | } |
| 10093 | }; |
| 10094 | // A `Content-Disposition` parameter, anchored to the start of a parameter: |
| 10095 | // the parameter name must follow the header name or a `;`. An unanchored |
| 10096 | // pattern found the `name=` inside `filename=`, so a part whose header wrote |
| 10097 | // the filename first landed under the filename. The grammar does not |
| 10098 | // constrain the parameter order, and both orders occur in the wild. Hoisted |
| 10099 | // because the previous shape compiled a regex per parameter per part. |
| 10100 | const __CD_NAME = |
| 10101 | /(?:^|;)\s*name\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i; |
| 10102 | const __CD_FILENAME = |
| 10103 | /(?:^|;)\s*filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i; |
| 10104 | // Body -> FormData for multipart/form-data and |
| 10105 | // application/x-www-form-urlencoded. Kept out of the class so V8 only |
| 10106 | // pre-parses it; the body is compiled on first actual formData() call. |
| 10107 | // |
| 10108 | // `bytes` is the undecoded body. A file part must reach `File` as the bytes |
| 10109 | // that arrived: decoding the body first and slicing part bodies out of the |
| 10110 | // string replaced every non-UTF-8 sequence with U+FFFD, and the re-encode in |
| 10111 | // the `Blob` constructor then wrote those replacement bytes into the file. |
| 10112 | __celld.__parseFormData = (bytes, contentType) => { |
| 10113 | const ct = String(contentType || ""); |
| 10114 | if (/^\s*application\/x-www-form-urlencoded/i.test(ct)) { |
| 10115 | // This form is decoded as UTF-8, so a declared charset that is not UTF-8 |
| 10116 | // cannot be honoured. Refuse rather than mis-decode. |
| 10117 | const charset = /;\s*charset\s*=\s*"?([^";]+)/i.exec(ct); |
| 10118 | if (charset && !/^utf-?8$/i.test(charset[1].trim())) |
| 10119 | throw new TypeError( |
| 10120 | `Unsupported charset "${charset[1].trim()}". FormData can only ` + |
| 10121 | "parse UTF-8 encoded bodies."); |
| 10122 | const form = new FormData(); |
| 10123 | for (const [key, value] of new URLSearchParams( |
| 10124 | new TextDecoder().decode(bytes))) |
| 10125 | form.append(key, value); |
| 10126 | return form; |
| 10127 | } |
| 10128 | if (!/^\s*multipart\/form-data/i.test(ct)) |
| 10129 | throw new TypeError( |
| 10130 | "Unrecognized Content-Type header value. FormData can only " + |
| 10131 | "parse the following MIME types: multipart/form-data, " + |
| 10132 | "application/x-www-form-urlencoded"); |
| 10133 | const found = /boundary\s*=\s*(?:"([^"]*)"|([^;]+))/i.exec(ct); |
| 10134 | if (!found) |
| 10135 | throw new TypeError( |
| 10136 | "No boundary was found in the multipart/form-data " + |
| 10137 | "Content-Type header."); |
| 10138 | const boundary = (found[1] !== undefined ? found[1] : found[2]).trim(); |
| 10139 | const form = new FormData(); |
| 10140 | const delimiter = new TextEncoder().encode("--" + boundary); |
| 10141 | // Walk the delimiters rather than splitting on them, so that a body whose |
| 10142 | // framing is truncated or corrupt is refused instead of silently yielding |
| 10143 | // the parts that happened to parse. Only the framing is checked; a part's |
| 10144 | // own bytes are carried through unexamined. The preamble before the first |
| 10145 | // delimiter and the epilogue after the closing one are ignored. |
| 10146 | let cursor = __delimiterIndex(bytes, delimiter, 0); |
| 10147 | if (cursor < 0) |
| 10148 | throw new TypeError( |
| 10149 | "No boundary delimiter was found in the multipart/form-data body."); |
| 10150 | cursor += delimiter.length; |
| 10151 | for (;;) { |
| 10152 | // What follows a delimiter decides everything: "--" closes the body, a |
| 10153 | // line break opens another part, and anything else is malformed. |
| 10154 | if (bytes[cursor] === __DASH && bytes[cursor + 1] === __DASH) break; |
| 10155 | const lineBreak = bytes[cursor] === __CR && bytes[cursor + 1] === __LF |
| 10156 | ? 2 |
| 10157 | : bytes[cursor] === __LF ? 1 : 0; |
| 10158 | if (lineBreak === 0) |
| 10159 | throw new TypeError( |
| 10160 | "A boundary delimiter must be followed by CRLF, LF, or \"--\"."); |
| 10161 | cursor += lineBreak; |
| 10162 | const partStart = cursor; |
| 10163 | const next = __delimiterIndex(bytes, delimiter, partStart); |
| 10164 | if (next < 0) |
| 10165 | throw new TypeError( |
| 10166 | "The multipart/form-data body ended without a closing boundary " + |
| 10167 | "delimiter."); |
| 10168 | // The line break before a delimiter belongs to the delimiter, not to the |
| 10169 | // part it terminates. |
| 10170 | let chunkEnd = next; |
| 10171 | if (chunkEnd > partStart && bytes[chunkEnd - 1] === __LF) { |
| 10172 | chunkEnd -= 1; |
| 10173 | if (chunkEnd > partStart && bytes[chunkEnd - 1] === __CR) chunkEnd -= 1; |
| 10174 | } |
| 10175 | cursor = next + delimiter.length; |
| 10176 | // The headers end at the first blank line. Either line break can be CRLF |
| 10177 | // or a bare LF, which accepted inputs can contain. |
| 10178 | let headerEnd = -1, bodyStart = -1; |
| 10179 | for (let i = partStart; i < chunkEnd; i++) { |
| 10180 | const first = bytes[i] === __CR && bytes[i + 1] === __LF |
| 10181 | ? 2 |
| 10182 | : bytes[i] === __LF ? 1 : 0; |
| 10183 | if (first === 0) continue; |
| 10184 | const after = i + first; |
| 10185 | const second = bytes[after] === __CR && bytes[after + 1] === __LF |
| 10186 | ? 2 |
| 10187 | : bytes[after] === __LF ? 1 : 0; |
| 10188 | if (second === 0) continue; |
| 10189 | headerEnd = i; |
| 10190 | bodyStart = after + second; |
| 10191 | break; |
| 10192 | } |
| 10193 | if (headerEnd < 0) |
| 10194 | throw new TypeError( |
| 10195 | "A FormData part's headers must be terminated by a blank line."); |
| 10196 | // Part headers are text. Decoding this slice as UTF-8 keeps a non-ASCII |
| 10197 | // name or filename intact and cannot reach the part body. |
| 10198 | const rawHeaders = new TextDecoder().decode( |
| 10199 | bytes.subarray(partStart, headerEnd)); |
| 10200 | const body = bytes.subarray(bodyStart, chunkEnd); |
| 10201 | let disposition = null; |
| 10202 | let type = ""; |
| 10203 | for (const line of rawHeaders.split(/\r?\n/)) { |
| 10204 | const colon = line.indexOf(":"); |
| 10205 | if (colon < 0) continue; |
| 10206 | const name = line.slice(0, colon).trim().toLowerCase(); |
| 10207 | const value = line.slice(colon + 1).trim(); |
| 10208 | if (name === "content-disposition") disposition = value; |
| 10209 | else if (name === "content-type") type = value; |
| 10210 | } |
| 10211 | if (disposition === null) |
| 10212 | throw new TypeError( |
| 10213 | "Content-Disposition header is required for each FormData " + |
| 10214 | "part."); |
| 10215 | const kind = disposition.split(";")[0].trim(); |
| 10216 | if (kind.toLowerCase() !== "form-data") |
| 10217 | throw new TypeError( |
| 10218 | "Content-Disposition header for FormData part must have the " + |
| 10219 | "value \"form-data\", possibly followed by parameters. Got: " + |
| 10220 | "\"" + kind + "\""); |
| 10221 | const param = (pattern) => { |
| 10222 | const m = pattern.exec(disposition); |
| 10223 | if (!m) return undefined; |
| 10224 | const raw = m[1] !== undefined ? m[1] : (m[2] || "").trim(); |
| 10225 | if (/\\$/.test(raw.replace(/\\\\/g, ""))) |
| 10226 | throw new TypeError( |
| 10227 | "Name or filename can't end with backslash"); |
| 10228 | return raw.replace(/\\(.)/g, "$1"); |
| 10229 | }; |
| 10230 | const name = param(__CD_NAME); |
| 10231 | if (name === undefined) |
| 10232 | throw new TypeError( |
| 10233 | "Content-Disposition header for FormData part must have a " + |
| 10234 | "name parameter."); |
| 10235 | const filename = param(__CD_FILENAME); |
| 10236 | // A part without a filename is an entry value, which the spec defines as a |
| 10237 | // string, so this one part is decoded as UTF-8. A file part keeps its |
| 10238 | // bytes. |
| 10239 | if (filename === undefined) |
| 10240 | form.append(name, new TextDecoder().decode(body)); |
| 10241 | else |
| 10242 | form.append( |
| 10243 | name, new File([body], filename, { type: type || "" })); |
| 10244 | } |
| 10245 | return form; |
| 10246 | }; |
| 10247 | // Spec entry conversion: strings stay strings; a Blob becomes a |
| 10248 | // File named "blob" (or `filename`); a File is renamed only when a |
| 10249 | // filename is supplied. |
| 10250 | const __formDataValue = (value, filename) => { |
| 10251 | if (!(value instanceof Blob)) return String(value); |
| 10252 | if (value instanceof File && filename === undefined) return value; |
| 10253 | return new File( |
| 10254 | [value], |
| 10255 | filename === undefined ? "blob" : String(filename), |
| 10256 | { |
| 10257 | type: value.type, |
| 10258 | lastModified: |
| 10259 | value instanceof File ? value.lastModified : undefined, |
| 10260 | }, |
| 10261 | ); |
| 10262 | }; |
| 10263 | globalThis.FormData = class FormData { |
| 10264 | constructor() { this._entries = []; } |
| 10265 | append(name, value, filename) { |
| 10266 | this._entries.push( |
| 10267 | [String(name), __formDataValue(value, filename)]); |
| 10268 | } |
| 10269 | set(name, value, filename) { |
| 10270 | value = __formDataValue(value, filename); |
| 10271 | const key = String(name); |
| 10272 | // Spec: replace the first match in place, keeping its position, |
| 10273 | // and drop any later matches. |
| 10274 | const first = this._entries.findIndex(([k]) => k === key); |
| 10275 | if (first < 0) { this._entries.push([key, value]); return; } |
| 10276 | this._entries[first] = [key, value]; |
| 10277 | for (let i = this._entries.length - 1; i > first; i--) |
| 10278 | if (this._entries[i][0] === key) this._entries.splice(i, 1); |
| 10279 | } |
| 10280 | get(name) { |
| 10281 | const row = this._entries.find(([key]) => key === String(name)); |
| 10282 | return row ? row[1] : null; |
| 10283 | } |
| 10284 | getAll(name) { |
| 10285 | return this._entries.filter(([key]) => key === String(name)).map(([, value]) => value); |
| 10286 | } |
| 10287 | has(name) { return this._entries.some(([key]) => key === String(name)); } |
| 10288 | delete(name) { |
| 10289 | const key = String(name); |
| 10290 | // Splice in place: the iterators below read the live list, so the |
| 10291 | // array identity must survive a delete during iteration. |
| 10292 | for (let i = this._entries.length - 1; i >= 0; i--) |
| 10293 | if (this._entries[i][0] === key) this._entries.splice(i, 1); |
| 10294 | } |
| 10295 | // Iteration is live: the iterator holds an index and re-reads the |
| 10296 | // entry list, so entries appended during iteration are visited and |
| 10297 | // an exhausted iterator resumes if entries are added later. A |
| 10298 | // generator cannot do this -- once it returns it is done forever. |
| 10299 | _iterate(pick) { |
| 10300 | const self = this; |
| 10301 | let index = 0; |
| 10302 | const iterator = { |
| 10303 | next() { |
| 10304 | if (index >= self._entries.length) |
| 10305 | return { value: undefined, done: true }; |
| 10306 | return { value: pick(self._entries[index++]), done: false }; |
| 10307 | }, |
| 10308 | [Symbol.iterator]() { return iterator; }, |
| 10309 | }; |
| 10310 | return iterator; |
| 10311 | } |
| 10312 | entries() { return this._iterate((e) => [e[0], e[1]]); } |
| 10313 | keys() { return this._iterate((e) => e[0]); } |
| 10314 | values() { return this._iterate((e) => e[1]); } |
| 10315 | [Symbol.iterator]() { return this.entries(); } |
| 10316 | forEach(callback, thisArg) { |
| 10317 | if (typeof callback !== "function") |
| 10318 | throw new TypeError( |
| 10319 | "Failed to execute 'forEach' on 'FormData': parameter 1 is " + |
| 10320 | "not of type 'Function'."); |
| 10321 | for (const [key, value] of this.entries()) |
| 10322 | callback.call(thisArg, value, key, this); |
| 10323 | } |
| 10324 | }; |
| 10325 | } |
| 10326 | // Node's Buffer lives in src/js/node_buffer.js, compiled |
| 10327 | // lazily (LAZY_GLOBALS / LAZY_MODULES) on first use. |
| 10328 | if (!globalThis.ErrorEvent) { |
| 10329 | globalThis.ErrorEvent = class ErrorEvent extends Event { |
| 10330 | constructor(type, init = {}) { |
| 10331 | super(type, init); |
| 10332 | this.message = String(init.message ?? ""); |
| 10333 | this.filename = String(init.filename ?? ""); |
| 10334 | this.lineno = Number(init.lineno ?? 0); |
| 10335 | this.colno = Number(init.colno ?? 0); |
| 10336 | this.error = init.error; |
| 10337 | } |
| 10338 | }; |
| 10339 | } |
| 10340 | // Web API globals a real bundle references at module scope but that the |
| 10341 | // prelude doesn't provide. Stub as empty classes (guarded so we never |
| 10342 | // clobber a real prelude implementation). Enough to LOAD; every name in |
| 10343 | // this first list has a real implementation elsewhere, so the empty class |
| 10344 | // only exists for the load-order window. |
| 10345 | for (const n of ["WebSocket", "EventTarget", "Event", "MessageEvent", |
| 10346 | "CloseEvent", "ErrorEvent", "SubtleCrypto", "TransformStream", |
| 10347 | "ReadableStream", "WritableStream", "ReadableStreamDefaultReader", |
| 10348 | "WritableStreamDefaultWriter", |
| 10349 | "ByteLengthQueuingStrategy", "CountQueuingStrategy", |
| 10350 | "TextEncoderStream", "TextDecoderStream"]) { |
| 10351 | if (!globalThis[n]) globalThis[n] = class {}; |
| 10352 | } |
| 10353 | // These have no implementation anywhere in celld. An empty class would |
| 10354 | // let `new BroadcastChannel(...)` hand back an inert object that fails |
| 10355 | // far from the cause; the compat contract is "reject at first use", so |
| 10356 | // the name loads but construction throws. (EventSource, MessageChannel, |
| 10357 | // and MessagePort are real; their scripts run after the harness.) |
| 10358 | for (const n of ["BroadcastChannel", "FileReader"]) { |
| 10359 | if (!globalThis[n]) globalThis[n] = class { |
| 10360 | constructor() { |
| 10361 | throw new Error(n + " is not implemented in celld"); |
| 10362 | } |
| 10363 | }; |
| 10364 | } |
| 10365 | const __sockets = __celld.__sockets = new Map(); |
| 10366 | globalThis.WebSocket = class WebSocket extends EventTarget { |
| 10367 | // The spec names, which workerd exposes and real bundles use. celld only |
| 10368 | // had the READY_STATE_* aliases, which no other runtime defines. |
| 10369 | static CONNECTING = 0; |
| 10370 | static OPEN = 1; |
| 10371 | static CLOSING = 2; |
| 10372 | static CLOSED = 3; |
| 10373 | static READY_STATE_CONNECTING = 0; |
| 10374 | static READY_STATE_OPEN = 1; |
| 10375 | static READY_STATE_CLOSING = 2; |
| 10376 | static READY_STATE_CLOSED = 3; |
| 10377 | constructor(id, protocols = [], boundTarget = null) { |
| 10378 | super(); |
| 10379 | const dialed = typeof id === "string"; |
| 10380 | // A socket bound to a Durable Object's socket behaves like a dialed one |
| 10381 | // in every way that matters here: the host carries its frames, so every |
| 10382 | // operation goes out through `__ws_*` on this id rather than to a peer |
| 10383 | // in this heap. |
| 10384 | const outbound = dialed || boundTarget !== null; |
| 10385 | this._outbound = outbound; |
| 10386 | this._boundTarget = boundTarget; |
| 10387 | this._bound = false; |
| 10388 | this._pendingClose = null; |
| 10389 | this._id = outbound ? __ws_alloc() : Number(id); |
| 10390 | this._attachment = undefined; |
| 10391 | this._target = null; |
| 10392 | this._accepted = false; |
| 10393 | this._hibernatable = false; |
| 10394 | this._pending = []; |
| 10395 | // The other end of an in-isolate upgrade (a WebSocketPair served |
| 10396 | // over a same-script service binding); frames route to it |
| 10397 | // directly instead of through the host connection. |
| 10398 | this._loopback = null; |
| 10399 | this.readyState = outbound ? 0 : 1; |
| 10400 | this._binaryType = __cell.compat?.websocketStandardBinaryType |
| 10401 | ? "blob" |
| 10402 | : "arraybuffer"; |
| 10403 | // A server-side socket has no URL, and reports null rather than an empty |
| 10404 | // string -- workerd's inspect output pins this. A socket that came back |
| 10405 | // from an upgrade has none either: nothing in this isolate dialed it. |
| 10406 | this.url = dialed ? id : null; |
| 10407 | this.protocol = ""; |
| 10408 | this.extensions = ""; |
| 10409 | if (boundTarget !== null) { |
| 10410 | // The caller drives this socket itself, exactly as a Worker drives one |
| 10411 | // it opened. The host pipe is not built until `accept()`, so a |
| 10412 | // response passed straight back out is left alone. |
| 10413 | this._polled = true; |
| 10414 | this._target = boundTarget; |
| 10415 | } |
| 10416 | if (dialed) { |
| 10417 | // workerd validates the URL in the constructor and throws |
| 10418 | // synchronously; letting the connector reject later would surface a |
| 10419 | // scheme mistake as a network failure instead of a TypeError. |
| 10420 | let parsed; |
| 10421 | try { |
| 10422 | parsed = new URL(id); |
| 10423 | } catch { |
| 10424 | throw new DOMException( |
| 10425 | "WebSocket Constructor: The url is invalid.", |
| 10426 | "SyntaxError"); |
| 10427 | } |
| 10428 | if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") { |
| 10429 | throw new DOMException( |
| 10430 | "WebSocket Constructor: The url scheme must be ws or wss.", |
| 10431 | "SyntaxError"); |
| 10432 | } |
| 10433 | // A Durable Object socket is pushed events by the host so it can revive |
| 10434 | // a hibernated cell. A Worker socket has no cell: the isolate polls it, |
| 10435 | // and it lives and dies with the request, which is the lifetime |
| 10436 | // Cloudflare gives one too. |
| 10437 | const scope = __currentActorScope(); |
| 10438 | this._polled = !scope; |
| 10439 | const requested = typeof protocols === "string" |
| 10440 | ? [protocols] |
| 10441 | : Array.from(protocols, String); |
| 10442 | for (const value of requested) { |
| 10443 | // RFC 6455 subprotocols are HTTP tokens; a space or separator would |
| 10444 | // otherwise be smuggled into the Sec-WebSocket-Protocol header. |
| 10445 | if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) { |
| 10446 | throw new DOMException( |
| 10447 | `WebSocket Constructor: The subprotocol '${value}' is invalid.`, |
| 10448 | "SyntaxError"); |
| 10449 | } |
| 10450 | } |
| 10451 | if (new Set(requested).size !== requested.length) { |
| 10452 | throw new DOMException( |
| 10453 | "WebSocket Constructor: The subprotocols must be unique.", |
| 10454 | "SyntaxError"); |
| 10455 | } |
| 10456 | __sockets.set(this._id, this); |
| 10457 | const connection = __ws_connect(this._id, scope, id, JSON.stringify(requested)); |
| 10458 | __registerWaitUntil(connection); |
| 10459 | if (this._polled) this._startPump(); |
| 10460 | connection.then((protocol) => { |
| 10461 | if (this.readyState === WebSocket.READY_STATE_CLOSING) { |
| 10462 | if (this._pendingClose) { |
| 10463 | const [code, reason] = this._pendingClose; |
| 10464 | __ws_close(this._id, code, reason); |
| 10465 | } |
| 10466 | return; |
| 10467 | } |
| 10468 | if (this.readyState !== WebSocket.READY_STATE_CONNECTING) return; |
| 10469 | this.protocol = protocol; |
| 10470 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 10471 | this.dispatchEvent(new Event("open")); |
| 10472 | }, (error) => { |
| 10473 | this.readyState = WebSocket.READY_STATE_CLOSED; |
| 10474 | __sockets.delete(this._id); |
| 10475 | this.dispatchEvent(new ErrorEvent("error", { message: String(error?.message || error), error })); |
| 10476 | this._dispatchClose(1006, "", false); |
| 10477 | }); |
| 10478 | } |
| 10479 | } |
| 10480 | // The pump ends only when the socket closes, so it must NOT be registered |
| 10481 | // as waitUntil work: that would hold the request open for as long as the |
| 10482 | // socket lives, and the host reclaims an abandoned socket only once the |
| 10483 | // request has retired. Its `__ws_next` ops are driven while the request |
| 10484 | // runs and normally resolve with the host's 1001 "request ended" close. |
| 10485 | // They resolve as 1006 only if the sender disappears without a close frame. |
| 10486 | _startPump() { |
| 10487 | if (this._pumping) return; |
| 10488 | this._pumping = true; |
| 10489 | this._pump().catch(() => {}); |
| 10490 | } |
| 10491 | // Drain the host queue for an isolate-polled socket. Each `__ws_next` is an |
| 10492 | // ordinary async op the request owns; a request that retires with the |
| 10493 | // socket still open closes it, which ends this loop with a close frame. |
| 10494 | async _pump() { |
| 10495 | for (;;) { |
| 10496 | const frame = await __ws_next(this._id); |
| 10497 | const tag = frame[0]; |
| 10498 | const body = frame.subarray(1); |
| 10499 | if (tag === 0) { |
| 10500 | this._dispatchMessage(new TextDecoder().decode(body)); |
| 10501 | } else if (tag === 1) { |
| 10502 | this._dispatchMessage( |
| 10503 | body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength), |
| 10504 | ); |
| 10505 | } else if (tag === 2) { |
| 10506 | if (this.readyState === WebSocket.READY_STATE_CONNECTING) { |
| 10507 | this.protocol = new TextDecoder().decode(body); |
| 10508 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 10509 | this.dispatchEvent(new Event("open")); |
| 10510 | } |
| 10511 | } else { |
| 10512 | const info = JSON.parse(new TextDecoder().decode(body)); |
| 10513 | this._dispatchClose(info.code, info.reason, info.wasClean); |
| 10514 | return; |
| 10515 | } |
| 10516 | } |
| 10517 | } |
| 10518 | // Deliver whatever this end queued before it had somewhere to send. |
| 10519 | _flushToPeer() { |
| 10520 | const peer = this._loopback; |
| 10521 | if (!peer) return; |
| 10522 | for (const frame of this._pending.splice(0)) { |
| 10523 | if (frame[0] === "send") { |
| 10524 | queueMicrotask(() => peer._dispatchMessage(frame[1])); |
| 10525 | } else if (frame[0] === "send-binary") { |
| 10526 | const data = frame[1]; |
| 10527 | const bytes = data instanceof ArrayBuffer |
| 10528 | ? data |
| 10529 | : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); |
| 10530 | queueMicrotask(() => peer._dispatchMessage(bytes)); |
| 10531 | } else { |
| 10532 | queueMicrotask(() => peer._dispatchClose(frame[1], frame[2], true)); |
| 10533 | } |
| 10534 | } |
| 10535 | } |
| 10536 | get binaryType() { return this._binaryType; } |
| 10537 | // The spec ignores an unrecognised value rather than throwing. |
| 10538 | set binaryType(value) { |
| 10539 | if (value === "blob" || value === "arraybuffer") this._binaryType = value; |
| 10540 | } |
| 10541 | accept() { |
| 10542 | this._accepted = true; |
| 10543 | // A pair used directly, without being returned through a 101 response, |
| 10544 | // still has to carry frames once both ends are accepted. celld only |
| 10545 | // linked a pair on the upgrade path, so such a pair queued forever. |
| 10546 | if (this._peer && this._peer._accepted && !this._loopback) { |
| 10547 | this._loopback = this._peer; |
| 10548 | this._peer._loopback = this; |
| 10549 | this._flushToPeer(); |
| 10550 | this._peer._flushToPeer(); |
| 10551 | } |
| 10552 | // A socket obtained from a `fetch()` upgrade is already connected and |
| 10553 | // delivers nothing until it is accepted; this is where it starts. |
| 10554 | if (this._outbound && this.readyState === WebSocket.READY_STATE_CONNECTING) { |
| 10555 | // Bind before the pump: the op registers this socket's queue on this |
| 10556 | // thread, so the first `__ws_next` cannot run ahead of it. |
| 10557 | if (this._boundTarget !== null && !this._bound) { |
| 10558 | this._bound = true; |
| 10559 | __ws_bind_target( |
| 10560 | this._id, |
| 10561 | JSON.stringify(this._boundTarget), |
| 10562 | __currentActorScope(), |
| 10563 | ); |
| 10564 | } |
| 10565 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 10566 | if (this._polled) this._startPump(); |
| 10567 | } |
| 10568 | } |
| 10569 | send(data) { |
| 10570 | if (this.readyState !== WebSocket.READY_STATE_OPEN) |
| 10571 | throw new DOMException("WebSocket is not open", "InvalidStateError"); |
| 10572 | const binary = data instanceof ArrayBuffer || ArrayBuffer.isView(data); |
| 10573 | const text = binary ? null : String(data); |
| 10574 | if (this._loopback) { |
| 10575 | const peer = this._loopback; |
| 10576 | const message = binary |
| 10577 | ? (data instanceof ArrayBuffer ? data.slice(0) : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)) |
| 10578 | : text; |
| 10579 | queueMicrotask(() => peer._dispatchMessage(message)); |
| 10580 | return; |
| 10581 | } |
| 10582 | // The pending queue belongs to an inbound pair socket that has been |
| 10583 | // accepted but not yet bound to a host transport. An outbound socket is |
| 10584 | // already bound -- queueing here would silently swallow its frames. |
| 10585 | if (!this._outbound && this._accepted && !this._target) { |
| 10586 | this._pending.push([binary ? "send-binary" : "send", binary ? data : text]); |
| 10587 | return; |
| 10588 | } |
| 10589 | if (binary) { |
| 10590 | const bytes = data instanceof ArrayBuffer |
| 10591 | ? new Uint8Array(data) |
| 10592 | : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); |
| 10593 | __ws_send_binary(this._id, bytes); |
| 10594 | } else { |
| 10595 | __ws_send(this._id, text); |
| 10596 | } |
| 10597 | } |
| 10598 | close(code = 1000, reason = "") { |
| 10599 | // WHATWG: an application may send 1000 or 3000-4999. Everything else is |
| 10600 | // reserved for the protocol itself. |
| 10601 | const wanted = Number(code); |
| 10602 | if (wanted !== 1000 && !(wanted >= 3000 && wanted <= 4999)) { |
| 10603 | throw new DOMException( |
| 10604 | `WebSocket close code ${code} is not permitted`, |
| 10605 | "InvalidAccessError"); |
| 10606 | } |
| 10607 | // RFC 6455 5.5: the close frame body is at most 125 bytes, two of which |
| 10608 | // are the code. Measured in UTF-8, so a multibyte reason can exceed the |
| 10609 | // cap at well under 123 characters. |
| 10610 | if (new TextEncoder().encode(String(reason)).length > 123) { |
| 10611 | throw new DOMException( |
| 10612 | "WebSocket close reason must not exceed 123 bytes", |
| 10613 | "SyntaxError"); |
| 10614 | } |
| 10615 | // Outbound sockets follow the WebSocket spec: closing a closed socket is a |
| 10616 | // no-op. Inbound sockets must NOT take that shortcut -- a Durable Object |
| 10617 | // answers a peer-initiated close from inside `webSocketClose`, by which |
| 10618 | // point `_dispatchClose` has already marked this side closed, and its |
| 10619 | // reply carries the reason the client is entitled to see. |
| 10620 | if (this._outbound && this.readyState === WebSocket.READY_STATE_CLOSED) { |
| 10621 | return; |
| 10622 | } |
| 10623 | const connecting = this.readyState === WebSocket.READY_STATE_CONNECTING; |
| 10624 | this.readyState = WebSocket.READY_STATE_CLOSING; |
| 10625 | if (this._outbound && connecting) { |
| 10626 | this._pendingClose = [code, reason]; |
| 10627 | return; |
| 10628 | } |
| 10629 | if (this._outbound) { |
| 10630 | __ws_close(this._id, code, reason); |
| 10631 | return; |
| 10632 | } |
| 10633 | this.readyState = 3; |
| 10634 | if (this._loopback) { |
| 10635 | const peer = this._loopback; |
| 10636 | queueMicrotask(() => peer._dispatchClose(code, reason, true)); |
| 10637 | return; |
| 10638 | } |
| 10639 | if (this._accepted && !this._target) { |
| 10640 | this._pending.push(["close", code, reason]); |
| 10641 | return; |
| 10642 | } |
| 10643 | __ws_close(this._id, code, reason); |
| 10644 | } |
| 10645 | _flushPending() { |
| 10646 | const pending = this._pending.splice(0); |
| 10647 | for (const frame of pending) { |
| 10648 | if (frame[0] === "send") __ws_send(this._id, frame[1]); |
| 10649 | else if (frame[0] === "send-binary") { |
| 10650 | const data = frame[1]; |
| 10651 | const bytes = data instanceof ArrayBuffer |
| 10652 | ? new Uint8Array(data) |
| 10653 | : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); |
| 10654 | __ws_send_binary(this._id, bytes); |
| 10655 | } |
| 10656 | else __ws_close(this._id, frame[1], frame[2]); |
| 10657 | } |
| 10658 | } |
| 10659 | serializeAttachment(value) { |
| 10660 | // Structured clone, not JSON: Cloudflare accepts anything cloneable |
| 10661 | // here, so a Date must come back a Date and a Map a Map. |
| 10662 | this._attachment = value; |
| 10663 | __ws_attachment_set(this._id, __sc_encode(value)); |
| 10664 | } |
| 10665 | deserializeAttachment() { return this._attachment; } |
| 10666 | _dispatchMessage(data) { |
| 10667 | if (this._binaryType === "blob" && data instanceof ArrayBuffer) { |
| 10668 | data = new Blob([data]); |
| 10669 | } |
| 10670 | const event = new MessageEvent("message", { data }); |
| 10671 | event._trust(); |
| 10672 | this.dispatchEvent(event); |
| 10673 | } |
| 10674 | _dispatchClose(code, reason, wasClean) { |
| 10675 | if (this.readyState === WebSocket.READY_STATE_CLOSED) return; |
| 10676 | this.readyState = WebSocket.READY_STATE_CLOSED; |
| 10677 | __sockets.delete(this._id); |
| 10678 | // An abnormal closure fires `error` before `close`. Code written against |
| 10679 | // the standard onerror never ran otherwise, which matters most for an |
| 10680 | // outbound socket: its peer is a remote server that can simply vanish. |
| 10681 | // An abnormal closure fires `error` before `close`. Code written against |
| 10682 | // the standard onerror never ran otherwise, which matters most for an |
| 10683 | // outbound socket: its peer is a remote server that can simply vanish. |
| 10684 | // An abnormal closure fires `error` before `close`. Code written against |
| 10685 | // the standard onerror never ran otherwise, which matters most for an |
| 10686 | // outbound socket: its peer is a remote server that can simply vanish. |
| 10687 | if (!wasClean) { |
| 10688 | this.dispatchEvent(new ErrorEvent("error", { |
| 10689 | message: reason |
| 10690 | ? `WebSocket closed abnormally: ${reason}` |
| 10691 | : "WebSocket closed abnormally", |
| 10692 | })); |
| 10693 | } |
| 10694 | const event = new CloseEvent("close", { code, reason, wasClean }); |
| 10695 | event._trust(); |
| 10696 | this.dispatchEvent(event); |
| 10697 | } |
| 10698 | }; |
| 10699 | const __makeSocket = __celld.__makeSocket = (id) => new WebSocket(id); |
| 10700 | const __socketFromRow = __celld.__socketFromRow = (row) => { |
| 10701 | let ws = __sockets.get(Number(row.id)); |
| 10702 | if (!ws) { |
| 10703 | ws = __makeSocket(row.id); |
| 10704 | __sockets.set(Number(row.id), ws); |
| 10705 | } |
| 10706 | ws._tags = row.tags || []; |
| 10707 | ws._hibernatable = true; |
| 10708 | if (row.attachment != null) { |
| 10709 | try { |
| 10710 | ws._attachment = __sc_decode(new Uint8Array(row.attachment)); |
| 10711 | } catch { |
| 10712 | ws._attachment = undefined; |
| 10713 | } |
| 10714 | } |
| 10715 | return ws; |
| 10716 | }; |
| 10717 | // Workerd's api::WebSocketRequestResponsePair (websocket.h): an immutable |
| 10718 | // request/response pair for state.setWebSocketAutoResponse. |
| 10719 | globalThis.WebSocketRequestResponsePair = |
| 10720 | class WebSocketRequestResponsePair { |
| 10721 | #request; |
| 10722 | #response; |
| 10723 | constructor(request, response) { |
| 10724 | this.#request = String(request); |
| 10725 | this.#response = String(response); |
| 10726 | } |
| 10727 | get request() { return this.#request; } |
| 10728 | get response() { return this.#response; } |
| 10729 | }; |
| 10730 | globalThis.WebSocketPair = function WebSocketPair() { |
| 10731 | const id = __ws_alloc(); |
| 10732 | const client = __makeSocket(id); |
| 10733 | const server = __makeSocket(id); |
| 10734 | client._peer = server; |
| 10735 | server._peer = client; |
| 10736 | // Indexed AND iterable: `const [client, server] = new WebSocketPair()` is |
| 10737 | // the form most Cloudflare code uses. |
| 10738 | return { |
| 10739 | 0: client, |
| 10740 | 1: server, |
| 10741 | length: 2, |
| 10742 | [Symbol.iterator]() { |
| 10743 | return [client, server][Symbol.iterator](); |
| 10744 | }, |
| 10745 | }; |
| 10746 | }; |
| 10747 | // Cloudflare exposes the time of the last I/O, not a clock that advances |
| 10748 | // while JavaScript runs. Keep Date and performance on one turn timestamp so |
| 10749 | // neither becomes a timing side channel and the two APIs cannot disagree. |
| 10750 | const __NativeDate = Date; |
| 10751 | let __ioTimestamp = 0; |
| 10752 | const __CloudflareDate = function Date(...args) { |
| 10753 | if (new.target) { |
| 10754 | return Reflect.construct( |
| 10755 | __NativeDate, |
| 10756 | args.length === 0 ? [__ioTimestamp] : args, |
| 10757 | new.target, |
| 10758 | ); |
| 10759 | } |
| 10760 | return new __NativeDate(__ioTimestamp).toString(); |
| 10761 | }; |
| 10762 | Object.defineProperties(__CloudflareDate, { |
| 10763 | length: { value: 7 }, |
| 10764 | prototype: { value: __NativeDate.prototype }, |
| 10765 | now: { |
| 10766 | value: () => __ioTimestamp, |
| 10767 | writable: true, |
| 10768 | configurable: true, |
| 10769 | }, |
| 10770 | parse: { |
| 10771 | value: __NativeDate.parse, |
| 10772 | writable: true, |
| 10773 | configurable: true, |
| 10774 | }, |
| 10775 | UTC: { |
| 10776 | value: __NativeDate.UTC, |
| 10777 | writable: true, |
| 10778 | configurable: true, |
| 10779 | }, |
| 10780 | }); |
| 10781 | Object.defineProperty(__NativeDate.prototype, "constructor", { |
| 10782 | value: __CloudflareDate, |
| 10783 | writable: true, |
| 10784 | configurable: true, |
| 10785 | }); |
| 10786 | globalThis.Date = __CloudflareDate; |
| 10787 | globalThis.performance = { |
| 10788 | now: () => __ioTimestamp, |
| 10789 | timeOrigin: 0, |
| 10790 | mark() {}, |
| 10791 | measure() {}, |
| 10792 | }; |
| 10793 | __celld.__advanceIoTime = (timestamp) => { |
| 10794 | __ioTimestamp = timestamp; |
| 10795 | }; |
| 10796 | // Workerd ServiceWorkerGlobalScope: `self` is the global scope, as a writable, |
| 10797 | // enumerable data property. Libraries probe it to find the global, and |
| 10798 | // @cloudflare/worker-bundler throws when it is absent. |
| 10799 | globalThis.self = globalThis; |
| 10800 | if (!globalThis.navigator) globalThis.navigator = { |
| 10801 | userAgent: "Cloudflare-Workers", hardwareConcurrency: 1, |
| 10802 | language: "en", languages: ["en"], |
| 10803 | }; |
| 10804 | if (!globalThis.queueMicrotask) |
| 10805 | globalThis.queueMicrotask = (f) => Promise.resolve().then(f); |
| 10806 | if (!globalThis.scheduler) |
| 10807 | globalThis.scheduler = { |
| 10808 | wait: (ms) => new Promise((resolve) => setTimeout(resolve, Number(ms) || 0)), |
| 10809 | }; |
| 10810 | if (!globalThis.structuredClone) { |
| 10811 | const hostBrand = Symbol("Cells.structuredCloneHost"); |
| 10812 | const deserializers = { |
| 10813 | Blob: (data) => new Blob([data.bytes], { type: data.mimeType }), |
| 10814 | File: (data) => new File([data.bytes], data.name, { |
| 10815 | type: data.mimeType, |
| 10816 | lastModified: data.lastModified, |
| 10817 | }), |
| 10818 | CryptoKey: (data) => new CryptoKey( |
| 10819 | data.keyType, data.algorithm, data.extractable, data.usages, data.material), |
| 10820 | DOMException: (data) => { |
| 10821 | const exception = new DOMException(data.message, data.name); |
| 10822 | if (data.stack !== undefined) |
| 10823 | Object.defineProperty(exception, "stack", { |
| 10824 | value: data.stack, configurable: true, writable: true, |
| 10825 | }); |
| 10826 | return exception; |
| 10827 | }, |
| 10828 | }; |
| 10829 | const defineHostType = (prototype, serialize) => { |
| 10830 | if (!Object.prototype.hasOwnProperty.call(prototype, hostBrand)) |
| 10831 | Object.defineProperty(prototype, hostBrand, { value: serialize }); |
| 10832 | }; |
| 10833 | const defineUnsupportedType = (constructor) => { |
| 10834 | if (typeof constructor === "function") |
| 10835 | defineHostType(constructor.prototype, null); |
| 10836 | }; |
| 10837 | |
| 10838 | defineHostType(Blob.prototype, function() { |
| 10839 | return { |
| 10840 | type: "Blob", bytes: this._bytes, |
| 10841 | mimeType: this.type, |
| 10842 | }; |
| 10843 | }); |
| 10844 | defineHostType(File.prototype, function() { |
| 10845 | return { |
| 10846 | type: "File", bytes: this._bytes, |
| 10847 | mimeType: this.type, name: this.name, |
| 10848 | lastModified: this.lastModified, |
| 10849 | }; |
| 10850 | }); |
| 10851 | defineHostType(DOMException.prototype, function() { |
| 10852 | return { |
| 10853 | type: "DOMException", message: this.message, |
| 10854 | name: this.name, stack: this.stack, |
| 10855 | }; |
| 10856 | }); |
| 10857 | |
| 10858 | globalThis.structuredClone = function(value, options) { |
| 10859 | if (arguments.length < 1) |
| 10860 | throw new TypeError( |
| 10861 | "Failed to execute 'structuredClone': 1 argument required"); |
| 10862 | const transfer = options?.transfer === undefined |
| 10863 | ? [] : Array.from(options.transfer); |
| 10864 | const seen = new Set(); |
| 10865 | for (let index = 0; index < transfer.length; index++) { |
| 10866 | const item = transfer[index]; |
| 10867 | if (!(item instanceof ArrayBuffer)) |
| 10868 | throw new DOMException( |
| 10869 | `Value at index ${index} is not transferable`, "DataCloneError"); |
| 10870 | if (item.detached) |
| 10871 | throw new DOMException( |
| 10872 | `ArrayBuffer at index ${index} is already detached`, |
| 10873 | "DataCloneError"); |
| 10874 | if (seen.has(item)) |
| 10875 | throw new DOMException( |
| 10876 | `ArrayBuffer at index ${index} is a duplicate`, "DataCloneError"); |
| 10877 | seen.add(item); |
| 10878 | } |
| 10879 | |
| 10880 | // Crypto loads after this harness, and MessagePort is also installed by a |
| 10881 | // later bootstrap script. Register every late type before V8 traverses the |
| 10882 | // graph. The delegate then sees host objects at any depth without a second |
| 10883 | // JavaScript traversal, which follows Deno's structured-clone design. |
| 10884 | if (typeof CryptoKey === "function") |
| 10885 | defineHostType(CryptoKey.prototype, function() { |
| 10886 | return { |
| 10887 | type: "CryptoKey", keyType: this.type, |
| 10888 | algorithm: this.algorithm, extractable: this.extractable, |
| 10889 | usages: this.usages, material: this.__celldMaterial, |
| 10890 | }; |
| 10891 | }); |
| 10892 | for (const constructor of [ |
| 10893 | URL, URLSearchParams, Headers, FormData, Request, Response, |
| 10894 | typeof MessagePort === "function" ? MessagePort : undefined, |
| 10895 | ]) defineUnsupportedType(constructor); |
| 10896 | |
| 10897 | let result; |
| 10898 | try { |
| 10899 | result = __structured_clone(value, hostBrand, deserializers); |
| 10900 | } catch (error) { |
| 10901 | if (error instanceof TypeError) |
| 10902 | throw new DOMException(error.message, "DataCloneError"); |
| 10903 | throw error; |
| 10904 | } |
| 10905 | // Validate the complete list and clone the value before detaching any |
| 10906 | // source. A later invalid entry therefore cannot leave an earlier buffer |
| 10907 | // detached after the operation fails. |
| 10908 | for (const item of transfer) item.transfer(); |
| 10909 | return result; |
| 10910 | }; |
| 10911 | } |
| 10912 | // Web Crypto is installed after the rest of the harness so it can use |
| 10913 | // DOMException, structuredClone, and Buffer. |
| 10914 | // `Buffer` is read at call time, which materializes the lazy global. |
| 10915 | const __zlibSync = (mode, data) => |
| 10916 | Buffer.from(__zlib(mode, Buffer.from(data))); |
| 10917 | __celld.__zlibModule = { |
| 10918 | constants: { |
| 10919 | Z_NO_FLUSH: 0, |
| 10920 | Z_PARTIAL_FLUSH: 1, |
| 10921 | Z_SYNC_FLUSH: 2, |
| 10922 | Z_FULL_FLUSH: 3, |
| 10923 | Z_FINISH: 4, |
| 10924 | Z_BLOCK: 5, |
| 10925 | }, |
| 10926 | gzipSync: (data, _options) => __zlibSync("gzip", data), |
| 10927 | gunzipSync: (data, _options) => __zlibSync("gunzip", data), |
| 10928 | deflateSync: (data, _options) => __zlibSync("deflate", data), |
| 10929 | inflateSync: (data, _options) => __zlibSync("inflate", data), |
| 10930 | deflateRawSync: (data, _options) => __zlibSync("deflateRaw", data), |
| 10931 | inflateRawSync: (data, _options) => __zlibSync("inflateRaw", data), |
| 10932 | }; |
| 10933 | // A Node dependency reads a `process` field at module scope and passes it |
| 10934 | // straight to something that rejects `undefined` -- `dirname(process.execPath)` |
| 10935 | // is one such case. Workerd defines every field |
| 10936 | // below with a neutral value, so the same bundle evaluates there. A missing |
| 10937 | // field therefore fails the whole Worker at load, which is why each one is |
| 10938 | // defined even though nothing in a cell has an executable path, a parent |
| 10939 | // process, or a real exit code. The values match workerd's |
| 10940 | // `src/node/internal/public_process.ts` at workerd revision 04a08513a419 |
| 10941 | // (2026-09-04); celld does not invent its own, because a dependency that reads |
| 10942 | // them is comparing them to what workerd reports. A field whose workerd |
| 10943 | // implementation throws at that revision -- `kill`, `binding`, `dlopen`, |
| 10944 | // `cpuUsage` -- stays absent, because it fails on both runtimes and a stub |
| 10945 | // here would only change the message. |
| 10946 | if (!globalThis.process) globalThis.process = { |
| 10947 | env: {}, platform: "linux", arch: "x64", version: "v20.0.0", |
| 10948 | versions: { node: "20.0.0" }, cwd: () => "/", |
| 10949 | title: "workerd", argv: ["workerd"], argv0: "workerd", execArgv: [], |
| 10950 | execPath: "", pid: 1, ppid: 0, exitCode: undefined, |
| 10951 | allowedNodeEnvironmentFlags: new Set(), |
| 10952 | release: { name: "node", lts: true, sourceUrl: "", headersUrl: "" }, |
| 10953 | channel: null, connected: false, debugPort: 0, domain: null, |
| 10954 | noDeprecation: false, traceDeprecation: false, throwDeprecation: false, |
| 10955 | sourceMapsEnabled: false, moduleLoadList: [], |
| 10956 | stdin: { fd: 0, isTTY: false }, |
| 10957 | stdout: { fd: 1, isTTY: false, write: (s) => { __log(String(s)); return true; } }, |
| 10958 | stderr: { fd: 2, isTTY: false, write: (s) => { __log(String(s)); return true; } }, |
| 10959 | nextTick: (f, ...a) => queueMicrotask(() => f(...a)), |
| 10960 | on() {}, once() {}, off() {}, emit() {}, hrtime: () => [0, 0], |
| 10961 | // Workerd routes a warning to the process 'warning' event, and this |
| 10962 | // process emits nothing, so a no-op keeps the two runtimes equivalent. |
| 10963 | emitWarning() {}, |
| 10964 | ref() {}, unref() {}, uptime: () => 0, |
| 10965 | constrainedMemory: () => 0, availableMemory: () => 0, |
| 10966 | memoryUsage: () => ({ |
| 10967 | rss: 0, heapTotal: 0, heapUsed: 0, external: 0, arrayBuffers: 0, |
| 10968 | }), |
| 10969 | }; |
| 10970 | globalThis.process.exit = (code = 0) => { |
| 10971 | const actorScope = __currentActorScope(); |
| 10972 | if (actorScope) { |
| 10973 | const instance = __cell.instances[actorScope]; |
| 10974 | if (instance?.__celldState) |
| 10975 | instance.__celldState._resetAfterConcurrencyFailure(); |
| 10976 | } |
| 10977 | __process_exit(Number(code) || 0, actorScope); |
| 10978 | }; |
| 10979 | globalThis.process.getBuiltinModule = |
| 10980 | (id) => __builtin_module(String(id)); |
| 10981 | if (!globalThis.global) globalThis.global = globalThis; |
| 10982 | // Events belong to the request, and the host owns the request. `__event_*` |
| 10983 | // and `__wait_until` operate on whichever context the host has made current |
| 10984 | // for this turn, so nothing here has to know which request is running -- and |
| 10985 | // two requests sharing an isolate cannot pop each other's events. |
| 10986 | const __registerWaitUntil = __celld.__registerWaitUntil = (promise) => { |
| 10987 | const tracked = Promise.resolve(promise).catch((error) => { |
| 10988 | console.error("waitUntil rejected", error); |
| 10989 | }); |
| 10990 | __wait_until(tracked); |
| 10991 | }; |
| 10992 | // `props` are the per-stub props a loopback service stub carries |
| 10993 | // (ctx.props); `exports` is built once, on first access. |
| 10994 | const __defaultProps = {}; |
| 10995 | const __entrypointContext = (props = __defaultProps) => ({ |
| 10996 | waitUntil: __registerWaitUntil, |
| 10997 | passThroughOnException() {}, |
| 10998 | abort: __ctxAbortCurrent, |
| 10999 | props, |
| 11000 | get exports() { return __ctxExports(); }, |
| 11001 | }); |
| 11002 | const __beginEvent = __celld.__beginEvent = (props = __defaultProps) => { |
| 11003 | __rpcSignalRefresh(); |
| 11004 | __event_begin(); |
| 11005 | return __entrypointContext(props); |
| 11006 | }; |
| 11007 | const __endEvent = __celld.__endEvent = () => __event_end(); |
| 11008 | // Workerd's writable filesystem is memory-backed and request-scoped. The |
| 11009 | // native IoContext owns the directory tree; this facade supplies Node's path, |
| 11010 | // error, Promise, and Stats shapes without exposing a host filesystem. |
| 11011 | const __fsPath = (value) => { |
| 11012 | if (value instanceof URL) { |
| 11013 | if (value.protocol !== "file:") { |
| 11014 | const error = new TypeError('The URL must be of scheme file'); |
| 11015 | error.code = "ERR_INVALID_URL_SCHEME"; |
| 11016 | throw error; |
| 11017 | } |
| 11018 | value = decodeURIComponent(value.pathname); |
| 11019 | } else if (globalThis.Buffer?.isBuffer(value)) { |
| 11020 | value = value.toString(); |
| 11021 | } else if (typeof value !== "string") { |
| 11022 | const error = new TypeError( |
| 11023 | 'The "path" argument must be of type string or an instance of Buffer or URL', |
| 11024 | ); |
| 11025 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11026 | throw error; |
| 11027 | } |
| 11028 | if (value.includes("\0")) { |
| 11029 | const error = new TypeError('The argument "path" must not contain null bytes'); |
| 11030 | error.code = "ERR_INVALID_ARG_VALUE"; |
| 11031 | throw error; |
| 11032 | } |
| 11033 | const absolute = value.startsWith("/") ? value : process.cwd() + "/" + value; |
| 11034 | const parts = []; |
| 11035 | for (const part of absolute.split("/")) { |
| 11036 | if (!part || part === ".") continue; |
| 11037 | if (part === "..") parts.pop(); |
| 11038 | else parts.push(part); |
| 11039 | } |
| 11040 | return "/" + parts.join("/"); |
| 11041 | }; |
| 11042 | const __fsError = (code, syscall, path) => { |
| 11043 | const e = new Error(`${code}: ${syscall} '${path}'`); |
| 11044 | e.errno = { EPERM: -1, ENOENT: -2, EEXIST: -17, ENOTDIR: -20 }[code]; |
| 11045 | e.code = code; |
| 11046 | e.syscall = syscall; |
| 11047 | e.path = path; |
| 11048 | return e; |
| 11049 | }; |
| 11050 | const __enoent = (path = "") => { throw __fsError("ENOENT", "open", path); }; |
| 11051 | const __fsStatsBadge = Symbol("fs.Stats"); |
| 11052 | class __FsStats { |
| 11053 | constructor(badge, kind, size, bigint) { |
| 11054 | if (badge !== __fsStatsBadge) throw new TypeError("Illegal constructor"); |
| 11055 | const file = kind === 3; |
| 11056 | this.dev = 0; |
| 11057 | this.ino = 0; |
| 11058 | // A bundle file is 0o100444 and a writable temporary directory is 0o40666, |
| 11059 | // matching the mode values workerd's fs-stat-test.js asserts. |
| 11060 | this.mode = (file ? 0o100000 : 0o40000) | 0o444 | (kind === 2 ? 0o222 : 0); |
| 11061 | this.nlink = 1; |
| 11062 | this.uid = 0; |
| 11063 | this.gid = 0; |
| 11064 | this.rdev = 0; |
| 11065 | this.size = size; |
| 11066 | this.blksize = 0; |
| 11067 | this.blocks = 0; |
| 11068 | this.atimeMs = this.mtimeMs = this.ctimeMs = this.birthtimeMs = 0; |
| 11069 | this.atime = new Date(0); |
| 11070 | this.mtime = new Date(0); |
| 11071 | this.ctime = new Date(0); |
| 11072 | this.birthtime = new Date(0); |
| 11073 | Object.defineProperty(this, "__kind", { value: file ? "file" : "directory" }); |
| 11074 | if (bigint) { |
| 11075 | for (const name of [ |
| 11076 | "dev", "ino", "mode", "nlink", "uid", "gid", "rdev", "size", |
| 11077 | "blksize", "blocks", "atimeMs", "mtimeMs", "ctimeMs", "birthtimeMs", |
| 11078 | ]) this[name] = BigInt(this[name]); |
| 11079 | this.atimeNs = 0n; |
| 11080 | this.mtimeNs = 0n; |
| 11081 | this.ctimeNs = 0n; |
| 11082 | this.birthtimeNs = 0n; |
| 11083 | } |
| 11084 | } |
| 11085 | isFile() { return this.__kind === "file"; } |
| 11086 | isDirectory() { return this.__kind === "directory"; } |
| 11087 | isBlockDevice() { return false; } |
| 11088 | isCharacterDevice() { return false; } |
| 11089 | isSymbolicLink() { return false; } |
| 11090 | isFIFO() { return false; } |
| 11091 | isSocket() { return false; } |
| 11092 | } |
| 11093 | const __fsOptions = (options, names) => { |
| 11094 | if (options === undefined) return {}; |
| 11095 | if (options === null || typeof options !== "object") { |
| 11096 | const error = new TypeError('The "options" argument must be of type object'); |
| 11097 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11098 | throw error; |
| 11099 | } |
| 11100 | for (const name of names) { |
| 11101 | if (options[name] !== undefined && typeof options[name] !== "boolean") { |
| 11102 | const error = new TypeError(`The "options.${name}" property must be of type boolean`); |
| 11103 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11104 | throw error; |
| 11105 | } |
| 11106 | } |
| 11107 | return options; |
| 11108 | }; |
| 11109 | const __fsMkdirSync = (value, options = {}) => { |
| 11110 | const path = __fsPath(value); |
| 11111 | if (typeof options === "number") options = { mode: options }; |
| 11112 | options = __fsOptions(options, ["recursive"]); |
| 11113 | const result = __vfs_mkdir(path, options.recursive === true); |
| 11114 | if (result && !result.startsWith("/")) throw __fsError(result, "mkdir", path); |
| 11115 | return result || undefined; |
| 11116 | }; |
| 11117 | const __fsStatSync = (value, options, syscall = "stat") => { |
| 11118 | const path = __fsPath(value); |
| 11119 | options = __fsOptions(options, ["bigint", "throwIfNoEntry"]); |
| 11120 | const [kind, size] = __vfs_stat(path); |
| 11121 | if (!kind) { |
| 11122 | if (options.throwIfNoEntry === false) return undefined; |
| 11123 | throw __fsError("ENOENT", syscall, path); |
| 11124 | } |
| 11125 | return new __FsStats(__fsStatsBadge, kind, size, options.bigint === true); |
| 11126 | }; |
| 11127 | const __fsLstatSync = (value, options) => __fsStatSync(value, options, "lstat"); |
| 11128 | const __fsRealpathSync = (value) => { |
| 11129 | const path = __fsPath(value); |
| 11130 | if (!__vfs_stat(path)[0]) throw __fsError("ENOENT", "realpath", path); |
| 11131 | return path; |
| 11132 | }; |
| 11133 | const __fsExistsSync = (value) => { |
| 11134 | try { return __vfs_stat(__fsPath(value))[0] !== 0; } |
| 11135 | catch { return false; } |
| 11136 | }; |
| 11137 | // Node returns a Buffer unless an encoding is given, as a string or as |
| 11138 | // `options.encoding`. Only `utf8` is decoded here; any other encoding falls |
| 11139 | // through to Buffer's own decoder. |
| 11140 | const __fsReadFileSync = (value, options) => { |
| 11141 | const path = __fsPath(value); |
| 11142 | const encoding = typeof options === "string" ? options : options?.encoding; |
| 11143 | const bytes = __vfs_read_file(path); |
| 11144 | if (bytes === undefined) { |
| 11145 | // A directory read fails differently from a missing path, so the stat |
| 11146 | // decides which error the caller sees. |
| 11147 | if (__vfs_stat(path)[0]) throw __fsError("EISDIR", "read", path); |
| 11148 | throw __fsError("ENOENT", "open", path); |
| 11149 | } |
| 11150 | const buffer = Buffer.from(bytes); |
| 11151 | return encoding ? buffer.toString(encoding) : buffer; |
| 11152 | }; |
| 11153 | // `fs.constants`, with the four access modes from workerd's |
| 11154 | // `src/node/internal/internal_fs_constants.ts`. The table carries only the |
| 11155 | // modes `access` reads. Every other constant belongs to an operation the |
| 11156 | // virtual filesystem does not implement, and that operation already fails |
| 11157 | // loudly at the unimplemented-builtin stub, so publishing its constants would |
| 11158 | // only make a caller build a mode for a call it cannot make. |
| 11159 | const __fsConstants = Object.freeze({ F_OK: 0, X_OK: 1, W_OK: 2, R_OK: 4 }); |
| 11160 | // Node validates a mode before it reaches the filesystem, so a bad mode is an |
| 11161 | // argument error and never a filesystem error. The range is the union of the |
| 11162 | // four access modes, which is what workerd's `validateMode` allows. |
| 11163 | const __fsMode = (mode) => { |
| 11164 | if (mode === undefined) return __fsConstants.F_OK; |
| 11165 | if (typeof mode !== "number") { |
| 11166 | const error = new TypeError('The "mode" argument must be of type number'); |
| 11167 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11168 | throw error; |
| 11169 | } |
| 11170 | if (!Number.isInteger(mode) || mode < 0 || mode > 7) { |
| 11171 | const error = new RangeError( |
| 11172 | `The value of "mode" is out of range. It must be >= 0 && <= 7. Received ${mode}`, |
| 11173 | ); |
| 11174 | error.code = "ERR_OUT_OF_RANGE"; |
| 11175 | throw error; |
| 11176 | } |
| 11177 | return mode; |
| 11178 | }; |
| 11179 | // `access` reports what the virtual filesystem can do and not a POSIX |
| 11180 | // permission, so it follows workerd's `accessSyncImpl`: no file is executable, |
| 11181 | // therefore `X_OK` always fails, and an unwritable path fails exactly like a |
| 11182 | // missing one, so a caller cannot tell the two apart. Kind 2 is the writable |
| 11183 | // tree; see `op_vfs_stat`. |
| 11184 | const __fsAccessSync = (value, mode) => { |
| 11185 | const path = __fsPath(value); |
| 11186 | mode = __fsMode(mode); |
| 11187 | const [kind] = __vfs_stat(path); |
| 11188 | const denied = mode & __fsConstants.X_OK |
| 11189 | || !kind |
| 11190 | || (mode & __fsConstants.W_OK && kind !== 2); |
| 11191 | if (denied) throw __fsError("ENOENT", "access", path); |
| 11192 | }; |
| 11193 | // The callback forms run the same synchronous core as `fs.promises`. |
| 11194 | // Validation and the operation are separate arguments, not one function, |
| 11195 | // because they fail differently: an argument error throws, and only a |
| 11196 | // filesystem error reaches the callback. One combined body would route both to |
| 11197 | // the callback and hide a caller's bug behind an error it did not expect. |
| 11198 | // |
| 11199 | // `validate()` runs before the callback check, which is workerd's order: each |
| 11200 | // entry point in `internal_fs_callback.ts` validates its path and its options, |
| 11201 | // and only then calls `callWithSingleArgCallback`. Node checks the callback |
| 11202 | // first, so a call that has a bad path and no callback reports the path here |
| 11203 | // and reports the callback in Node. Both are `ERR_INVALID_ARG_TYPE`, and the |
| 11204 | // runtime follows workerd. |
| 11205 | const __fsDeliver = (validate, run, callback, deliver) => { |
| 11206 | validate(); |
| 11207 | if (typeof callback !== "function") { |
| 11208 | const error = new TypeError('The "cb" argument must be of type function'); |
| 11209 | error.code = "ERR_INVALID_ARG_TYPE"; |
| 11210 | throw error; |
| 11211 | } |
| 11212 | let result; |
| 11213 | try { |
| 11214 | result = run(); |
| 11215 | } catch (error) { |
| 11216 | // A callback delivered in this turn would let a caller observe the result |
| 11217 | // before its own call returned, which Node never does. |
| 11218 | queueMicrotask(() => callback(error)); |
| 11219 | return; |
| 11220 | } |
| 11221 | queueMicrotask(() => deliver(result)); |
| 11222 | }; |
| 11223 | // An operation with a result calls back with `(error, result)`, and one |
| 11224 | // without calls back with `(error)` alone. Workerd splits the two the same way |
| 11225 | // (`callWithSingleArgCallback` and `callWithErrorOnlyCallback`), because a |
| 11226 | // caller can read `arguments.length` and see the difference. |
| 11227 | const __fsCallback = (validate, run, callback) => |
| 11228 | __fsDeliver(validate, run, callback, (result) => callback(null, result)); |
| 11229 | const __fsErrorOnlyCallback = (validate, run, callback) => |
| 11230 | __fsDeliver(validate, run, callback, () => callback(null)); |
| 11231 | // Node accepts `(path, callback)` or `(path, options, callback)` everywhere. |
| 11232 | const __fsCallbackArgs = (options, callback) => |
| 11233 | typeof options === "function" ? [undefined, options] : [options, callback]; |
| 11234 | const __fsAccess = (value, mode, callback) => { |
| 11235 | [mode, callback] = __fsCallbackArgs(mode, callback); |
| 11236 | __fsErrorOnlyCallback( |
| 11237 | () => { __fsPath(value); __fsMode(mode); }, |
| 11238 | () => __fsAccessSync(value, mode), |
| 11239 | callback, |
| 11240 | ); |
| 11241 | }; |
| 11242 | const __fsStat = (value, options, callback) => { |
| 11243 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11244 | __fsCallback( |
| 11245 | () => { __fsPath(value); __fsOptions(options, ["bigint", "throwIfNoEntry"]); }, |
| 11246 | () => __fsStatSync(value, options), |
| 11247 | callback, |
| 11248 | ); |
| 11249 | }; |
| 11250 | const __fsLstat = (value, options, callback) => { |
| 11251 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11252 | __fsCallback( |
| 11253 | () => { __fsPath(value); __fsOptions(options, ["bigint", "throwIfNoEntry"]); }, |
| 11254 | () => __fsLstatSync(value, options), |
| 11255 | callback, |
| 11256 | ); |
| 11257 | }; |
| 11258 | const __fsRealpath = (value, options, callback) => { |
| 11259 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11260 | __fsCallback( |
| 11261 | () => __fsPath(value), |
| 11262 | () => __fsRealpathSync(value), |
| 11263 | callback, |
| 11264 | ); |
| 11265 | }; |
| 11266 | const __fsReadFile = (value, options, callback) => { |
| 11267 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11268 | __fsCallback( |
| 11269 | () => __fsPath(value), |
| 11270 | () => __fsReadFileSync(value, options), |
| 11271 | callback, |
| 11272 | ); |
| 11273 | }; |
| 11274 | const __fsMkdir = (value, options, callback) => { |
| 11275 | [options, callback] = __fsCallbackArgs(options, callback); |
| 11276 | __fsCallback( |
| 11277 | () => { |
| 11278 | __fsPath(value); |
| 11279 | // A number is the mode, which `mkdirSync` validates but does not apply. |
| 11280 | if (typeof options !== "number") __fsOptions(options, ["recursive"]); |
| 11281 | }, |
| 11282 | () => __fsMkdirSync(value, options), |
| 11283 | callback, |
| 11284 | ); |
| 11285 | }; |
| 11286 | const __fsPromisesSurface = { |
| 11287 | // The promise form validates inside the promise, so an argument error |
| 11288 | // rejects instead of throwing. Workerd makes the same split, because a |
| 11289 | // caller of a promise API has no synchronous frame to catch. |
| 11290 | async access(...args) { return __fsAccessSync(...args); }, |
| 11291 | async mkdir(...args) { return __fsMkdirSync(...args); }, |
| 11292 | async stat(...args) { return __fsStatSync(...args); }, |
| 11293 | async lstat(...args) { return __fsLstatSync(...args); }, |
| 11294 | async realpath(...args) { return __fsRealpathSync(...args); }, |
| 11295 | async readFile(...args) { return __fsReadFileSync(...args); }, |
| 11296 | }; |
| 11297 | // A namespace import gets a fixed export set when V8 links the module, so a |
| 11298 | // partial module must enumerate unsupported Node exports too. A get trap alone |
| 11299 | // keeps default and named imports loud but silently omits these names from a |
| 11300 | // namespace. Keep the unsupported names lazy: materializing every stub in |
| 11301 | // every isolate would charge Workers that use only the implemented subset. |
| 11302 | const __fsNamespaceProxy = (surface, path, names, enoentNames = []) => { |
| 11303 | const namespaceNames = new Set([...Reflect.ownKeys(surface), ...names]); |
| 11304 | const enoentNameSet = new Set(enoentNames); |
| 11305 | return new Proxy(surface, { |
| 11306 | get: (target, p) => { |
| 11307 | if (Reflect.has(target, p)) return Reflect.get(target, p); |
| 11308 | if (enoentNameSet.has(p)) return __enoent; |
| 11309 | if (typeof p !== "string") return undefined; |
| 11310 | return __nodeStubFor(path + "." + p); |
| 11311 | }, |
| 11312 | ownKeys: () => [...namespaceNames], |
| 11313 | // A lazy name has no descriptor on the target, so the synthetic one below |
| 11314 | // completes to `writable: false`. Without this trap an assignment would |
| 11315 | // reach OrdinarySet, read that descriptor off the proxy as the receiver, |
| 11316 | // and throw "Cannot redefine property". CommonJS dependencies patch a |
| 11317 | // builtin at module scope, so the throw takes the whole Worker down at |
| 11318 | // load. Write through to the surface instead, which also promotes the name |
| 11319 | // to a real own property and keeps the descriptor honest from then on. |
| 11320 | // Materializing a complete descriptor in the trap below would fix the |
| 11321 | // assignment too, but it would charge every Worker for all the stubs the |
| 11322 | // moment anything enumerates the namespace. |
| 11323 | set: (target, p, value) => Reflect.set(target, p, value), |
| 11324 | getOwnPropertyDescriptor: (target, p) => |
| 11325 | Reflect.getOwnPropertyDescriptor(target, p) ?? |
| 11326 | (namespaceNames.has(p) |
| 11327 | ? { configurable: true, enumerable: true } |
| 11328 | : undefined), |
| 11329 | }); |
| 11330 | }; |
| 11331 | const __fsPromises = __celld.__fsPromises = __fsNamespaceProxy( |
| 11332 | __fsPromisesSurface, |
| 11333 | "node:fs/promises", |
| 11334 | [ |
| 11335 | "appendFile", "chmod", "chown", "copyFile", "cp", "lchmod", "lchown", |
| 11336 | "link", "lutimes", "mkdtemp", "open", "opendir", "readdir", "readlink", |
| 11337 | "rename", "rm", "rmdir", "statfs", "symlink", "truncate", "unlink", |
| 11338 | "utimes", "watch", "writeFile", |
| 11339 | ], |
| 11340 | ); |
| 11341 | const __fsSurface = { |
| 11342 | Stats: __FsStats, |
| 11343 | constants: __fsConstants, |
| 11344 | promises: __fsPromises, |
| 11345 | accessSync: __fsAccessSync, |
| 11346 | access: __fsAccess, |
| 11347 | existsSync: __fsExistsSync, |
| 11348 | mkdirSync: __fsMkdirSync, |
| 11349 | statSync: __fsStatSync, |
| 11350 | lstatSync: __fsLstatSync, |
| 11351 | realpathSync: __fsRealpathSync, |
| 11352 | readFileSync: __fsReadFileSync, |
| 11353 | stat: __fsStat, |
| 11354 | lstat: __fsLstat, |
| 11355 | realpath: __fsRealpath, |
| 11356 | readFile: __fsReadFile, |
| 11357 | mkdir: __fsMkdir, |
| 11358 | }; |
| 11359 | const __fsNamespaceNames = [ |
| 11360 | "Dir", "Dirent", "ReadStream", "WriteStream", "_toUnixTimestamp", |
| 11361 | "appendFile", "appendFileSync", "chmod", "chmodSync", "chown", "chownSync", |
| 11362 | "close", "closeSync", "copyFile", "copyFileSync", "cp", "cpSync", |
| 11363 | "createReadStream", "createWriteStream", "exists", "fchmod", "fchmodSync", |
| 11364 | "fchown", "fchownSync", "fdatasync", "fdatasyncSync", "fstat", "fstatSync", |
| 11365 | "fsync", "fsyncSync", "ftruncate", "ftruncateSync", "futimes", "futimesSync", |
| 11366 | "lchmod", "lchmodSync", "lchown", "lchownSync", "link", "linkSync", |
| 11367 | "lutimes", "lutimesSync", "mkdtemp", "mkdtempSync", "open", "openSync", |
| 11368 | "opendir", "opendirSync", "read", "readSync", "readdir", "readdirSync", |
| 11369 | "readlink", "readlinkSync", "readv", "readvSync", "rename", "renameSync", |
| 11370 | "rm", "rmSync", "rmdir", "rmdirSync", "statfs", "statfsSync", "symlink", |
| 11371 | "symlinkSync", "truncate", "truncateSync", "unlink", "unlinkSync", |
| 11372 | "unwatchFile", "utimes", "utimesSync", "watch", "watchFile", "write", |
| 11373 | "writeFile", "writeFileSync", "writeSync", "writev", "writevSync", |
| 11374 | ]; |
| 11375 | // Writable file contents and every mutation remain explicit unsupported |
| 11376 | // surfaces until a failing application seam requires them. These two reads |
| 11377 | // use ENOENT so dependencies can take their no-filesystem fallback path. |
| 11378 | __celld.__fs = __fsNamespaceProxy( |
| 11379 | __fsSurface, |
| 11380 | "node:fs", |
| 11381 | __fsNamespaceNames, |
| 11382 | ["readdirSync", "readlinkSync"], |
| 11383 | ); |
| 11384 | const __bridgeResponseStream = (body, requestControllers) => { |
| 11385 | const streamId = __response_stream_create(); |
| 11386 | const pump = (async () => { |
| 11387 | const reader = body.getReader(); |
| 11388 | const consumerClosed = __response_stream_closed(streamId) |
| 11389 | .then((status) => status === "cancelled" |
| 11390 | ? { consumerClosed: true } |
| 11391 | : new Promise(() => {})); |
| 11392 | const cancelProducer = async () => { |
| 11393 | const reason = new Error("The client has disconnected"); |
| 11394 | for (const controller of requestControllers || []) { |
| 11395 | if (!controller.signal.aborted) controller.abort(reason); |
| 11396 | } |
| 11397 | try { |
| 11398 | await reader.cancel(reason); |
| 11399 | } catch {} |
| 11400 | await __response_stream_close(streamId, ""); |
| 11401 | }; |
| 11402 | try { |
| 11403 | for (;;) { |
| 11404 | const result = await Promise.race([ |
| 11405 | reader.read().then((read) => ({ read })), |
| 11406 | consumerClosed, |
| 11407 | ]); |
| 11408 | if (result.consumerClosed) { |
| 11409 | await cancelProducer(); |
| 11410 | return; |
| 11411 | } |
| 11412 | if (result.read.done) { |
| 11413 | await __response_stream_close(streamId, ""); |
| 11414 | return; |
| 11415 | } |
| 11416 | const bytes = __bodyBytes(result.read.value); |
| 11417 | for (let offset = 0; offset < bytes.byteLength; offset += 64 * 1024) { |
| 11418 | await __response_stream_write( |
| 11419 | streamId, |
| 11420 | bytes.subarray(offset, offset + 64 * 1024), |
| 11421 | ); |
| 11422 | } |
| 11423 | } |
| 11424 | } catch (error) { |
| 11425 | if (String(error).includes("response stream consumer canceled")) { |
| 11426 | await cancelProducer(); |
| 11427 | return; |
| 11428 | } |
| 11429 | await __response_stream_close(streamId, String(error)); |
| 11430 | } |
| 11431 | })(); |
| 11432 | __registerWaitUntil(pump); |
| 11433 | return streamId; |
| 11434 | }; |
| 11435 | __celld.__readResponse = (r) => { |
| 11436 | if (!(r instanceof Response)) { |
| 11437 | return { |
| 11438 | status: 200, |
| 11439 | bodyBytes: new TextEncoder().encode(String(r)), |
| 11440 | bodyStreamId: 0, |
| 11441 | headersJson: "[]", |
| 11442 | wsTargetJson: "null", |
| 11443 | workerSocketId: 0, |
| 11444 | }; |
| 11445 | } |
| 11446 | // Keep the network-error marker out of the HTTP response fields. If status |
| 11447 | // zero reaches Rust as an ordinary response, the outer server can report |
| 11448 | // only a generic invalid status instead of the Worker contract failure. |
| 11449 | if (r.type === "error" || r.status === 0) |
| 11450 | return { error: __ERROR_RESPONSE_MESSAGE }; |
| 11451 | let workerSocketId = 0; |
| 11452 | let wsTarget = r._wsTarget || (r.webSocket && r.webSocket._target) || null; |
| 11453 | if (r.status === 101 && r.webSocket && wsTarget === null) { |
| 11454 | const server = r.webSocket._peer; |
| 11455 | if (server && server._accepted) { |
| 11456 | workerSocketId = server._id; |
| 11457 | // Install the host queue before the pump asks for its first frame. The |
| 11458 | // target marker makes sends use that queue instead of remaining in the |
| 11459 | // pair's pre-upgrade buffer. |
| 11460 | __ws_prepare_worker_handoff(workerSocketId); |
| 11461 | server._target = { id: workerSocketId, scope: "" }; |
| 11462 | server._polled = true; |
| 11463 | __sockets.set(workerSocketId, server); |
| 11464 | server._startPump(); |
| 11465 | server._flushPending(); |
| 11466 | } |
| 11467 | } |
| 11468 | const bodyStreamId = r._bodyBytes === null |
| 11469 | ? typeof r.body?.__celldStreamId === "number" && |
| 11470 | !r.__celldRequestControllers |
| 11471 | ? r.body.__celldStreamId |
| 11472 | : __bridgeResponseStream( |
| 11473 | r.body, |
| 11474 | r.__celldRequestControllers, |
| 11475 | ) |
| 11476 | : 0; |
| 11477 | if (bodyStreamId) { |
| 11478 | return { |
| 11479 | status: r.status, |
| 11480 | bodyBytes: new Uint8Array(), |
| 11481 | bodyStreamId, |
| 11482 | headersJson: JSON.stringify(Array.from(r.headers)), |
| 11483 | wsTargetJson: JSON.stringify(wsTarget), |
| 11484 | workerSocketId, |
| 11485 | }; |
| 11486 | } |
| 11487 | const bytes = r._bodyBytes; |
| 11488 | return { |
| 11489 | status: r.status, |
| 11490 | bodyBytes: bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), |
| 11491 | bodyStreamId: 0, |
| 11492 | headersJson: JSON.stringify(Array.from(r.headers)), |
| 11493 | wsTargetJson: JSON.stringify(wsTarget), |
| 11494 | workerSocketId, |
| 11495 | }; |
| 11496 | }; |