Diffinery

homeflare/celldpublic

v0.2.0

celld v0.2.0 changes three foundations: how cells share memory, how
their state replicates, and how a fleet stays available when its
object store fails or slows.

Isolates and memory:

- Resident cells share isolates and run turn by turn on a shared
  pool. v0.1.0 held one OS thread and one isolate for each cell.
- A resident cell costs ~471 KB against ~3.4 MB in v0.1.0, measured
  linear to 2,500 resident cells (~1.2 GB) on one node. Memory no
  longer limits the resident population; admission and RSS shedding
  set the limit.
- A handler that awaits I/O releases its isolate between turns, so
  co-resident cells cannot stall each other.
- celld reclaims empty cell heaps and reuses retired isolate slots,
  so a long-lived node cannot leak isolates.
- jemalloc is the global allocator.

Two listeners:

- celld now separates the data plane from the control plane. The
  public listener (--listen) serves only your Worker's routes and
  /__celld/health. A new internal listener (--internal-listen)
  carries everything else: the operator API (/state, /shutdown) and
  all node-to-node peer traffic. Keep the internal port on a private
  network.
- A public listener on a non-loopback address requires an explicit
  internal listener. --advertise names the internal address, and
  celld diagnose probes peers at that address.

Replication and compaction:

- celld compacts many small level-0 replication objects into additive
  level-1 blocks (LTX v0.5.2 block format). Compaction is on by
  default and never deletes a source object.
- A takeover of a write-heavy cell reads tens of objects instead of
  thousands. In one measured case, a cell with 4,096 durable writes
  restored from 42 objects and 0.6 MB instead of 4,116 objects and
  19 MB, 3.8 times faster.
- A restore downloads the objects in its plan concurrently, under one
  ceiling for the whole node.
- A takeover pins the exact point in the replicated history that it
  restored from. celld never restores data that a fenced former owner
  uploads after that point, so a cell's history cannot fork and a
  failed write cannot reappear after a failover.
- Compaction runs off the request path with a bounded duty cycle. A
  node that restarts with a large uncompacted backlog drains it
  without blocking durable writes.
- celld and Litestream v0.5.16 can read both block and frame files.
  Litestream v0.5.11 can read only frame files.

Availability under storage faults:

- The time that remains on the last renewed lease bounds each lease
  renewal attempt, so one hung conditional write can no longer use
  the whole authority window. In a test that silently dropped all
  established storage connections for 20 seconds, a v0.1.0-class node
  fenced; a v0.2.0 node kept serving.
- The core event loop owns the lease timer on a dedicated thread.
  Restores, compaction, and diagnostics cannot delay it.
- celld logs each lease attempt at start and at completion, so a
  storage hang is distinguishable from a timer failure.

Shutdown and restart:

- SIGTERM starts a graceful drain. The drain hands each cell to a
  peer directly, so takeover does not wait for the lease TTL.
- POST /shutdown?handoff=preserve on the internal listener prepares a
  same-node restart. The replacement process resumes its local cell
  databases and performs no owner or replica reads.
- The drain waits for its ownership release writes and bounds each
  connection, so one idle connection cannot use the full deadline.
- The process exits without unwinding. This fixes a crash when a warm
  node stops.

Storage backends:

- A gs:// bucket selects Cloud Storage's generation-based
  compare-and-swap and authenticates with Application Default
  Credentials.
- A bucket can take a key prefix, so several independent fleets can
  share one bucket without collisions.

Workers surface:

- Wasm modules deploy and load as compiled WebAssembly.Module values.
  A workers-rs example shows the path, and older nodes refuse the new
  wasm-v1 deployment feature at deploy time.
- A new RPC example exercises entrypoints, callbacks, RpcTarget
  returns, and promise pipelining end to end. Cross-isolate stubs
  remain limited to single method calls on named entrypoints.
- Web Crypto and node:crypto expand: asymmetric import and export
  (SPKI, PKCS#8, JWK, PEM), generateKey, P-384 and P-521, Ed25519 and
  X25519, ECDH derivation, AES-CBC and AES-CTR, DigestStream,
  timingSafeEqual, and one-shot sign and verify.
- setWebSocketAutoResponse answers ping-style messages without waking
  the cell.

OpenTelemetry support (off by default):

- CELLD_OTEL=1 turns on OpenTelemetry traces and logs with no
  collector required: celld writes them directly to the bucket as
  Parquet under a telemetry/ prefix, and DuckDB can query them.
- A standard OTLP/HTTP collector is the alternative sink
  (CELLD_OTEL_SINK=otlp), and the usual OTEL_* variables apply.
- W3C trace context propagates end to end: celld adopts an inbound
  traceparent, and fetch spans, cell dispatch, and console logs join
  the caller's trace.

Overload:

- A stateless request that finds every slot held now waits, bounded
  by CELLD_ADMISSION_WAIT_MS, instead of an immediate refusal. At
  overload, the node no longer spends its capacity on refusals.
- CPU-based shedding is removed. RSS shedding (on by default since
  v0.1.0) is the only pressure trigger.

Configuration:

- celld validates every variable at startup, and an invalid value
  stops startup. Boolean variables accept only 0 or 1.
- Removed: CELLD_WORKERS, CELLD_MAX_COHOSTED, CELLD_MAX_CPU_PERCENT,
  CELLD_RESIDENT_LOW_WATER (ignored since v0.1.0), CELLD_VALIDATE,
  and the /js route.
- Renamed: CELLD_HIBERNATIONS is now CELLD_EVICTIONS.
- Changed: CELLD_IDLE_EVICT_S no longer defaults to 300; idle
  eviction is off unless set. CELLD_UNSAFE_PUBLIC_ADVERTISE takes 1,
  not on.
- Added, among others: CELLD_INTERNAL_ADDR, CELLD_MAX_STATELESS_ISOLATES,
  CELLD_ADMISSION_WAIT_MS, CELLD_LTX_COMPACTION, CELLD_SHUTDOWN_DRAIN_MS,
  and the CELLD_OTEL family.

Upgrading from v0.1.0:

- A v0.1.0 command line with a non-loopback --listen refuses to start
  until an explicit --internal-listen is added.
- The upgrade must not be a rolling update: stop every v0.1.0 node,
  then start the v0.2.0 nodes. v0.2.0 advertises the internal
  listener, which v0.1.0 peers cannot follow, and writes compacted
  block objects, which a v0.1.0 reader cannot restore. A fleet must
  not mix the two versions.

Co-authored-by: Nathan Whitaker <[email protected]>
Co-authored-by: Connor Hindley <[email protected]>
Co-authored-by: Yusuke Tanaka <[email protected]>
Co-authored-by: Heyang Zhou <[email protected]>
Co-authored-by: Daniel Lee <[email protected]>
Ryan Dahl authored signed1 parent 553ae73commit 3f22aedd1ea4d413b93e84afb1ce385f04be84f1Browse files
99 files changed+43772−33618
Files (99)
modified.github/workflows/release.yml+2−16View file
@@ -96,13 +96,12 @@
9696 printf '%s' "$GHCR_TOKEN" |
9797 docker login ghcr.io --username "$GITHUB_ACTOR" --password-stdin
9898
99- - name: Build the test stage
99+ - name: Build and test the image
100100 run: |
101101 set -euo pipefail
102102 version=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/celld/Cargo.toml | head -1)
103103 docker buildx build \
104104 --platform linux/amd64 \
105- --target test \
106105 --build-arg "CELLD_COMMIT=$GITHUB_SHA" \
107106 --build-arg "CELLD_VERSION=$version" \
108107 --cache-from "type=registry,ref=$IMAGE:buildcache-amd64" \
@@ -230,22 +229,9 @@
230229 printf '%s' "$GHCR_TOKEN" |
231230 docker login ghcr.io --username "$GITHUB_ACTOR" --password-stdin
232231
233- - name: Test architecture image
232+ - name: Test, build, and push architecture image
234233 run: |
235234 set -euo pipefail
236- cache="$IMAGE:buildcache-${{ matrix.suffix }}"
237- docker buildx build \
238- --platform "${{ matrix.platform }}" \
239- --target test \
240- --build-arg "CELLD_COMMIT=$TAG_SHA" \
241- --build-arg "CELLD_VERSION=$CELLD_VERSION" \
242- --cache-from "type=registry,ref=$cache" \
243- --cache-to "type=registry,ref=$cache,mode=max" \
244- .
245-
246- - name: Build and push architecture image
247- run: |
248- set -euo pipefail
249235 tag="$IMAGE:$TAG_SHA-${{ matrix.suffix }}"
250236 cache="$IMAGE:buildcache-${{ matrix.suffix }}"
251237 docker buildx build \
modifiedCargo.lock+441−46View file
@@ -50,6 +50,8 @@
5050 checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
5151 dependencies = [
5252 "cfg-if",
53+ "const-random",
54+ "getrandom 0.3.4",
5355 "once_cell",
5456 "version_check",
5557 "zerocopy",
@@ -57,18 +59,18 @@
5759
5860 [[package]]
5961 name = "aho-corasick"
60-version = "1.1.4"
62+version = "1.1.5"
6163 source = "registry+https://github.com/rust-lang/crates.io-index"
62-checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
64+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
6365 dependencies = [
6466 "memchr",
6567 ]
6668
6769 [[package]]
6870 name = "android_system_properties"
69-version = "0.1.5"
71+version = "0.1.6"
7072 source = "registry+https://github.com/rust-lang/crates.io-index"
71-checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
73+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
7274 dependencies = [
7375 "libc",
7476 ]
@@ -233,6 +235,15 @@
233235 ]
234236
235237 [[package]]
238+name = "block-padding"
239+version = "0.3.3"
240+source = "registry+https://github.com/rust-lang/crates.io-index"
241+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
242+dependencies = [
243+ "generic-array",
244+]
245+
246+[[package]]
236247 name = "bumpalo"
237248 version = "3.20.3"
238249 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -255,31 +266,46 @@
255266 ]
256267
257268 [[package]]
269+name = "cbc"
270+version = "0.1.2"
271+source = "registry+https://github.com/rust-lang/crates.io-index"
272+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
273+dependencies = [
274+ "cipher",
275+]
276+
277+[[package]]
258278 name = "cc"
259-version = "1.4.0"
279+version = "1.4.1"
260280 source = "registry+https://github.com/rust-lang/crates.io-index"
261-checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
281+checksum = "9066c49992464636f92905fa096ec58baaa4d57ec19a5c096c68d3e25ef3d136"
262282 dependencies = [
263283 "find-msvc-tools",
284+ "jobserver",
285+ "libc",
264286 "shlex 2.0.1",
265287 ]
266288
267289 [[package]]
268290 name = "celld"
269-version = "0.1.0"
291+version = "0.2.0"
270292 dependencies = [
293+ "aes",
271294 "aes-gcm",
272295 "anyhow",
273296 "axum",
274297 "base64 0.22.1",
275298 "bytes",
299+ "cbc",
276300 "celld-logic",
277301 "celld-ltx",
302+ "crc",
303+ "ctr",
304+ "dsa",
278305 "ed25519-dalek",
279306 "encoding_rs",
280307 "fastwebsockets",
281308 "flate2",
282- "fs2",
283309 "futures-util",
284310 "getrandom 0.3.4",
285311 "hmac",
@@ -290,7 +316,11 @@
290316 "md-5",
291317 "object_store",
292318 "p256",
319+ "p384",
320+ "p521",
321+ "parquet",
293322 "percent-encoding",
323+ "pkcs8",
294324 "rand 0.8.7",
295325 "regex",
296326 "reqwest",
@@ -301,16 +331,21 @@
301331 "serde_json",
302332 "sha1",
303333 "sha2",
334+ "subtle",
335+ "tempfile",
336+ "tikv-jemallocator",
304337 "tokio",
305338 "tokio-rustls",
306339 "tokio-stream",
307340 "tokio-util",
308341 "tracing",
342+ "tracing-appender",
309343 "tracing-subscriber",
310344 "url",
311345 "urlpattern",
312346 "v8",
313347 "webpki-roots",
348+ "x25519-dalek",
314349 ]
315350
316351 [[package]]
@@ -323,15 +358,13 @@
323358 dependencies = [
324359 "async-trait",
325360 "bytes",
361+ "chrono",
326362 "futures-util",
327363 "hex",
328364 "lz4_flex",
329365 "object_store",
330366 "proptest",
331- "reqwest",
332367 "rusqlite",
333- "serde",
334- "serde_json",
335368 "tempfile",
336369 "thiserror 2.0.19",
337370 "tokio",
@@ -410,6 +443,26 @@
410443 checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
411444
412445 [[package]]
446+name = "const-random"
447+version = "0.1.18"
448+source = "registry+https://github.com/rust-lang/crates.io-index"
449+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
450+dependencies = [
451+ "const-random-macro",
452+]
453+
454+[[package]]
455+name = "const-random-macro"
456+version = "0.1.16"
457+source = "registry+https://github.com/rust-lang/crates.io-index"
458+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
459+dependencies = [
460+ "getrandom 0.2.17",
461+ "once_cell",
462+ "tiny-keccak",
463+]
464+
465+[[package]]
413466 name = "core-foundation"
414467 version = "0.10.1"
415468 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -453,6 +506,21 @@
453506 ]
454507
455508 [[package]]
509+name = "crc"
510+version = "3.4.0"
511+source = "registry+https://github.com/rust-lang/crates.io-index"
512+checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
513+dependencies = [
514+ "crc-catalog",
515+]
516+
517+[[package]]
518+name = "crc-catalog"
519+version = "2.5.0"
520+source = "registry+https://github.com/rust-lang/crates.io-index"
521+checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
522+
523+[[package]]
456524 name = "crc32fast"
457525 version = "1.5.0"
458526 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -462,6 +530,27 @@
462530 ]
463531
464532 [[package]]
533+name = "crossbeam-channel"
534+version = "0.5.16"
535+source = "registry+https://github.com/rust-lang/crates.io-index"
536+checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
537+dependencies = [
538+ "crossbeam-utils",
539+]
540+
541+[[package]]
542+name = "crossbeam-utils"
543+version = "0.8.22"
544+source = "registry+https://github.com/rust-lang/crates.io-index"
545+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
546+
547+[[package]]
548+name = "crunchy"
549+version = "0.2.4"
550+source = "registry+https://github.com/rust-lang/crates.io-index"
551+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
552+
553+[[package]]
465554 name = "crypto-bigint"
466555 version = "0.5.5"
467556 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -532,6 +621,12 @@
532621 ]
533622
534623 [[package]]
624+name = "deranged"
625+version = "0.5.8"
626+source = "registry+https://github.com/rust-lang/crates.io-index"
627+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
628+
629+[[package]]
535630 name = "digest"
536631 version = "0.10.7"
537632 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -545,34 +640,34 @@
545640
546641 [[package]]
547642 name = "diplomat"
548-version = "0.15.0"
643+version = "0.16.0"
549644 source = "registry+https://github.com/rust-lang/crates.io-index"
550-checksum = "7935649d00000f5c5d735448ad3dc07b9738160727017914cf42138b8e8e6611"
645+checksum = "26fdfa02eb9a2e1ff82a375524be1ce9fd50ae63787f5737da6951b25d21e857"
551646 dependencies = [
552647 "diplomat_core",
553648 "proc-macro2",
554649 "quote",
555- "syn 2.0.119",
650+ "syn 3.0.3",
556651 ]
557652
558653 [[package]]
559654 name = "diplomat-runtime"
560-version = "0.15.1"
655+version = "0.16.0"
561656 source = "registry+https://github.com/rust-lang/crates.io-index"
562-checksum = "970ac38ad677632efcee6d517e783958da9bc78ec206d8d5e35b459ffc5e4864"
657+checksum = "ae517853d9f82b2d144393b1c32c34c46c2e361de2b6c44a8fdfce23beb211cd"
563658
564659 [[package]]
565660 name = "diplomat_core"
566-version = "0.15.0"
661+version = "0.16.0"
567662 source = "registry+https://github.com/rust-lang/crates.io-index"
568-checksum = "9cf41b94101a4bce993febaf0098092b0bb31deaf0ecaf6e0a2562465f61b383"
663+checksum = "f4ede23809e2fcc555d8b2e10ffa7a1c31331ebca8e5477f4f2b48ab8a0a9a6b"
569664 dependencies = [
570665 "proc-macro2",
571666 "quote",
572667 "serde",
573668 "smallvec",
574669 "strck",
575- "syn 2.0.119",
670+ "syn 3.0.3",
576671 ]
577672
578673 [[package]]
@@ -587,6 +682,22 @@
587682 ]
588683
589684 [[package]]
685+name = "dsa"
686+version = "0.6.3"
687+source = "registry+https://github.com/rust-lang/crates.io-index"
688+checksum = "48bc224a9084ad760195584ce5abb3c2c34a225fa312a128ad245a6b412b7689"
689+dependencies = [
690+ "digest",
691+ "num-bigint-dig",
692+ "num-traits",
693+ "pkcs8",
694+ "rfc6979",
695+ "sha2",
696+ "signature",
697+ "zeroize",
698+]
699+
700+[[package]]
590701 name = "ecdsa"
591702 version = "0.16.9"
592703 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -642,6 +753,7 @@
642753 "ff",
643754 "generic-array",
644755 "group",
756+ "hkdf",
645757 "pem-rfc7468",
646758 "pkcs8",
647759 "rand_core 0.6.4",
@@ -733,9 +845,9 @@
733845
734846 [[package]]
735847 name = "find-msvc-tools"
736-version = "0.1.9"
848+version = "0.1.10"
737849 source = "registry+https://github.com/rust-lang/crates.io-index"
738-checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
850+checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de"
739851
740852 [[package]]
741853 name = "flate2"
@@ -763,16 +875,6 @@
763875 ]
764876
765877 [[package]]
766-name = "fs2"
767-version = "0.4.3"
768-source = "registry+https://github.com/rust-lang/crates.io-index"
769-checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
770-dependencies = [
771- "libc",
772- "winapi",
773-]
774-
775-[[package]]
776878 name = "fslock"
777879 version = "0.2.1"
778880 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -976,6 +1078,18 @@
9761078 ]
9771079
9781080 [[package]]
1081+name = "half"
1082+version = "2.7.1"
1083+source = "registry+https://github.com/rust-lang/crates.io-index"
1084+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
1085+dependencies = [
1086+ "cfg-if",
1087+ "crunchy",
1088+ "num-traits",
1089+ "zerocopy",
1090+]
1091+
1092+[[package]]
9791093 name = "hashbrown"
9801094 version = "0.14.5"
9811095 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1012,6 +1126,15 @@
10121126 checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
10131127
10141128 [[package]]
1129+name = "hkdf"
1130+version = "0.12.4"
1131+source = "registry+https://github.com/rust-lang/crates.io-index"
1132+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
1133+dependencies = [
1134+ "hmac",
1135+]
1136+
1137+[[package]]
10151138 name = "hmac"
10161139 version = "0.12.1"
10171140 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1331,6 +1454,7 @@
13311454 source = "registry+https://github.com/rust-lang/crates.io-index"
13321455 checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
13331456 dependencies = [
1457+ "block-padding",
13341458 "generic-array",
13351459 ]
13361460
@@ -1362,6 +1486,16 @@
13621486 checksum = "2ceaf4c6c48465bead8cb6a0b7c4ee0c86ecbb31239032b9c66ab9a08d2f3ee1"
13631487
13641488 [[package]]
1489+name = "jobserver"
1490+version = "0.1.35"
1491+source = "registry+https://github.com/rust-lang/crates.io-index"
1492+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
1493+dependencies = [
1494+ "getrandom 0.4.3",
1495+ "libc",
1496+]
1497+
1498+[[package]]
13651499 name = "js-sys"
13661500 version = "0.3.103"
13671501 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1563,6 +1697,16 @@
15631697 ]
15641698
15651699 [[package]]
1700+name = "num-bigint"
1701+version = "0.5.1"
1702+source = "registry+https://github.com/rust-lang/crates.io-index"
1703+checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0"
1704+dependencies = [
1705+ "num-integer",
1706+ "num-traits",
1707+]
1708+
1709+[[package]]
15661710 name = "num-bigint-dig"
15671711 version = "0.8.6"
15681712 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1579,6 +1723,12 @@
15791723 ]
15801724
15811725 [[package]]
1726+name = "num-conv"
1727+version = "0.2.2"
1728+source = "registry+https://github.com/rust-lang/crates.io-index"
1729+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
1730+
1731+[[package]]
15821732 name = "num-integer"
15831733 version = "0.1.46"
15841734 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1670,6 +1820,32 @@
16701820 ]
16711821
16721822 [[package]]
1823+name = "p384"
1824+version = "0.13.1"
1825+source = "registry+https://github.com/rust-lang/crates.io-index"
1826+checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"
1827+dependencies = [
1828+ "ecdsa",
1829+ "elliptic-curve",
1830+ "primeorder",
1831+ "sha2",
1832+]
1833+
1834+[[package]]
1835+name = "p521"
1836+version = "0.13.3"
1837+source = "registry+https://github.com/rust-lang/crates.io-index"
1838+checksum = "0fc9e2161f1f215afdfce23677034ae137bbd45016a880c2eb3ba8eb95f085b2"
1839+dependencies = [
1840+ "base16ct",
1841+ "ecdsa",
1842+ "elliptic-curve",
1843+ "primeorder",
1844+ "rand_core 0.6.4",
1845+ "sha2",
1846+]
1847+
1848+[[package]]
16731849 name = "parking_lot"
16741850 version = "0.12.5"
16751851 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1693,12 +1869,41 @@
16931869 ]
16941870
16951871 [[package]]
1872+name = "parquet"
1873+version = "59.2.0"
1874+source = "registry+https://github.com/rust-lang/crates.io-index"
1875+checksum = "7065842956a20c2a536924ce8e4d9955f7422451511b9eb7500d7bfe5077e59c"
1876+dependencies = [
1877+ "ahash",
1878+ "bytes",
1879+ "chrono",
1880+ "half",
1881+ "hashbrown 0.17.1",
1882+ "num-bigint",
1883+ "num-integer",
1884+ "num-traits",
1885+ "seq-macro",
1886+ "twox-hash",
1887+ "zstd",
1888+]
1889+
1890+[[package]]
16961891 name = "paste"
16971892 version = "1.0.15"
16981893 source = "registry+https://github.com/rust-lang/crates.io-index"
16991894 checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
17001895
17011896 [[package]]
1897+name = "pbkdf2"
1898+version = "0.12.2"
1899+source = "registry+https://github.com/rust-lang/crates.io-index"
1900+checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
1901+dependencies = [
1902+ "digest",
1903+ "hmac",
1904+]
1905+
1906+[[package]]
17021907 name = "pem-rfc7468"
17031908 version = "0.7.0"
17041909 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1751,12 +1956,29 @@
17511956 ]
17521957
17531958 [[package]]
1959+name = "pkcs5"
1960+version = "0.7.1"
1961+source = "registry+https://github.com/rust-lang/crates.io-index"
1962+checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6"
1963+dependencies = [
1964+ "aes",
1965+ "cbc",
1966+ "der",
1967+ "pbkdf2",
1968+ "scrypt",
1969+ "sha2",
1970+ "spki",
1971+]
1972+
1973+[[package]]
17541974 name = "pkcs8"
17551975 version = "0.10.2"
17561976 source = "registry+https://github.com/rust-lang/crates.io-index"
17571977 checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
17581978 dependencies = [
17591979 "der",
1980+ "pkcs5",
1981+ "rand_core 0.6.4",
17601982 "spki",
17611983 ]
17621984
@@ -1790,6 +2012,12 @@
17902012 ]
17912013
17922014 [[package]]
2015+name = "powerfmt"
2016+version = "0.2.0"
2017+source = "registry+https://github.com/rust-lang/crates.io-index"
2018+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
2019+
2020+[[package]]
17932021 name = "ppv-lite86"
17942022 version = "0.2.21"
17952023 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2055,9 +2283,9 @@
20552283
20562284 [[package]]
20572285 name = "regex-automata"
2058-version = "0.4.16"
2286+version = "0.4.18"
20592287 source = "registry+https://github.com/rust-lang/crates.io-index"
2060-checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
2288+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
20612289 dependencies = [
20622290 "aho-corasick",
20632291 "memchr",
@@ -2207,7 +2435,7 @@
22072435 "errno",
22082436 "libc",
22092437 "linux-raw-sys 0.4.15",
2210- "windows-sys 0.52.0",
2438+ "windows-sys 0.59.0",
22112439 ]
22122440
22132441 [[package]]
@@ -2304,6 +2532,15 @@
23042532 checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
23052533
23062534 [[package]]
2535+name = "salsa20"
2536+version = "0.10.2"
2537+source = "registry+https://github.com/rust-lang/crates.io-index"
2538+checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
2539+dependencies = [
2540+ "cipher",
2541+]
2542+
2543+[[package]]
23072544 name = "same-file"
23082545 version = "1.0.6"
23092546 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2328,6 +2565,17 @@
23282565 checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
23292566
23302567 [[package]]
2568+name = "scrypt"
2569+version = "0.11.0"
2570+source = "registry+https://github.com/rust-lang/crates.io-index"
2571+checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f"
2572+dependencies = [
2573+ "pbkdf2",
2574+ "salsa20",
2575+ "sha2",
2576+]
2577+
2578+[[package]]
23312579 name = "sec1"
23322580 version = "0.7.3"
23332581 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2371,6 +2619,12 @@
23712619 checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
23722620
23732621 [[package]]
2622+name = "seq-macro"
2623+version = "0.3.6"
2624+source = "registry+https://github.com/rust-lang/crates.io-index"
2625+checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
2626+
2627+[[package]]
23742628 name = "serde"
23752629 version = "1.0.229"
23762630 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2586,6 +2840,12 @@
25862840 checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
25872841
25882842 [[package]]
2843+name = "symlink"
2844+version = "0.1.0"
2845+source = "registry+https://github.com/rust-lang/crates.io-index"
2846+checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"
2847+
2848+[[package]]
25892849 name = "syn"
25902850 version = "2.0.119"
25912851 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2642,9 +2902,9 @@
26422902
26432903 [[package]]
26442904 name = "temporal_capi"
2645-version = "0.2.4"
2905+version = "0.2.6"
26462906 source = "registry+https://github.com/rust-lang/crates.io-index"
2647-checksum = "c534c1ac4165fb410b5ccd12c79040573622865e881bb8caad70981806a141f1"
2907+checksum = "f48eb9ca4ca22caaa48d1e7a534ad3fd598a23d1a71945e8ad5ac0be501fa5f2"
26482908 dependencies = [
26492909 "diplomat",
26502910 "diplomat-runtime",
@@ -2659,9 +2919,9 @@
26592919
26602920 [[package]]
26612921 name = "temporal_rs"
2662-version = "0.2.4"
2922+version = "0.2.6"
26632923 source = "registry+https://github.com/rust-lang/crates.io-index"
2664-checksum = "b1afc06e45b0d63943c777d0233523fa2e23a12431a73c37b1c0366777b31717"
2924+checksum = "1a978fef907a27736827d336c0bfaab14fb8a7509dd6dc2b43c44e51d59aca5b"
26652925 dependencies = [
26662926 "calendrical_calculations",
26672927 "core_maths",
@@ -2724,10 +2984,60 @@
27242984 ]
27252985
27262986 [[package]]
2987+name = "tikv-jemalloc-sys"
2988+version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7"
2989+source = "registry+https://github.com/rust-lang/crates.io-index"
2990+checksum = "cd8aa5b2ab86a2cefa406d889139c162cbb230092f7d1d7cbc1716405d852a3b"
2991+dependencies = [
2992+ "cc",
2993+ "libc",
2994+]
2995+
2996+[[package]]
2997+name = "tikv-jemallocator"
2998+version = "0.6.1"
2999+source = "registry+https://github.com/rust-lang/crates.io-index"
3000+checksum = "0359b4327f954e0567e69fb191cf1436617748813819c94b8cd4a431422d053a"
3001+dependencies = [
3002+ "libc",
3003+ "tikv-jemalloc-sys",
3004+]
3005+
3006+[[package]]
3007+name = "time"
3008+version = "0.3.55"
3009+source = "registry+https://github.com/rust-lang/crates.io-index"
3010+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
3011+dependencies = [
3012+ "deranged",
3013+ "num-conv",
3014+ "powerfmt",
3015+ "serde_core",
3016+ "time-core",
3017+ "time-macros",
3018+]
3019+
3020+[[package]]
3021+name = "time-core"
3022+version = "0.1.9"
3023+source = "registry+https://github.com/rust-lang/crates.io-index"
3024+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
3025+
3026+[[package]]
3027+name = "time-macros"
3028+version = "0.2.32"
3029+source = "registry+https://github.com/rust-lang/crates.io-index"
3030+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
3031+dependencies = [
3032+ "num-conv",
3033+ "time-core",
3034+]
3035+
3036+[[package]]
27273037 name = "timezone_provider"
2728-version = "0.2.4"
3038+version = "0.2.6"
27293039 source = "registry+https://github.com/rust-lang/crates.io-index"
2730-checksum = "48738555f588bc05b58cb55206843cde9875bb1fde50101dd1a7c50ac6535cd5"
3040+checksum = "89ec4f4eebb4817fde02a411aedc7ac5f66c89c68c49e5d4b17a8139f077af52"
27313041 dependencies = [
27323042 "tinystr",
27333043 "zerotrie",
@@ -2736,6 +3046,15 @@
27363046 ]
27373047
27383048 [[package]]
3049+name = "tiny-keccak"
3050+version = "2.0.2"
3051+source = "registry+https://github.com/rust-lang/crates.io-index"
3052+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
3053+dependencies = [
3054+ "crunchy",
3055+]
3056+
3057+[[package]]
27393058 name = "tinystr"
27403059 version = "0.8.3"
27413060 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2884,6 +3203,19 @@
28843203 ]
28853204
28863205 [[package]]
3206+name = "tracing-appender"
3207+version = "0.2.5"
3208+source = "registry+https://github.com/rust-lang/crates.io-index"
3209+checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c"
3210+dependencies = [
3211+ "crossbeam-channel",
3212+ "symlink",
3213+ "thiserror 2.0.19",
3214+ "time",
3215+ "tracing-subscriber",
3216+]
3217+
3218+[[package]]
28873219 name = "tracing-attributes"
28883220 version = "0.1.31"
28893221 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3017,9 +3349,9 @@
30173349
30183350 [[package]]
30193351 name = "v8"
3020-version = "152.0.0"
3352+version = "152.1.0"
30213353 source = "registry+https://github.com/rust-lang/crates.io-index"
3022-checksum = "91c89be3a18777511705994775d413eb7595c1efcf51ded4b19bbbf6aec7a66c"
3354+checksum = "eb60870e5cff45e02719ab782f1c67507d33c4ef184755656bcc11a9795ccf83"
30233355 dependencies = [
30243356 "bindgen",
30253357 "bitflags",
@@ -3303,6 +3635,15 @@
33033635
33043636 [[package]]
33053637 name = "windows-sys"
3638+version = "0.59.0"
3639+source = "registry+https://github.com/rust-lang/crates.io-index"
3640+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
3641+dependencies = [
3642+ "windows-targets",
3643+]
3644+
3645+[[package]]
3646+name = "windows-sys"
33063647 version = "0.61.2"
33073648 source = "registry+https://github.com/rust-lang/crates.io-index"
33083649 checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
@@ -3393,6 +3734,18 @@
33933734 checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
33943735
33953736 [[package]]
3737+name = "x25519-dalek"
3738+version = "2.0.1"
3739+source = "registry+https://github.com/rust-lang/crates.io-index"
3740+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
3741+dependencies = [
3742+ "curve25519-dalek",
3743+ "rand_core 0.6.4",
3744+ "serde",
3745+ "zeroize",
3746+]
3747+
3748+[[package]]
33963749 name = "yoke"
33973750 version = "0.8.3"
33983751 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3417,18 +3770,18 @@
34173770
34183771 [[package]]
34193772 name = "zerocopy"
3420-version = "0.8.55"
3773+version = "0.8.56"
34213774 source = "registry+https://github.com/rust-lang/crates.io-index"
3422-checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
3775+checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
34233776 dependencies = [
34243777 "zerocopy-derive",
34253778 ]
34263779
34273780 [[package]]
34283781 name = "zerocopy-derive"
3429-version = "0.8.55"
3782+version = "0.8.56"
34303783 source = "registry+https://github.com/rust-lang/crates.io-index"
3431-checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
3784+checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
34323785 dependencies = [
34333786 "proc-macro2",
34343787 "quote",
@@ -3461,8 +3814,22 @@
34613814 version = "1.9.0"
34623815 source = "registry+https://github.com/rust-lang/crates.io-index"
34633816 checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
3817+dependencies = [
3818+ "zeroize_derive",
3819+]
34643820
34653821 [[package]]
3822+name = "zeroize_derive"
3823+version = "1.5.0"
3824+source = "registry+https://github.com/rust-lang/crates.io-index"
3825+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
3826+dependencies = [
3827+ "proc-macro2",
3828+ "quote",
3829+ "syn 2.0.119",
3830+]
3831+
3832+[[package]]
34663833 name = "zerotrie"
34673834 version = "0.2.4"
34683835 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3515,3 +3882,31 @@
35153882 "resb",
35163883 "serde",
35173884 ]
3885+
3886+[[package]]
3887+name = "zstd"
3888+version = "0.13.3"
3889+source = "registry+https://github.com/rust-lang/crates.io-index"
3890+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
3891+dependencies = [
3892+ "zstd-safe",
3893+]
3894+
3895+[[package]]
3896+name = "zstd-safe"
3897+version = "7.2.4"
3898+source = "registry+https://github.com/rust-lang/crates.io-index"
3899+checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
3900+dependencies = [
3901+ "zstd-sys",
3902+]
3903+
3904+[[package]]
3905+name = "zstd-sys"
3906+version = "2.0.16+zstd.1.5.7"
3907+source = "registry+https://github.com/rust-lang/crates.io-index"
3908+checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
3909+dependencies = [
3910+ "cc",
3911+ "pkg-config",
3912+]
modifiedCargo.toml+39−3View file
@@ -21,11 +21,18 @@
2121 lto = "thin"
2222 codegen-units = 16
2323 incremental = true
24+[profile.dev.package.sha2]
25+opt-level = 3
26+[profile.dev.package.rsa]
27+opt-level = 3
2428
2529 # Every direct dependency lives here so the crates can never drift onto two
2630 # versions of the same crate; members add their own features.
2731 [workspace.dependencies]
32+aes = "0.8"
2833 aes-gcm = "0.10"
34+cbc = { version = "0.1", features = ["alloc"] }
35+ctr = "0.9"
2936 anyhow = "1"
3037 async-trait = "0.1"
3138 axum = { version = "0.7", features = ["multipart"] }
@@ -33,11 +40,11 @@
3340 bytes = "1"
3441 celld-logic = { path = "crates/logic" }
3542 celld-ltx = { path = "crates/ltx" }
43+chrono = { version = "0.4", default-features = false, features = ["std"] }
3644 ed25519-dalek = { version = "2", features = ["pkcs8"] }
3745 encoding_rs = "0.8"
3846 fastwebsockets = { version = "0.8", default-features = false, features = ["upgrade", "with_axum"] }
3947 flate2 = "1"
40-fs2 = "0.4"
4148 futures-util = "0.3"
4249 getrandom = "0.3"
4350 hex = "0.4"
@@ -49,7 +56,30 @@
4956 lz4_flex = { version = "0.11", features = ["frame"] }
5057 md-5 = "0.10"
5158 object_store = { version = "0.11", default-features = false }
52-p256 = { version = "0.13", features = ["ecdsa", "pkcs8"] }
59+# The native column-writer API only: no `arrow` feature, so the arrow
60+# crate stack stays out of the binary. Revisit only if the telemetry
61+# schema ever grows nested columns (wiki/designs/otel.md).
62+parquet = { version = "59.2.0", default-features = false, features = ["zstd"] }
63+p256 = { version = "0.13", features = ["ecdh", "ecdsa", "pkcs8"] }
64+# The other NIST curves the Workers key surface accepts. Parsing and JWK
65+# only -- signing stays on P-256, so neither needs `ecdsa`. Versions follow
66+# deno's workspace.
67+p384 = { version = "0.13", features = ["ecdh", "pkcs8"] }
68+p521 = { version = "0.13", features = ["ecdh", "pkcs8"] }
69+# Encrypted PKCS#8, for private keys that arrive password-protected. `rsa`
70+# already pulls pkcs8 in; naming it here adds the pkcs5 cipher suite on top.
71+# Feature set follows deno's ext/node_crypto.
72+pkcs8 = { version = "0.10", features = ["std", "pkcs5", "encryption"] }
73+# X25519 key parsing and generation. `static_secrets` gives the owned
74+# StaticSecret that a stored key needs; the ephemeral default cannot be
75+# serialized. Version and feature follow deno's ext/node_crypto.
76+x25519-dalek = { version = "2", features = ["static_secrets"] }
77+# DSA, for reading legacy keys. Signing with DSA is not offered; the suite
78+# only parses these. Version follows deno's ext/node_crypto.
79+dsa = "0.6"
80+# CRC32/CRC32C/CRC64-NVME for DigestStream. Cloudflare accepts these
81+# alongside the real digests because S3 and the AWS SDKs checksum with them.
82+crc = "3"
5383 percent-encoding = "2"
5484 proptest = "1"
5585 rand = "0.8"
@@ -62,15 +92,21 @@
6292 serde_json = "1"
6393 sha1 = "0.10"
6494 sha2 = "0.10"
95+subtle = "2"
6596 tempfile = "3"
6697 thiserror = "2"
98+tikv-jemallocator = "0.6"
6799 tokio = "1"
68100 tokio-rustls = { version = "0.26", default-features = false, features = ["ring"] }
69101 tokio-stream = "0.1"
70102 tokio-util = { version = "0.7", features = ["io", "time"] }
71103 tracing = "0.1"
104+tracing-appender = "0.2"
72105 tracing-subscriber = { version = "0.3", features = ["env-filter"] }
73106 url = "2"
74107 urlpattern = "=0.4.2"
75-v8 = "152"
108+# D1 (wiki/designs/isolate-threading.md) needs v8::Locker and Send Globals:
109+# denoland/rusty_v8#2044 and #2045. Both ship in 152.1.0, so this is an
110+# ordinary dependency again — no path override, and no hand-built archive.
111+v8 = "152.1"
76112 webpki-roots = "1"
modifiedDockerfile+9−6View file
@@ -18,17 +18,20 @@
1818 cargo build --profile "${CELLD_PROFILE}" --locked -p celld && \
1919 install -m 755 "target/${CELLD_PROFILE}/celld" /out/celld
2020
21-# The release workflow builds this stage on every candidate push, so a
22-# break in the engine's own tests or lints stops a release before any
23-# artifact is drafted.
21+# The final image depends on this stage, so a break in the engine's tests or
22+# lints stops the build.
2423 FROM build AS test
2524 ARG TARGETARCH
2625 RUN rustup component add clippy
26+# The ltx fault-injection oracle diffs databases with the sqlite3 CLI.
27+RUN apt-get update && \
28+ apt-get install -y --no-install-recommends sqlite3 && \
29+ rm -rf /var/lib/apt/lists/*
2730 RUN --mount=type=cache,id=celld-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
2831 --mount=type=cache,id=celld-cargo-git,target=/usr/local/cargo/git,sharing=locked \
2932 --mount=type=cache,id=celld-target-${TARGETARCH},target=/src/target,sharing=locked \
30- cargo test --release --locked && \
31- cargo clippy --release --all-targets --locked -- -D warnings
33+ cargo test --profile "${CELLD_PROFILE}" --locked && \
34+ cargo clippy --profile "${CELLD_PROFILE}" --all-targets --locked -- -D warnings
3235
3336 FROM debian:bookworm-slim
3437 RUN apt-get update && \
@@ -39,5 +42,5 @@
3942 LABEL org.opencontainers.image.title="celld" \
4043 org.opencontainers.image.revision="${CELLD_COMMIT}" \
4144 org.opencontainers.image.version="${CELLD_VERSION}"
42-COPY --from=build /out/celld /usr/local/bin/celld
45+COPY --from=test /out/celld /usr/local/bin/celld
4346 ENTRYPOINT ["/usr/local/bin/celld"]
modifiedREADME.md+58−56View file
@@ -3,26 +3,29 @@
33 Self-hosted, distributed **Durable Objects**.
44
55 celld is an open-source daemon that runs Cloudflare Workers and Durable
6-Objects on your own machines. Each object is its own SQLite database,
7-addressed by name and replicated to an
8-S3-compatible bucket you own; nodes coordinate through that bucket alone, with
9-no control plane or consensus. Because every object is its own small database,
6+Objects on your own machines. Each object is its own SQLite database.
7+celld addresses an object by name and replicates it to a bucket that you
8+own. The bucket can be S3-compatible or Google Cloud Storage. The nodes
9+coordinate through that bucket alone, with no control plane and no
10+consensus. Because every object is its own small database,
1011 applications shard by construction — the contention and blast-radius failures
11-of one shared database are designed out, not managed. Idle cells hibernate to
12-nearly nothing. Learn more at [celld.dev](https://celld.dev) or read the
12+of one shared database are designed out, not managed. A cell that no node
13+holds is inactive, and an inactive cell costs nearly nothing. Learn more at
14+[celld.dev](https://celld.dev) or read the
1315 [documentation](https://celld.dev/docs).
1416
1517 ## How it works
1618
17-Every `celld` node embeds V8 and executes Wrangler bundles. The fleet shares an
18-S3-compatible bucket containing deployments, cell state, and small ownership
19-records. Object-storage compare-and-swap ensures that exactly one node owns a
19+Every `celld` node embeds V8 and executes Wrangler bundles. The fleet shares
20+one bucket, which contains deployments, cell state, and small ownership
21+records. The bucket can be S3-compatible or Google Cloud Storage. Object-storage compare-and-swap ensures that exactly one node owns a
2022 cell at a time, without a membership protocol, failure detector, or consensus
2123 service.
2224
2325 celld continuously replicates each cell's SQLite database to the bucket.
24-When a cell moves or wakes up, its new owner restores that database and resumes
25-execution. The bucket is the durable source of truth; nodes are replaceable.
26+When a cell moves, or when an inactive cell activates, its new owner restores
27+that database and resumes execution. The bucket is the durable source of
28+truth; nodes are replaceable.
2629
2730 ## Install
2831
@@ -38,12 +41,12 @@
3841 Worker projects deployed with `celld deploy` need
3942 [esbuild](https://esbuild.github.io) on `PATH`; asset-only projects do not.
4043
41-The installer keeps verified releases under `~/.local/lib/celld/releases` and
42-atomically switches one `current` pointer. To remove celld, use the guarded
43-uninstaller:
44+The installer keeps each release under `~/.local/lib/celld/releases` and points
45+one symlink at the current one. To remove celld, delete the symlink and the
46+releases:
4447
4548 ```sh
46-curl -fsSL https://celld.dev/uninstall.sh | sh
49+rm `which celld` && rm -rf ~/.local/lib/celld
4750 ```
4851
4952 ## Container
@@ -71,11 +74,12 @@
7174 --endpoint https://ACCOUNT.r2.cloudflarestorage.com \
7275 --region auto \
7376 --listen 0.0.0.0:8080 \
74- --advertise node-a.internal:8080
77+ --internal-listen 10.0.0.12:8081 \
78+ --advertise node-a.internal:8081
7579 ```
7680
77-Drop `--endpoint`/`--region` for real AWS S3. Behind a load balancer,
78-give each node a distinct `--advertise` its peers can reach.
81+Drop `--endpoint` and `--region` for AWS S3. Expose port 8080 through the load
82+balancer, and keep port 8081 on the private network.
7983
8084 ## Run it
8185
@@ -89,11 +93,23 @@
8993 celld \
9094 --bucket s3://my-cells-bucket \
9195 --listen 0.0.0.0:8080 \
92- --advertise 10.0.0.12:8080
96+ --internal-listen 10.0.0.12:8081 \
97+ --advertise 10.0.0.12:8081
9398 ```
9499
95100 Use `--endpoint` for another S3-compatible service and `--region` when it
96-cannot be inferred. A fleet runs one application, and every node loads its
101+cannot be inferred. A `gs://` bucket selects Google Cloud Storage. celld then
102+uses the Cloud Storage XML API with generation preconditions. Authentication
103+uses Application Default Credentials. celld rejects an S3 `--endpoint` for a
104+`gs://` bucket, and it ignores the storage region:
105+
106+```sh
107+celld deploy . --bucket gs://my-cells-bucket
108+celld --bucket gs://my-cells-bucket --listen 0.0.0.0:8080 \
109+ --internal-listen 10.0.0.12:8081 --advertise 10.0.0.12:8081
110+```
111+
112+A fleet runs one application, and every node loads its
97113 latest successfully committed deployment from `deploy/current.json`. Run
98114 `celld --help` for the complete command line.
99115 Deployment objects use the documented types in `crates/celld/protocol.rs`. `celld
@@ -102,14 +118,17 @@
102118 assets—and writes those objects directly. Every node discovers owners and
103119 peers from bucket leases; there is no account or join service.
104120
105-Peer HTTP does not terminate TLS. Put every advertised address on a trusted
106-private network or an encrypted overlay such as WireGuard or Tailscale; do not
107-publish the peer port directly. A literal public IP is rejected unless
108-`--unsafe-public-advertise` is supplied explicitly. The first current node creates
109-`fleet/peer-auth.json` in the bucket. All peer requests are protocol-versioned,
110-body-bound, HMAC-authenticated, clock-bounded, and replay-protected with that
111-fleet secret. Treat access to the bucket and its credentials as fleet
112-administrator access.
121+Peer HTTP and the operator API use the internal listener. Put every advertised
122+address on a trusted private network or an encrypted overlay such as WireGuard
123+or Tailscale. Do not publish the internal port. celld rejects a literal public
124+IP unless you supply `--unsafe-public-advertise`. An explicit advertised
125+address requires an explicit internal-listener address. celld cannot verify a
126+hostname or a translated port, so you must route the advertised address to the
127+internal listener. The first current node creates `fleet/peer-auth.json` in the
128+bucket. All peer requests are
129+protocol-versioned, body-bound, HMAC-authenticated, clock-bounded, and
130+replay-protected with that fleet secret. Treat access to the bucket and its
131+credentials as fleet administrator access.
113132
114133 ## Operate a fleet
115134
@@ -126,41 +145,24 @@
126145 WebSocket, RSS, CPU, file-descriptor, pressure, and shedding sample. Pass one
127146 or more `--peer NODE_ID` options to restrict the check.
128147
129-Pressure shedding is opt-in while the first release's safe defaults are being
130-measured. Set a resident-cell high and low watermark on loaded nodes:
148+Set a hard resident-cell limit on each loaded node:
131149
132150 ```sh
133151 CELLD_MAX_RESIDENT_CELLS=1000 \
134-CELLD_RESIDENT_LOW_WATER=800 \
135152 celld --bucket s3://my-cells-bucket --listen 0.0.0.0:8080 \
136- --advertise node-a.internal:8080
153+ --internal-listen 10.0.0.12:8081 --advertise node-a.internal:8081
137154 ```
138155
139-On Linux, `CELLD_MAX_RSS_MB` and `CELLD_MAX_CPU_PERCENT` add process-memory and
140-CPU triggers; the resident-cell watermark is portable. Under pressure, celld
141-durably replicates and fences least-recently used idle cells, publishes them as
142-unowned without resetting their epoch, and refuses to reacquire new unowned
143-cells until the low watermark is reached. A spare receives no assignment: it
144-acquires released cells through the same bucket protocol when normal traffic
145-reaches it. Cells with active work or live host WebSockets are not shed.
156+celld enables an RSS threshold at 80% of the available memory by default. Set
157+`CELLD_MAX_RSS_MB` to change the threshold, or set it to `0` to disable memory
158+pressure shedding. Under pressure, celld durably replicates and fences the
159+least-recently used idle cells. It then publishes the cells as unowned without
160+resetting their epochs. Those cells become inactive, and celld refuses to
161+reacquire new unowned cells until RSS reaches 80% of the threshold. A spare
162+receives no assignment. It acquires a released cell through the same bucket
163+protocol when normal traffic reaches it. celld does not shed a cell with active
164+work or a live host WebSocket.
146165
147-## Build from source
148-
149-```sh
150-cargo build --locked
151-cargo test --locked
152-cargo clippy --all-targets --locked -- -D warnings
153-```
154-
155-The workspace builds the `celld` runtime. Its versioned object-storage
156-protocol lives in `crates/celld/protocol.rs`. Small Wrangler projects under `examples/`
157-exercise the supported Worker and Durable Object surface.
158-
159-The runtime and compatibility surface are still evolving. Public tests cover
160-the standalone engine smoke path; conformance against the Workers and Durable
161-Objects reference behavior, and a deterministic simulation of the distributed
162-protocol under fault injection, run before each release.
163-
164166 ## Contributions
165167
166168 Pull requests are disabled. Coding agents make it too easy to send a large,
modifiedcrates/celld/Cargo.toml+16−3View file
@@ -1,6 +1,6 @@
11 [package]
22 name = "celld"
3-version = "0.1.0"
3+version = "0.2.0"
44 edition = "2021"
55 rust-version = "1.94.1"
66 license = "Apache-2.0"
@@ -18,7 +18,10 @@
1818 check-cfg = ["cfg(celld_internal_tests)", "cfg(celld_proxy_internals)"]
1919
2020 [dependencies]
21+aes.workspace = true
2122 aes-gcm.workspace = true
23+cbc.workspace = true
24+ctr.workspace = true
2225 anyhow.workspace = true
2326 axum.workspace = true
2427 base64.workspace = true
@@ -29,7 +32,6 @@
2932 ed25519-dalek.workspace = true
3033 fastwebsockets.workspace = true
3134 flate2.workspace = true
32-fs2.workspace = true
3335 futures-util.workspace = true
3436 getrandom.workspace = true
3537 hmac.workspace = true
@@ -37,9 +39,16 @@
3739 hyper.workspace = true
3840 hyper-util.workspace = true
3941 md-5.workspace = true
40-object_store = { workspace = true, features = ["aws"] }
42+object_store = { workspace = true, features = ["aws", "gcp"] }
43+parquet.workspace = true
4144 percent-encoding.workspace = true
4245 p256.workspace = true
46+p384.workspace = true
47+p521.workspace = true
48+pkcs8.workspace = true
49+crc.workspace = true
50+dsa.workspace = true
51+x25519-dalek.workspace = true
4352 rand.workspace = true
4453 regex.workspace = true
4554 reqwest = { workspace = true, features = ["rustls-tls", "stream", "json"] }
@@ -50,11 +59,15 @@
5059 serde_json.workspace = true
5160 sha1.workspace = true
5261 sha2.workspace = true
62+subtle.workspace = true
63+tempfile.workspace = true
64+tikv-jemallocator.workspace = true
5365 tokio = { workspace = true, features = ["full"] }
5466 tokio-rustls.workspace = true
5567 tokio-stream.workspace = true
5668 tokio-util.workspace = true
5769 tracing.workspace = true
70+tracing-appender.workspace = true
5871 tracing-subscriber.workspace = true
5972 url.workspace = true
6073 urlpattern.workspace = true
modifiedcrates/celld/assets.rs+20−21View file
@@ -89,10 +89,13 @@
8989 return Err(anyhow!("unsupported asset index name: {}", reference.index));
9090 }
9191 let key = format!("{prefix}/{}", reference.index);
92- let (bytes, _) = bucket
93- .get(&key)
94- .await?
95- .with_context(|| format!("read s3://{}/{key}: no such key", bucket.name))?;
92+ let (bytes, _) = bucket.get(&key).await?.with_context(|| {
93+ format!(
94+ "read {}://{}/{key}: no such key",
95+ bucket.scheme(),
96+ bucket.name
97+ )
98+ })?;
9699 let sha256 = format!("{:x}", Sha256::digest(&bytes));
97100 if sha256 != reference.sha256 {
98101 return Err(anyhow!("asset index checksum mismatch"));
@@ -106,10 +109,8 @@
106109 .unwrap_or_else(|| std::env::temp_dir().join("celld").join("asset-cache"));
107110 std::fs::create_dir_all(&cache_root)
108111 .with_context(|| format!("create asset cache directory {}", cache_root.display()))?;
109- let cache_max_bytes = std::env::var("CELLD_ASSET_CACHE_BYTES")
110- .ok()
111- .and_then(|value| value.parse::<u64>().ok())
112- .unwrap_or(DEFAULT_ASSET_CACHE_BYTES);
112+ let cache_max_bytes =
113+ crate::env_vars::with_default("CELLD_ASSET_CACHE_BYTES", DEFAULT_ASSET_CACHE_BYTES)?;
113114 Ok(Self {
114115 inner: Arc::new(AssetResolverInner {
115116 bucket: bucket.clone(),
@@ -332,9 +333,6 @@
332333 });
333334 }
334335 let path = url::Url::parse(url).context("invalid assets binding URL")?;
335- let encoded_path = path.path().to_string();
336- let query = path.query().map(str::to_string);
337- let host = path.host_str().map(str::to_string);
338336 let mut request_headers = HeaderMap::new();
339337 for (name, value) in headers {
340338 let Ok(name) = name.parse::<axum::http::HeaderName>() else {
@@ -347,9 +345,9 @@
347345 }
348346 let response = match self
349347 .response(
350- &encoded_path,
351- query.as_deref(),
352- host.as_deref(),
348+ path.path(),
349+ path.query(),
350+ path.host_str(),
353351 method == "HEAD",
354352 &request_headers,
355353 true,
@@ -363,14 +361,14 @@
363361 .body(Body::from("Not found"))?,
364362 };
365363 let (parts, body) = response.into_parts();
366- let body = axum::body::to_bytes(body, 25 * 1024 * 1024 + 1)
367- .await
368- .context("buffer assets binding response")?
369- .to_vec();
370364 Ok(js::HttpResponse {
371365 status: parts.status.as_u16(),
372- body,
373- stream: None,
366+ body: Vec::new(),
367+ stream: Some(Box::pin(body.into_data_stream().map(|chunk| {
368+ chunk
369+ .map(|bytes| bytes.to_vec())
370+ .map_err(|error| format!("asset response stream: {error}"))
371+ }))),
374372 headers: parts
375373 .headers
376374 .iter()
@@ -494,7 +492,8 @@
494492 .with_context(|| format!("read asset {resolved_path}"))?
495493 .with_context(|| {
496494 format!(
497- "asset {resolved_path} missing from s3://{}/{key}",
495+ "asset {resolved_path} missing from {}://{}/{key}",
496+ self.inner.bucket.scheme(),
498497 self.inner.bucket.name
499498 )
500499 })?;
modifiedcrates/celld/asyncrt.rs+13−46View file
@@ -1,12 +1,10 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3-//! Host async runtime for the JS thread, using structured concurrency. Ops
4-//! never spawn detached: they ENQUEUE a future, and `js::run_loop` owns a
5-//! per-request tokio `JoinSet` (the "region") that spawns, drives, and — on
6-//! every exit path — aborts whatever is still pending.
7-//! Orphan tasks, leaked bookkeeping, and panic-hangs are impossible by
8-//! construction, not patched. The region is the one asupersync idea we take:
9-//! a task cannot outlive the scope that owns it.
3+//! Async operations started by JavaScript.
4+//!
5+//! An op is enqueued during a synchronous isolate turn. The request driver
6+//! takes those futures when the turn ends, polls them on celld's shared Tokio
7+//! runtime, and re-enters the isolate only to deliver a completed result.
108 use std::cell::RefCell;
119 use std::future::Future;
1210 use std::pin::Pin;
@@ -36,58 +34,27 @@
3634 pub type OpFuture = Pin<Box<dyn Future<Output = Result<OpOut, String>> + Send>>;
3735
3836 thread_local! {
39- // Per-JS-thread current-thread runtime: the Worker and each cell run on
40- // their own thread, so each needs its own runtime — a shared current-thread
41- // runtime cannot be driven by two threads at once. Held as `Rc` so a serve
42- // loop can `block_on` on a clone without keeping the RefCell borrowed (which
43- // would deadlock op spawns that clone the handle mid-drive).
44- static RT: RefCell<Option<std::rc::Rc<tokio::runtime::Runtime>>> =
45- const { RefCell::new(None) };
46- // Ops push (id, future); run_loop drains and spawns them into its region.
37+ // Ops push (id, future); the turn driver drains and owns them.
4738 static SPAWNS: RefCell<Vec<(u64, OpFuture)>> = const { RefCell::new(Vec::new()) };
4839 }
4940
50-pub fn init() {
51- RT.with(|r| {
52- if r.borrow().is_none() {
53- *r.borrow_mut() = Some(std::rc::Rc::new(
54- tokio::runtime::Builder::new_current_thread()
55- .enable_all()
56- .build()
57- .unwrap(),
58- ));
59- }
60- });
61-}
62-
63-/// The thread's runtime (an `Rc` clone), for a serve loop that drives both hyper
64-/// and this thread's JS ops on one runtime. `block_on` on the returned clone
65-/// leaves the thread-local RefCell free for `handle()`/op spawns.
66-pub fn runtime() -> std::rc::Rc<tokio::runtime::Runtime> {
67- RT.with(|r| r.borrow().as_ref().unwrap().clone())
68-}
69-
7041 /// Install celld's shared Tokio runtime for host I/O. Futures remain owned by
71-/// each request's JoinSet, but polling network work on the shared runtime lets
72-/// a reqwest response body move into Axum and continue streaming after the JS
42+/// each request driver, but polling network work on the shared runtime lets a
43+/// reqwest response body move into Axum and continue streaming after the JS
7344 /// handler has returned.
7445 pub fn set_host_handle(handle: tokio::runtime::Handle) {
7546 let _ = HOST_RT.set(handle);
7647 }
7748
78-pub fn handle() -> tokio::runtime::Handle {
79- RT.with(|r| r.borrow().as_ref().unwrap().handle().clone())
80-}
8149 pub fn op_handle() -> tokio::runtime::Handle {
82- HOST_RT.get().cloned().unwrap_or_else(handle)
50+ HOST_RT
51+ .get()
52+ .cloned()
53+ .unwrap_or_else(tokio::runtime::Handle::current)
8354 }
84-pub fn block_on<F: Future>(f: F) -> F::Output {
85- let rt = runtime();
86- rt.block_on(f)
87-}
8855
8956 /// Register an async op's future; returns its promise id. NOT spawned here — the
90-/// region in `run_loop` owns spawning, so a task is never detached.
57+/// request driver owns polling, so a task is never detached.
9158 pub fn enqueue<T: Into<OpOut>>(
9259 fut: impl Future<Output = Result<T, String>> + Send + 'static,
9360 ) -> u64 {
modifiedcrates/celld/bucket.rs+387−106View file
@@ -1,21 +1,33 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3-//! The engine's single S3 client: the `object_store` crate `celld-ltx`
4-//! already links, bound to one bucket (wiki/designs/s3-client-dedup.md).
5-//! Replaces aws-sdk-s3. No call site streamed a body, so everything is
6-//! in-memory `Bytes`.
3+//! The engine's single object-store client: the `object_store` crate
4+//! `celld-ltx` already links, bound to one bucket. Replaces aws-sdk-s3.
5+//! No call site streamed a body, so everything is in-memory `Bytes`.
76 //!
7+//! Two conditional-write dialects share the surface. An `s3://` (or
8+//! bare) spec speaks the S3 dialect: the CAS token is the etag, sent as
9+//! If-Match / If-None-Match with SigV4 credentials. A `gs://` spec
10+//! speaks the Cloud Storage XML API dialect: the CAS token is the
11+//! object generation, sent as x-goog-if-generation-match with OAuth
12+//! credentials. The distinction is the dialect, not the endpoint — GCS
13+//! accepts S3-style requests on the same host but does not apply
14+//! If-Match to a PUT, so only the generation dialect can fence there.
15+//! Callers never see the difference: the token is an opaque `String` a
16+//! read answers and a conditional write consumes.
17+//!
818 //! Error contract, relied on by the self-fence: `put_cas` answers
919 //! `Ok(None)` only for a clean 412/409 rejection; every other failure is
1020 //! ambiguous — the write may have committed — and surfaces as `Err`.
21+//! In the same spirit a response that carries no CAS token is an error,
22+//! never an empty token a later conditional write would trust.
1123
1224 use anyhow::anyhow;
1325 use anyhow::Context;
1426 use bytes::Bytes;
1527 use futures_util::StreamExt;
16-use object_store::aws::AmazonS3;
1728 use object_store::aws::AmazonS3Builder;
1829 use object_store::aws::S3ConditionalPut;
30+use object_store::gcp::GoogleCloudStorageBuilder;
1931 use object_store::path::Path;
2032 use object_store::Attribute;
2133 use object_store::Attributes;
@@ -41,21 +53,105 @@
4153 pub session_token: Option<String>,
4254 }
4355
44-/// One S3-compatible bucket. Cheap to clone; each `open` builds its own
45-/// HTTP transport, so a dedicated instance also isolates its traffic.
56+/// Which conditional-write dialect the bucket speaks, and therefore
57+/// what the opaque CAS token holds: the etag on S3, the object
58+/// generation on GCS. GCS ignores etags on writes, so its tokens must
59+/// come from the generation everywhere — reads, heads, and put results.
60+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61+pub(crate) enum StorageBackend {
62+ S3,
63+ Gcs,
64+}
65+
66+impl StorageBackend {
67+ fn scheme(self) -> &'static str {
68+ match self {
69+ StorageBackend::S3 => "s3",
70+ StorageBackend::Gcs => "gs",
71+ }
72+ }
73+
74+ /// The CAS token a read or applied write answers: etag or generation,
75+ /// per dialect. A response without one cannot be fenced against, so a
76+ /// missing or empty token is an error — never an empty string a later
77+ /// conditional write would send as a real precondition.
78+ fn token(self, e_tag: Option<String>, version: Option<String>) -> anyhow::Result<String> {
79+ let (token, header) = match self {
80+ StorageBackend::S3 => (e_tag, "ETag"),
81+ StorageBackend::Gcs => (version, "x-goog-generation"),
82+ };
83+ match token {
84+ Some(token) if !token.is_empty() => Ok(token),
85+ _ => Err(anyhow!(
86+ "response carries no {header}, so there is no CAS token"
87+ )),
88+ }
89+ }
90+
91+ /// The precondition a conditional update sends for a held token.
92+ fn update(self, token: &str) -> UpdateVersion {
93+ match self {
94+ StorageBackend::S3 => UpdateVersion {
95+ e_tag: Some(token.to_string()),
96+ version: None,
97+ },
98+ StorageBackend::Gcs => UpdateVersion {
99+ e_tag: None,
100+ version: Some(token.to_string()),
101+ },
102+ }
103+ }
104+}
105+
106+/// One object-store bucket, optionally scoped to a key prefix. Cheap to
107+/// clone; each `open` builds its own HTTP transport, so a dedicated
108+/// instance also isolates its traffic.
46109 #[derive(Clone)]
47110 pub struct Bucket {
48- store: Arc<AmazonS3>,
111+ store: Arc<dyn ObjectStore>,
49112 /// Conditional writes only, built with retries OFF: a retried CAS put
50- /// can land on the first attempt's own etag change and report a clean
113+ /// can land on the first attempt's own token change and report a clean
51114 /// 412 — converting "may have committed" into a false rejection. The
52115 /// ambiguity must surface as `Err` so the caller reconciles.
53- cas_store: Arc<AmazonS3>,
116+ cas_store: Arc<dyn ObjectStore>,
117+ backend: StorageBackend,
54118 /// Bucket name, for messages — the store is already bound to it.
55119 pub name: String,
120+ /// Empty, or a slash-terminated key prefix every operation is scoped
121+ /// to. Call sites keep forming unprefixed keys; this type is the one
122+ /// place that knows where in the bucket a fleet lives.
123+ pub prefix: String,
56124 }
57125
126+/// Split a `[s3://|gs://]NAME[/PREFIX]` bucket spec into the backend, the
127+/// bucket name and a normalized key prefix: empty, or slash-terminated. A
128+/// spec without a scheme stays S3-compatible, and a spec without a PREFIX
129+/// keeps every key at the bucket root, so a fleet provisioned before
130+/// either existed never moves its objects.
131+fn split_spec(spec: &str) -> (StorageBackend, &str, String) {
132+ let (backend, spec) = match spec.strip_prefix("gs://") {
133+ Some(rest) => (StorageBackend::Gcs, rest),
134+ None => (StorageBackend::S3, spec.trim_start_matches("s3://")),
135+ };
136+ let (name, prefix) = spec.split_once('/').unwrap_or((spec, ""));
137+ let parts = prefix.split('/').filter(|part| !part.is_empty());
138+ (
139+ backend,
140+ name,
141+ parts.map(|part| format!("{part}/")).collect(),
142+ )
143+}
144+
58145 impl Bucket {
146+ /// `bucket` is `[s3://|gs://]NAME[/PREFIX]`. With a PREFIX every key
147+ /// this client reads or writes lives under `PREFIX/`, so several
148+ /// fleets can share one bucket without colliding.
149+ ///
150+ /// A `gs://` bucket authenticates through Google Application Default
151+ /// Credentials (or the `GOOGLE_*` service-account environment) and
152+ /// takes no S3 endpoint, static credentials, or region — the bucket
153+ /// carries its own location.
154+ ///
59155 /// `app` labels this client's traffic in the User-Agent (the aws
60156 /// AppName format, `app/<name>`), keeping e.g. the lease safety lane
61157 /// observable in black-box storage traces.
@@ -66,6 +162,36 @@
66162 credentials: Option<StaticCredentials>,
67163 app: Option<&str>,
68164 ) -> anyhow::Result<Bucket> {
165+ Self::open_with_gcs_builder(
166+ bucket,
167+ endpoint,
168+ region,
169+ credentials,
170+ app,
171+ GoogleCloudStorageBuilder::from_env(),
172+ )
173+ }
174+
175+ /// The body of [`Self::open`], taking the base GCS builder instead of
176+ /// deriving it from the `GOOGLE_*` environment. A caller that passes
177+ /// an explicit builder is independent of that environment.
178+ fn open_with_gcs_builder(
179+ bucket: &str,
180+ endpoint: Option<&str>,
181+ region: &str,
182+ credentials: Option<StaticCredentials>,
183+ app: Option<&str>,
184+ gcs_builder: GoogleCloudStorageBuilder,
185+ ) -> anyhow::Result<Bucket> {
186+ let (backend, bucket, prefix) = split_spec(bucket);
187+ // The prefix is spliced into keys as plain text and stripped off
188+ // listed keys the same way. A character `object_store` would
189+ // percent-encode would make the two disagree, so refuse it here
190+ // rather than mis-parse every listing later.
191+ let illegal = |c: char| !c.is_ascii_alphanumeric() && !"-_./".contains(c);
192+ if prefix.contains(illegal) {
193+ anyhow::bail!("bucket prefix accepts only letters, digits and -_./: {prefix:?}");
194+ }
69195 // These bounds mirror the aws-sdk TimeoutConfig they replace
70196 // (connect 3 s / attempt 15 s / operation 30 s) — a correctness
71197 // condition for the node self-fence, not tuning. The read-timeout
@@ -80,90 +206,174 @@
80206 .context("app user agent")?,
81207 );
82208 }
83- let mut builder = AmazonS3Builder::from_env()
84- .with_bucket_name(bucket)
85- .with_region(region)
86- .with_conditional_put(S3ConditionalPut::ETagMatch)
87- .with_retry(RetryConfig {
88- max_retries: 2,
89- retry_timeout: Duration::from_secs(30),
90- ..RetryConfig::default()
91- })
92- .with_client_options(options);
93- if let Some(endpoint) = endpoint {
94- // Path-style against explicit S3-compatible endpoints, exactly
95- // as the aws client's force_path_style(endpoint.is_some()).
96- builder = builder
97- .with_endpoint(endpoint)
98- .with_virtual_hosted_style_request(false);
99- } else {
100- builder = builder.with_virtual_hosted_style_request(true);
101- }
102- if let Some(credentials) = credentials {
103- builder = builder
104- .with_access_key_id(credentials.access_key_id)
105- .with_secret_access_key(credentials.secret_access_key);
106- if let Some(token) = credentials.session_token {
107- builder = builder.with_token(token);
108- }
109- }
110- let cas_builder = builder.clone().with_retry(RetryConfig {
209+ let retry = RetryConfig {
210+ max_retries: 2,
211+ retry_timeout: Duration::from_secs(30),
212+ ..RetryConfig::default()
213+ };
214+ let cas_retry = RetryConfig {
111215 max_retries: 0,
112216 retry_timeout: Duration::from_secs(30),
113217 ..RetryConfig::default()
114- });
218+ };
219+ let (store, cas_store): (Arc<dyn ObjectStore>, Arc<dyn ObjectStore>) = match backend {
220+ StorageBackend::S3 => {
221+ let mut builder = AmazonS3Builder::from_env()
222+ .with_bucket_name(bucket)
223+ .with_region(region)
224+ .with_conditional_put(S3ConditionalPut::ETagMatch)
225+ .with_retry(retry)
226+ .with_client_options(options);
227+ if let Some(endpoint) = endpoint {
228+ // Path-style against explicit S3-compatible endpoints, exactly
229+ // as the aws client's force_path_style(endpoint.is_some()).
230+ builder = builder
231+ .with_endpoint(endpoint)
232+ .with_virtual_hosted_style_request(false);
233+ } else {
234+ builder = builder.with_virtual_hosted_style_request(true);
235+ }
236+ if let Some(credentials) = credentials {
237+ builder = builder
238+ .with_access_key_id(credentials.access_key_id)
239+ .with_secret_access_key(credentials.secret_access_key);
240+ if let Some(token) = credentials.session_token {
241+ builder = builder.with_token(token);
242+ }
243+ }
244+ let cas_builder = builder.clone().with_retry(cas_retry);
245+ (
246+ Arc::new(builder.build().context("build s3 client")?),
247+ Arc::new(cas_builder.build().context("build s3 cas client")?),
248+ )
249+ }
250+ StorageBackend::Gcs => {
251+ // The generation dialect only. celld's S3 client fences
252+ // with If-Match, which GCS does not apply to a PUT; and
253+ // this GCS client authenticates with OAuth, not HMAC keys.
254+ // So an S3 endpoint or S3 static credentials with gs:// is
255+ // a configuration error, not something to quietly
256+ // reinterpret.
257+ if endpoint.is_some() {
258+ anyhow::bail!(
259+ "a gs:// bucket takes no S3 endpoint; unset --endpoint / S3_ENDPOINT"
260+ );
261+ }
262+ if credentials.is_some() {
263+ anyhow::bail!(
264+ "a gs:// bucket cannot use S3 static credentials; it authenticates \
265+ with Google Application Default Credentials"
266+ );
267+ }
268+ let builder = gcs_builder
269+ .with_bucket_name(bucket)
270+ .with_retry(retry)
271+ .with_client_options(options);
272+ let cas_builder = builder.clone().with_retry(cas_retry);
273+ (
274+ Arc::new(builder.build().context("build gcs client")?),
275+ Arc::new(cas_builder.build().context("build gcs cas client")?),
276+ )
277+ }
278+ };
115279 Ok(Bucket {
116- store: Arc::new(builder.build().context("build s3 client")?),
117- cas_store: Arc::new(cas_builder.build().context("build s3 cas client")?),
280+ store,
281+ cas_store,
282+ backend,
118283 name: bucket.to_string(),
284+ prefix,
119285 })
120286 }
121287
122- /// Body and etag, or `None` when the key does not exist.
288+ /// The bucket's URL scheme, `s3` or `gs`, for operator-facing
289+ /// messages.
290+ pub fn scheme(&self) -> &'static str {
291+ self.backend.scheme()
292+ }
293+
294+ /// The dialect this bucket speaks, for choosing the matching
295+ /// replication store.
296+ pub(crate) fn backend(&self) -> StorageBackend {
297+ self.backend
298+ }
299+
300+ /// Scope a caller's key to this client's prefix.
301+ fn key(&self, key: &str) -> String {
302+ format!("{}{key}", self.prefix)
303+ }
304+
305+ /// The inverse of [`Self::key`]: a listing answers with full keys, and
306+ /// every caller parses back the key it asked for, not the prefix.
307+ fn unkey<'a>(&self, key: &'a str) -> &'a str {
308+ key.strip_prefix(self.prefix.as_str()).unwrap_or(key)
309+ }
310+
311+ /// Body and CAS token, or `None` when the key does not exist.
123312 pub async fn get(&self, key: &str) -> anyhow::Result<Option<(Bytes, String)>> {
124- match self.store.get(&Path::from(key)).await {
313+ let key = self.key(key);
314+ match self.store.get(&Path::from(key.as_str())).await {
125315 Ok(result) => {
126- let etag = result.meta.e_tag.clone().unwrap_or_default();
127- let bytes = result
128- .bytes()
129- .await
130- .with_context(|| format!("read body s3://{}/{key}", self.name))?;
131- Ok(Some((bytes, etag)))
316+ let token = self
317+ .backend
318+ .token(result.meta.e_tag.clone(), result.meta.version.clone())
319+ .with_context(|| format!("read {}://{}/{key}", self.scheme(), self.name))?;
320+ let bytes = result.bytes().await.with_context(|| {
321+ format!("read body {}://{}/{key}", self.scheme(), self.name)
322+ })?;
323+ Ok(Some((bytes, token)))
132324 }
133325 Err(Error::NotFound { .. }) => Ok(None),
134- Err(error) => Err(anyhow!(error).context(format!("read s3://{}/{key}", self.name))),
326+ Err(error) => {
327+ Err(anyhow!(error).context(format!("read {}://{}/{key}", self.scheme(), self.name)))
328+ }
135329 }
136330 }
137331
138- /// Size and etag, or `None` when the key does not exist.
332+ /// Size and CAS token, or `None` when the key does not exist.
139333 pub async fn head(&self, key: &str) -> anyhow::Result<Option<(u64, String)>> {
140- match self.store.head(&Path::from(key)).await {
141- Ok(meta) => Ok(Some((meta.size as u64, meta.e_tag.unwrap_or_default()))),
334+ let key = self.key(key);
335+ match self.store.head(&Path::from(key.as_str())).await {
336+ Ok(meta) => {
337+ let token = self
338+ .backend
339+ .token(meta.e_tag, meta.version)
340+ .with_context(|| format!("head {}://{}/{key}", self.scheme(), self.name))?;
341+ Ok(Some((meta.size as u64, token)))
342+ }
142343 Err(Error::NotFound { .. }) => Ok(None),
143- Err(error) => Err(anyhow!(error).context(format!("head s3://{}/{key}", self.name))),
344+ Err(error) => {
345+ Err(anyhow!(error).context(format!("head {}://{}/{key}", self.scheme(), self.name)))
346+ }
144347 }
145348 }
146349
147350 pub async fn put(&self, key: &str, body: impl Into<PutPayload>) -> anyhow::Result<()> {
351+ let key = self.key(key);
148352 self.store
149- .put(&Path::from(key), body.into())
353+ .put(&Path::from(key.as_str()), body.into())
150354 .await
151- .with_context(|| format!("write s3://{}/{key}", self.name))?;
355+ .with_context(|| format!("write {}://{}/{key}", self.scheme(), self.name))?;
152356 Ok(())
153357 }
154358
155- /// Size plus one `x-amz-meta-*` value, or `None` when the key does not
156- /// exist. A plain `head` cannot see user metadata; this one can.
359+ /// Size plus one user-metadata value (`x-amz-meta-*` / `x-goog-meta-*`),
360+ /// or `None` when the key does not exist. A plain `head` cannot see
361+ /// user metadata; this one can.
157362 pub async fn head_with_meta(
158363 &self,
159364 key: &str,
160365 name: &str,
161366 ) -> anyhow::Result<Option<(u64, Option<String>)>> {
367+ let key = self.key(key);
162368 let options = GetOptions {
163369 head: true,
164370 ..GetOptions::default()
165371 };
166- match self.store.get_opts(&Path::from(key), options).await {
372+ match self
373+ .store
374+ .get_opts(&Path::from(key.as_str()), options)
375+ .await
376+ {
167377 Ok(result) => {
168378 let value = result
169379 .attributes
@@ -172,17 +382,20 @@
172382 Ok(Some((result.meta.size as u64, value)))
173383 }
174384 Err(Error::NotFound { .. }) => Ok(None),
175- Err(error) => Err(anyhow!(error).context(format!("head s3://{}/{key}", self.name))),
385+ Err(error) => {
386+ Err(anyhow!(error).context(format!("head {}://{}/{key}", self.scheme(), self.name)))
387+ }
176388 }
177389 }
178390
179- /// Plain write carrying `x-amz-meta-*` user metadata.
391+ /// Plain write carrying user metadata (`x-amz-meta-*` / `x-goog-meta-*`).
180392 pub async fn put_with_meta(
181393 &self,
182394 key: &str,
183395 body: impl Into<PutPayload>,
184396 meta: &[(&'static str, &str)],
185397 ) -> anyhow::Result<()> {
398+ let key = self.key(key);
186399 let mut attributes = Attributes::new();
187400 for (name, value) in meta {
188401 attributes.insert(
@@ -195,38 +408,57 @@
195408 ..PutOptions::default()
196409 };
197410 self.store
198- .put_opts(&Path::from(key), body.into(), options)
411+ .put_opts(&Path::from(key.as_str()), body.into(), options)
199412 .await
200- .with_context(|| format!("write s3://{}/{key}", self.name))?;
413+ .with_context(|| format!("write {}://{}/{key}", self.scheme(), self.name))?;
201414 Ok(())
202415 }
203416
204- /// Conditional write. `etag: None` requires the key to be absent
205- /// (If-None-Match: *); `Some` requires the current etag (If-Match).
206- /// `Ok(Some(new_etag))` applied, `Ok(None)` cleanly rejected; any other
207- /// failure is ambiguous and stays an error.
417+ /// Conditional write. `token: None` requires the key to be absent;
418+ /// `Some` requires the current CAS token — the etag on S3 (If-Match),
419+ /// the generation on GCS (x-goog-if-generation-match).
420+ /// `Ok(Some(new_token))` applied, `Ok(None)` cleanly rejected; any
421+ /// other failure is ambiguous and stays an error.
208422 pub async fn put_cas(
209423 &self,
210424 key: &str,
211425 body: impl Into<PutPayload>,
212- etag: Option<&str>,
426+ token: Option<&str>,
213427 ) -> anyhow::Result<Option<String>> {
214- let mode = match etag {
428+ let key = self.key(key);
429+ let mode = match token {
215430 None => PutMode::Create,
216- Some(etag) => PutMode::Update(UpdateVersion {
217- e_tag: Some(etag.to_string()),
218- version: None,
219- }),
431+ Some(token) => PutMode::Update(self.backend.update(token)),
220432 };
221433 match self
222434 .cas_store
223- .put_opts(&Path::from(key), body.into(), PutOptions::from(mode))
435+ .put_opts(
436+ &Path::from(key.as_str()),
437+ body.into(),
438+ PutOptions::from(mode),
439+ )
224440 .await
225441 {
226- Ok(result) => Ok(Some(result.e_tag.unwrap_or_default())),
442+ Ok(result) => {
443+ // The write applied; a result without a usable token still
444+ // surfaces as `Err`, which callers already treat as "may
445+ // have committed" and reconcile.
446+ let token = self
447+ .backend
448+ .token(result.e_tag, result.version)
449+ .with_context(|| {
450+ format!(
451+ "conditional write {}://{}/{key} applied without a CAS token",
452+ self.scheme(),
453+ self.name
454+ )
455+ })?;
456+ Ok(Some(token))
457+ }
227458 Err(Error::Precondition { .. } | Error::AlreadyExists { .. }) => Ok(None),
228459 Err(error) => Err(anyhow!(error).context(format!(
229- "conditional write s3://{}/{key} may have committed",
460+ "conditional write {}://{}/{key} may have committed",
461+ self.scheme(),
230462 self.name
231463 ))),
232464 }
@@ -234,61 +466,105 @@
234466
235467 /// Idempotent: deleting an absent key succeeds, as S3's DELETE does.
236468 pub async fn delete(&self, key: &str) -> anyhow::Result<()> {
237- match self.store.delete(&Path::from(key)).await {
469+ let key = self.key(key);
470+ match self.store.delete(&Path::from(key.as_str())).await {
238471 Ok(()) | Err(Error::NotFound { .. }) => Ok(()),
239- Err(error) => Err(anyhow!(error).context(format!("delete s3://{}/{key}", self.name))),
472+ Err(error) => Err(anyhow!(error).context(format!(
473+ "delete {}://{}/{key}",
474+ self.scheme(),
475+ self.name
476+ ))),
240477 }
241478 }
242479
243480 /// Every object under `prefix/`; the client paginates internally.
481+ /// Listed keys come back the way the caller wrote them, because the
482+ /// caller parses them and knows nothing of the fleet's prefix.
244483 pub async fn list(&self, prefix: &str) -> anyhow::Result<Vec<ObjectMeta>> {
245- let path = Path::from(prefix.trim_end_matches('/'));
484+ let path = Path::from(self.key(prefix.trim_end_matches('/')));
246485 let mut stream = self.store.list(Some(&path));
247486 let mut objects = Vec::new();
248487 while let Some(meta) = stream.next().await {
249- objects.push(meta.with_context(|| format!("list s3://{}/{prefix}", self.name))?);
488+ let mut meta =
489+ meta.with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?;
490+ if !self.prefix.is_empty() {
491+ // The listing gave object_store a valid key, so re-parsing
492+ // the tail of it cannot fail.
493+ meta.location = Path::parse(self.unkey(meta.location.as_ref())).unwrap();
494+ }
495+ objects.push(meta);
250496 }
251497 Ok(objects)
252498 }
253499
254500 /// Does anything exist under `prefix/`? One page at most.
255501 pub async fn list_any(&self, prefix: &str) -> anyhow::Result<bool> {
256- let path = Path::from(prefix.trim_end_matches('/'));
502+ let path = Path::from(self.key(prefix.trim_end_matches('/')));
257503 match self.store.list(Some(&path)).next().await {
258504 None => Ok(false),
259505 Some(Ok(_)) => Ok(true),
260- Some(Err(error)) => {
261- Err(anyhow!(error).context(format!("list s3://{}/{prefix}", self.name)))
262- }
506+ Some(Err(error)) => Err(anyhow!(error).context(format!(
507+ "list {}://{}/{path}",
508+ self.scheme(),
509+ self.name
510+ ))),
263511 }
264512 }
265513
266514 /// Immediate child "directories" under `prefix/` (delimiter listing),
267515 /// as full prefixes with the trailing slash stripped.
268516 pub async fn common_prefixes(&self, prefix: &str) -> anyhow::Result<Vec<String>> {
269- let path = Path::from(prefix.trim_end_matches('/'));
517+ let path = Path::from(self.key(prefix.trim_end_matches('/')));
270518 let result = self
271519 .store
272520 .list_with_delimiter(Some(&path))
273521 .await
274- .with_context(|| format!("list s3://{}/{prefix}", self.name))?;
522+ .with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?;
275523 Ok(result
276524 .common_prefixes
277525 .into_iter()
278- .map(|p| p.as_ref().to_string())
526+ .map(|p| self.unkey(p.as_ref()).to_string())
279527 .collect())
280528 }
281529
282530 /// The head_bucket replacement: prove the bucket is reachable and the
283- /// credential is accepted with one list page.
531+ /// credential is accepted with one list page. Scoped to the prefix, so
532+ /// a credential scoped to it validates too.
284533 pub async fn validate(&self) -> anyhow::Result<()> {
285- match self.store.list(None).next().await {
534+ let scope = (!self.prefix.is_empty()).then(|| Path::from(self.prefix.as_str()));
535+ match self.store.list(scope.as_ref()).next().await {
286536 None | Some(Ok(_)) => Ok(()),
287- Some(Err(error)) => Err(anyhow!(error).context(format!("validate s3://{}", self.name))),
537+ Some(Err(error)) => {
538+ Err(anyhow!(error).context(format!("validate {}://{}", self.scheme(), self.name)))
539+ }
288540 }
289541 }
290542 }
291543
544+/// The replica-lane store for a `gs://` fleet bucket: its own transport
545+/// and connection pool, authenticated like [`Bucket::open`]'s gs:// path
546+/// (OAuth via Application Default Credentials or the `GOOGLE_*` env),
547+/// with the same default retry policy the S3 replica lane gets from its
548+/// litestream-ported config in `ltx_repl`. Replica writes are plain puts,
549+/// so retries stay on.
550+pub(crate) fn gcs_replica_store(bucket: &str) -> anyhow::Result<Arc<dyn ObjectStore>> {
551+ gcs_replica_store_with_builder(GoogleCloudStorageBuilder::from_env(), bucket)
552+}
553+
554+/// The body of [`gcs_replica_store`], taking the base builder for the same
555+/// reason [`Bucket::open_with_gcs_builder`] does.
556+fn gcs_replica_store_with_builder(
557+ builder: GoogleCloudStorageBuilder,
558+ bucket: &str,
559+) -> anyhow::Result<Arc<dyn ObjectStore>> {
560+ Ok(Arc::new(
561+ builder
562+ .with_bucket_name(bucket)
563+ .build()
564+ .context("build gcs replica store")?,
565+ ))
566+}
567+
292568 /// Was this a 401/403 — the credential itself rejected? Used by the managed
293569 /// path to report a revoked credential rather than a flaky bucket.
294570 pub fn is_unauthorized(error: &anyhow::Error) -> bool {
@@ -310,12 +586,15 @@
310586 mod live_cas {
311587 use super::{Bucket, StaticCredentials};
312588
313- // Live CAS contract against a real S3-compatible bucket (R2). Gated on
589+ // Live CAS contract against a real bucket (R2 or GCS). Gated on
314590 // CELLD_CAS_LIVE=1 so it never runs in CI; a mock cannot answer whether
315- // object_store maps R2's precondition failures to Ok(None) (the fencing
316- // contract) rather than Err. Run:
591+ // object_store maps the provider's precondition failures to Ok(None)
592+ // (the fencing contract) rather than Err. Run:
317593 // CELLD_CAS_LIVE=1 CELLD_CAS_BUCKET=<b> CELLD_CAS_ENDPOINT=<ep> AWS_*=... \
318594 // cargo test -p celld put_cas_contract -- --nocapture
595+ // or against GCS (Application Default Credentials, no endpoint):
596+ // CELLD_CAS_LIVE=1 CELLD_CAS_BUCKET=gs://<b> \
597+ // cargo test -p celld put_cas_contract -- --nocapture
319598 #[tokio::test]
320599 async fn put_cas_contract_against_real_bucket() {
321600 if std::env::var("CELLD_CAS_LIVE").as_deref() != Ok("1") {
@@ -324,19 +603,16 @@
324603 let name = std::env::var("CELLD_CAS_BUCKET").expect("CELLD_CAS_BUCKET");
325604 let endpoint = std::env::var("CELLD_CAS_ENDPOINT").ok();
326605 let region = std::env::var("AWS_REGION").unwrap_or_else(|_| "auto".into());
327- let creds = StaticCredentials {
328- access_key_id: std::env::var("AWS_ACCESS_KEY_ID").unwrap(),
329- secret_access_key: std::env::var("AWS_SECRET_ACCESS_KEY").unwrap(),
330- session_token: std::env::var("AWS_SESSION_TOKEN").ok(),
331- };
332- let bucket = Bucket::open(
333- &name,
334- endpoint.as_deref(),
335- &region,
336- Some(creds),
337- Some("cas-test"),
338- )
339- .expect("open bucket");
606+ let creds = std::env::var("AWS_ACCESS_KEY_ID")
607+ .ok()
608+ .map(|access_key_id| StaticCredentials {
609+ access_key_id,
610+ secret_access_key: std::env::var("AWS_SECRET_ACCESS_KEY")
611+ .expect("AWS_SECRET_ACCESS_KEY"),
612+ session_token: std::env::var("AWS_SESSION_TOKEN").ok(),
613+ });
614+ let bucket = Bucket::open(&name, endpoint.as_deref(), &region, creds, Some("cas-test"))
615+ .expect("open bucket");
340616 let nanos = std::time::SystemTime::now()
341617 .duration_since(std::time::UNIX_EPOCH)
342618 .unwrap()
@@ -377,3 +653,8 @@
377653 eprintln!("CAS verified on {name}: create / reject-create / update / reject-stale");
378654 }
379655 }
656+
657+#[cfg(all(test, celld_internal_tests))]
658+mod conformance_bucket_tests {
659+ include!(env!("CELLD_CONFORMANCE_BUCKET_TESTS"));
660+}
modifiedcrates/celld/control_plane.rs+26−25View file
@@ -33,8 +33,8 @@
3333 const MAX_MANAGED_MODULE_BYTES: usize = 25 * 1024 * 1024;
3434
3535 fn restart_on_deployment_enabled() -> bool {
36- !std::env::var("CELLD_CLOUD_RESTART_ON_DEPLOY")
37- .is_ok_and(|value| value.eq_ignore_ascii_case("off"))
36+ crate::env_vars::flag("CELLD_CLOUD_RESTART_ON_DEPLOY", true)
37+ .expect("validated CELLD_CLOUD_RESTART_ON_DEPLOY")
3838 }
3939
4040 #[cfg(unix)]
@@ -917,15 +917,14 @@
917917 advertise = %runtime.advertise,
918918 "node session connected to the Managed Control Plane"
919919 );
920- let heartbeat_period = std::env::var("CELLD_PRESENCE_HEARTBEAT_MS")
921- .ok()
922- .and_then(|value| value.parse::<u64>().ok())
923- .filter(|value| (50..=30_000).contains(value))
924- .map(Duration::from_millis)
925- .unwrap_or(Duration::from_secs(30));
920+ let heartbeat_period = Duration::from_millis(
921+ crate::env_vars::with_default("CELLD_PRESENCE_HEARTBEAT_MS", 30_000)
922+ .expect("validated CELLD_PRESENCE_HEARTBEAT_MS"),
923+ );
926924 let mut heartbeat = tokio::time::interval(heartbeat_period);
927925 heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
928- let shadow_presence = std::env::var("CELLD_PRESENCE_SHADOW").as_deref() == Ok("on");
926+ let shadow_presence = crate::env_vars::flag("CELLD_PRESENCE_SHADOW", false)
927+ .expect("validated CELLD_PRESENCE_SHADOW");
929928 loop {
930929 tokio::select! {
931930 _ = heartbeat.tick() => {
@@ -1080,11 +1079,7 @@
10801079 /// into the core or changes whether the node serves.
10811080 async fn lease_shadow_observation(runtime: &PresenceRuntime) -> serde_json::Value {
10821081 let checked_at_ms = crate::ownership_store::now_ms();
1083- let ownership = crate::ownership_store::S3Ownership::new(
1084- runtime.s3.clone(),
1085- runtime.node_session_id.clone(),
1086- );
1087- match ownership.read_node_lease(&runtime.node_session_id).await {
1082+ match crate::ownership_store::load_node_lease(&runtime.s3, &runtime.node_session_id).await {
10881083 Ok(Some(record)) => serde_json::json!({
10891084 "bucket_status": if record.expires_ms > checked_at_ms { "live" } else { "expired" },
10901085 "node": record.node,
@@ -1476,9 +1471,17 @@
14761471 HeaderName::from_static("x-cells-version"),
14771472 HeaderValue::from_static(env!("CARGO_PKG_VERSION")),
14781473 );
1474+ // Deployment features come from the shared list so the advertised
1475+ // capabilities can never drift from what apply_deployment accepts.
1476+ let capabilities = crate::protocol::SUPPORTED_DEPLOYMENT_FEATURES
1477+ .iter()
1478+ .copied()
1479+ .chain(["sqlite-explorer-v1", "sqlite-explorer-v2"])
1480+ .collect::<Vec<_>>()
1481+ .join(",");
14791482 headers.insert(
14801483 HeaderName::from_static("x-cells-capabilities"),
1481- HeaderValue::from_static("assets-v1,sqlite-explorer-v1,sqlite-explorer-v2"),
1484+ HeaderValue::from_str(&capabilities)?,
14821485 );
14831486 headers.insert(
14841487 HeaderName::from_static("x-cells-hostname"),
@@ -1711,11 +1714,7 @@
17111714 }
17121715 validate_managed_module_envelope(deployment)?;
17131716 validate_managed_class_migrations(&deployment.manifest)?;
1714- for feature in &deployment.manifest.required_features {
1715- if feature != "assets-v1" {
1716- return Err(anyhow!("unsupported deployment feature: {feature}"));
1717- }
1718- }
1717+ crate::protocol::validate_required_features(&deployment.manifest.required_features)?;
17191718
17201719 let mut asset_files = 0_u32;
17211720 let mut asset_bytes = 0_u64;
@@ -2073,7 +2072,7 @@
20732072 }
20742073 for tag in ["old_tag", "new_tag"] {
20752074 if let Some(value) = migrations.get(tag) {
2076- if !value.is_null() && !value.as_str().is_some_and(|value| !value.is_empty()) {
2075+ if !value.is_null() && value.as_str().is_none_or(str::is_empty) {
20772076 return Err(anyhow!(
20782077 "managed manifest migrations.{tag} must be null or a non-empty string"
20792078 ));
@@ -2631,10 +2630,12 @@
26312630
26322631 async fn try_acquire_enrollment_lock(config: &Path) -> anyhow::Result<Option<EnrollmentLock>> {
26332632 let (file, lock_path) = open_enrollment_lock(config).await?;
2634- tokio::task::spawn_blocking(move || match fs2::FileExt::try_lock_exclusive(&file) {
2633+ tokio::task::spawn_blocking(move || match file.try_lock() {
26352634 Ok(()) => Ok(Some(EnrollmentLock { _file: file })),
2636- Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(None),
2637- Err(error) => Err(error).with_context(|| format!("lock {}", lock_path.display())),
2635+ Err(std::fs::TryLockError::WouldBlock) => Ok(None),
2636+ Err(std::fs::TryLockError::Error(error)) => {
2637+ Err(error).with_context(|| format!("lock {}", lock_path.display()))
2638+ }
26382639 })
26392640 .await
26402641 .context("join enrollment try-lock task")?
@@ -2643,7 +2644,7 @@
26432644 async fn acquire_enrollment_lock(config: &Path) -> anyhow::Result<EnrollmentLock> {
26442645 let (file, lock_path) = open_enrollment_lock(config).await?;
26452646 tokio::task::spawn_blocking(move || {
2646- fs2::FileExt::lock_exclusive(&file)
2647+ file.lock()
26472648 .with_context(|| format!("lock {}", lock_path.display()))?;
26482649 Ok(EnrollmentLock { _file: file })
26492650 })
modifiedcrates/celld/dead_node_gc.rs+1−1View file
@@ -326,6 +326,6 @@
326326 return Ok(None);
327327 };
328328 let record = serde_json::from_slice(&bytes)
329- .with_context(|| format!("decode s3://{}/{key}", bucket.name))?;
329+ .with_context(|| format!("decode {}://{}/{key}", bucket.scheme(), bucket.name))?;
330330 Ok(Some((record, etag)))
331331 }
modifiedcrates/celld/deploy.rs+99−16View file
@@ -9,7 +9,7 @@
99 use crate::bucket::Bucket;
1010 use crate::protocol::{
1111 asset_blob_key, AssetConfig, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest,
12- ModuleRef, Rollout, RunWorkerFirst,
12+ ModuleKind, ModuleRef, Rollout, RunWorkerFirst, FEATURE_ASSETS_V1, FEATURE_WASM_V1,
1313 };
1414 use anyhow::{anyhow, bail, Context};
1515 use flate2::write::GzEncoder;
@@ -37,6 +37,7 @@
3737 "assets",
3838 "services",
3939 "vars",
40+ "no_bundle",
4041 ];
4142
4243 const MAX_ASSET_FILES: usize = 20_000;
@@ -56,11 +57,12 @@
5657 pub fn print_help() {
5758 println!(
5859 "celld deploy — build a Worker with esbuild and write it to the fleet bucket\n\n\
59-USAGE:\n celld deploy [PROJECT] --bucket s3://NAME [OPTIONS]\n\n\
60+USAGE:\n celld deploy [PROJECT] --bucket [s3://|gs://]NAME[/PREFIX] [OPTIONS]\n\n\
6061 PROJECT is a directory or a Wrangler config; it defaults to the working\n\
6162 directory, where celld looks for wrangler.jsonc or wrangler.json.\n\n\
62-OPTIONS:\n --config PATH Same as passing PROJECT positionally\n --bucket s3://NAME Fleet bucket; defaults to CELLD_BUCKET\n --endpoint URL S3-compatible endpoint; defaults to S3_ENDPOINT\n --region REGION Storage region; defaults to AWS_REGION\n --dry-run Bundle and print the version without writing\n -h, --help Show this help\n\n\
63-Credentials come from the standard AWS credential chain.\n\n\
63+OPTIONS:\n --config PATH Same as passing PROJECT positionally\n --bucket [s3://|gs://]NAME[/PREFIX]\n Fleet bucket and prefix; defaults to CELLD_BUCKET.\n gs:// selects a Google Cloud Storage bucket; celld\n then rejects --endpoint and ignores --region\n --endpoint URL S3-compatible endpoint; defaults to S3_ENDPOINT\n --region REGION Storage region; defaults to AWS_REGION\n --dry-run Bundle and print the version without writing\n -h, --help Show this help\n\n\
64+Credentials come from the standard AWS credential chain, or from Google\n\
65+Application Default Credentials for a gs:// bucket.\n\n\
6466 Worker projects require `esbuild` on PATH; asset-only projects do not. Static\n\
6567 assets, service bindings, and string vars are supported. Routes are not; use\n\
6668 Wrangler for route configuration.\n\
@@ -112,6 +114,10 @@
112114 /// What a config resolves to once the allowlist has been applied.
113115 struct Project {
114116 script_name: String,
117+ /// `no_bundle: true` uploads the entry file as written instead of running
118+ /// esbuild. A Vite build has already bundled the Worker, and bundling it
119+ /// twice is what breaks that output.
120+ no_bundle: bool,
115121 /// Entry relative to the project root. esbuild stamps this path into the
116122 /// bundle, so it must not depend on the working directory celld was
117123 /// invoked from — identical source would otherwise hash two ways.
@@ -272,15 +278,35 @@
272278 let bundle = project
273279 .entry
274280 .as_deref()
275- .map(|entry| run_esbuild(&root, entry))
281+ .map(|entry| {
282+ if project.no_bundle {
283+ // Already bundled by the caller's toolchain. Read it as it is;
284+ // running esbuild over a Vite build is what corrupts it. A
285+ // pre-bundled entry carries no sibling wasm: esbuild's copy
286+ // loader is what would have produced them.
287+ let path = root.join(entry);
288+ std::fs::read(&path)
289+ .with_context(|| format!("read entry point {}", path.display()))
290+ .map(|bundle| BundleOutput {
291+ bundle,
292+ wasm: Vec::new(),
293+ })
294+ } else {
295+ run_esbuild(&root, entry)
296+ }
297+ })
276298 .transpose()?;
277299 let bundled_in = started.elapsed();
278300
279- // esbuild emits one module, so the graph is always a single entry.
301+ // esbuild emits one JS module plus a copy of every wasm file the bundle
302+ // imports; the copies ship as sibling modules.
280303 let module_name = "index.js".to_string();
281- let modules = bundle
282- .map(|bundle| vec![(module_name.clone(), bundle)])
283- .unwrap_or_default();
304+ let (mut modules, wasm_modules) = match bundle {
305+ Some(output) => (vec![(module_name.clone(), output.bundle)], output.wasm),
306+ None => (Vec::new(), Vec::new()),
307+ };
308+ let wasm_names: BTreeSet<String> = wasm_modules.iter().map(|(name, _)| name.clone()).collect();
309+ modules.extend(wasm_modules);
284310 // Identity is over the exact metadata bytes the manifest retains, so the
285311 // serialization happens once and is reused for both.
286312 let metadata_json = serde_json::to_vec(&project.metadata)?;
@@ -309,13 +335,22 @@
309335 name: name.clone(),
310336 bytes: bytes.len(),
311337 sha256: format!("{:x}", Sha256::digest(bytes))[..16].to_string(),
338+ kind: wasm_names.contains(name).then_some(ModuleKind::Wasm),
312339 })
313340 .collect(),
314341 assets: asset_reference,
315- required_features: if built_assets.is_some() {
316- vec!["assets-v1".to_string()]
317- } else {
318- Vec::new()
342+ // Each capability the manifest depends on is named here, so a node
343+ // that predates it rejects the deployment up front instead of
344+ // partially deserializing the manifest and failing at worker load.
345+ required_features: {
346+ let mut features = Vec::new();
347+ if built_assets.is_some() {
348+ features.push(FEATURE_ASSETS_V1.to_string());
349+ }
350+ if !wasm_names.is_empty() {
351+ features.push(FEATURE_WASM_V1.to_string());
352+ }
353+ features
319354 },
320355 raw_metadata: project.metadata,
321356 };
@@ -399,8 +434,9 @@
399434 match bucket.put_cas(key, body, etag.as_deref()).await {
400435 Ok(Some(_)) => Ok(()),
401436 Ok(None) => Err(anyhow!(
402- "write s3://{}/{key} lost a race\n\
437+ "write {}://{}/{key} lost a race\n\
403438 Another deploy may have landed first; re-run `celld deploy`.",
439+ bucket.scheme(),
404440 bucket.name
405441 )),
406442 Err(error) => {
@@ -480,6 +516,14 @@
480516 bail!("entry point {} is not a regular file", entry.display());
481517 }
482518 }
519+ let no_bundle = match object.get("no_bundle") {
520+ None => false,
521+ Some(Value::Bool(value)) => *value,
522+ Some(_) => bail!("config `no_bundle` must be a boolean"),
523+ };
524+ if no_bundle && main.is_none() {
525+ bail!("config sets `no_bundle` without `main`");
526+ }
483527 let assets = object
484528 .get("assets")
485529 .map(|value| read_asset_project(value, root, object))
@@ -623,6 +667,7 @@
623667
624668 Ok(Project {
625669 script_name,
670+ no_bundle,
626671 entry: main,
627672 assets,
628673 metadata: Value::Object(metadata),
@@ -1072,11 +1117,19 @@
10721117 })
10731118 }
10741119
1075-fn run_esbuild(root: &Path, entry: &str) -> anyhow::Result<Vec<u8>> {
1120+/// esbuild's outputs: the bundled entry module, and the wasm files its
1121+/// imports were resolved to (each under the name the rewritten import uses).
1122+struct BundleOutput {
1123+ bundle: Vec<u8>,
1124+ wasm: Vec<(String, Vec<u8>)>,
1125+}
1126+
1127+fn run_esbuild(root: &Path, entry: &str) -> anyhow::Result<BundleOutput> {
10761128 // node: builtins stay external. Wrangler polyfills them with unenv; celld
10771129 // implements the workerd `nodejs_compat` subset itself, so the runtime
10781130 // provides them.
10791131 let binary = std::env::var("CELLD_ESBUILD").unwrap_or_else(|_| "esbuild".to_string());
1132+ let outdir = tempfile::tempdir().context("create esbuild output directory")?;
10801133 let output = Command::new(&binary)
10811134 .current_dir(root)
10821135 .arg(entry)
@@ -1087,6 +1140,15 @@
10871140 .arg("--conditions=workerd,worker,browser")
10881141 .arg("--external:node:*")
10891142 .arg("--external:cloudflare:*")
1143+ // Wasm becomes a sibling module (Wrangler's CompiledWasm rule). The
1144+ // `copy` loader makes esbuild resolve each wasm import like any other
1145+ // import (importer-relative, node_modules, deduplicated) and rewrite
1146+ // the specifier to the copied file, so the bundle and the emitted
1147+ // files agree on names; the runtime serves each file as a compiled
1148+ // WebAssembly.Module default export.
1149+ .arg("--loader:.wasm=copy")
1150+ .arg(format!("--outdir={}", outdir.path().display()))
1151+ .arg("--entry-names=index")
10901152 .output()
10911153 .map_err(|error| {
10921154 if error.kind() == std::io::ErrorKind::NotFound {
@@ -1105,7 +1167,28 @@
11051167 String::from_utf8_lossy(&output.stderr).trim()
11061168 );
11071169 }
1108- Ok(output.stdout)
1170+ let bundle =
1171+ std::fs::read(outdir.path().join("index.js")).context("read esbuild output bundle")?;
1172+ // The copied wasm files land beside the bundle; each becomes its own
1173+ // deployed module under the name the rewritten imports use.
1174+ let mut wasm = Vec::new();
1175+ for dirent in std::fs::read_dir(outdir.path()).context("read esbuild output directory")? {
1176+ let path = dirent?.path();
1177+ if path.extension().and_then(|extension| extension.to_str()) == Some("wasm") {
1178+ let name = path
1179+ .file_name()
1180+ .expect("read_dir entries have a file name")
1181+ .to_string_lossy()
1182+ .into_owned();
1183+ let bytes = std::fs::read(&path)
1184+ .with_context(|| format!("read wasm module {}", path.display()))?;
1185+ wasm.push((name, bytes));
1186+ }
1187+ }
1188+ // read_dir order is platform-defined; the deployment version hashes the
1189+ // module list, so keep it stable.
1190+ wasm.sort();
1191+ Ok(BundleOutput { bundle, wasm })
11091192 }
11101193
11111194 /// Minimal JSONC support: line and block comments, and trailing commas.
addedcrates/celld/env_vars.rs+167−0View file
@@ -1,0 +1,167 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! Strict runtime environment parsing.
4+//!
5+//! An unset variable selects its caller's documented default. A supplied
6+//! variable must contain a valid value, so a typo cannot silently change the
7+//! configuration of a running node.
8+
9+use anyhow::{anyhow, bail};
10+
11+/// Validate every typed production variable before the runtime starts.
12+///
13+/// Some consumers cache a value or read it from a synchronous callback, so
14+/// they cannot return a configuration error at the point of use. This pass
15+/// makes those reads infallible without giving malformed values a default.
16+pub fn validate() -> anyhow::Result<()> {
17+ for name in [
18+ "CELLD_CLOUD",
19+ "CELLD_CLOUD_RESTART_ON_DEPLOY",
20+ "CELLD_LTX_COMPACTION",
21+ "CELLD_OUTPUT_GATE",
22+ "CELLD_PRESENCE_SHADOW",
23+ "CELLD_UNSAFE_PUBLIC_ADVERTISE",
24+ ] {
25+ flag(name, false)?;
26+ }
27+
28+ for name in [
29+ "CELLD_ACTIVATIONS",
30+ "CELLD_EVICTIONS",
31+ "CELLD_FETCH_TIMEOUT_S",
32+ "CELLD_HANDLER_BUDGET_S",
33+ "CELLD_IDLE_EVICT_S",
34+ "CELLD_LTX_COMPACTIONS",
35+ "CELLD_LTX_COMPACTION_MIN_TXIDS",
36+ "CELLD_MAX_LOADED_WORKERS",
37+ "CELLD_MAX_OUTBOUND_WEBSOCKETS",
38+ "CELLD_MAX_REQUESTS",
39+ "CELLD_MAX_STATELESS_ISOLATES",
40+ "CELLD_OPERATION_DEADLINE_MS",
41+ "CELLD_RELEASES",
42+ "CELLD_SHUTDOWN_DRAIN_MS",
43+ "CELLD_TOKIO_THREADS",
44+ "CELLD_TTL_MS",
45+ "CELLD_WAKER_TICK_MS",
46+ ] {
47+ positive::<u64>(name)?;
48+ }
49+
50+ for name in [
51+ "CELLD_ADMISSION_WAIT_MS",
52+ "CELLD_ALARM_RESIDENT_MS",
53+ "CELLD_ASSET_CACHE_BYTES",
54+ "CELLD_LEASE_LINGER_MS",
55+ "CELLD_LOCAL_CACHE_MAX_BYTES",
56+ "CELLD_MAX_RESIDENT_CELLS",
57+ "CELLD_MAX_RSS_MB",
58+ ] {
59+ optional::<u64>(name)?;
60+ }
61+
62+ if let Some(value) = optional::<u64>("CELLD_PRESENCE_HEARTBEAT_MS")? {
63+ if !(50..=30_000).contains(&value) {
64+ bail!("CELLD_PRESENCE_HEARTBEAT_MS must be between 50 and 30000, not {value}");
65+ }
66+ }
67+
68+ if let Some(megabytes) = positive::<usize>("CELLD_V8_HEAP_LIMIT_MB")? {
69+ if megabytes.checked_mul(1024 * 1024).is_none() {
70+ bail!("CELLD_V8_HEAP_LIMIT_MB is too large: {megabytes}");
71+ }
72+ }
73+
74+ if let Some(value) = value("CELLD_LAZY_NODE_LEASE")? {
75+ if !matches!(value.as_str(), "continuous" | "lazy" | "shadow") {
76+ bail!("CELLD_LAZY_NODE_LEASE must be continuous, lazy, or shadow, not {value:?}");
77+ }
78+ }
79+ if let Some(value) = value("CELLD_PRESSURE_OWNERSHIP")? {
80+ if !matches!(value.as_str(), "release" | "sticky") {
81+ bail!("CELLD_PRESSURE_OWNERSHIP must be release or sticky, not {value:?}");
82+ }
83+ }
84+ Ok(())
85+}
86+
87+pub fn value(name: &str) -> anyhow::Result<Option<String>> {
88+ match std::env::var(name) {
89+ Ok(value) => Ok(Some(value)),
90+ Err(std::env::VarError::NotPresent) => Ok(None),
91+ Err(error) => Err(anyhow!("read {name}: {error}")),
92+ }
93+}
94+
95+pub fn flag(name: &str, default: bool) -> anyhow::Result<bool> {
96+ let value = value(name)?;
97+ parse_flag(name, value.as_deref(), default)
98+}
99+
100+pub fn parse_flag(name: &str, value: Option<&str>, default: bool) -> anyhow::Result<bool> {
101+ match value {
102+ None => Ok(default),
103+ Some("0") => Ok(false),
104+ Some("1") => Ok(true),
105+ Some(other) => bail!("{name} must be 0 or 1, not {other:?}"),
106+ }
107+}
108+
109+pub fn optional<T>(name: &str) -> anyhow::Result<Option<T>>
110+where
111+ T: std::str::FromStr,
112+ T::Err: std::fmt::Display,
113+{
114+ parse_optional(name, value(name)?)
115+}
116+
117+pub fn parse_optional<T>(name: &str, value: Option<String>) -> anyhow::Result<Option<T>>
118+where
119+ T: std::str::FromStr,
120+ T::Err: std::fmt::Display,
121+{
122+ value
123+ .map(|value| {
124+ value
125+ .parse::<T>()
126+ .map_err(|error| anyhow!("{name} has invalid value {value:?}: {error}"))
127+ })
128+ .transpose()
129+}
130+
131+pub fn with_default<T>(name: &str, default: T) -> anyhow::Result<T>
132+where
133+ T: std::str::FromStr,
134+ T::Err: std::fmt::Display,
135+{
136+ Ok(optional(name)?.unwrap_or(default))
137+}
138+
139+pub fn positive<T>(name: &str) -> anyhow::Result<Option<T>>
140+where
141+ T: std::str::FromStr + Default + PartialOrd + std::fmt::Display,
142+ T::Err: std::fmt::Display,
143+{
144+ parse_positive(name, value(name)?)
145+}
146+
147+pub fn parse_positive<T>(name: &str, value: Option<String>) -> anyhow::Result<Option<T>>
148+where
149+ T: std::str::FromStr + Default + PartialOrd + std::fmt::Display,
150+ T::Err: std::fmt::Display,
151+{
152+ let Some(value) = parse_optional::<T>(name, value)? else {
153+ return Ok(None);
154+ };
155+ if value <= T::default() {
156+ bail!("{name} must be greater than zero, not {value}");
157+ }
158+ Ok(Some(value))
159+}
160+
161+pub fn positive_or<T>(name: &str, default: T) -> anyhow::Result<T>
162+where
163+ T: std::str::FromStr + Default + PartialOrd + std::fmt::Display,
164+ T::Err: std::fmt::Display,
165+{
166+ Ok(positive(name)?.unwrap_or(default))
167+}
modifiedcrates/celld/fleet.rs+77−48View file
@@ -4,16 +4,16 @@
44
55 use crate::bucket::Bucket;
66 use crate::deploy;
7-use crate::js::WorkerConfigOptions;
8-use crate::protocol::{DeployPointer, Manifest};
7+use crate::js::{ModuleSource, WorkerConfigOptions};
8+use crate::ownership_store::NodeLeaseWire;
9+use crate::protocol::{DeployPointer, Manifest, ModuleKind};
910 use anyhow::{bail, Context};
10-use serde::Deserialize;
1111 use std::collections::BTreeMap;
1212 use std::time::Duration;
1313 use tracing::info;
1414
15-pub fn s3_client(bucket: &str, endpoint: Option<&str>, region: &str) -> anyhow::Result<Bucket> {
16- s3_client_with_credentials(bucket, endpoint, region, None)
15+pub fn bucket_client(bucket: &str, endpoint: Option<&str>, region: &str) -> anyhow::Result<Bucket> {
16+ bucket_client_with_credentials(bucket, endpoint, region, None)
1717 }
1818
1919 /// Build the authority-heartbeat client on its own HTTP connection pool.
@@ -22,7 +22,7 @@
2222 /// or replica requests. Every `Bucket::open` builds its own transport, so a
2323 /// dedicated instance keeps the safety lane isolated, and the `celld-lease`
2424 /// app tag labels it in black-box storage traces.
25-pub fn s3_lease_client_with_credentials(
25+pub fn lease_bucket_client_with_credentials(
2626 bucket: &str,
2727 endpoint: Option<&str>,
2828 region: &str,
@@ -31,7 +31,7 @@
3131 open(bucket, endpoint, region, managed, Some("celld-lease"))
3232 }
3333
34-pub fn s3_client_with_credentials(
34+pub fn bucket_client_with_credentials(
3535 bucket: &str,
3636 endpoint: Option<&str>,
3737 region: &str,
@@ -56,10 +56,13 @@
5656 }
5757
5858 pub async fn validate_bucket(bucket: &Bucket) -> anyhow::Result<()> {
59- bucket
60- .validate()
61- .await
62- .with_context(|| format!("bucket unavailable or inaccessible: s3://{}", bucket.name))
59+ bucket.validate().await.with_context(|| {
60+ format!(
61+ "bucket unavailable or inaccessible: {}://{}",
62+ bucket.scheme(),
63+ bucket.name
64+ )
65+ })
6366 }
6467
6568 /// Validate storage issued by the Managed Control Plane and preserve the
@@ -93,12 +96,14 @@
9396 crate::control_plane::ManagedRuntimeState::CredentialRevoked,
9497 );
9598 bail!(
96- "managed storage credential was rejected or revoked for s3://{}",
99+ "managed storage credential was rejected or revoked for {}://{}",
100+ bucket.scheme(),
97101 bucket.name
98102 );
99103 }
100104 bail!(
101- "managed storage credential was not accepted yet for s3://{}",
105+ "managed storage credential was not accepted yet for {}://{}",
106+ bucket.scheme(),
102107 bucket.name
103108 );
104109 }
@@ -109,32 +114,23 @@
109114 );
110115 }
111116 Err(error).with_context(|| {
112- format!("bucket unavailable or inaccessible: s3://{}", bucket.name)
117+ format!(
118+ "bucket unavailable or inaccessible: {}://{}",
119+ bucket.scheme(),
120+ bucket.name
121+ )
113122 })
114123 }
115124 }
116125 }
117126
118-#[derive(Deserialize)]
119-pub(crate) struct DiagnosticNode {
120- pub(crate) node: String,
121- pub(crate) expires_ms: u64,
122- pub(crate) addr: String,
123- #[serde(default)]
124- pub(crate) probe_public_key: String,
125- #[serde(default)]
126- pub(crate) peer_protocol: u16,
127- #[serde(default)]
128- pub(crate) load: crate::ownership_store::NodeLoadWire,
129-}
130-
131127 pub async fn diagnose(
132128 bucket: &Bucket,
133129 peers: Vec<String>,
134130 unsafe_public_advertise: bool,
135131 ) -> anyhow::Result<()> {
136132 validate_bucket(bucket).await?;
137- println!("ok bucket s3://{}", bucket.name);
133+ println!("ok bucket {}://{}", bucket.scheme(), bucket.name);
138134
139135 let enumerated = peers.is_empty();
140136 let peers = if enumerated {
@@ -220,7 +216,7 @@
220216 println!(
221217 "ok peer {} at {} (signed direct probe) protocol={} resident_cells={} \
222218 websockets={} rss_bytes={} cpu_percent={:.2} fds={}/{} pressured={} \
223- shed_cells={} load_age_ms={}",
219+ shed_cells={} restoring={} load_age_ms={}",
224220 node.node,
225221 node.addr,
226222 node.peer_protocol,
@@ -232,6 +228,7 @@
232228 node.load.fd_limit,
233229 node.load.pressured,
234230 node.load.shed_cells,
231+ node.load.restoring,
235232 load_age_ms,
236233 );
237234 }
@@ -244,10 +241,10 @@
244241 Ok(())
245242 }
246243
247-async fn diagnostic_node(bucket: &Bucket, peer: &str) -> anyhow::Result<Option<DiagnosticNode>> {
244+async fn diagnostic_node(bucket: &Bucket, peer: &str) -> anyhow::Result<Option<NodeLeaseWire>> {
248245 let key = format!("nodes/{peer}.json");
249- let node: DiagnosticNode = serde_json::from_str(&get_string(bucket, &key).await?)
250- .with_context(|| format!("decode s3://{}/{key}", bucket.name))?;
246+ let node: NodeLeaseWire = serde_json::from_str(&get_string(bucket, &key).await?)
247+ .with_context(|| format!("decode {}://{}/{key}", bucket.scheme(), bucket.name))?;
251248 if node.node != peer {
252249 bail!(
253250 "node lease {key} identifies unexpected node {:?}",
@@ -305,7 +302,7 @@
305302 options.endpoint = env("S3_ENDPOINT");
306303 }
307304 if !options.dry_run && options.bucket.is_none() {
308- bail!("celld deploy requires --bucket s3://NAME (or CELLD_BUCKET)");
305+ bail!("celld deploy requires --bucket s3://NAME or gs://NAME (or CELLD_BUCKET)");
309306 }
310307 let built = deploy::build(&options)?;
311308 built.report();
@@ -323,7 +320,7 @@
323320 .or_else(|| env("AWS_REGION"))
324321 .or_else(|| env("AWS_DEFAULT_REGION"))
325322 .unwrap_or_else(|| "us-east-1".to_string());
326- let store = s3_client(&bucket, options.endpoint.as_deref(), &region)?;
323+ let store = bucket_client(&bucket, options.endpoint.as_deref(), &region)?;
327324 validate_bucket(&store).await?;
328325 let started = std::time::Instant::now();
329326 deploy::write(&store, &built).await?;
@@ -332,20 +329,34 @@
332329 built.script_name,
333330 started.elapsed().as_secs_f64()
334331 );
335- println!(" s3://{bucket}/{}", built.prefix);
332+ println!(
333+ " {}://{}/{}{}",
334+ store.scheme(),
335+ store.name,
336+ store.prefix,
337+ built.prefix
338+ );
336339 println!("Current Version ID: {}", built.version);
337340 println!("Nodes load a deployment at startup; restart them to serve this version.");
338341 Ok(())
339342 }
340343
341344 async fn get_string(bucket: &Bucket, key: &str) -> anyhow::Result<String> {
342- let (bytes, _) = bucket
343- .get(key)
344- .await?
345- .with_context(|| format!("read s3://{}/{key}: no such key", bucket.name))?;
346- String::from_utf8(bytes.to_vec()).context("deployment module is not UTF-8")
345+ String::from_utf8(get_bytes(bucket, key).await?.into())
346+ .context("deployment module is not UTF-8")
347347 }
348348
349+async fn get_bytes(bucket: &Bucket, key: &str) -> anyhow::Result<bytes::Bytes> {
350+ let (bytes, _) = bucket.get(key).await?.with_context(|| {
351+ format!(
352+ "read {}://{}/{key}: no such key",
353+ bucket.scheme(),
354+ bucket.name
355+ )
356+ })?;
357+ Ok(bytes)
358+}
359+
349360 pub async fn load_current_worker(
350361 bucket: &Bucket,
351362 node: String,
@@ -372,6 +383,7 @@
372383 &get_string(bucket, &format!("{}/manifest.json", pointer.prefix)).await?,
373384 )
374385 .context("decode deployment manifest")?;
386+ crate::protocol::validate_required_features(&manifest.required_features)?;
375387 let src = match manifest.main_module.as_deref() {
376388 Some(main) => get_string(bucket, &format!("{}/{main}", pointer.prefix)).await?,
377389 None if manifest.assets.is_some() => {
@@ -383,13 +395,30 @@
383395 }
384396 None => bail!("deployment has neither a main module nor assets"),
385397 };
386- let mut text = Vec::new();
387- for module in &manifest.modules {
388- if manifest.main_module.as_deref() == Some(module.name.as_str()) {
389- continue;
390- }
391- let source = get_string(bucket, &format!("{}/{}", pointer.prefix, module.name)).await?;
392- text.push((format!("./{}", module.name), source));
398+ let prefix = &pointer.prefix;
399+ let fetched = futures_util::future::try_join_all(
400+ manifest
401+ .modules
402+ .iter()
403+ .filter(|module| manifest.main_module.as_deref() != Some(module.name.as_str()))
404+ .map(|module| async move {
405+ let key = format!("{prefix}/{}", module.name);
406+ anyhow::Ok((module, get_bytes(bucket, &key).await?))
407+ }),
408+ )
409+ .await?;
410+ let mut modules = Vec::new();
411+ for (module, bytes) in fetched {
412+ let entry = match module.kind {
413+ Some(ModuleKind::Wasm) => (module.name.clone(), ModuleSource::Wasm(bytes)),
414+ None => (
415+ format!("./{}", module.name),
416+ ModuleSource::Text(
417+ String::from_utf8(bytes.into()).context("deployment module is not UTF-8")?,
418+ ),
419+ ),
420+ };
421+ modules.push(entry);
393422 }
394423 let do_bindings = bindings(&manifest, "durable_object_namespace")
395424 .filter_map(|binding| {
@@ -436,7 +465,7 @@
436465 ai_binding,
437466 vars,
438467 node,
439- text,
468+ modules,
440469 compat,
441470 },
442471 script_name,
modifiedcrates/celld/js.rs+5689−7807View file
@@ -10,7811 +10,5693 @@
1010 //! `async` by the JS harness.
1111 use crate::asyncrt;
1212 use crate::storage;
13-use anyhow::{anyhow, Result};
14-use futures_util::StreamExt as _;
15-use std::cell::RefCell;
16-use std::collections::{HashMap, HashSet};
17-use std::pin::Pin;
18-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
19-use std::sync::{Arc, Mutex, OnceLock};
20-use std::time::{Duration, Instant};
21-use tokio::task::JoinSet;
22-use v8::{ValueDeserializerHelper, ValueSerializerHelper};
23-
24-/// The pending exception text from a TryCatch scope (a macro so it needs no
25-/// bound on the crate-private scope traits).
26-macro_rules! exc {
27- ($tc:expr) => {
28- $tc.exception()
29- .map(|e| e.to_rust_string_lossy(&*$tc))
30- .unwrap_or_else(|| "<none>".into())
31- };
32-}
33-
34-/// A cross-node dispatch: the isolate hit `env.NS.get(id)` for a cell this node
35-/// does not own. The op hands this to the tokio runtime, which resolves the
36-/// owner and HTTP-proxies the fetch, replying on `reply` (an async oneshot the
37-/// async-op future awaits — the JS thread is never blocked).
38-pub struct DoCallReq {
39- pub request_id: Option<RequestId>,
40- pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
41- pub scope: String,
42- pub name: Option<String>,
43- pub url: String,
44- pub method: String,
45- pub body: Vec<u8>,
46- pub headers: Vec<(String, String)>,
47- pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
48-}
49-static DO_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<DoCallReq>> = OnceLock::new();
50-
51-/// An output-gate request for the co-hosted (same-isolate) Durable Object fast
52-/// path. That path runs a resident DO's `fetch` inline, bypassing
53-/// `dispatch_do_call` where the gate lives; the inline handler samples the
54-/// cell's committed-write position and, on a write, asks the actor to hold the
55-/// inline response here until the cell is durable. `position` is the sampled
56-/// committed-write position (the same signal the routed gate uses).
57-pub struct GateReq {
58- pub scope: String,
59- pub position: u64,
60- pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>,
61-}
62-static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new();
63-pub fn set_gate_tx(tx: tokio::sync::mpsc::UnboundedSender<GateReq>) {
64- let _ = GATE_TX.set(tx);
65-}
66-
67-/// A service-binding call: `env.NAME.fetch()`. Unlike a Durable Object call
68-/// there is no identity to resolve — any isolate running `script` will do — so
69-/// the runtime hands this straight to that script's worker pool.
70-pub struct SvcCallReq {
71- /// Fires when the caller's request signal aborts, so the router stops
72- /// waiting on the target instead of leaving the call outstanding.
73- pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
74- pub script: String,
75- pub url: String,
76- pub method: String,
77- pub body: Vec<u8>,
78- pub headers: Vec<(String, String)>,
79- pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
80-}
81-static SVC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcCallReq>> = OnceLock::new();
82-
83-/// A Worker assets-binding call. The script name selects the immutable asset
84-/// index loaded for that Worker; unlike ingress this never falls back into the
85-/// Worker and therefore cannot recurse.
86-pub struct AssetCallReq {
87- pub script: String,
88- pub url: String,
89- pub method: String,
90- pub headers: Vec<(String, String)>,
91- pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
92-}
93-static ASSET_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<AssetCallReq>> = OnceLock::new();
94-
95-/// An RPC call on a named `WorkerEntrypoint` of another script. Arguments and
96-/// the result cross as V8 structured-clone bytes.
97-pub struct SvcRpcReq {
98- pub script: String,
99- pub entrypoint: String,
100- pub method: String,
101- pub args: Vec<u8>,
102- pub reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
103-}
104-static SVC_RPC_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcRpcReq>> = OnceLock::new();
105-pub fn set_svc_rpc_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcRpcReq>) {
106- let _ = SVC_RPC_TX.set(tx);
107-}
108-pub fn set_svc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcCallReq>) {
109- let _ = SVC_CALL_TX.set(tx);
110-}
111-pub fn set_asset_call_tx(tx: tokio::sync::mpsc::UnboundedSender<AssetCallReq>) {
112- let _ = ASSET_CALL_TX.set(tx);
113-}
114-pub fn set_do_call_tx(tx: tokio::sync::mpsc::UnboundedSender<DoCallReq>) {
115- let _ = DO_CALL_TX.set(tx);
116-}
117-
118-/// Hand a Durable Object call to the dispatcher. Public HTTP ingress uses the
119-/// same queue a Worker's `env.NAME.get(id).fetch()` does, so both resolve
120-/// ownership, forward, and redispatch by one policy rather than two.
121-#[must_use]
122-pub fn submit_do_call(call: DoCallReq) -> bool {
123- DO_CALL_TX.get().is_some_and(|tx| tx.send(call).is_ok())
124-}
125-
126-/// The arm-time wake-entry gate, output-gate style (matching Durable
127-/// Objects): `setAlarm()` resolves optimistically on the committed local
128-/// write — it never yields the cell's event scheduling to remote I/O — and
129-/// the cell's response edge is withheld until every pending wake-entry PUT
130-/// has landed. Invariant: an arm the caller has OBSERVED acknowledged
131-/// (received the response) is covered by a durable entry.
132-pub struct ArmGate {
133- pub bucket: crate::bucket::Bucket,
134- pub flusher: Arc<crate::wake::WakeFlusher>,
135-}
136-static ARM_GATE: OnceLock<ArmGate> = OnceLock::new();
137-pub fn set_arm_gate(gate: ArmGate) {
138- let _ = ARM_GATE.set(gate);
139-}
140-
141-/// Whether this node still holds a wake entry for `cell`.
142-pub fn wake_entry_tracked(cell: &str) -> bool {
143- ARM_GATE.get().is_some_and(|gate| gate.flusher.tracks(cell))
144-}
145-
146-/// Adopt the wake entry a restored alarm implies, so consuming that alarm
147-/// deletes it rather than orphaning it.
148-pub fn adopt_wake_entry(cell: &str, at_ms: i64) {
149- if let Some(gate) = ARM_GATE.get() {
150- gate.flusher.adopt(cell, at_ms);
151- }
152-}
153-
154-/// Bring the bucket's wake entry for `cell` into line with its alarm.
155-///
156-/// Arming writes an entry; something has to take it away again once the alarm
157-/// has been consumed, or the entry outlives its alarm and every later due scan
158-/// finds it and wakes a cell with nothing to do. `consume_durable` gates that
159-/// final delete on the consuming commit being replicated -- removing the hint
160-/// while the commit that consumed the alarm is still only local would lose
161-/// both the alarm and the record that could have revived it.
162-pub async fn reconcile_wake_entry(cell: &str, next_alarm_ms: i64, consume_durable: bool) {
163- let Some(gate) = ARM_GATE.get() else {
164- return;
165- };
166- gate.flusher
167- .reconcile(&gate.bucket, cell, next_alarm_ms, consume_durable)
168- .await;
169-}
170-
171-type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>;
172-static PENDING_ARM_GATES: OnceLock<Mutex<HashMap<String, Vec<ArmGateRx>>>> = OnceLock::new();
173-fn pending_arm_gates() -> &'static Mutex<HashMap<String, Vec<ArmGateRx>>> {
174- PENDING_ARM_GATES.get_or_init(Default::default)
175-}
176-
177-/// A committed alarm tightened the durable wake bound: launch the entry PUT
178-/// and register it against the cell's output gate. No-op when the bound
179-/// already covers it or no gate is configured (unit tests).
180-fn spawn_arm_gate(cell: &str, at_ms: i64) {
181- let Some(gate) = ARM_GATE.get() else { return };
182- let Some(celld_logic::wake::Op::Put { key, due_ms }) = gate.flusher.arm_op(cell, at_ms) else {
183- return;
184- };
185- let cell_ = cell.to_string();
186- let (tx, rx) = tokio::sync::oneshot::channel();
187- {
188- let mut pending = pending_arm_gates().lock().unwrap();
189- let gates = pending.entry(cell_.clone()).or_default();
190- // Arms with no response edge to drain them (alarm handlers,
191- // WebSocket events) must not accumulate: drop already-settled gates.
192- gates.retain_mut(|gate| {
193- matches!(
194- gate.try_recv(),
195- Err(tokio::sync::oneshot::error::TryRecvError::Empty)
196- )
197- });
198- gates.push(rx);
199- }
200- asyncrt::op_handle().spawn(async move {
201- let gate = ARM_GATE.get().unwrap();
202- // The core may have demanded this PUT because the tracked entry's
203- // consume-delete is already on the wire; the PUT must land after
204- // that delete, not race it (S3 orders concurrent same-key writes
205- // arbitrarily).
206- gate.flusher.await_no_inflight_delete(&cell_).await;
207- let body = format!("{{\"cell\":{cell_:?},\"due_ms\":{due_ms}}}");
208- let result = gate
209- .bucket
210- .put(&key, body.into_bytes())
211- .await
212- .map(|_| gate.flusher.confirm_arm(&cell_, due_ms, key))
213- .map_err(|e| format!("setAlarm wake entry: {e}"));
214- let _ = tx.send(result);
215- });
216-}
217-
218-/// Await the cell's pending wake-entry PUTs — the output-gate drain a
219-/// response edge performs before releasing its reply. An error means an arm
220-/// the response would acknowledge is not durably covered; the caller must
221-/// fail the response rather than lie (the flusher retries the entry).
222-pub async fn drain_arm_gates(cell: &str) -> Result<(), String> {
223- let gates = pending_arm_gates().lock().unwrap().remove(cell);
224- let Some(gates) = gates else { return Ok(()) };
225- for gate in gates {
226- match gate.await {
227- Ok(Ok(())) => {}
228- Ok(Err(error)) => return Err(error),
229- Err(_) => return Err("wake-entry gate task dropped".into()),
230- }
231- }
232- Ok(())
233-}
234-
235-pub type RequestId = u128;
236-
237-#[derive(Clone, Copy)]
238-pub struct FetchRequest<'a> {
239- pub url: &'a str,
240- pub method: &'a str,
241- pub body: &'a [u8],
242- pub headers: &'a [(String, String)],
243- pub request_id: Option<RequestId>,
244-}
245-
246-/// Allocate an id for an ingress or service-binding request so it can be
247-/// aborted mid-flight.
248-pub fn next_request_id() -> RequestId {
249- next_do_request_id()
250-}
251-
252-static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
253-static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new();
254-static DO_CALL_CANCELS: OnceLock<
255- std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>>,
256-> = OnceLock::new();
257-fn do_call_cancels(
258-) -> &'static std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>> {
259- DO_CALL_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
260-}
261-
262-fn next_do_request_id() -> RequestId {
263- let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| {
264- let mut bytes = [0; 8];
265- getrandom::fill(&mut bytes).expect("OS random source unavailable");
266- u64::from_ne_bytes(bytes)
267- });
268- let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
269- (u128::from(prefix) << 64) | u128::from(sequence)
270-}
271-
272-pub fn request_id_string(request_id: RequestId) -> String {
273- format!("{request_id:032x}")
274-}
275-
276-pub fn parse_request_id(value: &str) -> Option<RequestId> {
277- u128::from_str_radix(value, 16).ok()
278-}
279-
280-struct DoCallCancelGuard(RequestId);
281-
282-impl Drop for DoCallCancelGuard {
283- fn drop(&mut self) {
284- do_call_cancels().lock().unwrap().remove(&self.0);
285- }
286-}
287-
288-/// An RPC payload crossing the host boundary. JS stubs marshal by V8
289-/// structured clone (`V8`); the legacy cross-node JSON envelope and the test
290-/// harness use `Json`. `__dispatchRpc` answers in the flavor it was asked in.
291-pub enum RpcData {
292- Json(String),
293- V8(Vec<u8>),
294-}
295-
296-/// A native Durable Object RPC call (`stub.someMethod(...args)`).
297-/// Routing/activation is identical to fetch calls.
298-pub struct RpcCallReq {
299- pub scope: String,
300- pub name: Option<String>,
301- pub method: String,
302- pub args: RpcData,
303- pub reply: tokio::sync::oneshot::Sender<Result<RpcData>>,
304-}
305-static RPC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<RpcCallReq>> = OnceLock::new();
306-pub fn set_rpc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<RpcCallReq>) {
307- let _ = RPC_CALL_TX.set(tx);
308-}
309-
310-pub struct OutboundWsReq {
311- pub scope: String,
312- pub id: u64,
313- pub url: String,
314- pub protocols: Vec<String>,
315- /// Present for an isolate-polled (Worker) socket. Created and registered
316- /// on the JS thread before the request is sent, so `__ws_next` can never
317- /// run ahead of its own queue.
318- pub pull: Option<WsPullSender>,
319- /// Extra request headers, for the `fetch()` upgrade form.
320- pub headers: Vec<(String, String)>,
321- /// A `fetch()` upgrade wants the whole handshake outcome, including the
322- /// ordinary response a server that declines to upgrade sent instead.
323- pub want_response: bool,
324- pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>,
325-}
326-
327-/// The ordinary HTTP response a server sent instead of upgrading. `fetch()`
328-/// returns it verbatim rather than turning it into a connection error.
329-pub struct DeclinedUpgrade {
330- pub status: u16,
331- pub headers: Vec<(String, String)>,
332- pub body: Vec<u8>,
333-}
334-
335-/// What an outbound handshake produced.
336-pub struct OutboundWsOpen {
337- pub protocol: Option<String>,
338- pub declined: Option<DeclinedUpgrade>,
339-}
340-static OUTBOUND_WS_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> =
341- OnceLock::new();
342-pub fn set_outbound_ws_tx(tx: tokio::sync::mpsc::UnboundedSender<OutboundWsReq>) {
343- let _ = OUTBOUND_WS_TX.set(tx);
344-}
345-
346-static NEXT_TIMER_ID: AtomicU64 = AtomicU64::new(1);
347-static TIMER_CANCELS: OnceLock<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>> =
348- OnceLock::new();
349-fn timer_cancels() -> &'static std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>> {
350- TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
351-}
352-static NEXT_HTTP_STREAM_ID: AtomicU64 = AtomicU64::new(1);
353-enum HttpStreamSource {
354- Response(reqwest::Response),
355- Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>),
356- Stream(HttpChunkStream),
357-}
358-struct HttpStreamEntry {
359- created: Instant,
360- source: Option<HttpStreamSource>,
361- cancelled: tokio::sync::watch::Sender<bool>,
362-}
363-static HTTP_STREAMS: OnceLock<std::sync::Mutex<HashMap<u64, HttpStreamEntry>>> = OnceLock::new();
364-fn http_streams() -> &'static std::sync::Mutex<HashMap<u64, HttpStreamEntry>> {
365- HTTP_STREAMS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
366-}
367-fn register_http_stream(stream_id: u64, source: HttpStreamSource) {
368- let (cancelled, _) = tokio::sync::watch::channel(false);
369- let mut streams = http_streams().lock().unwrap();
370- streams.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60));
371- streams.insert(
372- stream_id,
373- HttpStreamEntry {
374- created: Instant::now(),
375- source: Some(source),
376- cancelled,
377- },
378- );
379-}
380-struct ResponseStreamWriter {
381- created: Instant,
382- writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>,
383- finished: tokio::sync::watch::Sender<bool>,
384-}
385-static RESPONSE_STREAM_WRITERS: OnceLock<std::sync::Mutex<HashMap<u64, ResponseStreamWriter>>> =
386- OnceLock::new();
387-fn response_stream_writers() -> &'static std::sync::Mutex<HashMap<u64, ResponseStreamWriter>> {
388- RESPONSE_STREAM_WRITERS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
389-}
390-
391-pub type HttpChunkStream =
392- Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>;
393-
394-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
395-pub struct WsTarget {
396- pub id: u64,
397- pub scope: String,
398- #[serde(default, skip_serializing_if = "Option::is_none")]
399- pub peer_node: Option<String>,
400- #[serde(default, skip_serializing_if = "Option::is_none")]
401- pub peer_addr: Option<String>,
402- #[serde(default, skip_serializing_if = "Option::is_none")]
403- pub peer_epoch: Option<u64>,
404-}
405-
406-/// Encode a cell/service response for the JS side. A text body crosses as a
407-/// JS string (cheap, lossless), binary as a byte array, and a streaming body
408-/// by id — serializing a Vec<u8> as a JSON number array is the dominant cost
409-/// for real DO responses. `ws_target` is carried only by the DO path.
410-fn encode_http_response(mut response: HttpResponse, ws_target: bool) -> String {
411- let mut obj = serde_json::json!({
412- "status": response.status,
413- "headers": response.headers,
414- });
415- if ws_target {
416- obj["wsTarget"] = serde_json::json!(response.ws);
417- }
418- if let Some(stream) = response.stream.take() {
419- let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
420- register_http_stream(stream_id, HttpStreamSource::Stream(stream));
421- obj["streamId"] = serde_json::json!(stream_id);
422- } else {
423- match std::str::from_utf8(&response.body) {
424- Ok(text) => obj["body"] = serde_json::Value::String(text.into()),
425- Err(_) => obj["bodyBytes"] = serde_json::json!(response.body),
426- }
427- }
428- obj.to_string()
429-}
430-
431-pub struct HttpResponse {
432- pub status: u16,
433- pub body: Vec<u8>,
434- /// A final Worker response that directly forwards an outbound fetch body.
435- /// Main hands this reqwest stream to Axum without materializing it.
436- pub stream: Option<HttpChunkStream>,
437- pub headers: Vec<(String, String)>,
438- pub ws: Option<WsTarget>,
439- /// The cell's committed-write position after the handler ran, for a local
440- /// Durable Object request. The shell gates the response on durability when
441- /// this advanced past the cell's last seen position. `None` for responses
442- /// with no cell storage (Worker, asset, or proxied remote).
443- pub write_position: Option<u64>,
444-}
445-
446-/// Jobs accepted by one resident cell isolate. While a handler awaits an
447-/// outbound operation, the isolate may service another event, matching the
448-/// Durable Objects event-loop semantics and allowing RPC call-backs (A→B→A).
449-pub enum CellJob {
450- Fetch {
451- request_id: Option<RequestId>,
452- scope: String,
453- name: Option<String>,
454- url: String,
455- method: String,
456- body: Vec<u8>,
457- headers: Vec<(String, String)>,
458- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
459- },
460- /// Run the worker's `export default fetch` INSIDE this cell isolate. When
461- /// the worker routes `env.NS.get(id)` to a scope this isolate owns, the DO
462- /// call resolves in-isolate, avoiding the `__do_call` host round trip.
463- WorkerFetch {
464- request_id: RequestId,
465- url: String,
466- method: String,
467- body: Vec<u8>,
468- headers: Vec<(String, String)>,
469- /// Keeps the landing cell unavailable to another top-level Worker
470- /// request until this event, including post-response work, is done.
471- inline_activity: crate::CellActivityGuard,
472- /// If this job is observed while another event is already driving the
473- /// landing isolate, run it on the ordinary stateless Worker pool. A
474- /// Worker fetch cannot be nested in the same V8 isolate, but its DO
475- /// calls may safely re-enter this cell through the normal host path.
476- fallback_workers: Arc<crate::WorkerPool>,
477- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
478- },
479- Rpc {
480- scope: String,
481- name: Option<String>,
482- method: String,
483- args: RpcData,
484- reply: tokio::sync::oneshot::Sender<Result<RpcData>>,
485- },
486- WsOpen {
487- scope: String,
488- ws_id: u64,
489- protocol: String,
490- reply: tokio::sync::oneshot::Sender<Result<()>>,
491- },
492- WsMessage {
493- scope: String,
494- ws_id: u64,
495- data: WsIn,
496- reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>,
497- },
498- WsClosed {
499- scope: String,
500- ws_id: u64,
501- code: u16,
502- reason: String,
503- was_clean: bool,
504- reply: tokio::sync::oneshot::Sender<Result<()>>,
505- },
506- AbortFetch {
507- request_id: RequestId,
508- },
509- Alarm {
510- scope: String,
511- scheduled_ms: i64,
512- reply: tokio::sync::oneshot::Sender<Result<Option<i64>>>,
513- },
514- Shutdown,
515-}
516-
517-/// Outbound WebSocket traffic from a DO's `ws.send`/`ws.close`. The host holds
518-/// the socket in a task decoupled from the isolate (so the cell can hibernate
519-/// while the socket lives); `ws.send` routes here by wsId.
520-pub enum WsOut {
521- Text(String),
522- Binary(Vec<u8>),
523- Close(u16, String),
524-}
525-
526-/// The result of delivering one `webSocketMessage`. `frames` are the outbound
527-/// frames the handler produced, captured by the output gate; `write_position`
528-/// is the cell's committed-write count after the handler when it advanced past
529-/// where it stood before — i.e. the handler wrote, and its frames must be held
530-/// until that position is durable. `None` means no write: flush the frames.
531-pub struct WsDispatch {
532- pub frames: Vec<(u64, WsOut)>,
533- pub write_position: Option<u64>,
534-}
535-
536-/// One inbound event on a socket the ISOLATE polls, rather than one the host
537-/// pushes into a cell.
538-///
539-/// A Durable Object socket must survive between events and wake a hibernated
540-/// cell, so its frames arrive as `CellJob`s. A Worker socket cannot work that
541-/// way: the stateless pool has no addressable isolate, and `asyncrt`'s region
542-/// aborts every pending op when the request ends. That is not a limitation to
543-/// route around — it is exactly the lifetime Cloudflare gives a Worker socket,
544-/// which lives and dies with its `IoContext`. So the isolate pulls, the same
545-/// way it already pulls a streamed response body.
546-pub enum WsPull {
547- Open(String),
548- Text(String),
549- Binary(Vec<u8>),
550- Close(u16, String, bool),
551-}
552-
553-/// Tags for the byte frame `__ws_next` resolves with. A tagged buffer keeps a
554-/// binary message on its fast path instead of base64 through a JSON envelope.
555-const WS_PULL_TAG_TEXT: u8 = 0;
556-const WS_PULL_TAG_BINARY: u8 = 1;
557-const WS_PULL_TAG_OPEN: u8 = 2;
558-const WS_PULL_TAG_CLOSE: u8 = 3;
559-
560-impl WsPull {
561- fn encode(self) -> Vec<u8> {
562- let (tag, mut body) = match self {
563- WsPull::Text(text) => (WS_PULL_TAG_TEXT, text.into_bytes()),
564- WsPull::Binary(bytes) => (WS_PULL_TAG_BINARY, bytes),
565- WsPull::Open(protocol) => (WS_PULL_TAG_OPEN, protocol.into_bytes()),
566- WsPull::Close(code, reason, was_clean) => (
567- WS_PULL_TAG_CLOSE,
568- serde_json::json!({
569- "code": code,
570- "reason": reason,
571- "wasClean": was_clean,
572- })
573- .to_string()
574- .into_bytes(),
575- ),
576- };
577- let mut framed = Vec::with_capacity(body.len() + 1);
578- framed.push(tag);
579- framed.append(&mut body);
580- framed
581- }
582-}
583-
584-pub type WsPullReceiver = tokio::sync::mpsc::UnboundedReceiver<WsPull>;
585-pub type WsPullSender = tokio::sync::mpsc::UnboundedSender<WsPull>;
586-
587-/// One socket's inbound queue. Shared so an op can await it without holding
588-/// the registry lock; one isolate polls a given socket serially.
589-type WsPullQueue = Arc<tokio::sync::Mutex<WsPullReceiver>>;
590-type WsPullRegistry = std::sync::Mutex<HashMap<u64, WsPullQueue>>;
591-
592-/// Inbound queues for isolate-polled sockets, keyed by wsId.
593-static WS_PULL: OnceLock<WsPullRegistry> = OnceLock::new();
594-
595-fn ws_pull() -> &'static WsPullRegistry {
596- WS_PULL.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
597-}
598-
599-pub fn ws_pull_register(id: u64, rx: WsPullReceiver) {
600- ws_pull()
601- .lock()
602- .unwrap()
603- .insert(id, Arc::new(tokio::sync::Mutex::new(rx)));
604-}
605-
606-pub fn ws_pull_unregister(id: u64) {
607- ws_pull().lock().unwrap().remove(&id);
608-}
609-
610-thread_local! {
611- /// Sockets opened by the region currently running on this thread, one
612- /// frame per nested region. `asyncrt` aborts a region's pending ops on
613- /// exit; these are the host-side resources that abort cannot reach, so
614- /// the region closes them itself.
615- static WS_PULL_REGION: RefCell<Vec<Vec<u64>>> = const { RefCell::new(Vec::new()) };
616- /// Sockets opened before the region exists. A handler runs synchronously
617- /// up to its first await BEFORE its run loop is entered, so a socket
618- /// constructed at the top of a handler is created with no frame to belong
619- /// to. The loop adopts these when it starts.
620- static WS_PULL_PENDING: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
621-}
622-
623-pub fn ws_region_enter() {
624- let adopted =
625- WS_PULL_PENDING.with(|pending| pending.borrow_mut().drain(..).collect::<Vec<_>>());
626- WS_PULL_REGION.with(|regions| regions.borrow_mut().push(adopted));
627-}
628-
629-/// Close every isolate-polled socket the closing region opened. A Worker
630-/// socket lives and dies with its request, exactly as it does on Cloudflare.
631-pub fn ws_region_exit() {
632- let opened = WS_PULL_REGION.with(|regions| regions.borrow_mut().pop().unwrap_or_default());
633- for id in opened {
634- ws_emit(id, WsOut::Close(1001, "request ended".into()));
635- ws_pull_unregister(id);
636- ws_unregister(id);
637- }
638-}
639-
640-fn ws_region_track(id: u64) {
641- WS_PULL_REGION.with(|regions| {
642- if let Some(current) = regions.borrow_mut().last_mut() {
643- current.push(id);
644- return;
645- }
646- WS_PULL_PENDING.with(|pending| pending.borrow_mut().push(id));
647- });
648-}
649-pub enum WsIn {
650- Text(String),
651- Binary(Vec<u8>),
652-}
653-struct WsMeta {
654- scope: String,
655- hibernatable: bool,
656- tags: Vec<String>,
657- attachment: Option<String>,
658- pending: Vec<WsOut>,
659-}
660-#[derive(Default)]
661-struct WsRegistry {
662- outputs: HashMap<u64, tokio::sync::mpsc::UnboundedSender<WsOut>>,
663- metadata: HashMap<u64, WsMeta>,
664-}
665-impl WsRegistry {
666- fn register(&mut self, id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) {
667- if let Some(meta) = self.metadata.get_mut(&id) {
668- for pending in meta.pending.drain(..) {
669- let _ = tx.send(pending);
670- }
671- }
672- self.outputs.insert(id, tx);
673- }
674-
675- fn unregister(&mut self, id: u64) -> Option<WsMeta> {
676- self.outputs.remove(&id);
677- self.metadata.remove(&id)
678- }
679-
680- fn emit(&mut self, id: u64, out: WsOut) {
681- if let Some(tx) = self.outputs.get(&id) {
682- tracing::debug!(ws_id = id, "queued outbound WebSocket frame");
683- let _ = tx.send(out);
684- } else if let Some(meta) = self.metadata.get_mut(&id) {
685- tracing::debug!(ws_id = id, "buffered pre-upgrade WebSocket frame");
686- meta.pending.push(out);
687- } else {
688- // The socket is gone and the frame has nowhere to go. Silence here
689- // is what made a held frame indistinguishable from a sent one.
690- tracing::warn!(ws_id = id, "dropped a frame for a closed WebSocket");
691- }
692- }
693-}
694-static WS_REGISTRY: OnceLock<std::sync::Mutex<WsRegistry>> = OnceLock::new();
695-static REGULAR_WS_COUNTS: OnceLock<std::sync::Mutex<HashMap<String, usize>>> = OnceLock::new();
696-static NEXT_WS_ID: AtomicU64 = AtomicU64::new(1);
697-fn ws_registry() -> &'static std::sync::Mutex<WsRegistry> {
698- WS_REGISTRY.get_or_init(|| std::sync::Mutex::new(WsRegistry::default()))
699-}
700-fn regular_ws_counts() -> &'static std::sync::Mutex<HashMap<String, usize>> {
701- REGULAR_WS_COUNTS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
702-}
703-fn increment_regular_ws(scope: &str) {
704- *regular_ws_counts()
705- .lock()
706- .unwrap()
707- .entry(scope.to_string())
708- .or_default() += 1;
709-}
710-fn decrement_regular_ws(scope: &str) {
711- let mut counts = regular_ws_counts().lock().unwrap();
712- let Some(count) = counts.get_mut(scope) else {
713- return;
714- };
715- *count = count.saturating_sub(1);
716- if *count == 0 {
717- counts.remove(scope);
718- }
719-}
720-pub fn has_regular_websocket(scope: &str) -> bool {
721- regular_ws_counts()
722- .lock()
723- .unwrap()
724- .get(scope)
725- .is_some_and(|count| *count > 0)
726-}
727-pub fn ws_hibernatable(id: u64) -> Option<bool> {
728- ws_registry()
729- .lock()
730- .unwrap()
731- .metadata
732- .get(&id)
733- .map(|meta| meta.hibernatable)
734-}
735-pub fn ws_next_id() -> u64 {
736- NEXT_WS_ID.fetch_add(1, Ordering::Relaxed)
737-}
738-pub fn ws_register(id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) {
739- ws_registry().lock().unwrap().register(id, tx);
740-}
741-pub fn ws_register_outbound(id: u64, scope: &str) {
742- let inserted = {
743- let mut registry = ws_registry().lock().unwrap();
744- if let std::collections::hash_map::Entry::Vacant(entry) = registry.metadata.entry(id) {
745- entry.insert(WsMeta {
746- scope: scope.to_string(),
747- hibernatable: false,
748- tags: Vec::new(),
749- attachment: None,
750- pending: Vec::new(),
751- });
752- true
753- } else {
754- false
755- }
756- };
757- if inserted {
758- increment_regular_ws(scope);
759- }
760-}
761-pub fn ws_unregister(id: u64) {
762- let meta = ws_registry().lock().unwrap().unregister(id);
763- if let Some(meta) = meta.filter(|meta| !meta.hibernatable) {
764- decrement_regular_ws(&meta.scope);
765- }
766-}
767-thread_local! {
768- // Output-gate capture. While a `webSocketMessage` runs, its outbound frames
769- // are collected here instead of hitting the wire, so the shell can hold them
770- // until the message's write is durable. A stack: a reentrant event pushes
771- // its own buffer, and frames nested inside a capturing event land on top.
772- //
773- // What may be captured is decided per socket, by `ws_gate_may_hold`, and
774- // that check is what keeps this from deadlocking. Delivering a message runs
775- // the isolate's event loop, which drives every ready task on this thread,
776- // not just this handler -- so anything captured here is withheld for as
777- // long as that loop runs.
778- static WS_CAPTURE: RefCell<Vec<Vec<(u64, WsOut)>>> = const { RefCell::new(Vec::new()) };
779-}
780-
781-fn ws_capture_begin() {
782- WS_CAPTURE.with(|c| c.borrow_mut().push(Vec::new()));
783-}
784-
785-fn ws_capture_take() -> Vec<(u64, WsOut)> {
786- WS_CAPTURE.with(|c| c.borrow_mut().pop().unwrap_or_default())
787-}
788-
789-/// Whether a socket is one the output gate may hold frames for: a hibernatable
790-/// transport, whose messages the host pushes into the cell.
791-///
792-/// A socket the isolate opened and polls itself is not. Its handler runs inside
793-/// the isolate's event loop, and that loop is what a held frame would be
794-/// waiting on: the reply to a frame the gate is withholding never arrives, so
795-/// the loop never finishes, so the frame is never released. Frames from those
796-/// sockets go straight out, as they did before the gate existed.
797-fn ws_gate_may_hold(id: u64) -> bool {
798- let registry = ws_registry().lock().unwrap();
799- registry
800- .metadata
801- .get(&id)
802- .is_some_and(|meta| meta.hibernatable)
803-}
804-
805-fn ws_emit(id: u64, out: WsOut) {
806- let capturing = WS_CAPTURE.with(|c| !c.borrow().is_empty());
807- if capturing && ws_gate_may_hold(id) {
808- WS_CAPTURE.with(|c| c.borrow_mut().last_mut().unwrap().push((id, out)));
809- return;
810- }
811- ws_registry().lock().unwrap().emit(id, out);
812-}
813-
814-/// Flush frames the output gate held: send each to its socket's task. Called
815-/// from the actor thread once the gating write is proved durable.
816-pub fn ws_emit_batch(frames: Vec<(u64, WsOut)>) {
817- let mut registry = ws_registry().lock().unwrap();
818- for (id, out) in frames {
819- registry.emit(id, out);
820- }
821-}
822-
823-/// Break a cell's sockets: the output gate could not prove a write durable, so
824-/// close every socket the cell owns rather than let a client keep a connection
825-/// whose acknowledged effects may not have persisted (a reset DO).
826-pub fn ws_close_scope(scope: &str, code: u16, reason: &str) {
827- tracing::warn!(scope, code, "PROBE close_scope");
828- let mut registry = ws_registry().lock().unwrap();
829- let ids: Vec<u64> = registry
830- .metadata
831- .iter()
832- .filter(|(_, meta)| meta.scope == scope)
833- .map(|(id, _)| *id)
834- .collect();
835- for id in ids {
836- registry.emit(id, WsOut::Close(code, reason.to_string()));
837- }
838-}
839-
840-thread_local! {
841- // JS promise resolvers awaiting an async op, keyed by the op's id.
842- static PROMISES: RefCell<HashMap<u64, v8::Global<v8::PromiseResolver>>> =
843- RefCell::new(HashMap::new());
844- // One outbound HTTP client per JS thread — building it per fetch rebuilds
845- // the TLS stack every call (async-op-hazards.md).
846- static HTTP: reqwest::Client = reqwest::Client::new();
847- static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder()
848- .redirect(reqwest::redirect::Policy::none()).build().unwrap();
849- static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new());
850- static CANCELLED_REQUESTS: RefCell<HashSet<RequestId>> = RefCell::new(HashSet::new());
851-}
852-fn promise_store(id: u64, r: v8::Global<v8::PromiseResolver>) {
853- PROMISES.with(|p| {
854- p.borrow_mut().insert(id, r);
855- });
856-}
857-
858-/// Resolve or reject op `id`'s promise with its outcome.
859-fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) {
860- let g = match PROMISES.with(|p| p.borrow_mut().remove(&id)) {
861- Some(g) => g,
862- None => return,
863- };
864- let r = v8::Local::new(tc, g);
865- match res {
866- Ok(asyncrt::OpOut::Str(v)) => {
867- let s = v8::String::new(tc, &v).unwrap();
868- r.resolve(tc, s.into());
869- }
870- Ok(asyncrt::OpOut::Bytes(b)) => {
871- let v = bytes_value(tc, b);
872- r.resolve(tc, v);
873- }
874- Err(e) => {
875- let s = v8::String::new(tc, &e).unwrap();
876- let ex = v8::Exception::error(tc, s);
877- r.reject(tc, ex);
878- }
879- }
880-}
881-
882-/// Move `bytes` into a `Uint8Array` without copying.
883-fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> {
884- let len = bytes.len();
885- let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();
886- let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);
887- v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into()
888-}
889-
890-fn handler_budget() -> Duration {
891- static BUDGET: OnceLock<Duration> = OnceLock::new();
892- *BUDGET.get_or_init(|| {
893- Duration::from_secs(
894- std::env::var("CELLD_HANDLER_BUDGET_S")
895- .ok()
896- .and_then(|value| value.parse().ok())
897- .filter(|seconds| *seconds > 0)
898- .unwrap_or(300),
899- )
900- })
901-}
902-
903-/// Aborts raised on another thread — an HTTP or service-binding caller
904-/// disconnecting while the target runs in a worker pool. Durable Object aborts
905-/// also arrive as a reentrant `CellJob::AbortFetch` when a cell thread can
906-/// service its own channel; a pool worker is blocked inside its handler, so
907-/// the abort has to be visible from wherever the loop happens to be.
908-///
909-/// The counter keeps the common path to one relaxed atomic load per loop turn:
910-/// with nothing pending, the mutex is never taken.
911-static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> =
912- OnceLock::new();
913-static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
914-
915-fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> {
916- PENDING_ABORTS.get_or_init(Default::default)
917-}
918-
919-/// Mark an in-flight request cancelled from any thread.
920-pub fn abort_request(request_id: RequestId) {
921- if pending_aborts().lock().unwrap().insert(request_id) {
922- PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed);
923- }
924-}
925-
926-fn clear_request_cancellation(request_id: RequestId) {
927- let _ = take_pending_abort(request_id);
928-}
929-
930-fn take_pending_abort(request_id: RequestId) -> bool {
931- if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 {
932- return false;
933- }
934- if pending_aborts().lock().unwrap().remove(&request_id) {
935- PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed);
936- return true;
937- }
938- false
939-}
940-
941-fn take_request_cancellation(request_id: Option<RequestId>) -> bool {
942- request_id.is_some_and(|request_id| {
943- CANCELLED_REQUESTS.with(|requests| requests.borrow_mut().remove(&request_id))
944- || take_pending_abort(request_id)
945- })
946-}
947-
948-enum RunLoopOutcome<T> {
949- Complete(T),
950- RequestCancelled,
951-}
952-
953-/// Drive a promise and apply `on_fulfilled` as soon as it settles. The callback
954-/// may return a composite waitUntil promise after publishing its response.
955-/// Top-level fetches retain only registered waitUntil work; Durable Object
956-/// events additionally drain I/O started by the handler because libraries
957-/// commonly launch that work from synchronous callbacks.
958-///
959-/// Every exit path drops the region and purges unresolved host promises. A
960-/// panicked/aborted op is rejected into JS rather than hanging the isolate.
961-fn run_loop_then<'s, T, F>(
962- tc: &mut v8::PinScope<'s, '_>,
963- promise: v8::Local<v8::Promise>,
964- cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
965- actor_scope: Option<&str>,
966- request_id: Option<RequestId>,
967- drain_spawned_ops: bool,
968- on_fulfilled: F,
969-) -> Result<RunLoopOutcome<T>>
970-where
971- F: FnOnce(
972- &mut v8::PinScope<'s, '_>,
973- v8::Local<'s, v8::Value>,
974- ) -> Result<(T, Option<v8::Local<'s, v8::Promise>>)>,
975-{
976- let mut region: JoinSet<(u64, Result<asyncrt::OpOut, String>)> = JoinSet::new();
977- ws_region_enter();
978- // Paired with `ws_region_exit` on the close path below, which every exit
979- // from this function reaches.
980- struct WsRegionGuard;
981- impl Drop for WsRegionGuard {
982- fn drop(&mut self) {
983- ws_region_exit();
984- }
985- }
986- let _ws_region = WsRegionGuard;
987- let mut idmap: HashMap<tokio::task::Id, u64> = HashMap::new();
988- let started = Instant::now();
989- let budget = handler_budget();
990- let mut on_fulfilled = Some(on_fulfilled);
991- let mut output = None;
992- let mut background = None;
993- let mut request_cancelled = false;
994- // Unknown until the handler first suspends. Cache the deadline so an actor
995- // with pending async I/O does not query SQLite on every 10 ms input-gate
996- // wakeup. Reentrant events invalidate it because they may change the alarm.
997- let mut next_alarm_at: Option<Option<i64>> = None;
998- let result = loop {
999- let mut published_this_turn = false;
1000- if !request_cancelled && take_request_cancellation(request_id) {
1001- request_cancelled = true;
1002- if let Some(id) = request_id {
1003- let _ = abort_incoming_request(tc, id);
1004- }
1005- background = end_event_context(tc)?;
1006- }
1007- for (id, fut) in asyncrt::drain_spawns() {
1008- let h = region.spawn_on(async move { (id, fut.await) }, &asyncrt::op_handle());
1009- idmap.insert(h.id(), id);
1010- }
1011- tc.perform_microtask_checkpoint(); // fire .then chains; they may enqueue ops
1012- if let Some(error) = take_execution_termination(tc) {
1013- break Err(error);
1014- }
1015- for (id, fut) in asyncrt::drain_spawns() {
1016- let h = region.spawn_on(async move { (id, fut.await) }, &asyncrt::op_handle());
1017- idmap.insert(h.id(), id);
1018- }
1019- if !request_cancelled && output.is_none() {
1020- match promise.state() {
1021- v8::PromiseState::Fulfilled => {
1022- let callback = on_fulfilled.take().expect("handler callback used once");
1023- let (value, wait_until) = callback(tc, promise.result(tc))?;
1024- published_this_turn = wait_until.is_some();
1025- output = Some(value);
1026- background = wait_until;
1027- }
1028- v8::PromiseState::Rejected => {
1029- break Err(anyhow!("rejected: {}", reject_reason(tc, promise)))
1030- }
1031- v8::PromiseState::Pending => {}
1032- }
1033- }
1034- // Reentrant jobs are serviced before AND after the response publishes:
1035- // post-response waitUntil work may call back into this cell (A→A), and
1036- // a pending job would otherwise stall until the handler budget.
1037- if let Some(rx) = cell_rx {
1038- let mut serviced_event = false;
1039- while service_reentrant(tc, rx)? {
1040- serviced_event = true;
1041- // Adopt ops the job just enqueued (an AbortFetch's abort
1042- // listener registering waitUntil work, say) BEFORE the next
1043- // job runs: a reentrant dispatch drains the shared spawn
1044- // queue into its own region and aborts the survivors on
1045- // exit, so an op left queued here would be silently killed
1046- // and its promise purged — this event then waits on it
1047- // forever.
1048- for (id, fut) in asyncrt::drain_spawns() {
1049- let h = region.spawn_on(async move { (id, fut.await) }, &asyncrt::op_handle());
1050- idmap.insert(h.id(), id);
1051- }
1052- }
1053- if output.is_none() && !request_cancelled && take_request_cancellation(request_id) {
1054- request_cancelled = true;
1055- if let Some(id) = request_id {
1056- let _ = abort_incoming_request(tc, id);
1057- }
1058- background = end_event_context(tc)?;
1059- }
1060- if serviced_event {
1061- next_alarm_at = None;
1062- }
1063- tc.perform_microtask_checkpoint();
1064- if let Some(error) = take_execution_termination(tc) {
1065- break Err(error);
1066- }
1067- if !request_cancelled && output.is_none() {
1068- match promise.state() {
1069- v8::PromiseState::Fulfilled => {
1070- let callback = on_fulfilled.take().expect("handler callback used once");
1071- let (value, wait_until) = callback(tc, promise.result(tc))?;
1072- published_this_turn = wait_until.is_some();
1073- output = Some(value);
1074- background = wait_until;
1075- }
1076- v8::PromiseState::Rejected => {
1077- break Err(anyhow!("rejected: {}", reject_reason(tc, promise)))
1078- }
1079- v8::PromiseState::Pending => {}
1080- }
1081- }
1082- }
1083- // Response marshalling can start a bounded JS-to-host body pump and
1084- // register it with waitUntil. Drive the pump once and move its native
1085- // ops into this event region before checking whether the region is
1086- // empty. Pending handlers pay only the branch above.
1087- if published_this_turn {
1088- tc.perform_microtask_checkpoint();
1089- if let Some(error) = take_execution_termination(tc) {
1090- break Err(error);
1091- }
1092- for (id, fut) in asyncrt::drain_spawns() {
1093- let h = region.spawn_on(async move { (id, fut.await) }, &asyncrt::op_handle());
1094- idmap.insert(h.id(), id);
1095- }
1096- }
1097- if request_cancelled || output.is_some() {
1098- let event_done = match background {
1099- None => true,
1100- Some(wait_until) => match wait_until.state() {
1101- v8::PromiseState::Fulfilled => true,
1102- v8::PromiseState::Rejected => {
1103- tracing::warn!(
1104- error = %reject_reason(tc, wait_until),
1105- "waitUntil aggregate rejected",
1106- );
1107- true
1108- }
1109- v8::PromiseState::Pending => false,
1110- },
1111- };
1112- if event_done && (request_cancelled || !drain_spawned_ops || region.is_empty()) {
1113- if request_cancelled {
1114- break Ok(RunLoopOutcome::RequestCancelled);
1115- }
1116- break Ok(RunLoopOutcome::Complete(output.take().unwrap()));
1117- }
1118- }
1119- if !request_cancelled && output.is_none() {
1120- if let Some(scope) = actor_scope {
1121- let alarm_at = *next_alarm_at.get_or_insert_with(|| storage::get_alarm(scope));
1122- if alarm_at.is_some_and(|alarm_at| alarm_at <= unix_now_ms()) {
1123- service_due_alarm(tc, scope, cell_rx.expect("actor events have a receiver"))?;
1124- next_alarm_at = None;
1125- continue;
1126- }
1127- }
1128- }
1129- if region.is_empty() {
1130- if request_cancelled {
1131- tracing::warn!("request-cancellation waitUntil stalled with no pending op");
1132- break Ok(RunLoopOutcome::RequestCancelled);
1133- }
1134- if output.is_none() {
1135- if let (Some(rx), Some(Some(alarm_at))) = (cell_rx, next_alarm_at) {
1136- let elapsed = started.elapsed();
1137- if elapsed >= budget {
1138- break Err(anyhow!("handler exceeded {}s budget", budget.as_secs()));
1139- }
1140- let until_alarm =
1141- Duration::from_millis(alarm_at.saturating_sub(unix_now_ms()).max(0) as u64);
1142- let wait = (budget - elapsed).min(until_alarm);
1143- match rx.recv_timeout(wait) {
1144- Ok(job) => {
1145- if !handle_reentrant_job(tc, rx, job)? {
1146- break Err(anyhow!("cell shutting down"));
1147- }
1148- next_alarm_at = None;
1149- }
1150- Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
1151- Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
1152- break Err(anyhow!("cell channel disconnected"));
1153- }
1154- }
1155- continue;
1156- }
1157- }
1158- break match output.take() {
1159- Some(_) => Err(anyhow!("waitUntil stalled with no pending op")),
1160- None => Err(anyhow!("handler stalled: awaited work with no pending op")),
1161- };
1162- }
1163- let elapsed = started.elapsed();
1164- if elapsed >= budget {
1165- if request_cancelled {
1166- tracing::warn!("request-cancellation waitUntil exceeded handler budget");
1167- break Ok(RunLoopOutcome::RequestCancelled);
1168- }
1169- break Err(anyhow!("handler exceeded {}s budget", budget.as_secs()));
1170- }
1171- // block until one op completes (or the remaining budget elapses). The
1172- // timeout must be built INSIDE the runtime context, hence the async {}.
1173- let remaining = budget - elapsed;
1174- // An abortable ingress or service-binding request has to notice a
1175- // cancellation raised on another thread, so its wait is bounded the
1176- // same way an actor's is. Non-abortable internal fetches retain the
1177- // uncapped wait.
1178- let mut wait = if cell_rx.is_some() || request_id.is_some() {
1179- remaining.min(Duration::from_millis(10))
1180- } else {
1181- remaining
1182- };
1183- if let Some(Some(alarm_at)) = next_alarm_at {
1184- wait = wait.min(Duration::from_millis(
1185- alarm_at.saturating_sub(unix_now_ms()).max(0) as u64,
1186- ));
1187- }
1188- let joined = asyncrt::block_on(async {
1189- tokio::time::timeout(wait, region.join_next_with_id()).await
1190- });
1191- match joined {
1192- Ok(Some(Ok((tid, (id, res))))) => {
1193- idmap.remove(&tid);
1194- resolve_res(tc, id, res);
1195- next_alarm_at = None;
1196- }
1197- Ok(Some(Err(je))) => {
1198- // op panicked/aborted → reject its promise
1199- if let Some(id) = idmap.remove(&je.id()) {
1200- resolve_res(tc, id, Err("op aborted".into()));
1201- next_alarm_at = None;
1202- }
1203- }
1204- Ok(None) => {} // region drained concurrently; loop re-checks
1205- Err(_) if cell_rx.is_some() || request_id.is_some() => continue,
1206- Err(_) => break Err(anyhow!("handler exceeded {}s budget", budget.as_secs())),
1207- }
1208- };
1209- // region close: `region` drops here (aborts survivors); purge resolvers for
1210- // anything still pending or enqueued-but-unspawned so PROMISES can't leak.
1211- for id in idmap.values() {
1212- PROMISES.with(|p| {
1213- p.borrow_mut().remove(id);
1214- });
1215- }
1216- for (id, _) in asyncrt::drain_spawns() {
1217- PROMISES.with(|p| {
1218- p.borrow_mut().remove(&id);
1219- });
1220- }
1221- result
1222-}
1223-
1224-fn run_loop<'s>(
1225- tc: &mut v8::PinScope<'s, '_>,
1226- promise: v8::Local<v8::Promise>,
1227- cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
1228-) -> Result<v8::Local<'s, v8::Value>> {
1229- match run_loop_then(tc, promise, cell_rx, None, None, false, |_tc, value| {
1230- Ok((value, None))
1231- })? {
1232- RunLoopOutcome::Complete(value) => Ok(value),
1233- RunLoopOutcome::RequestCancelled => Err(anyhow!("The client has disconnected")),
1234- }
1235-}
1236-
1237-fn resolved_promise<'s>(
1238- tc: &mut v8::PinScope<'s, '_>,
1239- value: v8::Local<'s, v8::Value>,
1240-) -> Result<v8::Local<'s, v8::Promise>> {
1241- let resolver =
1242- v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?;
1243- resolver.resolve(tc, value);
1244- Ok(resolver.get_promise(tc))
1245-}
1246-
1247-/// Publish a fetch response when the handler settles, then keep driving the
1248-/// event region so waitUntil work can complete without delaying headers or a
1249-/// streaming body.
1250-fn complete_fetch_event<'s>(
1251- tc: &mut v8::PinScope<'s, '_>,
1252- ret: v8::Local<'s, v8::Value>,
1253- cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
1254- critical_scope: Option<&str>,
1255- // The cell's committed-write position sampled before the handler ran. The
1256- // response's `write_position` is set only if the handler advanced it, so
1257- // the output gate sees a per-request write and ignores celld's own
1258- // activation-time writes (the DO actor name, alarm bookkeeping).
1259- writes_before: Option<u64>,
1260- request_id: Option<RequestId>,
1261- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
1262-) {
1263- let promise = match ret.try_cast::<v8::Promise>() {
1264- Ok(promise) => Ok(promise),
1265- Err(_) => resolved_promise(tc, ret),
1266- };
1267- let mut reply = Some(reply);
1268- let result = promise.and_then(|promise| {
1269- run_loop_then(
1270- tc,
1271- promise,
1272- cell_rx,
1273- critical_scope,
1274- request_id,
1275- false,
1276- |tc, value| {
1277- if let Some(error) = critical_scope.and_then(storage::sql_critical_error) {
1278- return Err(anyhow!(error));
1279- }
1280- let mut response = read_response(tc, value, cell_rx)?;
1281- // Gate on durability only if this handler advanced the cell's
1282- // committed-write position past where it was before the handler
1283- // ran -- a per-request write, not celld's activation writes.
1284- response.write_position = match (
1285- writes_before,
1286- critical_scope.and_then(storage::write_position),
1287- ) {
1288- (Some(before), Some(after)) if after > before => Some(after),
1289- _ => None,
1290- };
1291- let wait_until = end_event_context(tc)?;
1292- if let Some(reply) = reply.take() {
1293- let _ = reply.send(Ok(response));
1294- }
1295- Ok(((), wait_until))
1296- },
1297- )
1298- });
1299- let result = match critical_scope.and_then(storage::sql_critical_error) {
1300- Some(error) => Err(anyhow!(error)),
1301- None => result,
1302- };
1303- match result {
1304- Ok(RunLoopOutcome::Complete(())) => {}
1305- Ok(RunLoopOutcome::RequestCancelled) => {
1306- if let Some(reply) = reply.take() {
1307- let _ = reply.send(Err(anyhow!("The client has disconnected")));
1308- }
1309- }
1310- Err(error) => {
1311- let _ = end_event_context(tc);
1312- if let Some(reply) = reply.take() {
1313- let _ = reply.send(Err(error));
1314- } else {
1315- tracing::warn!(%error, "post-response event work failed");
1316- }
1317- }
1318- }
1319-}
1320-
1321-fn run_event_value<'s>(
1322- tc: &mut v8::PinScope<'s, '_>,
1323- ret: v8::Local<'s, v8::Value>,
1324- cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
1325- actor_scope: Option<&str>,
1326- request_id: Option<RequestId>,
1327-) -> Result<v8::Local<'s, v8::Value>> {
1328- let promise = match ret.try_cast::<v8::Promise>() {
1329- Ok(promise) => promise,
1330- Err(_) => resolved_promise(tc, ret)?,
1331- };
1332- let result = run_loop_then(
1333- tc,
1334- promise,
1335- cell_rx,
1336- actor_scope,
1337- request_id,
1338- true,
1339- |tc, value| Ok((value, end_event_context(tc)?)),
1340- );
1341- match result {
1342- Ok(RunLoopOutcome::Complete(value)) => Ok(value),
1343- Ok(RunLoopOutcome::RequestCancelled) => Err(anyhow!("The client has disconnected")),
1344- Err(error) => {
1345- let _ = end_event_context(tc);
1346- Err(error)
1347- }
1348- }
1349-}
1350-
1351-fn handle_reentrant_job(
1352- tc: &mut v8::PinScope,
1353- rx: &std::sync::mpsc::Receiver<CellJob>,
1354- job: CellJob,
1355-) -> Result<bool> {
1356- match job {
1357- CellJob::Fetch {
1358- request_id,
1359- scope,
1360- name,
1361- url,
1362- method,
1363- body,
1364- headers,
1365- reply,
1366- } => {
1367- let result = register_actor_name(tc, &scope, name.as_deref()).and_then(|()| {
1368- call_dispatch_to(
1369- tc,
1370- &scope,
1371- FetchRequest {
1372- url: &url,
1373- method: &method,
1374- body: &body,
1375- headers: &headers,
1376- request_id,
1377- },
1378- rx,
1379- )
1380- });
1381- let _ = reply.send(result);
1382- }
1383- CellJob::Rpc {
1384- scope,
1385- name,
1386- method,
1387- args,
1388- reply,
1389- } => {
1390- let result = register_actor_name(tc, &scope, name.as_deref())
1391- .and_then(|()| call_dispatch_rpc(tc, &scope, &method, args, rx));
1392- let _ = reply.send(result);
1393- }
1394- CellJob::WsOpen {
1395- scope,
1396- ws_id,
1397- protocol,
1398- reply,
1399- } => {
1400- let result = call_dispatch_ws_open(tc, &scope, ws_id, &protocol, rx);
1401- let _ = reply.send(result);
1402- }
1403- CellJob::WsMessage {
1404- scope,
1405- ws_id,
1406- data,
1407- reply,
1408- } => {
1409- let result = call_dispatch_ws(tc, &scope, ws_id, data, rx);
1410- let _ = reply.send(result);
1411- }
1412- CellJob::WsClosed {
1413- scope,
1414- ws_id,
1415- code,
1416- reason,
1417- was_clean,
1418- reply,
1419- } => {
1420- let result = call_dispatch_ws_closed(tc, &scope, ws_id, code, &reason, was_clean, rx);
1421- let _ = reply.send(result);
1422- }
1423- // Two top-level Worker events cannot run concurrently in one isolate.
1424- // The idle reservation normally prevents this path, but a queued job
1425- // can be observed by a nested actor event under enough overlap. Move
1426- // it to the stateless pool; any call back to this cell then arrives as
1427- // an ordinary reentrant CellJob::Fetch, which is supported above.
1428- CellJob::WorkerFetch {
1429- request_id,
1430- url,
1431- method,
1432- body,
1433- headers,
1434- inline_activity: _inline_activity,
1435- fallback_workers,
1436- reply,
1437- } => {
1438- // The reentrant pump implies this isolate is running an actor event,
1439- // so the sans-IO routing is fixed: a Worker event never runs nested
1440- // — reschedule to the pool carrying the request identity.
1441- debug_assert_eq!(
1442- celld_logic::schedule::route_worker_fetch(true),
1443- celld_logic::schedule::Route::RescheduleToPool,
1444- );
1445- let _ = fallback_workers.send(crate::WorkerJob::Fetch {
1446- queued_at: Instant::now(),
1447- url,
1448- method,
1449- body,
1450- headers,
1451- request_id: Some(request_id),
1452- reply,
1453- });
1454- }
1455- CellJob::AbortFetch { request_id } => match abort_incoming_request(tc, request_id) {
1456- Ok(true) => {
1457- CANCELLED_REQUESTS.with(|requests| {
1458- requests.borrow_mut().insert(request_id);
1459- });
1460- }
1461- Ok(false) => {}
1462- Err(error) => {
1463- tracing::warn!(%error, request_id, "incoming request abort listener failed");
1464- }
1465- },
1466- CellJob::Alarm {
1467- scope,
1468- scheduled_ms,
1469- reply,
1470- } => {
1471- let now = unix_now_ms();
1472- let result = if now < scheduled_ms {
1473- Err(anyhow!("alarm dispatched before its deadline"))
1474- } else {
1475- service_due_alarm(tc, &scope, rx).map(|()| storage::get_alarm(&scope))
1476- };
1477- let _ = reply.send(result);
1478- }
1479- CellJob::Shutdown => return Ok(false),
1480- }
1481- Ok(true)
1482-}
1483-
1484-fn abort_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) -> Result<bool> {
1485- let global = tc.get_current_context().global(tc);
1486- let key = v8::String::new(tc, "__abortIncomingRequest").unwrap();
1487- let function: v8::Local<v8::Function> = global
1488- .get(tc, key.into())
1489- .ok_or_else(|| anyhow!("no __abortIncomingRequest"))?
1490- .try_into()
1491- .map_err(|_| anyhow!("__abortIncomingRequest is not a function"))?;
1492- let request_id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
1493- let recv = v8::undefined(tc).into();
1494- let result = function
1495- .call(tc, recv, &[request_id.into()])
1496- .ok_or_else(|| anyhow!("__abortIncomingRequest threw"))?;
1497- Ok(result.boolean_value(tc))
1498-}
1499-
1500-fn service_reentrant(
1501- tc: &mut v8::PinScope,
1502- rx: &std::sync::mpsc::Receiver<CellJob>,
1503-) -> Result<bool> {
1504- let job = match rx.try_recv() {
1505- Ok(job) => job,
1506- Err(std::sync::mpsc::TryRecvError::Empty) => return Ok(false),
1507- Err(std::sync::mpsc::TryRecvError::Disconnected) => return Ok(false),
1508- };
1509- handle_reentrant_job(tc, rx, job)
1510-}
1511-
1512-fn unix_now_ms() -> i64 {
1513- std::time::SystemTime::now()
1514- .duration_since(std::time::UNIX_EPOCH)
1515- .unwrap_or_default()
1516- .as_millis()
1517- .min(i64::MAX as u128) as i64
1518-}
1519-
1520-fn call_fire_alarm(
1521- tc: &mut v8::PinScope,
1522- scope: &str,
1523- scheduled_time: i64,
1524- retry: i64,
1525- rx: &std::sync::mpsc::Receiver<CellJob>,
1526-) -> std::result::Result<(), AlarmRunError> {
1527- let context = tc.get_current_context();
1528- let global = context.global(tc);
1529- let key = v8::String::new(tc, "__fireAlarm").unwrap();
1530- let function: v8::Local<v8::Function> = global
1531- .get(tc, key.into())
1532- .ok_or_else(|| AlarmRunError::infrastructure(anyhow!("no __fireAlarm")))?
1533- .try_into()
1534- .map_err(|_| AlarmRunError::infrastructure(anyhow!("__fireAlarm is not a function")))?;
1535- let scope = v8::String::new(tc, scope).unwrap();
1536- let scheduled_time = v8::Number::new(tc, scheduled_time as f64);
1537- let retry = v8::Number::new(tc, retry as f64);
1538- let recv = v8::undefined(tc).into();
1539- begin_event_context(tc).map_err(AlarmRunError::infrastructure)?;
1540- let Some(ret) = function.call(
1541- tc,
1542- recv,
1543- &[scope.into(), scheduled_time.into(), retry.into()],
1544- ) else {
1545- let _ = end_event_context(tc);
1546- return Err(AlarmRunError::user(anyhow!("alarm threw")));
1547- };
1548- run_event_value(tc, ret, Some(rx), None, None).map_err(AlarmRunError::user)?;
1549- Ok(())
1550-}
1551-
1552-fn service_due_alarm(
1553- tc: &mut v8::PinScope,
1554- scope: &str,
1555- rx: &std::sync::mpsc::Receiver<CellJob>,
1556-) -> Result<()> {
1557- let now = unix_now_ms();
1558- let Some((scheduled_time, retry)) = storage::due_alarm_entry(scope, now) else {
1559- return Ok(());
1560- };
1561- storage::begin_alarm_handler(scope, scheduled_time);
1562- match call_fire_alarm(tc, scope, scheduled_time, retry, rx) {
1563- Ok(()) => {
1564- storage::finish_alarm_handler(scope, true, now);
1565- tracing::info!(cell = %scope, scheduled_time, "alarm fired reentrantly");
1566- }
1567- Err(error) => {
1568- let counts_against_limit = error.counts_against_limit();
1569- storage::finish_alarm_handler_with_retry_policy(
1570- scope,
1571- false,
1572- now,
1573- counts_against_limit,
1574- );
1575- tracing::warn!(
1576- %error,
1577- cell = %scope,
1578- scheduled_time,
1579- counts_against_limit,
1580- "reentrant alarm failed; backing off",
1581- );
1582- }
1583- }
1584- Ok(())
1585-}
1586-
1587-fn call_dispatch_to(
1588- tc: &mut v8::PinScope,
1589- scope: &str,
1590- request: FetchRequest<'_>,
1591- rx: &std::sync::mpsc::Receiver<CellJob>,
1592-) -> Result<HttpResponse> {
1593- let context = tc.get_current_context();
1594- let global = context.global(tc);
1595- let key = v8::String::new(tc, "__dispatchTo").unwrap();
1596- let f: v8::Local<v8::Function> = global
1597- .get(tc, key.into())
1598- .ok_or_else(|| anyhow!("no __dispatchTo"))?
1599- .try_into()
1600- .map_err(|_| anyhow!("not fn"))?;
1601- let sc = v8::String::new(tc, scope).unwrap();
1602- let u = v8::String::new(tc, request.url).unwrap();
1603- let m = v8::String::new(tc, request.method).unwrap();
1604- let b = bytes_value(tc, request.body.to_vec());
1605- let h = v8::String::new(tc, &serde_json::to_string(request.headers)?).unwrap();
1606- let request_id_value: v8::Local<v8::Value> = match request.request_id {
1607- Some(request_id) => v8::String::new(tc, &request_id_string(request_id))
1608- .unwrap()
1609- .into(),
1610- None => v8::null(tc).into(),
1611- };
1612- let recv = v8::undefined(tc).into();
1613- begin_event_context(tc)?;
1614- let Some(ret) = f.call(
1615- tc,
1616- recv,
1617- &[sc.into(), u.into(), m.into(), b, h.into(), request_id_value],
1618- ) else {
1619- let _ = end_event_context(tc);
1620- return Err(anyhow!("dispatchTo threw"));
1621- };
1622- let ret = run_event_value(tc, ret, Some(rx), Some(scope), request.request_id);
1623- if let Some(error) = storage::sql_critical_error(scope) {
1624- return Err(anyhow!(error));
1625- }
1626- let ret = ret?;
1627- read_response(tc, ret, Some(rx))
1628-}
1629-
1630-/// An `RpcData` payload as the JS argument `__dispatchRpc` expects: a string
1631-/// for the JSON flavor, a `Uint8Array` for structured clone.
1632-fn rpc_data_value<'s>(scope: &mut v8::PinScope<'s, '_>, data: RpcData) -> v8::Local<'s, v8::Value> {
1633- match data {
1634- RpcData::Json(json) => v8::String::new(scope, &json).unwrap().into(),
1635- RpcData::V8(bytes) => bytes_value(scope, bytes),
1636- }
1637-}
1638-
1639-/// The inverse: `__dispatchRpc` answers in the flavor it was asked in.
1640-fn rpc_data_ret(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> RpcData {
1641- match view_bytes(ret) {
1642- Some(bytes) => RpcData::V8(bytes),
1643- None => RpcData::Json(ret.to_rust_string_lossy(scope)),
1644- }
1645-}
1646-
1647-fn call_dispatch_rpc(
1648- tc: &mut v8::PinScope,
1649- scope: &str,
1650- method: &str,
1651- args: RpcData,
1652- rx: &std::sync::mpsc::Receiver<CellJob>,
1653-) -> Result<RpcData> {
1654- let context = tc.get_current_context();
1655- let global = context.global(tc);
1656- let key = v8::String::new(tc, "__dispatchRpc").unwrap();
1657- let f: v8::Local<v8::Function> = global
1658- .get(tc, key.into())
1659- .ok_or_else(|| anyhow!("no __dispatchRpc"))?
1660- .try_into()
1661- .map_err(|_| anyhow!("not fn"))?;
1662- let sc = v8::String::new(tc, scope).unwrap();
1663- let method = v8::String::new(tc, method).unwrap();
1664- let args = rpc_data_value(tc, args);
1665- let recv = v8::undefined(tc).into();
1666- begin_event_context(tc)?;
1667- let Some(ret) = f.call(tc, recv, &[sc.into(), method.into(), args]) else {
1668- let _ = end_event_context(tc);
1669- return Err(anyhow!("dispatchRpc threw"));
1670- };
1671- let ret = run_event_value(tc, ret, Some(rx), Some(scope), None);
1672- if let Some(error) = storage::sql_critical_error(scope) {
1673- return Err(anyhow!(error));
1674- }
1675- let ret = ret?;
1676- Ok(rpc_data_ret(tc, ret))
1677-}
1678-
1679-fn call_dispatch_ws(
1680- tc: &mut v8::PinScope,
1681- scope: &str,
1682- ws_id: u64,
1683- data: WsIn,
1684- rx: &std::sync::mpsc::Receiver<CellJob>,
1685-) -> Result<WsDispatch> {
1686- let context = tc.get_current_context();
1687- let global = context.global(tc);
1688- let (key, data) = match data {
1689- WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()),
1690- WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)),
1691- };
1692- let key = v8::String::new(tc, key).unwrap();
1693- let f: v8::Local<v8::Function> = global
1694- .get(tc, key.into())
1695- .ok_or_else(|| anyhow!("no WebSocket message dispatcher"))?
1696- .try_into()
1697- .map_err(|_| anyhow!("not fn"))?;
1698- let sc = v8::String::new(tc, scope).unwrap();
1699- let id = v8::Number::new(tc, ws_id as f64);
1700- let recv = v8::undefined(tc).into();
1701- // Sample the committed-write position and capture outbound frames across the
1702- // handler: the output gate holds a message's frames until its write proves
1703- // durable (the same delta discipline as the fetch path).
1704- let before = storage::write_position(scope);
1705- ws_capture_begin();
1706- begin_event_context(tc)?;
1707- let Some(ret) = f.call(tc, recv, &[sc.into(), id.into(), data]) else {
1708- let _ = end_event_context(tc);
1709- let _ = ws_capture_take();
1710- return Err(anyhow!("WebSocket message dispatch threw"));
1711- };
1712- let result = run_event_value(tc, ret, Some(rx), Some(scope), None);
1713- let frames = ws_capture_take();
1714- if let Some(error) = storage::sql_critical_error(scope) {
1715- return Err(anyhow!(error));
1716- }
1717- result?;
1718- let write_position = match (before, storage::write_position(scope)) {
1719- (Some(before), Some(after)) if after > before => Some(after),
1720- _ => None,
1721- };
1722- // A handler that did not write has nothing to hold its frames behind, so
1723- // send them here rather than shipping them to the actor and back. That
1724- // detour is not free: it races the socket's own teardown, and a frame that
1725- // arrives after `ws_unregister` is discarded -- the handler's send silently
1726- // never happens. Only a write's frames take the barrier path.
1727- if write_position.is_none() {
1728- ws_emit_batch(frames);
1729- return Ok(WsDispatch {
1730- frames: Vec::new(),
1731- write_position,
1732- });
1733- }
1734- Ok(WsDispatch {
1735- frames,
1736- write_position,
1737- })
1738-}
1739-
1740-fn call_dispatch_ws_open(
1741- tc: &mut v8::PinScope,
1742- scope: &str,
1743- ws_id: u64,
1744- protocol: &str,
1745- rx: &std::sync::mpsc::Receiver<CellJob>,
1746-) -> Result<()> {
1747- let context = tc.get_current_context();
1748- let global = context.global(tc);
1749- let key = v8::String::new(tc, "__wsOpen").unwrap();
1750- let f: v8::Local<v8::Function> = global
1751- .get(tc, key.into())
1752- .ok_or_else(|| anyhow!("no __wsOpen"))?
1753- .try_into()
1754- .map_err(|_| anyhow!("not fn"))?;
1755- let sc = v8::String::new(tc, scope).unwrap();
1756- let id = v8::Number::new(tc, ws_id as f64);
1757- let protocol = v8::String::new(tc, protocol).unwrap();
1758- let recv = v8::undefined(tc).into();
1759- begin_event_context(tc)?;
1760- let Some(ret) = f.call(tc, recv, &[sc.into(), id.into(), protocol.into()]) else {
1761- let _ = end_event_context(tc);
1762- return Err(anyhow!("wsOpen threw"));
1763- };
1764- run_event_value(tc, ret, Some(rx), Some(scope), None)?;
1765- Ok(())
1766-}
1767-
1768-fn call_dispatch_ws_closed(
1769- tc: &mut v8::PinScope,
1770- scope: &str,
1771- ws_id: u64,
1772- code: u16,
1773- reason: &str,
1774- was_clean: bool,
1775- rx: &std::sync::mpsc::Receiver<CellJob>,
1776-) -> Result<()> {
1777- let context = tc.get_current_context();
1778- let global = context.global(tc);
1779- let key = v8::String::new(tc, "__wsClosed").unwrap();
1780- let f: v8::Local<v8::Function> = global
1781- .get(tc, key.into())
1782- .ok_or_else(|| anyhow!("no __wsClosed"))?
1783- .try_into()
1784- .map_err(|_| anyhow!("not fn"))?;
1785- let sc = v8::String::new(tc, scope).unwrap();
1786- let id = v8::Number::new(tc, ws_id as f64);
1787- let code = v8::Number::new(tc, f64::from(code));
1788- let reason = v8::String::new(tc, reason).unwrap();
1789- let was_clean = v8::Boolean::new(tc, was_clean);
1790- let recv = v8::undefined(tc).into();
1791- begin_event_context(tc)?;
1792- let Some(ret) = f.call(
1793- tc,
1794- recv,
1795- &[
1796- sc.into(),
1797- id.into(),
1798- code.into(),
1799- reason.into(),
1800- was_clean.into(),
1801- ],
1802- ) else {
1803- let _ = end_event_context(tc);
1804- return Err(anyhow!("wsClosed threw"));
1805- };
1806- let result = run_event_value(tc, ret, Some(rx), Some(scope), None);
1807- if let Some(error) = storage::sql_critical_error(scope) {
1808- return Err(anyhow!(error));
1809- }
1810- result?;
1811- Ok(())
1812-}
1813-
1814-/// The rejection reason of a settled-rejected promise, with a little stack.
1815-fn reject_reason(tc: &mut v8::PinScope, p: v8::Local<v8::Promise>) -> String {
1816- let r = p.result(tc);
1817- let msg = r.to_rust_string_lossy(tc);
1818- let stk = r
1819- .to_object(tc)
1820- .and_then(|o| {
1821- let k = v8::String::new(tc, "stack")?;
1822- o.get(tc, k.into())
1823- })
1824- .map(|s| s.to_rust_string_lossy(tc))
1825- .unwrap_or_default();
1826- let tail = stk
1827- .lines()
1828- .skip(1)
1829- .take(3)
1830- .map(|l| l.trim())
1831- .collect::<Vec<_>>()
1832- .join(" <- ");
1833- if tail.is_empty() {
1834- msg
1835- } else {
1836- format!("{msg} [{tail}]")
1837- }
1838-}
1839-
1840-pub struct Engine;
1841-impl Engine {
1842- pub fn init() {
1843- // No `v8::icu::set_common_data_78` call: the rusty_v8 152 prebuilt
1844- // statically links the complete ICU data (full locale tables and
1845- // regex property-of-strings, e.g. /\p{RGI_Emoji}/v — verified
1846- // empirically), so overriding it with an embedded icudtl.dat only
1847- // duplicated 10.8 MB in the binary. A test pins that coverage, so a
1848- // future v8 bump that reduces the builtin data fails rather than
1849- // silently narrowing it; the fix would be to re-embed rusty_v8's
1850- // `third_party/icu/common/icudtl.dat`, 16-byte-aligned.
1851- let platform = v8::new_default_platform(0, false).make_shared();
1852- v8::V8::initialize_platform(platform);
1853- v8::V8::initialize();
1854- }
1855-}
1856-
1857-/// Per-worker compatibility switches, derived from the manifest's
1858-/// compatibility date and flags (Workerd compatibility-date.capnp). `Default`
1859-/// is every switch off; production derives real values in `main`.
1860-#[derive(Clone, Copy, Default)]
1861-pub struct Compat {
1862- pub delete_all_deletes_alarm: bool,
1863- /// `js_rpc`: RPC on a Durable Object class that does not extend
1864- /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()).
1865- pub js_rpc: bool,
1866- /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`,
1867- /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/
1868- /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher).
1869- pub fetcher_get_put_delete: bool,
1870- /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and
1871- /// a binary message arrives as a `Blob`, per the WHATWG default. Without
1872- /// it celld keeps the historical `"arraybuffer"`.
1873- pub websocket_standard_binary_type: bool,
1874-}
1875-
1876-pub struct WorkerConfig {
1877- src: String,
1878- script_name: String,
1879- do_classes: Vec<String>,
1880- bindings: Vec<(String, String)>,
1881- r2_bindings: Vec<String>,
1882- ai_binding: Option<String>,
1883- vars: Vec<(String, String)>,
1884- node: String,
1885- text: Vec<(String, String)>,
1886- compat: Compat,
1887- /// `[[services]]`: (binding name, target script, optional entrypoint).
1888- /// The target runs in this process; see [[service-bindings]].
1889- services: Vec<(String, String, Option<String>)>,
1890- asset_binding: Option<String>,
1891- /// `env` name of the Worker Loader binding, if this Worker may spawn
1892- /// dynamic isolates.
1893- loader_binding: Option<String>,
1894- /// Ambient outbound authority. Loaded workers may be denied.
1895- egress: EgressPolicy,
1896- /// Extra `env` values a loaded worker was handed, as a JSON object string
1897- /// merged onto its `env`. Loader-only; empty for normal workers.
1898- loader_env: Option<String>,
1899- /// A loaded worker's non-main modules as (name, source), so the main module
1900- /// can import siblings. Loader-only; empty for normal single-file bundles.
1901- loader_modules: Vec<(String, String)>,
1902-}
1903-
1904-pub struct WorkerConfigOptions {
1905- pub src: String,
1906- pub script_name: String,
1907- pub do_classes: Vec<String>,
1908- pub bindings: Vec<(String, String)>,
1909- pub r2_bindings: Vec<String>,
1910- pub ai_binding: Option<String>,
1911- pub vars: Vec<(String, String)>,
1912- pub node: String,
1913- pub text: Vec<(String, String)>,
1914- pub compat: Compat,
1915-}
1916-
1917-impl WorkerConfig {
1918- pub fn new(options: WorkerConfigOptions) -> Self {
1919- let WorkerConfigOptions {
1920- src,
1921- script_name,
1922- do_classes,
1923- bindings,
1924- r2_bindings,
1925- ai_binding,
1926- vars,
1927- node,
1928- text,
1929- compat,
1930- } = options;
1931- Self {
1932- src,
1933- script_name,
1934- do_classes,
1935- bindings,
1936- r2_bindings,
1937- ai_binding,
1938- vars,
1939- node,
1940- text,
1941- compat,
1942- services: Vec::new(),
1943- asset_binding: None,
1944- loader_binding: None,
1945- egress: EgressPolicy::Allow,
1946- loader_env: None,
1947- loader_modules: Vec::new(),
1948- }
1949- }
1950-
1951- /// Grant this Worker a Worker Loader binding at `env` name `binding`.
1952- pub fn with_loader(mut self, binding: Option<String>) -> Self {
1953- self.loader_binding = binding;
1954- self
1955- }
1956-
1957- /// Set this Worker's ambient outbound authority (loaded workers only).
1958- fn with_egress(mut self, egress: EgressPolicy) -> Self {
1959- self.egress = egress;
1960- self
1961- }
1962-
1963- /// Merge `env` (a JSON object string) onto a loaded worker's `env`.
1964- fn with_loader_env(mut self, env: Option<String>) -> Self {
1965- self.loader_env = env;
1966- self
1967- }
1968-
1969- /// Non-main modules a loaded worker's main module may import.
1970- fn with_loader_modules(mut self, modules: Vec<(String, String)>) -> Self {
1971- self.loader_modules = modules;
1972- self
1973- }
1974-
1975- /// Declare the service bindings this Worker may call.
1976- pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self {
1977- self.services = services;
1978- self
1979- }
1980-
1981- pub fn with_asset_binding(mut self, binding: Option<String>) -> Self {
1982- self.asset_binding = binding;
1983- self
1984- }
1985-}
1986-
1987-pub struct Worker {
1988- inner: Option<WorkerIsolate>,
1989- config: Arc<WorkerConfig>,
1990- owned: Arc<[String]>,
1991-}
1992-
1993-pub struct WorkerIsolate {
1994- isolate: v8::OwnedIsolate,
1995- context: v8::Global<v8::Context>,
1996- fetch: v8::Global<v8::Function>,
1997- original_heap_limit: usize,
1998- runtime_state: Arc<ActorRuntimeState>,
1999-}
2000-
2001-impl std::ops::Deref for Worker {
2002- type Target = WorkerIsolate;
2003-
2004- fn deref(&self) -> &Self::Target {
2005- self.inner.as_ref().expect("Worker isolate unavailable")
2006- }
2007-}
2008-
2009-impl std::ops::DerefMut for Worker {
2010- fn deref_mut(&mut self) -> &mut Self::Target {
2011- self.inner.as_mut().expect("Worker isolate unavailable")
2012- }
2013-}
2014-
2015-const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024;
2016-const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024;
2017-
2018-#[derive(Default)]
2019-struct HeapLimitState {
2020- excessively_exceeded: AtomicBool,
2021-}
2022-
2023-type SerializedPut = (String, Vec<u8>);
2024-type PendingPuts = HashMap<String, Vec<SerializedPut>>;
2025-
2026-/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a
2027-/// Worker Loader can hand a loaded worker `Deny` (globalOutbound: null) so its
2028-/// global `fetch()` throws and it must reach the world through `env`
2029-/// capabilities.
2030-#[derive(Clone, Copy, Default, PartialEq)]
2031-enum EgressPolicy {
2032- #[default]
2033- Allow,
2034- Deny,
2035-}
2036-
2037-#[derive(Default)]
2038-struct ActorRuntimeState {
2039- termination: std::sync::Mutex<Option<ExecutionTermination>>,
2040- pending_puts: std::sync::Mutex<PendingPuts>,
2041- worker_exit_requested: AtomicBool,
2042- egress: EgressPolicy,
2043-}
2044-
2045-struct ExecutionTermination {
2046- error: String,
2047- actor_scope: Option<String>,
2048-}
2049-
2050-fn finish_terminated_actor_event(scope: &mut v8::PinScope, actor_scope: &str) {
2051- let global = scope.get_current_context().global(scope);
2052- let key = v8::String::new(scope, "__endTerminatedActorEvent").unwrap();
2053- let Some(value) = global.get(scope, key.into()) else {
2054- return;
2055- };
2056- let Ok(function) = v8::Local::<v8::Function>::try_from(value) else {
2057- return;
2058- };
2059- let actor_scope = v8::String::new(scope, actor_scope).unwrap();
2060- let recv = v8::undefined(scope).into();
2061- let _ = function.call(scope, recv, &[actor_scope.into()]);
2062-}
2063-
2064-fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> {
2065- let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned();
2066- let termination = state.and_then(|state| state.termination.lock().ok()?.take());
2067- let is_terminating = scope.is_execution_terminating();
2068- if termination.is_some() || is_terminating {
2069- scope.cancel_terminate_execution();
2070- }
2071- if let Some(termination) = termination {
2072- if let Some(actor_scope) = termination.actor_scope {
2073- finish_terminated_actor_event(scope, &actor_scope);
2074- }
2075- return Some(anyhow!(termination.error));
2076- }
2077- is_terminating.then(|| anyhow!("JavaScript execution was terminated"))
2078-}
2079-
2080-extern "C" fn near_heap_limit(
2081- data: *mut std::ffi::c_void,
2082- current_heap_limit: usize,
2083- _initial_heap_limit: usize,
2084-) -> usize {
2085- // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop
2086- // removes this callback before the isolate (and its slots) are destroyed.
2087- let state = unsafe { &*(data as *const HeapLimitState) };
2088- state.excessively_exceeded.store(true, Ordering::Relaxed);
2089- // V8 fatally aborts the process if a near-limit callback does not extend
2090- // the limit. This reserve lets JS observe condemnation and unwind.
2091- current_heap_limit.saturating_add(V8_HEAP_EMERGENCY_BYTES)
2092-}
2093-
2094-fn v8_heap_limit_bytes() -> usize {
2095- std::env::var("CELLD_V8_HEAP_LIMIT_MB")
2096- .ok()
2097- .and_then(|value| value.parse::<usize>().ok())
2098- .and_then(|megabytes| megabytes.checked_mul(1024 * 1024))
2099- .filter(|bytes| *bytes > 0)
2100- .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES)
2101-}
2102-
2103-impl Drop for WorkerIsolate {
2104- fn drop(&mut self) {
2105- self.isolate
2106- .remove_near_heap_limit_callback(near_heap_limit, self.original_heap_limit);
2107- }
2108-}
2109-
2110-#[derive(Debug)]
2111-pub struct AlarmRunError {
2112- source: anyhow::Error,
2113- counts_against_limit: bool,
2114-}
2115-
2116-impl AlarmRunError {
2117- fn infrastructure(source: anyhow::Error) -> Self {
2118- Self {
2119- source,
2120- counts_against_limit: false,
2121- }
2122- }
2123-
2124- fn user(source: anyhow::Error) -> Self {
2125- Self {
2126- source,
2127- counts_against_limit: true,
2128- }
2129- }
2130-
2131- pub fn counts_against_limit(&self) -> bool {
2132- self.counts_against_limit
2133- }
2134-}
2135-
2136-impl std::fmt::Display for AlarmRunError {
2137- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2138- self.source.fmt(formatter)
2139- }
2140-}
2141-
2142-impl std::error::Error for AlarmRunError {
2143- fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2144- self.source.source()
2145- }
2146-}
2147-
2148-impl Worker {
2149- /// Compile the worker module, wire the DO harness, and extract the entry
2150- /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding
2151- /// name to a DO class name (from wrangler metadata).
2152- ///
2153- /// The runtime builds a `WorkerConfig` directly; this helper is
2154- /// test-only.
2155- #[cfg(test)]
2156- pub fn load(options: WorkerConfigOptions, owned: &[String]) -> Result<Worker> {
2157- let config = Arc::new(WorkerConfig::new(options));
2158- Self::load_config(config, owned)
2159- }
2160-
2161- pub fn load_config(config: Arc<WorkerConfig>, owned: &[String]) -> Result<Worker> {
2162- Self::load_config_owned(config, Arc::from(owned.to_vec()))
2163- }
2164-
2165- fn load_config_owned(config: Arc<WorkerConfig>, owned: Arc<[String]>) -> Result<Worker> {
2166- let src = config.src.as_str();
2167- let script_name = config.script_name.as_str();
2168- let do_classes = config.do_classes.as_slice();
2169- let node = config.node.as_str();
2170- let text = config.text.as_slice();
2171- let compat = config.compat;
2172- let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes());
2173- let mut isolate = v8::Isolate::new(params);
2174- // Dynamic `import()` of builtin specifiers; per-import()-call only.
2175- isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically);
2176- let original_heap_limit = isolate.get_heap_statistics().heap_size_limit();
2177- let heap_limit_state = Arc::new(HeapLimitState::default());
2178- let runtime_state = Arc::new(ActorRuntimeState {
2179- egress: config.egress,
2180- ..Default::default()
2181- });
2182- let heap_limit_state_ptr =
2183- Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void;
2184- isolate.set_slot(heap_limit_state);
2185- isolate.set_slot(runtime_state.clone());
2186- isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr);
2187- let (context, fetch) = {
2188- v8::scope!(let hs, &mut isolate);
2189- let context = v8::Context::new(hs, Default::default());
2190- let cs = &mut v8::ContextScope::new(hs, context);
2191- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2192- let scope = &mut tc.init();
2193-
2194- install_ops(scope, context);
2195- install_prelude(scope)?; // Web Platform APIs
2196- install_harness(scope)?; // DO object model + minimal Response
2197- install_lazy_globals(scope)?;
2198- // A global, so it must exist before the module evaluates: bundles
2199- // read Cloudflare.compatibilityFlags at module scope.
2200- inject_compatibility_flags(scope, compat)?;
2201- inject_storage_compatibility(scope, compat)?;
2202-
2203- let module = match compile_module(scope, "worker.js", src) {
2204- Some(m) => m,
2205- None => return Err(anyhow!("compile: {}", exc!(scope))),
2206- };
2207- register_stubs(scope, src, text); // cloudflare:*/node:* + text modules
2208- if !config.loader_modules.is_empty() {
2209- register_loader_modules(scope, &config.loader_modules);
2210- }
2211- module
2212- .instantiate_module(scope, resolve_external)
2213- .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?;
2214- let ev = match module.evaluate(scope) {
2215- Some(value) => value,
2216- None => {
2217- if let Some(error) = take_execution_termination(scope) {
2218- return Err(error);
2219- }
2220- return Err(anyhow!("evaluate: {}", exc!(scope)));
2221- }
2222- };
2223- if let Some(error) = take_execution_termination(scope) {
2224- return Err(error);
2225- }
2226- if let Ok(p) = ev.try_cast::<v8::Promise>() {
2227- if p.state() == v8::PromiseState::Rejected {
2228- let r = p.result(scope);
2229- let stk = r
2230- .to_object(scope)
2231- .and_then(|o| {
2232- let k = v8::String::new(scope, "stack")?;
2233- o.get(scope, k.into())
2234- })
2235- .map(|s| s.to_rust_string_lossy(scope))
2236- .unwrap_or_default();
2237- return Err(anyhow!(
2238- "top-level rejected: {} | {}",
2239- r.to_rust_string_lossy(scope),
2240- stk.lines().take(4).collect::<Vec<_>>().join(" <- ")
2241- ));
2242- }
2243- }
2244-
2245- let ns = module
2246- .get_module_namespace()
2247- .to_object(scope)
2248- .ok_or_else(|| anyhow!("ns"))?;
2249-
2250- // register each exported DO class into the harness registry
2251- for cn in do_classes {
2252- let key = v8::String::new(scope, cn).unwrap();
2253- let cls = ns
2254- .get(scope, key.into())
2255- .ok_or_else(|| anyhow!("DO class {cn} not exported"))?;
2256- register_class(scope, cn, cls)?;
2257- }
2258- inject_namespace_keys(scope, script_name, do_classes)?;
2259- populate_cf_exports(scope, ns, do_classes)?;
2260- register_entrypoints(scope, ns)?;
2261- // build env from bindings and stash it in the harness
2262- build_env(scope, &config)?;
2263- // tell the harness which cells are local (route the rest cross-node)
2264- inject_routing(scope, owned.as_ref(), node)?;
2265-
2266- // entry fetch
2267- let dk = v8::String::new(scope, "default").unwrap();
2268- let default = ns
2269- .get(scope, dk.into())
2270- .ok_or_else(|| anyhow!("no default export"))?
2271- .to_object(scope)
2272- .ok_or_else(|| anyhow!("default not object"))?;
2273- let fk = v8::String::new(scope, "fetch").unwrap();
2274- let f: v8::Local<v8::Function> = default
2275- .get(scope, fk.into())
2276- .ok_or_else(|| anyhow!("no fetch"))?
2277- .try_into()
2278- .map_err(|_| anyhow!("fetch not fn"))?;
2279-
2280- // Lets a self-targeted service binding invoke the handler in
2281- // this isolate instead of crossing to a pool thread.
2282- {
2283- let cell_key = v8::String::new(scope, "__cell").unwrap();
2284- if let Some(cell) = context
2285- .global(scope)
2286- .get(scope, cell_key.into())
2287- .and_then(|value| value.to_object(scope))
2288- {
2289- let key = v8::String::new(scope, "selfFetch").unwrap();
2290- cell.set(scope, key.into(), f.into());
2291- // Optional scheduled handler, reached by a self-targeted
2292- // service binding's scheduled().
2293- let sk = v8::String::new(scope, "scheduled").unwrap();
2294- if let Some(handler) = default.get(scope, sk.into()) {
2295- if handler.is_function() {
2296- let key_ = v8::String::new(scope, "selfScheduled").unwrap();
2297- cell.set(scope, key_.into(), handler);
2298- }
2299- }
2300- }
2301- }
2302- (v8::Global::new(scope, context), v8::Global::new(scope, f))
2303- };
2304- Ok(Worker {
2305- inner: Some(WorkerIsolate {
2306- isolate,
2307- context,
2308- fetch,
2309- original_heap_limit,
2310- runtime_state,
2311- }),
2312- config,
2313- owned,
2314- })
2315- }
2316-
2317- fn reload_after_process_exit(&mut self) -> Result<()> {
2318- if !self
2319- .runtime_state
2320- .worker_exit_requested
2321- .load(Ordering::Relaxed)
2322- {
2323- return Ok(());
2324- }
2325- let config = self.config.clone();
2326- let owned = self.owned.clone();
2327- drop(self.inner.take());
2328- let replacement = Self::load_config_owned(config, owned)
2329- .map_err(|error| anyhow!("reload after process.exit: {error:#}"))?;
2330- self.inner = replacement.inner;
2331- Ok(())
2332- }
2333-
2334- /// Restore an idFromName() actor's human-readable identity before its
2335- /// constructor runs. The host calls this on activation and before a named
2336- /// request is dispatched.
2337- pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> {
2338- let context_g = self.context.clone();
2339- v8::scope!(let hs, &mut self.isolate);
2340- let context = v8::Local::new(hs, context_g);
2341- let cs = &mut v8::ContextScope::new(hs, context);
2342- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2343- register_actor_name(&mut tc.init(), scope, Some(name))
2344- }
2345-
2346- /// Fire the DO's alarm() handler for `scope`. Returns Ok on success, Err if
2347- /// the handler threw (caller retries per the at-least-once contract).
2348- pub fn fire_alarm(
2349- &mut self,
2350- scope: &str,
2351- retry: i64,
2352- rx: &std::sync::mpsc::Receiver<CellJob>,
2353- ) -> std::result::Result<(), AlarmRunError> {
2354- let scheduled_time = storage::active_alarm_scheduled_time(scope).ok_or_else(|| {
2355- AlarmRunError::infrastructure(anyhow!(
2356- "alarm handler started without a scheduled alarm",
2357- ))
2358- })?;
2359- let context_g = self.context.clone();
2360- v8::scope!(let hs, &mut self.isolate);
2361- let context = v8::Local::new(hs, context_g);
2362- let cs = &mut v8::ContextScope::new(hs, context);
2363- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2364- let result = call_fire_alarm(&mut tc.init(), scope, scheduled_time, retry, rx);
2365- if let Some(error) = storage::sql_critical_error(scope) {
2366- return Err(AlarmRunError::user(anyhow!(error)));
2367- }
2368- result
2369- }
2370-
2371- /// Run a specific DO instance's fetch, addressed by its scope — the target
2372- /// of a cross-node proxy hop. Bypasses the Worker's default export (which
2373- /// would re-route). Called on the owner node via the `/__do/<scope>` endpoint.
2374- pub fn dispatch_to_and_reply(
2375- &mut self,
2376- scope: &str,
2377- request: FetchRequest<'_>,
2378- rx: &std::sync::mpsc::Receiver<CellJob>,
2379- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2380- ) {
2381- let context_g = self.context.clone();
2382- v8::scope!(let hs, &mut self.isolate);
2383- let context = v8::Local::new(hs, context_g);
2384- let cs = &mut v8::ContextScope::new(hs, context);
2385- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2386- let tc = &mut tc.init();
2387- let global = context.global(tc);
2388- let key = v8::String::new(tc, "__dispatchTo").unwrap();
2389- let f: v8::Local<v8::Function> = match global
2390- .get(tc, key.into())
2391- .ok_or_else(|| anyhow!("no __dispatchTo"))
2392- .and_then(|value| value.try_into().map_err(|_| anyhow!("not fn")))
2393- {
2394- Ok(f) => f,
2395- Err(error) => {
2396- let _ = reply.send(Err(error));
2397- return;
2398- }
2399- };
2400- let sc = v8::String::new(tc, scope).unwrap();
2401- let u = v8::String::new(tc, request.url).unwrap();
2402- let m = v8::String::new(tc, request.method).unwrap();
2403- let b = bytes_value(tc, request.body.to_vec());
2404- let headers = match serde_json::to_string(request.headers) {
2405- Ok(headers) => v8::String::new(tc, &headers).unwrap(),
2406- Err(error) => {
2407- let _ = reply.send(Err(error.into()));
2408- return;
2409- }
2410- };
2411- let request_id_value: v8::Local<v8::Value> = match request.request_id {
2412- Some(request_id) => v8::String::new(tc, &request_id_string(request_id))
2413- .unwrap()
2414- .into(),
2415- None => v8::null(tc).into(),
2416- };
2417- let recv = v8::undefined(tc).into();
2418- // Sample the committed-write position before the handler runs, so the
2419- // output gate can tell an app write from celld's own activation writes.
2420- let writes_before = storage::write_position(scope);
2421- if let Err(error) = begin_event_context(tc) {
2422- let _ = reply.send(Err(error));
2423- return;
2424- }
2425- let Some(ret) = f.call(
2426- tc,
2427- recv,
2428- &[
2429- sc.into(),
2430- u.into(),
2431- m.into(),
2432- b,
2433- headers.into(),
2434- request_id_value,
2435- ],
2436- ) else {
2437- let _ = end_event_context(tc);
2438- let _ = reply.send(Err(anyhow!("dispatchTo threw: {}", exc!(tc))));
2439- return;
2440- };
2441- complete_fetch_event(
2442- tc,
2443- ret,
2444- Some(rx),
2445- Some(scope),
2446- writes_before,
2447- request.request_id,
2448- reply,
2449- );
2450- }
2451-
2452- /// Invoke one public method on a DO instance (Cloudflare native RPC),
2453- /// with arguments and result in either `RpcData` flavor.
2454- pub fn dispatch_rpc_data(
2455- &mut self,
2456- scope: &str,
2457- method: &str,
2458- args: RpcData,
2459- rx: &std::sync::mpsc::Receiver<CellJob>,
2460- ) -> Result<RpcData> {
2461- let context_g = self.context.clone();
2462- v8::scope!(let hs, &mut self.isolate);
2463- let context = v8::Local::new(hs, context_g);
2464- let cs = &mut v8::ContextScope::new(hs, context);
2465- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2466- let tc = &mut tc.init();
2467- let global = context.global(tc);
2468- let key = v8::String::new(tc, "__dispatchRpc").unwrap();
2469- let f: v8::Local<v8::Function> = global
2470- .get(tc, key.into())
2471- .ok_or_else(|| anyhow!("no __dispatchRpc"))?
2472- .try_into()
2473- .map_err(|_| anyhow!("not fn"))?;
2474- let sc = v8::String::new(tc, scope).unwrap();
2475- let method = v8::String::new(tc, method).unwrap();
2476- let args = rpc_data_value(tc, args);
2477- let recv = v8::undefined(tc).into();
2478- begin_event_context(tc)?;
2479- let Some(ret) = f.call(tc, recv, &[sc.into(), method.into(), args]) else {
2480- let _ = end_event_context(tc);
2481- return Err(anyhow!("dispatchRpc threw: {}", exc!(tc)));
2482- };
2483- let ret = run_event_value(tc, ret, Some(rx), Some(scope), None);
2484- if let Some(error) = storage::sql_critical_error(scope) {
2485- return Err(anyhow!(error));
2486- }
2487- let ret = ret?;
2488- Ok(rpc_data_ret(tc, ret))
2489- }
2490-
2491- /// JSON-flavored `dispatch_rpc_data`, the test harness's entry point.
2492- #[cfg(test)]
2493- pub fn dispatch_rpc(
2494- &mut self,
2495- scope: &str,
2496- method: &str,
2497- args: &str,
2498- rx: &std::sync::mpsc::Receiver<CellJob>,
2499- ) -> Result<String> {
2500- let args = RpcData::Json(args.into());
2501- match self.dispatch_rpc_data(scope, method, args, rx)? {
2502- RpcData::Json(json) => Ok(json),
2503- RpcData::V8(_) => Err(anyhow!("JSON RPC answered bytes")),
2504- }
2505- }
2506-
2507- /// Invoke `method` on the named `WorkerEntrypoint`. The service-binding
2508- /// counterpart of `dispatch_rpc_data`: no actor scope, so no cell
2509- /// receiver and no SQL critical-error check. Arguments and result are V8
2510- /// structured-clone bytes.
2511- pub fn dispatch_entrypoint_rpc(
2512- &mut self,
2513- entrypoint: &str,
2514- method: &str,
2515- args: Vec<u8>,
2516- ) -> Result<Vec<u8>> {
2517- let context_g = self.context.clone();
2518- v8::scope!(let hs, &mut self.isolate);
2519- let context = v8::Local::new(hs, context_g);
2520- let cs = &mut v8::ContextScope::new(hs, context);
2521- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2522- let tc = &mut tc.init();
2523- let global = context.global(tc);
2524- let key = v8::String::new(tc, "__dispatchEntrypointRpc").unwrap();
2525- let f: v8::Local<v8::Function> = global
2526- .get(tc, key.into())
2527- .ok_or_else(|| anyhow!("no __dispatchEntrypointRpc"))?
2528- .try_into()
2529- .map_err(|_| anyhow!("not fn"))?;
2530- let entrypoint = v8::String::new(tc, entrypoint).unwrap();
2531- let method = v8::String::new(tc, method).unwrap();
2532- let args = bytes_value(tc, args);
2533- let recv = v8::undefined(tc).into();
2534- begin_event_context(tc)?;
2535- let Some(ret) = f.call(tc, recv, &[entrypoint.into(), method.into(), args]) else {
2536- let _ = end_event_context(tc);
2537- return Err(anyhow!("entrypoint RPC threw: {}", exc!(tc)));
2538- };
2539- let ret = run_event_value(tc, ret, None, None, None)?;
2540- view_bytes(ret).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes"))
2541- }
2542-
2543- pub fn dispatch_ws_open(
2544- &mut self,
2545- scope: &str,
2546- ws_id: u64,
2547- protocol: &str,
2548- rx: &std::sync::mpsc::Receiver<CellJob>,
2549- ) -> Result<()> {
2550- let context_g = self.context.clone();
2551- v8::scope!(let hs, &mut self.isolate);
2552- let context = v8::Local::new(hs, context_g);
2553- let cs = &mut v8::ContextScope::new(hs, context);
2554- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2555- let tc = &mut tc.init();
2556- call_dispatch_ws_open(tc, scope, ws_id, protocol, rx)
2557- }
2558-
2559- /// Deliver a WebSocket message to the cell's DO (`webSocketMessage`). The
2560- /// socket lives in the host; `ws.send` inside the handler routes back out by
2561- /// wsId. The isolate may have been hibernated between messages — the host
2562- /// re-activates before calling this.
2563- pub fn dispatch_ws(
2564- &mut self,
2565- scope: &str,
2566- ws_id: u64,
2567- data: WsIn,
2568- rx: &std::sync::mpsc::Receiver<CellJob>,
2569- ) -> Result<WsDispatch> {
2570- let context_g = self.context.clone();
2571- v8::scope!(let hs, &mut self.isolate);
2572- let context = v8::Local::new(hs, context_g);
2573- let cs = &mut v8::ContextScope::new(hs, context);
2574- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2575- let tc = &mut tc.init();
2576- call_dispatch_ws(tc, scope, ws_id, data, rx)
2577- }
2578-
2579- pub fn dispatch_ws_closed(
2580- &mut self,
2581- scope: &str,
2582- ws_id: u64,
2583- code: u16,
2584- reason: &str,
2585- was_clean: bool,
2586- rx: &std::sync::mpsc::Receiver<CellJob>,
2587- ) -> Result<()> {
2588- let context_g = self.context.clone();
2589- v8::scope!(let hs, &mut self.isolate);
2590- let context = v8::Local::new(hs, context_g);
2591- let cs = &mut v8::ContextScope::new(hs, context);
2592- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2593- let tc = &mut tc.init();
2594- let global = context.global(tc);
2595- let key = v8::String::new(tc, "__wsClosed").unwrap();
2596- let f: v8::Local<v8::Function> = global
2597- .get(tc, key.into())
2598- .ok_or_else(|| anyhow!("no __wsClosed"))?
2599- .try_into()
2600- .map_err(|_| anyhow!("not fn"))?;
2601- let sc = v8::String::new(tc, scope).unwrap();
2602- let id = v8::Number::new(tc, ws_id as f64);
2603- let code = v8::Number::new(tc, f64::from(code));
2604- let reason = v8::String::new(tc, reason).unwrap();
2605- let was_clean = v8::Boolean::new(tc, was_clean);
2606- let recv = v8::undefined(tc).into();
2607- begin_event_context(tc)?;
2608- let Some(ret) = f.call(
2609- tc,
2610- recv,
2611- &[
2612- sc.into(),
2613- id.into(),
2614- code.into(),
2615- reason.into(),
2616- was_clean.into(),
2617- ],
2618- ) else {
2619- let _ = end_event_context(tc);
2620- return Err(anyhow!("wsClosed threw: {}", exc!(tc)));
2621- };
2622- let result = run_event_value(tc, ret, Some(rx), Some(scope), None);
2623- if let Some(error) = storage::sql_critical_error(scope) {
2624- return Err(anyhow!(error));
2625- }
2626- result?;
2627- Ok(())
2628- }
2629-
2630- /// Run the worker `fetch` and reply on the oneshot. Test-only: it drives
2631- /// one request at a time and registers no signal, so the shipped binary
2632- /// never needs it.
2633- #[cfg(all(test, celld_internal_tests))]
2634- pub fn fetch_and_reply(
2635- &mut self,
2636- url: &str,
2637- method: &str,
2638- body: &[u8],
2639- headers: &[(String, String)],
2640- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2641- ) -> Result<()> {
2642- self.fetch_and_reply_id(url, method, body, headers, None, reply)
2643- }
2644-
2645- /// As `fetch_and_reply`, but the request's signal is registered under
2646- /// `request_id` so an HTTP or service-binding caller that disconnects
2647- /// reaches the target's `request.signal` mid-flight.
2648- pub fn fetch_and_reply_id(
2649- &mut self,
2650- url: &str,
2651- method: &str,
2652- body: &[u8],
2653- headers: &[(String, String)],
2654- request_id: Option<RequestId>,
2655- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2656- ) -> Result<()> {
2657- self.fetch_and_reply_inner(url, method, body, headers, request_id, reply);
2658- self.reload_after_process_exit()
2659- }
2660-
2661- fn fetch_and_reply_inner(
2662- &mut self,
2663- url: &str,
2664- method: &str,
2665- body: &[u8],
2666- headers: &[(String, String)],
2667- request_id: Option<RequestId>,
2668- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2669- ) {
2670- let context_g = self.context.clone();
2671- let fetch = self.fetch.clone();
2672- v8::scope!(let hs, &mut self.isolate);
2673- let context = v8::Local::new(hs, context_g);
2674- let cs = &mut v8::ContextScope::new(hs, context);
2675- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2676- let tc = &mut tc.init();
2677-
2678- let built = match request_id {
2679- Some(_) => make_incoming_request(tc, url, method, body, headers),
2680- None => make_request(tc, url, method, body, headers),
2681- };
2682- let req = match built {
2683- Ok(req) => req,
2684- Err(error) => {
2685- let _ = reply.send(Err(error));
2686- return;
2687- }
2688- };
2689- // env comes from the harness (globalThis.__cell.env)
2690- let env = match harness_env(tc) {
2691- Ok(env) => env,
2692- Err(error) => {
2693- let _ = reply.send(Err(error));
2694- return;
2695- }
2696- };
2697- let recv = v8::undefined(tc).into();
2698- let f = v8::Local::new(tc, fetch);
2699- let execution_ctx = match begin_event_context(tc) {
2700- Ok(execution_ctx) => execution_ctx,
2701- Err(error) => {
2702- let _ = reply.send(Err(error));
2703- return;
2704- }
2705- };
2706- let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else {
2707- let error = take_execution_termination(tc)
2708- .unwrap_or_else(|| anyhow!("fetch threw: {}", exc!(tc)));
2709- let _ = end_event_context(tc);
2710- let _ = reply.send(Err(error));
2711- return;
2712- };
2713- let active_request_id = match request_id {
2714- Some(request_id)
2715- if ret
2716- .try_cast::<v8::Promise>()
2717- .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) =>
2718- {
2719- if let Err(error) = register_incoming_request(tc, request_id, req) {
2720- clear_request_cancellation(request_id);
2721- let _ = end_event_context(tc);
2722- let _ = reply.send(Err(error));
2723- return;
2724- }
2725- Some(request_id)
2726- }
2727- Some(request_id) => {
2728- clear_request_cancellation(request_id);
2729- None
2730- }
2731- None => None,
2732- };
2733- complete_fetch_event(tc, ret, None, None, None, active_request_id, reply);
2734- if let Some(request_id) = active_request_id {
2735- finish_incoming_request(tc, request_id);
2736- }
2737- }
2738-
2739- /// Run the worker `fetch` in a CELL isolate, pumping this cell's job
2740- /// receiver so an in-isolate `env.NS.get(ownScope).fetch()` resolves without
2741- /// a host hop. Identical to `fetch_and_reply_id` except the event loop is
2742- /// driven with `Some(rx)`.
2743- pub fn worker_fetch_and_reply(
2744- &mut self,
2745- request: FetchRequest<'_>,
2746- rx: &std::sync::mpsc::Receiver<CellJob>,
2747- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2748- ) -> Result<()> {
2749- self.worker_fetch_and_reply_inner(request, rx, reply);
2750- self.reload_after_process_exit()
2751- }
2752-
2753- fn worker_fetch_and_reply_inner(
2754- &mut self,
2755- request: FetchRequest<'_>,
2756- rx: &std::sync::mpsc::Receiver<CellJob>,
2757- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2758- ) {
2759- let context_g = self.context.clone();
2760- let fetch = self.fetch.clone();
2761- v8::scope!(let hs, &mut self.isolate);
2762- let context = v8::Local::new(hs, context_g);
2763- let cs = &mut v8::ContextScope::new(hs, context);
2764- let tc = std::pin::pin!(v8::TryCatch::new(cs));
2765- let tc = &mut tc.init();
2766- let built = match request.request_id {
2767- Some(_) => make_incoming_request(
2768- tc,
2769- request.url,
2770- request.method,
2771- request.body,
2772- request.headers,
2773- ),
2774- None => make_request(
2775- tc,
2776- request.url,
2777- request.method,
2778- request.body,
2779- request.headers,
2780- ),
2781- };
2782- let req = match built {
2783- Ok(req) => req,
2784- Err(error) => {
2785- let _ = reply.send(Err(error));
2786- return;
2787- }
2788- };
2789- let env = match harness_env(tc) {
2790- Ok(env) => env,
2791- Err(error) => {
2792- let _ = reply.send(Err(error));
2793- return;
2794- }
2795- };
2796- let recv = v8::undefined(tc).into();
2797- let f = v8::Local::new(tc, fetch);
2798- let execution_ctx = match begin_event_context(tc) {
2799- Ok(execution_ctx) => execution_ctx,
2800- Err(error) => {
2801- let _ = reply.send(Err(error));
2802- return;
2803- }
2804- };
2805- let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else {
2806- let error = take_execution_termination(tc)
2807- .unwrap_or_else(|| anyhow!("fetch threw: {}", exc!(tc)));
2808- let _ = end_event_context(tc);
2809- let _ = reply.send(Err(error));
2810- return;
2811- };
2812- let active_request_id = match request.request_id {
2813- Some(request_id)
2814- if ret
2815- .try_cast::<v8::Promise>()
2816- .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) =>
2817- {
2818- if let Err(error) = register_incoming_request(tc, request_id, req) {
2819- clear_request_cancellation(request_id);
2820- let _ = end_event_context(tc);
2821- let _ = reply.send(Err(error));
2822- return;
2823- }
2824- Some(request_id)
2825- }
2826- Some(request_id) => {
2827- clear_request_cancellation(request_id);
2828- None
2829- }
2830- None => None,
2831- };
2832- complete_fetch_event(tc, ret, Some(rx), None, None, active_request_id, reply);
2833- if let Some(request_id) = active_request_id {
2834- finish_incoming_request(tc, request_id);
2835- }
2836- }
2837-}
2838-
2839-// ---- native ops exposed to JS ----
2840-
2841-/// Host ops, defined non-enumerable. They are runtime internals: a bundle
2842-/// walking `globalThis` must not find them, let alone `new` one — `for (const
2843-/// k in globalThis) new globalThis[k]()` used to reach `__actor_abort` and
2844-/// kill the actor.
2845-macro_rules! ops {
2846- ($scope:expr, $global:expr, $($name:literal => $op:path),* $(,)?) => {
2847- $({
2848- let f = v8::Function::new($scope, $op).unwrap();
2849- let k = v8::String::new($scope, $name).unwrap();
2850- $global.define_own_property(
2851- $scope, k.into(), f.into(), v8::PropertyAttribute::DONT_ENUM);
2852- })*
2853- };
2854-}
2855-
2856-fn install_ops(scope: &mut v8::PinScope, context: v8::Local<v8::Context>) {
2857- let global = context.global(scope);
2858- ops! { scope, global,
2859- "__heap_limit_excessively_exceeded" =>
2860- op_heap_limit_excessively_exceeded,
2861- "__ws_send" => op_ws_send,
2862- "__ws_send_binary" => op_ws_send_binary,
2863- "__ws_close" => op_ws_close,
2864- "__ws_alloc" => op_ws_alloc,
2865- "__ws_accept" => op_ws_accept,
2866- "__ws_accept_regular" => op_ws_accept_regular,
2867- "__ws_list" => op_ws_list,
2868- "__ws_attachment_set" => op_ws_attachment_set,
2869- "__ws_connect" => op_ws_connect,
2870- "__ws_next" => op_ws_next,
2871- "__ws_upgrade" => op_ws_upgrade,
2872- "__storage_get" => op_storage_get,
2873- "__storage_get_many" => op_storage_get_many,
2874- "__sql_exec" => op_sql_exec,
2875- "__sql_ingest" => op_sql_ingest,
2876- "__sql_cursor_start" => op_sql_cursor_start,
2877- "__sql_cursor_next" => op_sql_cursor_next,
2878- "__sql_cursor_close" => op_sql_cursor_close,
2879- "__sql_database_size" => op_sql_database_size,
2880- "__storage_transaction_control" => op_storage_transaction_control,
2881- "__log" => op_log,
2882- "__storage_put" => op_storage_put,
2883- "__storage_put_many" => op_storage_put_many,
2884- "__storage_queue_put" => op_storage_queue_put,
2885- "__storage_queue_put_many" => op_storage_queue_put_many,
2886- "__storage_put_serialized" => op_storage_put_serialized,
2887- "__storage_queue_put_serialized" => op_storage_queue_put_serialized,
2888- "__storage_flush_pending_puts" => op_storage_flush_pending_puts,
2889- "__storage_cancel_pending_puts" => op_storage_cancel_pending_puts,
2890- "__actor_abort" => op_actor_abort,
2891- "__process_exit" => op_process_exit,
2892- "__storage_delete" => op_storage_delete,
2893- "__storage_delete_many" => op_storage_delete_many,
2894- "__storage_list" => op_storage_list,
2895- "__storage_sync_list_start" => op_storage_sync_list_start,
2896- "__storage_sync_list_next" => op_storage_sync_list_next,
2897- "__storage_delete_all" => op_storage_delete_all,
2898- "$$urlParse" => op_url_parse,
2899- "$$urlPatternParse" => op_urlpattern_parse,
2900- "$$urlPatternMatchInput" => op_urlpattern_match_input,
2901- "$$atob" => op_atob,
2902- "$$btoa" => op_btoa,
2903- "$$textDecoderLabel" => op_text_decoder_label,
2904- "$$textDecoderNew" => op_text_decoder_new,
2905- "$$textDecoderDecode" => op_text_decoder_decode,
2906- "$$textDecoderFree" => op_text_decoder_free,
2907- "__alarm_set" => op_alarm_set,
2908- "__alarm_get" => op_alarm_get,
2909- "__alarm_delete" => op_alarm_delete,
2910- "__loader_load" => op_loader_load,
2911- "__loader_fetch" => op_loader_fetch,
2912- "__loader_rpc" => op_loader_rpc,
2913- "__loader_drop" => op_loader_drop,
2914- "__do_call" => op_do_call,
2915- "__writePosition" => op_write_position,
2916- "__gateWrite" => op_gate_write,
2917- "__svc_call" => op_svc_call,
2918- "__svc_call_cancellable" => op_svc_call_cancellable,
2919- "__svc_rpc" => op_svc_rpc,
2920- "__do_call_cancellable" => op_do_call_cancellable,
2921- "__do_call_cancel" => op_do_call_cancel,
2922- "__do_id" => op_do_id,
2923- "__rpc_call" => op_rpc_call,
2924- "__sc_encode" => op_sc_encode,
2925- "__sc_decode" => op_sc_decode,
2926- "__op_fetch" => op_fetch,
2927- "__asset_fetch" => op_asset_fetch,
2928- "__http_stream_read" => op_http_stream_read,
2929- "__http_stream_cancel" => op_http_stream_cancel,
2930- "__http_stream_tee" => op_http_stream_tee,
2931- "__response_stream_create" => op_response_stream_create,
2932- "__response_stream_write" => op_response_stream_write,
2933- "__response_stream_closed" => op_response_stream_closed,
2934- "__response_stream_close" => op_response_stream_close,
2935- "__op_timer" => op_timer,
2936- "__timer_alloc" => op_timer_alloc,
2937- "__timer_cancel" => op_timer_cancel,
2938- "__crypto_operation" => op_crypto_operation,
2939- "$$randomValues" => op_webcrypto_random,
2940- "$$digest" => op_webcrypto_digest,
2941- "$$hmacSign" => op_webcrypto_hmac_sign,
2942- "$$hmacVerify" => op_webcrypto_hmac_verify,
2943- "$$aesEncrypt" => op_webcrypto_aes_encrypt,
2944- "$$aesDecrypt" => op_webcrypto_aes_decrypt,
2945- "$$pbkdf2" => op_node_pbkdf2,
2946- "$$hkdf" => op_node_hkdf,
2947- "__als_get" => op_als_get,
2948- "__als_set" => op_als_set,
2949- "__util_type_flags" => op_util_type_flags,
2950- "__util_constructor_name" => op_util_constructor_name,
2951- "__util_proxy_details" => op_util_proxy_details,
2952- "__util_promise_details" => op_util_promise_details,
2953- "__util_preview_entries" => op_util_preview_entries,
2954- "__builtin_module" => op_builtin_module,
2955- "__zlib" => op_zlib,
2956- "__zlib_stream_new" => op_zlib_stream_new,
2957- "__zlib_stream_push" => op_zlib_stream_push,
2958- "__zlib_stream_end" => op_zlib_stream_end,
2959- "__zlib_stream_drop" => op_zlib_stream_drop,
2960- }
2961- #[cfg(all(test, celld_internal_tests))]
2962- ops! { scope, global,
2963- "__test_gc" => op_test_gc,
2964- "__loader_count" => op_loader_count,
2965- "__test_set_heap_limit_excessively_exceeded" =>
2966- op_test_set_heap_limit_excessively_exceeded,
2967- "__sql_set_max_page_count_for_test" =>
2968- op_sql_set_max_page_count_for_test,
2969- "__sql_set_write_fault_for_test" => op_sql_set_write_fault_for_test,
2970- "__sql_set_cache_size_for_test" => op_sql_set_cache_size_for_test,
2971- "__sql_set_interrupt_fault_for_test" =>
2972- op_sql_set_interrupt_fault_for_test,
2973- "__sql_register_nomem_function_for_test" =>
2974- op_sql_register_nomem_function_for_test,
2975- }
2976-}
2977-
2978-/// Create a JS promise for an async op `id` and return it to JS.
2979-fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> {
2980- let resolver = v8::PromiseResolver::new(scope).unwrap();
2981- let promise = resolver.get_promise(scope);
2982- promise_store(id, v8::Global::new(scope, resolver));
2983- promise.into()
2984-}
2985-
2986-/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await
2987-/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON
2988-/// `{status, body, headers}` string the harness turns back into a Response.
2989-/// `__svc_rpc(script, entrypoint, method, argsSc)` -> Promise<Uint8Array>;
2990-/// arguments and result are V8 structured-clone bytes.
2991-fn op_svc_rpc(
2992- scope: &mut v8::PinScope,
2993- args: v8::FunctionCallbackArguments,
2994- mut rv: v8::ReturnValue<v8::Value>,
2995-) {
2996- let script = args.get(0).to_rust_string_lossy(scope);
2997- let entrypoint = args.get(1).to_rust_string_lossy(scope);
2998- let method = args.get(2).to_rust_string_lossy(scope);
2999- let call_args = view_bytes(args.get(3)).unwrap_or_default();
3000- let (tx, rx) = tokio::sync::oneshot::channel();
3001- let sent = SVC_RPC_TX
3002- .get()
3003- .map(|t| {
3004- t.send(SvcRpcReq {
3005- script,
3006- entrypoint,
3007- method,
3008- args: call_args,
3009- reply: tx,
3010- })
3011- .is_ok()
3012- })
3013- .unwrap_or(false);
3014- let id = asyncrt::enqueue(async move {
3015- if !sent {
3016- return Err("no service binding channel".into());
3017- }
3018- match rx.await {
3019- Ok(Ok(result)) => Ok(result),
3020- Ok(Err(error)) => Err(format!("{error}")),
3021- Err(error) => Err(format!("service dropped: {error}")),
3022- }
3023- });
3024- rv.set(promise_for(scope, id));
3025-}
3026-
3027-/// `__svc_call(script, url, method, body, headersJson)` -> Promise<json>.
3028-/// The service-binding equivalent of `__do_call`: no scope to resolve and no
3029-/// cancellation token, just a handoff to the target script's pool.
3030-fn op_svc_call(
3031- scope: &mut v8::PinScope,
3032- args: v8::FunctionCallbackArguments,
3033- mut rv: v8::ReturnValue<v8::Value>,
3034-) {
3035- op_svc_call_impl(scope, args, &mut rv, false);
3036-}
3037-
3038-fn op_svc_call_cancellable(
3039- scope: &mut v8::PinScope,
3040- args: v8::FunctionCallbackArguments,
3041- mut rv: v8::ReturnValue<v8::Value>,
3042-) {
3043- op_svc_call_impl(scope, args, &mut rv, true);
3044-}
3045-
3046-fn op_svc_call_impl(
3047- scope: &mut v8::PinScope,
3048- args: v8::FunctionCallbackArguments,
3049- rv: &mut v8::ReturnValue<v8::Value>,
3050- cancellable: bool,
3051-) {
3052- let script = args.get(0).to_rust_string_lossy(scope);
3053- let url = args.get(1).to_rust_string_lossy(scope);
3054- let method = args.get(2).to_rust_string_lossy(scope);
3055- let body = view_bytes(args.get(3)).unwrap_or_default();
3056- let headers =
3057- serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default();
3058- let (tx, rx) = tokio::sync::oneshot::channel();
3059- // Shares the Durable Object cancel registry, so `__do_call_cancel` works
3060- // unchanged for a service call.
3061- let (request_id, cancel, cancel_guard) = if cancellable {
3062- let request_id = next_do_request_id();
3063- let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
3064- do_call_cancels()
3065- .lock()
3066- .unwrap()
3067- .insert(request_id, cancel_sender);
3068- (
3069- Some(request_id),
3070- Some(cancel_receiver),
3071- Some(DoCallCancelGuard(request_id)),
3072- )
3073- } else {
3074- (None, None, None)
3075- };
3076- let sent = SVC_CALL_TX
3077- .get()
3078- .map(|t| {
3079- t.send(SvcCallReq {
3080- cancel,
3081- script,
3082- url,
3083- method,
3084- body,
3085- headers,
3086- reply: tx,
3087- })
3088- .is_ok()
3089- })
3090- .unwrap_or(false);
3091- let id = asyncrt::enqueue(async move {
3092- let _cancel_guard = cancel_guard;
3093- if !sent {
3094- return Err("no service binding channel".into());
3095- }
3096- match rx.await {
3097- Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3098- Ok(Err(error)) => Err(format!("{error}")),
3099- Err(error) => Err(format!("service dropped: {error}")),
3100- }
3101- });
3102- let promise = promise_for(scope, id);
3103- if let Some(request_id) = request_id {
3104- if let Some(object) = promise.to_object(scope) {
3105- let key = v8::String::new(scope, "__celldCancelId").unwrap();
3106- let value = v8::String::new(scope, &request_id.to_string()).unwrap();
3107- object.set(scope, key.into(), value.into());
3108- }
3109- }
3110- rv.set(promise);
3111-}
3112-
3113-// --- Worker Loader: dynamic isolates for Code Mode ---
3114-// A running Worker spawns a fresh isolate from code it supplies at runtime and
3115-// invokes it. Walking skeleton: `env.LOADER.load(code)` -> stub;
3116-// `stub.getEntrypoint().fetch(req)` runs the loaded worker's default fetch,
3117-// reusing the co-hosted-worker thread model and `__svc_call` response
3118-// marshalling. Capability-scoped env, controlled outbound, named-entrypoint
3119-// RPC, and memoized `get(name, getCode)` are not yet wired.
3120-
3121-// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total
3122-// module bytes, 1 MiB env. Messages match so the conformance cases pass.
3123-const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024;
3124-const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024;
3125-
3126-enum LoaderJob {
3127- Fetch {
3128- url: String,
3129- method: String,
3130- body: Vec<u8>,
3131- headers: Vec<(String, String)>,
3132- reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
3133- },
3134- // Named-entrypoint RPC: args and result are V8 structured-clone bytes,
3135- // like the service-binding `__svc_rpc` path.
3136- Rpc {
3137- entrypoint: String,
3138- method: String,
3139- args: Vec<u8>,
3140- reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
3141- },
3142-}
3143-
3144-type LoaderRegistry = HashMap<u64, std::sync::mpsc::Sender<LoaderJob>>;
3145-static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new();
3146-static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1);
3147-
3148-fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> {
3149- LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
3150-}
3151-
3152-fn loader_throw(scope: &mut v8::PinScope, message: &str) {
3153- let message = v8::String::new(scope, message).unwrap();
3154- let exception = v8::Exception::error(scope, message);
3155- scope.throw_exception(exception);
3156-}
3157-
3158-/// `__loader_load(codeJson)` -> stub id. Builds a WorkerConfig from the
3159-/// supplied modules, spawns a fresh isolate on its own thread (isolates are
3160-/// pinned per thread), and registers its job channel. The isolate compiles
3161-/// asynchronously; jobs queue until it is ready, and a load failure drains
3162-/// queued jobs with the error rather than dropping their reply channels.
3163-fn op_loader_load(
3164- scope: &mut v8::PinScope,
3165- args: v8::FunctionCallbackArguments,
3166- mut rv: v8::ReturnValue<v8::Value>,
3167-) {
3168- let code_json = args.get(0).to_rust_string_lossy(scope);
3169- let code: serde_json::Value = match serde_json::from_str(&code_json) {
3170- Ok(code) => code,
3171- Err(e) => return loader_throw(scope, &format!("worker loader: {e}")),
3172- };
3173- let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else {
3174- return loader_throw(scope, "worker loader: missing mainModule");
3175- };
3176- let Some(src) = code
3177- .get("modules")
3178- .and_then(|m| m.get(main))
3179- .and_then(|v| v.as_str())
3180- .map(str::to_string)
3181- else {
3182- return loader_throw(
3183- scope,
3184- &format!("worker loader: module {main:?} missing or not a string"),
3185- );
3186- };
3187- // Every module other than the main one is a sibling the main module may
3188- // import.
3189- let loader_modules: Vec<(String, String)> = code
3190- .get("modules")
3191- .and_then(|m| m.as_object())
3192- .map(|m| {
3193- m.iter()
3194- .filter(|(name, _)| name.as_str() != main)
3195- .filter_map(|(name, v)| v.as_str().map(|s| (name.clone(), s.to_string())))
3196- .collect()
3197- })
3198- .unwrap_or_default();
3199- // Total module bytes, checked before compiling anything (the oversized
3200- // module is never parsed) — the extra modules are not yet loaded but do
3201- // count against the ceiling, as upstream.
3202- let code_size: usize = code
3203- .get("modules")
3204- .and_then(|m| m.as_object())
3205- .map(|m| m.values().filter_map(|v| v.as_str()).map(str::len).sum())
3206- .unwrap_or(0);
3207- if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE {
3208- return loader_throw(
3209- scope,
3210- &format!(
3211- "Dynamic Worker code size ({code_size} bytes) exceeds the \
3212- maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes."
3213- ),
3214- );
3215- }
3216- // Plain JSON `env` values merge onto the loaded worker's env; capability
3217- // stubs are not yet supported and would fail to serialize upstream in JS.
3218- let loader_env = code
3219- .get("env")
3220- .filter(|v| !v.is_null())
3221- .map(|v| v.to_string());
3222- if let Some(env) = &loader_env {
3223- if env.len() > MAX_DYNAMIC_WORKER_ENV_SIZE {
3224- return loader_throw(
3225- scope,
3226- &format!(
3227- "Dynamic Worker env size ({} bytes) exceeds the maximum \
3228- allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.",
3229- env.len()
3230- ),
3231- );
3232- }
3233- }
3234- // globalOutbound: absent inherits the caller's authority, null denies
3235- // ambient egress, a Fetcher (broker) is not implemented yet.
3236- let egress = match code.get("globalOutbound") {
3237- None => actor_runtime_state(scope).egress,
3238- Some(v) if v.is_null() => EgressPolicy::Deny,
3239- Some(_) => {
3240- return loader_throw(
3241- scope,
3242- "worker loader: globalOutbound broker is not implemented yet",
3243- );
3244- }
3245- };
3246- // Bound live loaded workers so a runaway agent loop cannot exhaust
3247- // threads and isolates. Evicted workers (dropped stubs) free their slot.
3248- let max = std::env::var("CELLD_MAX_LOADED_WORKERS")
3249- .ok()
3250- .and_then(|v| v.parse::<usize>().ok())
3251- .unwrap_or(256);
3252- if loader_registry().lock().unwrap().len() >= max {
3253- return loader_throw(
3254- scope,
3255- &format!("worker loader: too many loaded workers (limit {max})"),
3256- );
3257- }
3258- // Honor the WorkerCode's declared compatibility (workerd worker_compat
3259- // reads snake_case keys); Code Mode workers keep RPC on regardless.
3260- let mut compat = crate::worker_compat(&serde_json::json!({
3261- "compatibility_date": code.get("compatibilityDate"),
3262- "compatibility_flags": code.get("compatibilityFlags"),
3263- }));
3264- compat.js_rpc = true;
3265- let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed);
3266- let config = Arc::new(
3267- WorkerConfig::new(WorkerConfigOptions {
3268- src,
3269- script_name: format!("__loader:{id}"),
3270- do_classes: Vec::new(),
3271- bindings: Vec::new(),
3272- r2_bindings: Vec::new(),
3273- ai_binding: None,
3274- vars: Vec::new(),
3275- node: String::new(),
3276- text: Vec::new(),
3277- compat,
3278- })
3279- .with_egress(egress)
3280- .with_loader_env(loader_env)
3281- .with_loader_modules(loader_modules),
3282- );
3283- let (tx, rx) = std::sync::mpsc::channel::<LoaderJob>();
3284- loader_registry().lock().unwrap().insert(id, tx);
3285- std::thread::spawn(move || {
3286- asyncrt::init();
3287- let mut w = match Worker::load_config(config, &[]) {
3288- Ok(w) => w,
3289- Err(e) => return drain_loader_load_error(rx, &format!("{e}")),
3290- };
3291- for job in rx {
3292- match job {
3293- LoaderJob::Fetch {
3294- url,
3295- method,
3296- body,
3297- headers,
3298- reply,
3299- } => {
3300- if w.fetch_and_reply_id(&url, &method, &body, &headers, None, reply)
3301- .is_err()
3302- {
3303- break;
3304- }
3305- }
3306- LoaderJob::Rpc {
3307- entrypoint,
3308- method,
3309- args,
3310- reply,
3311- } => {
3312- let _ = reply.send(w.dispatch_entrypoint_rpc(&entrypoint, &method, args));
3313- }
3314- }
3315- }
3316- });
3317- rv.set(v8::Number::new(scope, id as f64).into());
3318-}
3319-
3320-/// Reply to every queued job with the load error, so a worker that failed to
3321-/// compile rejects its callers cleanly instead of dropping their channels.
3322-fn drain_loader_load_error(rx: std::sync::mpsc::Receiver<LoaderJob>, error: &str) {
3323- for job in rx {
3324- match job {
3325- LoaderJob::Fetch { reply, .. } => {
3326- let _ = reply.send(Err(anyhow!("{error}")));
3327- }
3328- LoaderJob::Rpc { reply, .. } => {
3329- let _ = reply.send(Err(anyhow!("{error}")));
3330- }
3331- }
3332- }
3333-}
3334-
3335-/// `__loader_fetch(id, url, method, body, headersJson)` -> Promise<json>. The
3336-/// loaded-worker analog of `__svc_call`: encodes the response the same way.
3337-fn op_loader_fetch(
3338- scope: &mut v8::PinScope,
3339- args: v8::FunctionCallbackArguments,
3340- mut rv: v8::ReturnValue<v8::Value>,
3341-) {
3342- let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3343- let url = args.get(1).to_rust_string_lossy(scope);
3344- let method = args.get(2).to_rust_string_lossy(scope);
3345- let body = view_bytes(args.get(3)).unwrap_or_default();
3346- let headers =
3347- serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default();
3348- let (tx, rx) = tokio::sync::oneshot::channel();
3349- let sent = loader_registry()
3350- .lock()
3351- .unwrap()
3352- .get(&id)
3353- .map(|s| {
3354- s.send(LoaderJob::Fetch {
3355- url,
3356- method,
3357- body,
3358- headers,
3359- reply: tx,
3360- })
3361- .is_ok()
3362- })
3363- .unwrap_or(false);
3364- let async_id = asyncrt::enqueue(async move {
3365- if !sent {
3366- return Err("worker loader: unknown worker".into());
3367- }
3368- match rx.await {
3369- Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3370- Ok(Err(error)) => Err(format!("{error}")),
3371- Err(error) => Err(format!("loaded worker dropped: {error}")),
3372- }
3373- });
3374- rv.set(promise_for(scope, async_id));
3375-}
3376-
3377-/// `__loader_rpc(id, entrypoint, method, argsSc)` -> Promise<Uint8Array>. The
3378-/// loaded-worker analog of `__svc_rpc`: a named-entrypoint method call whose
3379-/// args and result are V8 structured-clone bytes.
3380-fn op_loader_rpc(
3381- scope: &mut v8::PinScope,
3382- args: v8::FunctionCallbackArguments,
3383- mut rv: v8::ReturnValue<v8::Value>,
3384-) {
3385- let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3386- let entrypoint = args.get(1).to_rust_string_lossy(scope);
3387- let method = args.get(2).to_rust_string_lossy(scope);
3388- let call_args = view_bytes(args.get(3)).unwrap_or_default();
3389- let (tx, rx) = tokio::sync::oneshot::channel();
3390- let sent = loader_registry()
3391- .lock()
3392- .unwrap()
3393- .get(&id)
3394- .map(|s| {
3395- s.send(LoaderJob::Rpc {
3396- entrypoint,
3397- method,
3398- args: call_args,
3399- reply: tx,
3400- })
3401- .is_ok()
3402- })
3403- .unwrap_or(false);
3404- let async_id = asyncrt::enqueue(async move {
3405- if !sent {
3406- return Err("worker loader: unknown worker".into());
3407- }
3408- match rx.await {
3409- Ok(Ok(result)) => Ok(result),
3410- Ok(Err(error)) => Err(format!("{error}")),
3411- Err(error) => Err(format!("loaded worker dropped: {error}")),
3412- }
3413- });
3414- rv.set(promise_for(scope, async_id));
3415-}
3416-
3417-/// `__loader_drop(id)` — evict a loaded worker. Called from a
3418-/// FinalizationRegistry when its stub is GC'd: removing the registry entry
3419-/// drops the job-channel Sender, so the worker thread's receive loop ends and
3420-/// the isolate is dropped on that thread. Without this every load() would leak
3421-/// a thread and isolate.
3422-fn op_loader_drop(
3423- scope: &mut v8::PinScope,
3424- args: v8::FunctionCallbackArguments,
3425- _rv: v8::ReturnValue<v8::Value>,
3426-) {
3427- let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3428- loader_registry().lock().unwrap().remove(&id);
3429-}
3430-
3431-/// `__loader_count()` -> live loaded-worker count, for eviction tests.
3432-#[cfg(all(test, celld_internal_tests))]
3433-fn op_loader_count(
3434- scope: &mut v8::PinScope,
3435- _args: v8::FunctionCallbackArguments,
3436- mut rv: v8::ReturnValue<v8::Value>,
3437-) {
3438- let n = loader_registry().lock().unwrap().len();
3439- rv.set(v8::Number::new(scope, n as f64).into());
3440-}
3441-
3442-/// `__writePosition(scope)` -> the cell's committed-write position (a number),
3443-/// or `null` when the scope has no open connection. The co-hosted DO fast path
3444-/// samples this around an inline `fetch` to tell a write from a read.
3445-fn op_write_position(
3446- scope: &mut v8::PinScope,
3447- args: v8::FunctionCallbackArguments,
3448- mut rv: v8::ReturnValue<v8::Value>,
3449-) {
3450- let cell = args.get(0).to_rust_string_lossy(scope);
3451- match storage::write_position(&cell) {
3452- Some(position) => rv.set(v8::Number::new(scope, position as f64).into()),
3453- None => rv.set(v8::null(scope).into()),
3454- }
3455-}
3456-
3457-/// `__gateWrite(scope, position)` -> a promise that resolves once the cell is
3458-/// durable and rejects if durability cannot be proved. The co-hosted DO fast
3459-/// path awaits this before returning an inline write's response, so the caller
3460-/// never observes a write the node cannot prove durable — the routed output
3461-/// gate, applied where the inline write actually happens.
3462-fn op_gate_write(
3463- scope: &mut v8::PinScope,
3464- args: v8::FunctionCallbackArguments,
3465- mut rv: v8::ReturnValue<v8::Value>,
3466-) {
3467- let cell = args.get(0).to_rust_string_lossy(scope);
3468- let position = args
3469- .get(1)
3470- .to_integer(scope)
3471- .map(|n| n.value() as u64)
3472- .unwrap_or(0);
3473- let (tx, receive) = tokio::sync::oneshot::channel();
3474- let sent = GATE_TX
3475- .get()
3476- .map(|gate| {
3477- gate.send(GateReq {
3478- scope: cell,
3479- position,
3480- reply: tx,
3481- })
3482- .is_ok()
3483- })
3484- .unwrap_or(false);
3485- let id = asyncrt::enqueue(async move {
3486- if !sent {
3487- return Err("no output-gate channel".into());
3488- }
3489- match receive.await {
3490- Ok(Ok(())) => Ok(String::new()),
3491- Ok(Err(error)) => Err(format!("{error:?}")),
3492- Err(_) => Err("output gate dropped".into()),
3493- }
3494- });
3495- rv.set(promise_for(scope, id));
3496-}
3497-
3498-fn op_do_call(
3499- scope: &mut v8::PinScope,
3500- args: v8::FunctionCallbackArguments,
3501- mut rv: v8::ReturnValue<v8::Value>,
3502-) {
3503- op_do_call_impl(scope, args, &mut rv, false);
3504-}
3505-
3506-fn op_do_call_cancellable(
3507- scope: &mut v8::PinScope,
3508- args: v8::FunctionCallbackArguments,
3509- mut rv: v8::ReturnValue<v8::Value>,
3510-) {
3511- op_do_call_impl(scope, args, &mut rv, true);
3512-}
3513-
3514-fn op_do_call_impl(
3515- scope: &mut v8::PinScope,
3516- args: v8::FunctionCallbackArguments,
3517- rv: &mut v8::ReturnValue<v8::Value>,
3518- cancellable: bool,
3519-) {
3520- let cell = args.get(0).to_rust_string_lossy(scope);
3521- let name_value = args.get(1);
3522- let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
3523- let url = args.get(2).to_rust_string_lossy(scope);
3524- let method = args.get(3).to_rust_string_lossy(scope);
3525- let body = view_bytes(args.get(4)).unwrap_or_default();
3526- let headers =
3527- serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)).unwrap_or_default();
3528- let (tx, rx) = tokio::sync::oneshot::channel();
3529- let (request_id, cancel, cancel_guard) = if cancellable {
3530- let request_id = next_do_request_id();
3531- let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
3532- do_call_cancels()
3533- .lock()
3534- .unwrap()
3535- .insert(request_id, cancel_sender);
3536- (
3537- Some(request_id),
3538- Some(cancel_receiver),
3539- Some(DoCallCancelGuard(request_id)),
3540- )
3541- } else {
3542- (None, None, None)
3543- };
3544- let sent = DO_CALL_TX
3545- .get()
3546- .map(|t| {
3547- t.send(DoCallReq {
3548- request_id,
3549- cancel,
3550- scope: cell,
3551- name,
3552- url,
3553- method,
3554- body,
3555- headers,
3556- reply: tx,
3557- })
3558- .is_ok()
3559- })
3560- .unwrap_or(false);
3561- let id = asyncrt::enqueue(async move {
3562- let _cancel_guard = cancel_guard;
3563- if !sent {
3564- return Err("no proxy channel".into());
3565- }
3566- match rx.await {
3567- Ok(Ok(response)) => Ok(encode_http_response(response, true)),
3568- Ok(Err(e)) => Err(format!("{e}")),
3569- Err(e) => Err(format!("proxy dropped: {e}")),
3570- }
3571- });
3572- let p = promise_for(scope, id);
3573- if let Some(request_id) = request_id {
3574- if let Some(promise) = p.to_object(scope) {
3575- let key = v8::String::new(scope, "__celldCancelId").unwrap();
3576- let request_id = v8::String::new(scope, &request_id_string(request_id)).unwrap();
3577- promise.set(scope, key.into(), request_id.into());
3578- }
3579- }
3580- rv.set(p);
3581-}
3582-
3583-fn op_do_call_cancel(
3584- scope: &mut v8::PinScope,
3585- args: v8::FunctionCallbackArguments,
3586- _rv: v8::ReturnValue<v8::Value>,
3587-) {
3588- let request_id = args.get(0).to_rust_string_lossy(scope);
3589- let Some(request_id) = parse_request_id(&request_id) else {
3590- return;
3591- };
3592- if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) {
3593- let _ = cancel.send(());
3594- }
3595-}
3596-
3597-/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>;
3598-/// arguments and result are V8 structured-clone bytes.
3599-fn op_rpc_call(
3600- scope: &mut v8::PinScope,
3601- args: v8::FunctionCallbackArguments,
3602- mut rv: v8::ReturnValue<v8::Value>,
3603-) {
3604- let cell = args.get(0).to_rust_string_lossy(scope);
3605- let name_value = args.get(1);
3606- let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
3607- let method = args.get(2).to_rust_string_lossy(scope);
3608- let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default());
3609- let (tx, rx) = tokio::sync::oneshot::channel();
3610- let sent = RPC_CALL_TX
3611- .get()
3612- .map(|t| {
3613- t.send(RpcCallReq {
3614- scope: cell,
3615- name,
3616- method,
3617- args,
3618- reply: tx,
3619- })
3620- .is_ok()
3621- })
3622- .unwrap_or(false);
3623- let id = asyncrt::enqueue(async move {
3624- if !sent {
3625- return Err("no RPC channel".into());
3626- }
3627- match rx.await {
3628- Ok(Ok(RpcData::V8(bytes))) => Ok(bytes),
3629- Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()),
3630- Ok(Err(e)) => Err(format!("{e}")),
3631- Err(e) => Err(format!("RPC proxy dropped: {e}")),
3632- }
3633- });
3634- let p = promise_for(scope, id);
3635- rv.set(p);
3636-}
3637-
3638-/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON
3639-/// `{status, body, headers}` string. Streaming is a later layer.
3640-fn op_fetch(
3641- scope: &mut v8::PinScope,
3642- args: v8::FunctionCallbackArguments,
3643- mut rv: v8::ReturnValue<v8::Value>,
3644-) {
3645- // A loaded worker with globalOutbound: null has no ambient egress: it must
3646- // reach the world through `env` capabilities. Message matches workerd.
3647- if actor_runtime_state(scope).egress == EgressPolicy::Deny {
3648- return loader_throw(
3649- scope,
3650- "This worker is not permitted to access the internet via global \
3651- functions like fetch(). It must use capabilities (such as \
3652- bindings in 'env') to talk to the outside world.",
3653- );
3654- }
3655- let method = args.get(0).to_rust_string_lossy(scope);
3656- let url = args.get(1).to_rust_string_lossy(scope);
3657- let b = args.get(2);
3658- let body: Option<Vec<u8>> = if b.is_undefined() || b.is_null() {
3659- None
3660- } else {
3661- serde_json::from_str(&b.to_rust_string_lossy(scope)).ok()
3662- };
3663- let headers: Vec<(String, String)> =
3664- serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
3665- let redirect = args.get(4).to_rust_string_lossy(scope);
3666- let client = if redirect == "manual" {
3667- HTTP_MANUAL.with(|client| client.clone())
3668- } else {
3669- HTTP.with(|client| client.clone())
3670- };
3671- let id = asyncrt::enqueue(async move {
3672- let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET);
3673- // a timeout bounds a black-hole host: the future settles (Err) instead
3674- // of parking run_loop forever — the hang the Drop guard can't catch.
3675- let fetch_timeout = std::env::var("CELLD_FETCH_TIMEOUT_S")
3676- .ok()
3677- .and_then(|value| value.parse().ok())
3678- .filter(|seconds| *seconds > 0)
3679- .unwrap_or(120);
3680- let mut rb = client
3681- .request(m, &url)
3682- .timeout(std::time::Duration::from_secs(fetch_timeout));
3683- for (name, value) in headers {
3684- rb = rb.header(name, value);
3685- }
3686- if let Some(b) = body {
3687- rb = rb.body(b);
3688- }
3689- match rb.send().await {
3690- Ok(resp) => {
3691- let status = resp.status().as_u16();
3692- let headers = resp
3693- .headers()
3694- .iter()
3695- .map(|(name, value)| {
3696- (
3697- name.as_str().to_string(),
3698- value.to_str().unwrap_or_default().to_string(),
3699- )
3700- })
3701- .collect::<Vec<_>>();
3702- let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3703- register_http_stream(stream_id, HttpStreamSource::Response(resp));
3704- Ok(serde_json::json!({
3705- "status": status, "streamId": stream_id, "headers": headers,
3706- })
3707- .to_string())
3708- }
3709- Err(e) => Err(format!("fetch: {e}")),
3710- }
3711- });
3712- let p = promise_for(scope, id);
3713- rv.set(p);
3714-}
3715-
3716-fn op_asset_fetch(
3717- scope: &mut v8::PinScope,
3718- args: v8::FunctionCallbackArguments,
3719- mut rv: v8::ReturnValue<v8::Value>,
3720-) {
3721- let script = args.get(0).to_rust_string_lossy(scope);
3722- let method = args.get(1).to_rust_string_lossy(scope);
3723- let url = args.get(2).to_rust_string_lossy(scope);
3724- let headers: Vec<(String, String)> =
3725- serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
3726- let (tx, rx) = tokio::sync::oneshot::channel();
3727- let sent = ASSET_CALL_TX.get().is_some_and(|sender| {
3728- sender
3729- .send(AssetCallReq {
3730- script,
3731- url,
3732- method,
3733- headers,
3734- reply: tx,
3735- })
3736- .is_ok()
3737- });
3738- let id = asyncrt::enqueue(async move {
3739- if !sent {
3740- return Err("no asset resolver channel".to_string());
3741- }
3742- match rx.await {
3743- Ok(Ok(response)) => {
3744- let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3745- let (body_tx, body_rx) = tokio::sync::mpsc::channel(1);
3746- if !response.body.is_empty() {
3747- let _ = body_tx.send(Ok(response.body)).await;
3748- }
3749- drop(body_tx);
3750- register_http_stream(stream_id, HttpStreamSource::Receiver(body_rx));
3751- Ok(serde_json::json!({
3752- "status": response.status,
3753- "streamId": stream_id,
3754- "headers": response.headers,
3755- })
3756- .to_string())
3757- }
3758- Ok(Err(error)) => Err(format!("asset fetch: {error}")),
3759- Err(error) => Err(format!("asset resolver dropped: {error}")),
3760- }
3761- });
3762- rv.set(promise_for(scope, id));
3763-}
3764-
3765-async fn next_http_stream_chunk(source: &mut HttpStreamSource) -> Result<Option<Vec<u8>>, String> {
3766- match source {
3767- HttpStreamSource::Response(response) => response
3768- .chunk()
3769- .await
3770- .map(|chunk| chunk.map(|bytes| bytes.to_vec()))
3771- .map_err(|error| format!("response stream: {error}")),
3772- HttpStreamSource::Receiver(receiver) => match receiver.recv().await {
3773- Some(Ok(bytes)) => Ok(Some(bytes)),
3774- Some(Err(error)) => Err(error),
3775- None => Ok(None),
3776- },
3777- HttpStreamSource::Stream(stream) => stream.next().await.transpose(),
3778- }
3779-}
3780-
3781-/// Move a host response source into a directly-polled stream. No pump task is
3782-/// needed: the eventual HTTP or JS consumer supplies the backpressure.
3783-fn http_chunk_stream(source: HttpStreamSource) -> HttpChunkStream {
3784- match source {
3785- HttpStreamSource::Response(response) => Box::pin(response.bytes_stream().map(|chunk| {
3786- chunk
3787- .map(|bytes| bytes.to_vec())
3788- .map_err(|error| format!("response stream: {error}"))
3789- })),
3790- HttpStreamSource::Receiver(receiver) => {
3791- Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver))
3792- }
3793- HttpStreamSource::Stream(stream) => stream,
3794- }
3795-}
3796-
3797-/// Host-native tee for an outbound response. Both branches are represented by
3798-/// stream IDs, so one can be returned through Axum while JS independently
3799-/// scans the other for observability or usage accounting.
3800-fn tee_http_stream(mut source: HttpStreamSource) -> (u64, u64) {
3801- let (tx1, rx1) = tokio::sync::mpsc::channel(16);
3802- let (tx2, rx2) = tokio::sync::mpsc::channel(16);
3803- let id1 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3804- let id2 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3805- register_http_stream(id1, HttpStreamSource::Receiver(rx1));
3806- register_http_stream(id2, HttpStreamSource::Receiver(rx2));
3807- asyncrt::op_handle().spawn(async move {
3808- loop {
3809- match next_http_stream_chunk(&mut source).await {
3810- Ok(Some(bytes)) => {
3811- let first = tx1.send(Ok(bytes.clone())).await.is_ok();
3812- let second = tx2.send(Ok(bytes)).await.is_ok();
3813- if !first && !second {
3814- break;
3815- }
3816- }
3817- Ok(None) => break,
3818- Err(error) => {
3819- let _ = tx1.send(Err(error.clone())).await;
3820- let _ = tx2.send(Err(error)).await;
3821- break;
3822- }
3823- }
3824- }
3825- });
3826- (id1, id2)
3827-}
3828-
3829-fn op_http_stream_read(
3830- scope: &mut v8::PinScope,
3831- args: v8::FunctionCallbackArguments,
3832- mut rv: v8::ReturnValue<v8::Value>,
3833-) {
3834- let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3835- let source = http_streams()
3836- .lock()
3837- .unwrap()
3838- .get_mut(&stream_id)
3839- .and_then(|stream| {
3840- stream
3841- .source
3842- .take()
3843- .map(|source| (source, stream.cancelled.subscribe()))
3844- });
3845- let id = asyncrt::enqueue(async move {
3846- let Some((mut source, mut cancelled)) = source else {
3847- return Ok(serde_json::json!({ "done": true }).to_string());
3848- };
3849- let next = tokio::select! {
3850- result = next_http_stream_chunk(&mut source) => Some(result),
3851- _ = cancelled.changed() => None,
3852- };
3853- match next {
3854- None => Ok(serde_json::json!({ "done": true }).to_string()),
3855- Some(Ok(Some(bytes))) => {
3856- if let Some(stream) = http_streams().lock().unwrap().get_mut(&stream_id) {
3857- stream.created = Instant::now();
3858- stream.source = Some(source);
3859- }
3860- Ok(serde_json::json!({ "done": false, "bytes": bytes }).to_string())
3861- }
3862- Some(Ok(None)) => {
3863- http_streams().lock().unwrap().remove(&stream_id);
3864- Ok(serde_json::json!({ "done": true }).to_string())
3865- }
3866- Some(Err(error)) => {
3867- http_streams().lock().unwrap().remove(&stream_id);
3868- Err(error)
3869- }
3870- }
3871- });
3872- rv.set(promise_for(scope, id));
3873-}
3874-
3875-fn op_http_stream_tee(
3876- scope: &mut v8::PinScope,
3877- args: v8::FunctionCallbackArguments,
3878- mut rv: v8::ReturnValue<v8::Value>,
3879-) {
3880- let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3881- let source = http_streams()
3882- .lock()
3883- .unwrap()
3884- .remove(&stream_id)
3885- .and_then(|stream| stream.source);
3886- let Some(source) = source else {
3887- let message = v8::String::new(scope, "response stream is no longer available").unwrap();
3888- let exception = v8::Exception::type_error(scope, message);
3889- scope.throw_exception(exception);
3890- return;
3891- };
3892- let ids = tee_http_stream(source);
3893- let json = serde_json::to_string(&ids).unwrap();
3894- rv.set(v8::String::new(scope, &json).unwrap().into());
3895-}
3896-
3897-fn op_http_stream_cancel(
3898- scope: &mut v8::PinScope,
3899- args: v8::FunctionCallbackArguments,
3900- _rv: v8::ReturnValue<v8::Value>,
3901-) {
3902- let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3903- if let Some(stream) = http_streams().lock().unwrap().remove(&stream_id) {
3904- let _ = stream.cancelled.send(true);
3905- }
3906-}
3907-
3908-fn op_response_stream_create(
3909- scope: &mut v8::PinScope,
3910- _args: v8::FunctionCallbackArguments,
3911- mut rv: v8::ReturnValue<v8::Value>,
3912-) {
3913- let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3914- let (writer, receiver) = tokio::sync::mpsc::channel(1);
3915- let (finished, _) = tokio::sync::watch::channel(false);
3916- let now = Instant::now();
3917- register_http_stream(stream_id, HttpStreamSource::Receiver(receiver));
3918- let mut writers = response_stream_writers().lock().unwrap();
3919- writers.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60));
3920- writers.insert(
3921- stream_id,
3922- ResponseStreamWriter {
3923- created: now,
3924- writer,
3925- finished,
3926- },
3927- );
3928- rv.set(v8::Number::new(scope, stream_id as f64).into());
3929-}
3930-
3931-fn op_response_stream_write(
3932- scope: &mut v8::PinScope,
3933- args: v8::FunctionCallbackArguments,
3934- mut rv: v8::ReturnValue<v8::Value>,
3935-) {
3936- let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3937- let bytes = args
3938- .get(1)
3939- .try_cast::<v8::ArrayBufferView>()
3940- .ok()
3941- .map(|view| {
3942- let mut bytes = vec![0; view.byte_length()];
3943- view.copy_contents(&mut bytes);
3944- bytes
3945- });
3946- let writer = response_stream_writers()
3947- .lock()
3948- .unwrap()
3949- .get_mut(&stream_id)
3950- .map(|stream| {
3951- stream.created = Instant::now();
3952- stream.writer.clone()
3953- });
3954- let id = asyncrt::enqueue(async move {
3955- let Some(bytes) = bytes else {
3956- return Err("response stream chunks must be ArrayBuffer views".into());
3957- };
3958- let Some(writer) = writer else {
3959- return Err("response stream consumer canceled".into());
3960- };
3961- if writer.send(Ok(bytes)).await.is_err() {
3962- response_stream_writers().lock().unwrap().remove(&stream_id);
3963- return Err("response stream consumer canceled".into());
3964- }
3965- Ok(String::new())
3966- });
3967- rv.set(promise_for(scope, id));
3968-}
3969-
3970-fn op_response_stream_closed(
3971- scope: &mut v8::PinScope,
3972- args: v8::FunctionCallbackArguments,
3973- mut rv: v8::ReturnValue<v8::Value>,
3974-) {
3975- let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3976- let (writer, mut finished) = response_stream_writers()
3977- .lock()
3978- .unwrap()
3979- .get(&stream_id)
3980- .map(|stream| (stream.writer.clone(), stream.finished.subscribe()))
3981- .unzip();
3982- let id = asyncrt::enqueue(async move {
3983- let cancelled = match (writer, finished.as_mut()) {
3984- (Some(writer), Some(finished)) => tokio::select! {
3985- biased;
3986- result = finished.changed() => result.is_err(),
3987- _ = writer.closed() => true,
3988- },
3989- _ => false,
3990- };
3991- Ok(String::from(if cancelled {
3992- "cancelled"
3993- } else {
3994- "finished"
3995- }))
3996- });
3997- rv.set(promise_for(scope, id));
3998-}
3999-
4000-fn op_response_stream_close(
4001- scope: &mut v8::PinScope,
4002- args: v8::FunctionCallbackArguments,
4003- mut rv: v8::ReturnValue<v8::Value>,
4004-) {
4005- let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4006- let error = args.get(1).to_rust_string_lossy(scope);
4007- let stream = response_stream_writers().lock().unwrap().remove(&stream_id);
4008- let id = asyncrt::enqueue(async move {
4009- if let Some(stream) = stream {
4010- let _ = stream.finished.send(true);
4011- if !error.is_empty() {
4012- let _ = stream.writer.send(Err(error)).await;
4013- }
4014- }
4015- Ok(String::new())
4016- });
4017- rv.set(promise_for(scope, id));
4018-}
4019-
4020-pub fn reqwest_response_stream(response: reqwest::Response) -> HttpChunkStream {
4021- http_chunk_stream(HttpStreamSource::Response(response))
4022-}
4023-
4024-/// Timer op behind `setTimeout`: a promise resolving after `ms`.
4025-fn op_timer(
4026- scope: &mut v8::PinScope,
4027- args: v8::FunctionCallbackArguments,
4028- mut rv: v8::ReturnValue<v8::Value>,
4029-) {
4030- let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4031- let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64;
4032- let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
4033- timer_cancels().lock().unwrap().insert(timer_id, cancel_tx);
4034- let id = asyncrt::enqueue(async move {
4035- tokio::select! {
4036- _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {}
4037- _ = &mut cancel_rx => {}
4038- }
4039- timer_cancels().lock().unwrap().remove(&timer_id);
4040- Ok(String::new())
4041- });
4042- let p = promise_for(scope, id);
4043- rv.set(p);
4044-}
4045-
4046-fn op_timer_alloc(
4047- scope: &mut v8::PinScope,
4048- _args: v8::FunctionCallbackArguments,
4049- mut rv: v8::ReturnValue<v8::Value>,
4050-) {
4051- let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64);
4052- rv.set(id.into());
4053-}
4054-
4055-fn op_timer_cancel(
4056- scope: &mut v8::PinScope,
4057- args: v8::FunctionCallbackArguments,
4058- _rv: v8::ReturnValue<v8::Value>,
4059-) {
4060- let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4061- if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) {
4062- let _ = cancel.send(());
4063- }
4064-}
4065-
4066-fn durable_object_id_key(namespace_key: &str) -> [u8; 32] {
4067- DO_ID_KEYS.with(|keys| {
4068- if let Some(key) = keys.borrow().get(namespace_key) {
4069- return *key;
4070- }
4071- use sha2::Digest;
4072- let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into();
4073- keys.borrow_mut().insert(namespace_key.to_string(), key);
4074- key
4075- })
4076-}
4077-
4078-fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> {
4079- use hmac::Mac;
4080- let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key)
4081- .expect("SHA-256 accepts any HMAC key");
4082- mac.update(input);
4083- mac
4084-}
4085-
4086-fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] {
4087- use hmac::Mac;
4088-
4089- let key = durable_object_id_key(namespace_key);
4090- let mut id = [0_u8; 32];
4091- let digest = durable_object_id_hmac(&key, name.as_bytes())
4092- .finalize()
4093- .into_bytes();
4094- id[..16].copy_from_slice(&digest[..16]);
4095- let digest = durable_object_id_hmac(&key, &id[..16])
4096- .finalize()
4097- .into_bytes();
4098- id[16..].copy_from_slice(&digest[..16]);
4099- id
4100-}
4101-
4102-fn durable_object_id_hex(bytes: &[u8; 32]) -> String {
4103- const HEX: &[u8; 16] = b"0123456789abcdef";
4104- let mut output = String::with_capacity(64);
4105- for byte in bytes {
4106- output.push(HEX[(byte >> 4) as usize] as char);
4107- output.push(HEX[(byte & 0x0f) as usize] as char);
4108- }
4109- output
4110-}
4111-
4112-fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> {
4113- if value.len() != 64 {
4114- return None;
4115- }
4116- let mut output = [0_u8; 32];
4117- for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
4118- let nibble = |byte| match byte {
4119- b'0'..=b'9' => Some(byte - b'0'),
4120- b'a'..=b'f' => Some(byte - b'a' + 10),
4121- b'A'..=b'F' => Some(byte - b'A' + 10),
4122- _ => None,
4123- };
4124- output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
4125- }
4126- Some(output)
4127-}
4128-
4129-fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) {
4130- let message = v8::String::new(scope, message).unwrap();
4131- let exception = v8::Exception::type_error(scope, message);
4132- scope.throw_exception(exception);
4133-}
4134-
4135-fn register_actor_name(
4136- scope: &mut v8::PinScope,
4137- actor_scope: &str,
4138- name: Option<&str>,
4139-) -> Result<()> {
4140- let Some(name) = name else {
4141- return Ok(());
4142- };
4143- let context = scope.get_current_context();
4144- let global = context.global(scope);
4145- let cell_key = v8::String::new(scope, "__cell").unwrap();
4146- let cell = global
4147- .get(scope, cell_key.into())
4148- .and_then(|value| value.to_object(scope))
4149- .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
4150- let names_key = v8::String::new(scope, "idNames").unwrap();
4151- let names = cell
4152- .get(scope, names_key.into())
4153- .and_then(|value| value.to_object(scope))
4154- .ok_or_else(|| anyhow!("missing Durable Object name registry"))?;
4155- let actor_scope_key = v8::String::new(scope, actor_scope).unwrap();
4156- if let Some(existing) = names.get(scope, actor_scope_key.into()) {
4157- if !existing.is_undefined() {
4158- if existing.to_rust_string_lossy(scope) == name {
4159- return Ok(());
4160- }
4161- anyhow::bail!("actor name conflicts with active identity for {actor_scope}");
4162- }
4163- }
4164-
4165- let (class_name, id) = actor_scope
4166- .split_once(':')
4167- .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?;
4168- let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
4169- let namespace_keys = cell
4170- .get(scope, namespace_keys_key.into())
4171- .and_then(|value| value.to_object(scope))
4172- .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
4173- let class_name_key = v8::String::new(scope, class_name).unwrap();
4174- let namespace_key = namespace_keys
4175- .get(scope, class_name_key.into())
4176- .filter(|value| value.is_string())
4177- .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))?
4178- .to_rust_string_lossy(scope);
4179- let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name));
4180- if id != expected {
4181- anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}");
4182- }
4183- storage::set_actor_name(actor_scope, name)?;
4184-
4185- let name_value = v8::String::new(scope, name).unwrap();
4186- if !names
4187- .set(scope, actor_scope_key.into(), name_value.into())
4188- .unwrap_or(false)
4189- {
4190- anyhow::bail!("could not register Durable Object name");
4191- }
4192- Ok(())
4193-}
4194-
4195-fn op_do_id(
4196- scope: &mut v8::PinScope,
4197- args: v8::FunctionCallbackArguments,
4198- mut rv: v8::ReturnValue<v8::Value>,
4199-) {
4200- use hmac::Mac;
4201-
4202- let namespace_key = args.get(0).to_rust_string_lossy(scope);
4203- let operation = args.get(1).to_rust_string_lossy(scope);
4204- let input = args.get(2).to_rust_string_lossy(scope);
4205- let key = durable_object_id_key(&namespace_key);
4206- let mut id = [0_u8; 32];
4207-
4208- match operation.as_str() {
4209- "name" => {
4210- id = durable_object_id_for_name(&namespace_key, &input);
4211- rv.set(
4212- v8::String::new(scope, &durable_object_id_hex(&id))
4213- .unwrap()
4214- .into(),
4215- );
4216- return;
4217- }
4218- "unique" => {
4219- if getrandom::fill(&mut id[..16]).is_err() {
4220- throw_durable_object_id_error(scope, "secure random generation failed");
4221- return;
4222- }
4223- }
4224- "validate" => {
4225- let Some(decoded) = decode_durable_object_id(&input) else {
4226- throw_durable_object_id_error(
4227- scope,
4228- "Invalid Durable Object ID: must be 64 hex digits",
4229- );
4230- return;
4231- };
4232- if durable_object_id_hmac(&key, &decoded[..16])
4233- .verify_truncated_left(&decoded[16..])
4234- .is_err()
4235- {
4236- throw_durable_object_id_error(
4237- scope,
4238- "Durable Object ID is not valid for this namespace",
4239- );
4240- return;
4241- }
4242- rv.set(
4243- v8::String::new(scope, &input.to_ascii_lowercase())
4244- .unwrap()
4245- .into(),
4246- );
4247- return;
4248- }
4249- _ => {
4250- throw_durable_object_id_error(scope, "unknown Durable Object ID operation");
4251- return;
4252- }
4253- }
4254-
4255- let digest = durable_object_id_hmac(&key, &id[..16])
4256- .finalize()
4257- .into_bytes();
4258- id[16..].copy_from_slice(&digest[..16]);
4259- rv.set(
4260- v8::String::new(scope, &durable_object_id_hex(&id))
4261- .unwrap()
4262- .into(),
4263- );
4264-}
4265-
4266-fn crypto_bytes(value: &serde_json::Value, name: &str) -> Result<Vec<u8>> {
4267- serde_json::from_value(value.get(name).cloned().unwrap_or_default())
4268- .map_err(|_| anyhow!("invalid {name} bytes"))
4269-}
4270-
4271-fn rsa_jwk_uint(value: &serde_json::Value, name: &str) -> Result<rsa::BigUint> {
4272- use base64::Engine;
4273- let encoded = value
4274- .get(name)
4275- .and_then(|value| value.as_str())
4276- .ok_or_else(|| anyhow!("RSA JWK missing {name}"))?;
4277- let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
4278- .decode(encoded)
4279- .map_err(|_| anyhow!("invalid RSA JWK {name}"))?;
4280- Ok(rsa::BigUint::from_bytes_be(&bytes))
4281-}
4282-
4283-fn rsa_jwk_encode(value: &rsa::BigUint) -> String {
4284- use base64::Engine;
4285- base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value.to_bytes_be())
4286-}
4287-
4288-fn crypto_operation(operation: &str, args: &serde_json::Value) -> Result<serde_json::Value> {
4289- match operation {
4290- "hmac-sign" => {
4291- use hmac::Mac;
4292- let key = crypto_bytes(args, "key")?;
4293- let data = crypto_bytes(args, "data")?;
4294- let hash = args
4295- .get("hash")
4296- .and_then(|value| value.as_str())
4297- .unwrap_or("SHA-256");
4298- if !hash.eq_ignore_ascii_case("SHA-256") && !hash.eq_ignore_ascii_case("SHA256") {
4299- return Err(anyhow!("unsupported HMAC hash"));
4300- }
4301- let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(&key)
4302- .map_err(|_| anyhow!("invalid HMAC key"))?;
4303- mac.update(&data);
4304- Ok(serde_json::json!({ "bytes": mac.finalize().into_bytes().to_vec() }))
4305- }
4306- "aes-gcm-encrypt" | "aes-gcm-decrypt" => {
4307- use aes_gcm::aead::{Aead, KeyInit};
4308- let key = crypto_bytes(args, "key")?;
4309- let iv = crypto_bytes(args, "iv")?;
4310- let data = crypto_bytes(args, "data")?;
4311- let cipher = aes_gcm::Aes256Gcm::new_from_slice(&key)
4312- .map_err(|_| anyhow!("AES-GCM requires a 256-bit key"))?;
4313- let nonce = aes_gcm::Nonce::from_slice(&iv);
4314- let bytes = if operation == "aes-gcm-encrypt" {
4315- cipher.encrypt(nonce, data.as_ref())
4316- } else {
4317- cipher.decrypt(nonce, data.as_ref())
4318- }
4319- .map_err(|_| anyhow!("AES-GCM operation failed"))?;
4320- Ok(serde_json::json!({ "bytes": bytes }))
4321- }
4322- "ed25519-sign" => {
4323- use ed25519_dalek::pkcs8::DecodePrivateKey;
4324- use ed25519_dalek::Signer;
4325- let key = crypto_bytes(args, "key")?;
4326- let data = crypto_bytes(args, "data")?;
4327- let key = ed25519_dalek::SigningKey::from_pkcs8_der(&key)
4328- .map_err(|_| anyhow!("invalid Ed25519 PKCS#8 key"))?;
4329- Ok(serde_json::json!({ "bytes": key.sign(&data).to_bytes().to_vec() }))
4330- }
4331- "p256-sign" => {
4332- use p256::ecdsa::signature::Signer;
4333- use p256::pkcs8::DecodePrivateKey;
4334- let key = crypto_bytes(args, "key")?;
4335- let data = crypto_bytes(args, "data")?;
4336- let key = p256::ecdsa::SigningKey::from_pkcs8_der(&key)
4337- .map_err(|_| anyhow!("invalid P-256 PKCS#8 key"))?;
4338- let signature: p256::ecdsa::Signature = key.sign(&data);
4339- Ok(serde_json::json!({ "bytes": signature.to_bytes().to_vec() }))
4340- }
4341- "rsa-generate" => {
4342- use rsa::traits::{PrivateKeyParts, PublicKeyParts};
4343- let mut rng = rand::rngs::OsRng;
4344- let mut private = rsa::RsaPrivateKey::new(&mut rng, 2048)?;
4345- private.precompute()?;
4346- let public = rsa::RsaPublicKey::from(&private);
4347- let public_jwk = serde_json::json!({
4348- "kty": "RSA",
4349- "n": rsa_jwk_encode(public.n()),
4350- "e": rsa_jwk_encode(public.e()),
4351- "alg": "RSA-OAEP-256",
4352- "ext": true,
4353- "key_ops": ["encrypt"],
4354- });
4355- let private_jwk = serde_json::json!({
4356- "kty": "RSA",
4357- "n": rsa_jwk_encode(private.n()),
4358- "e": rsa_jwk_encode(private.e()),
4359- "d": rsa_jwk_encode(private.d()),
4360- "p": rsa_jwk_encode(&private.primes()[0]),
4361- "q": rsa_jwk_encode(&private.primes()[1]),
4362- "alg": "RSA-OAEP-256",
4363- "ext": true,
4364- "key_ops": ["decrypt"],
4365- });
4366- Ok(serde_json::json!({ "publicKey": public_jwk, "privateKey": private_jwk }))
4367- }
4368- "rsa-oaep-decrypt" => {
4369- let jwk = args.get("jwk").ok_or_else(|| anyhow!("missing RSA JWK"))?;
4370- let n = rsa_jwk_uint(jwk, "n")?;
4371- let e = rsa_jwk_uint(jwk, "e")?;
4372- let d = rsa_jwk_uint(jwk, "d")?;
4373- let p = rsa_jwk_uint(jwk, "p")?;
4374- let q = rsa_jwk_uint(jwk, "q")?;
4375- let mut key = rsa::RsaPrivateKey::from_components(n, e, d, vec![p, q])?;
4376- key.precompute()?;
4377- let data = crypto_bytes(args, "data")?;
4378- let bytes = key.decrypt(rsa::Oaep::new::<sha2::Sha256>(), &data)?;
4379- Ok(serde_json::json!({ "bytes": bytes }))
4380- }
4381- _ => Err(anyhow!("unsupported crypto operation")),
4382- }
4383-}
4384-
4385-fn op_crypto_operation(
4386- scope: &mut v8::PinScope,
4387- args: v8::FunctionCallbackArguments,
4388- mut rv: v8::ReturnValue<v8::Value>,
4389-) {
4390- let operation = args.get(0).to_rust_string_lossy(scope);
4391- let input: serde_json::Value =
4392- serde_json::from_str(&args.get(1).to_rust_string_lossy(scope)).unwrap_or_default();
4393- match crypto_operation(&operation, &input) {
4394- Ok(value) => {
4395- let json = value.to_string();
4396- rv.set(v8::String::new(scope, &json).unwrap().into());
4397- }
4398- Err(error) => {
4399- let message = v8::String::new(scope, &format!("crypto: {error}")).unwrap();
4400- let exception = v8::Exception::error(scope, message);
4401- scope.throw_exception(exception);
4402- }
4403- }
4404-}
4405-
4406-fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> {
4407- let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
4408- let mut bytes = vec![0_u8; view.byte_length()];
4409- view.copy_contents(&mut bytes);
4410- Some(bytes)
4411-}
4412-
4413-fn webcrypto_return_bytes(
4414- scope: &mut v8::PinScope,
4415- mut rv: v8::ReturnValue<v8::Value>,
4416- bytes: &[u8],
4417-) {
4418- let buffer = v8::ArrayBuffer::new(scope, bytes.len());
4419- if !bytes.is_empty() {
4420- let store = buffer.get_backing_store();
4421- let destination = unsafe {
4422- std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len())
4423- };
4424- destination.copy_from_slice(bytes);
4425- }
4426- let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap();
4427- rv.set(view.into());
4428-}
4429-
4430-/// Fill an existing integer typed array in-place. JS performs the WebCrypto
4431-/// type and 65,536-byte quota checks before entering this host op.
4432-fn op_webcrypto_random(
4433- scope: &mut v8::PinScope,
4434- args: v8::FunctionCallbackArguments,
4435- _rv: v8::ReturnValue<v8::Value>,
4436-) {
4437- let Ok(view) = v8::Local::<v8::ArrayBufferView>::try_from(args.get(0)) else {
4438- return;
4439- };
4440- let Some(buffer) = view.buffer(scope) else {
4441- return;
4442- };
4443- let store = buffer.get_backing_store();
4444- let offset = view.byte_offset();
4445- let len = view.byte_length();
4446- let bytes = unsafe {
4447- std::slice::from_raw_parts_mut(store[offset..offset + len].as_ptr() as *mut u8, len)
4448- };
4449- if getrandom::fill(bytes).is_err() {
4450- let message = v8::String::new(scope, "secure random generation failed").unwrap();
4451- let exception = v8::Exception::error(scope, message);
4452- scope.throw_exception(exception);
4453- }
4454-}
4455-
4456-/// WebCrypto digest: (algorithm, ArrayBufferView) -> Uint8Array.
4457-fn op_webcrypto_digest(
4458- scope: &mut v8::PinScope,
4459- args: v8::FunctionCallbackArguments,
4460- rv: v8::ReturnValue<v8::Value>,
4461-) {
4462- use sha2::Digest;
4463- let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
4464- let Some(bytes) = view_bytes(args.get(1)) else {
4465- return;
4466- };
4467- let digest = match algorithm.as_str() {
4468- "MD5" => md5::Md5::digest(&bytes).to_vec(),
4469- "SHA-1" => sha1::Sha1::digest(&bytes).to_vec(),
4470- "SHA-224" => sha2::Sha224::digest(&bytes).to_vec(),
4471- "SHA-256" => sha2::Sha256::digest(&bytes).to_vec(),
4472- "SHA-384" => sha2::Sha384::digest(&bytes).to_vec(),
4473- "SHA-512" => sha2::Sha512::digest(&bytes).to_vec(),
4474- _ => return,
4475- };
4476- webcrypto_return_bytes(scope, rv, &digest);
4477-}
4478-
4479-fn op_webcrypto_hmac_sign(
4480- scope: &mut v8::PinScope,
4481- args: v8::FunctionCallbackArguments,
4482- rv: v8::ReturnValue<v8::Value>,
4483-) {
4484- use hmac::Mac;
4485- let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
4486- let Some(key) = view_bytes(args.get(1)) else {
4487- return;
4488- };
4489- let Some(data) = view_bytes(args.get(2)) else {
4490- return;
4491- };
4492- macro_rules! sign {
4493- ($digest:ty) => {{
4494- let Ok(mut mac) = <hmac::Hmac<$digest> as hmac::Mac>::new_from_slice(&key) else {
4495- return;
4496- };
4497- mac.update(&data);
4498- mac.finalize().into_bytes().to_vec()
4499- }};
4500- }
4501- let signature = match algorithm.as_str() {
4502- "MD5" => sign!(md5::Md5),
4503- "SHA-1" => sign!(sha1::Sha1),
4504- "SHA-224" => sign!(sha2::Sha224),
4505- "SHA-256" => sign!(sha2::Sha256),
4506- "SHA-384" => sign!(sha2::Sha384),
4507- "SHA-512" => sign!(sha2::Sha512),
4508- _ => return,
4509- };
4510- webcrypto_return_bytes(scope, rv, &signature);
4511-}
4512-
4513-/// HMAC-based KDF cores for node:crypto. Manual PBKDF2 (RFC 2898) and HKDF
4514-/// (RFC 5869) over the hmac crate — no extra dependencies. The JS layer has
4515-/// already validated the digest name and the 255×hashLen output cap.
4516-fn hmac_once<D>(key: &[u8], parts: &[&[u8]]) -> Vec<u8>
4517-where
4518- D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
4519-{
4520- use hmac::Mac;
4521- let mut mac = <hmac::SimpleHmac<D> as hmac::Mac>::new_from_slice(key)
4522- .expect("HMAC accepts any key length");
4523- for part in parts {
4524- mac.update(part);
4525- }
4526- mac.finalize().into_bytes().to_vec()
4527-}
4528-
4529-fn pbkdf2_kdf<D>(password: &[u8], salt: &[u8], iterations: u32, keylen: usize) -> Vec<u8>
4530-where
4531- D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
4532-{
4533- let mut out = Vec::with_capacity(keylen);
4534- let mut block: u32 = 1;
4535- while out.len() < keylen {
4536- let mut u = hmac_once::<D>(password, &[salt, &block.to_be_bytes()]);
4537- let mut t = u.clone();
4538- for _ in 1..iterations {
4539- u = hmac_once::<D>(password, &[&u]);
4540- for (t_, u_) in t.iter_mut().zip(&u) {
4541- *t_ ^= u_;
4542- }
4543- }
4544- out.extend_from_slice(&t);
4545- block += 1;
4546- }
4547- out.truncate(keylen);
4548- out
4549-}
4550-
4551-fn hkdf_kdf<D>(ikm: &[u8], salt: &[u8], info: &[u8], length: usize) -> Vec<u8>
4552-where
4553- D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
4554-{
4555- let prk = hmac_once::<D>(salt, &[ikm]);
4556- let mut out = Vec::with_capacity(length);
4557- let mut t: Vec<u8> = Vec::new();
4558- let mut counter: u8 = 1;
4559- while out.len() < length {
4560- t = hmac_once::<D>(&prk, &[&t, info, &[counter]]);
4561- out.extend_from_slice(&t);
4562- counter += 1;
4563- }
4564- out.truncate(length);
4565- out
4566-}
4567-
4568-macro_rules! dispatch_digest {
4569- ($name:expr, $fn:ident, ($($arg:expr),*)) => {
4570- match $name {
4571- "MD5" => Some($fn::<md5::Md5>($($arg),*)),
4572- "SHA-1" => Some($fn::<sha1::Sha1>($($arg),*)),
4573- "SHA-224" => Some($fn::<sha2::Sha224>($($arg),*)),
4574- "SHA-256" => Some($fn::<sha2::Sha256>($($arg),*)),
4575- "SHA-384" => Some($fn::<sha2::Sha384>($($arg),*)),
4576- "SHA-512" => Some($fn::<sha2::Sha512>($($arg),*)),
4577- _ => None,
4578- }
4579- };
4580-}
4581-
4582-/// `$$pbkdf2(algorithm, password, salt, iterations, keylen)` -> Uint8Array
4583-fn op_node_pbkdf2(
4584- scope: &mut v8::PinScope,
4585- args: v8::FunctionCallbackArguments,
4586- rv: v8::ReturnValue<v8::Value>,
4587-) {
4588- let algorithm = args.get(0).to_rust_string_lossy(scope);
4589- let Some(password) = view_bytes(args.get(1)) else {
4590- return;
4591- };
4592- let Some(salt) = view_bytes(args.get(2)) else {
4593- return;
4594- };
4595- let iterations = args.get(3).uint32_value(scope).unwrap_or(0).max(1);
4596- let keylen = args.get(4).uint32_value(scope).unwrap_or(0) as usize;
4597- let out = dispatch_digest!(
4598- algorithm.as_str(),
4599- pbkdf2_kdf,
4600- (&password, &salt, iterations, keylen)
4601- );
4602- if let Some(out) = out {
4603- webcrypto_return_bytes(scope, rv, &out);
4604- }
4605-}
4606-
4607-/// `$$hkdf(algorithm, ikm, salt, info, length)` -> Uint8Array
4608-fn op_node_hkdf(
4609- scope: &mut v8::PinScope,
4610- args: v8::FunctionCallbackArguments,
4611- rv: v8::ReturnValue<v8::Value>,
4612-) {
4613- let algorithm = args.get(0).to_rust_string_lossy(scope);
4614- let Some(ikm) = view_bytes(args.get(1)) else {
4615- return;
4616- };
4617- let Some(salt) = view_bytes(args.get(2)) else {
4618- return;
4619- };
4620- let Some(info) = view_bytes(args.get(3)) else {
4621- return;
4622- };
4623- let length = args.get(4).uint32_value(scope).unwrap_or(0) as usize;
4624- let out = dispatch_digest!(algorithm.as_str(), hkdf_kdf, (&ikm, &salt, &info, length));
4625- if let Some(out) = out {
4626- webcrypto_return_bytes(scope, rv, &out);
4627- }
4628-}
4629-
4630-fn op_webcrypto_hmac_verify(
4631- scope: &mut v8::PinScope,
4632- args: v8::FunctionCallbackArguments,
4633- mut rv: v8::ReturnValue<v8::Value>,
4634-) {
4635- use hmac::Mac;
4636- let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
4637- let Some(key) = view_bytes(args.get(1)) else {
4638- return;
4639- };
4640- let Some(signature) = view_bytes(args.get(2)) else {
4641- return;
4642- };
4643- let Some(data) = view_bytes(args.get(3)) else {
4644- return;
4645- };
4646- macro_rules! verify {
4647- ($digest:ty) => {{
4648- let Ok(mut mac) = <hmac::Hmac<$digest> as hmac::Mac>::new_from_slice(&key) else {
4649- return;
4650- };
4651- mac.update(&data);
4652- mac.verify_slice(&signature).is_ok()
4653- }};
4654- }
4655- let valid = match algorithm.as_str() {
4656- "SHA-1" => verify!(sha1::Sha1),
4657- "SHA-256" => verify!(sha2::Sha256),
4658- "SHA-384" => verify!(sha2::Sha384),
4659- "SHA-512" => verify!(sha2::Sha512),
4660- _ => return,
4661- };
4662- rv.set(v8::Boolean::new(scope, valid).into());
4663-}
4664-
4665-fn op_webcrypto_aes_encrypt(
4666- scope: &mut v8::PinScope,
4667- args: v8::FunctionCallbackArguments,
4668- rv: v8::ReturnValue<v8::Value>,
4669-) {
4670- use aes_gcm::aead::{Aead, KeyInit};
4671- let Some(key) = view_bytes(args.get(0)) else {
4672- return;
4673- };
4674- let Some(iv) = view_bytes(args.get(1)) else {
4675- return;
4676- };
4677- let Some(data) = view_bytes(args.get(2)) else {
4678- return;
4679- };
4680- if iv.len() != 12 {
4681- return;
4682- }
4683- let nonce = aes_gcm::Nonce::from_slice(&iv);
4684- let encrypted = match key.len() {
4685- 16 => {
4686- let Ok(cipher) = aes_gcm::Aes128Gcm::new_from_slice(&key) else {
4687- return;
4688- };
4689- cipher.encrypt(nonce, data.as_ref())
4690- }
4691- 32 => {
4692- let Ok(cipher) = aes_gcm::Aes256Gcm::new_from_slice(&key) else {
4693- return;
4694- };
4695- cipher.encrypt(nonce, data.as_ref())
4696- }
4697- _ => return,
4698- };
4699- let Ok(encrypted) = encrypted else { return };
4700- webcrypto_return_bytes(scope, rv, &encrypted);
4701-}
4702-
4703-fn op_webcrypto_aes_decrypt(
4704- scope: &mut v8::PinScope,
4705- args: v8::FunctionCallbackArguments,
4706- rv: v8::ReturnValue<v8::Value>,
4707-) {
4708- use aes_gcm::aead::{Aead, KeyInit};
4709- let Some(key) = view_bytes(args.get(0)) else {
4710- return;
4711- };
4712- let Some(iv) = view_bytes(args.get(1)) else {
4713- return;
4714- };
4715- let Some(data) = view_bytes(args.get(2)) else {
4716- return;
4717- };
4718- if iv.len() != 12 {
4719- return;
4720- }
4721- let nonce = aes_gcm::Nonce::from_slice(&iv);
4722- let decrypted = match key.len() {
4723- 16 => {
4724- let Ok(cipher) = aes_gcm::Aes128Gcm::new_from_slice(&key) else {
4725- return;
4726- };
4727- cipher.decrypt(nonce, data.as_ref())
4728- }
4729- 32 => {
4730- let Ok(cipher) = aes_gcm::Aes256Gcm::new_from_slice(&key) else {
4731- return;
4732- };
4733- cipher.decrypt(nonce, data.as_ref())
4734- }
4735- _ => return,
4736- };
4737- let Ok(decrypted) = decrypted else { return };
4738- webcrypto_return_bytes(scope, rv, &decrypted);
4739-}
4740-
4741-fn op_zlib(
4742- scope: &mut v8::PinScope,
4743- args: v8::FunctionCallbackArguments,
4744- mut rv: v8::ReturnValue<v8::Value>,
4745-) {
4746- use std::io::{Read, Write};
4747- let mode = args.get(0).to_rust_string_lossy(scope);
4748- let bytes: Vec<u8> =
4749- serde_json::from_str(&args.get(1).to_rust_string_lossy(scope)).unwrap_or_default();
4750- let result = (|| -> Result<Vec<u8>> {
4751- match mode.as_str() {
4752- "gzip" => {
4753- let mut encoder =
4754- flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
4755- encoder.write_all(&bytes)?;
4756- Ok(encoder.finish()?)
4757- }
4758- "gunzip" => {
4759- let mut decoder = flate2::read::GzDecoder::new(bytes.as_slice());
4760- let mut out = Vec::new();
4761- decoder.read_to_end(&mut out)?;
4762- Ok(out)
4763- }
4764- "deflate" => {
4765- let mut encoder =
4766- flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
4767- encoder.write_all(&bytes)?;
4768- Ok(encoder.finish()?)
4769- }
4770- "inflate" => {
4771- let mut decoder = flate2::read::ZlibDecoder::new(bytes.as_slice());
4772- let mut out = Vec::new();
4773- decoder.read_to_end(&mut out)?;
4774- Ok(out)
4775- }
4776- "deflateRaw" => {
4777- let mut encoder =
4778- flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
4779- encoder.write_all(&bytes)?;
4780- Ok(encoder.finish()?)
4781- }
4782- "inflateRaw" => {
4783- let mut decoder = flate2::read::DeflateDecoder::new(bytes.as_slice());
4784- let mut out = Vec::new();
4785- decoder.read_to_end(&mut out)?;
4786- Ok(out)
4787- }
4788- _ => Err(anyhow!("unsupported zlib operation")),
4789- }
4790- })();
4791- match result {
4792- Ok(bytes) => {
4793- let json = serde_json::to_string(&bytes).unwrap();
4794- rv.set(v8::String::new(scope, &json).unwrap().into());
4795- }
4796- Err(error) => {
4797- let message = v8::String::new(scope, &format!("zlib: {error}")).unwrap();
4798- let exception = v8::Exception::error(scope, message);
4799- scope.throw_exception(exception);
4800- }
4801- }
4802-}
4803-
4804-/// One live `CompressionStream`/`DecompressionStream`: a stateful flate2
4805-/// writer whose `Vec` sink is drained after every push, so output streams
4806-/// chunk by chunk instead of arriving once at close.
4807-enum ZlibStream {
4808- GzipEncode(flate2::write::GzEncoder<Vec<u8>>),
4809- GzipDecode(flate2::write::GzDecoder<Vec<u8>>),
4810- ZlibEncode(flate2::write::ZlibEncoder<Vec<u8>>),
4811- ZlibDecode(flate2::write::ZlibDecoder<Vec<u8>>),
4812- RawEncode(flate2::write::DeflateEncoder<Vec<u8>>),
4813- RawDecode(flate2::write::DeflateDecoder<Vec<u8>>),
4814-}
4815-
4816-/// The six writer types share `write`/`flush`/`get_mut`/`finish` but no
4817-/// trait, so dispatch once here.
4818-macro_rules! zlib_each {
4819- ($stream:expr, $w:ident => $body:expr) => {
4820- match $stream {
4821- ZlibStream::GzipEncode($w) => $body,
4822- ZlibStream::GzipDecode($w) => $body,
4823- ZlibStream::ZlibEncode($w) => $body,
4824- ZlibStream::ZlibDecode($w) => $body,
4825- ZlibStream::RawEncode($w) => $body,
4826- ZlibStream::RawDecode($w) => $body,
4827- }
4828- };
4829-}
4830-
4831-impl ZlibStream {
4832- fn new(format: &str, decompress: bool) -> Option<ZlibStream> {
4833- use flate2::write as z;
4834- let level = flate2::Compression::default();
4835- let sink = Vec::new;
4836- Some(match (format, decompress) {
4837- ("gzip", false) => Self::GzipEncode(z::GzEncoder::new(sink(), level)),
4838- ("gzip", true) => Self::GzipDecode(z::GzDecoder::new(sink())),
4839- ("deflate", false) => Self::ZlibEncode(z::ZlibEncoder::new(sink(), level)),
4840- ("deflate", true) => Self::ZlibDecode(z::ZlibDecoder::new(sink())),
4841- ("deflate-raw", false) => Self::RawEncode(z::DeflateEncoder::new(sink(), level)),
4842- ("deflate-raw", true) => Self::RawDecode(z::DeflateDecoder::new(sink())),
4843- _ => return None,
4844- })
4845- }
4846-
4847- fn decompress(&self) -> bool {
4848- matches!(
4849- self,
4850- Self::GzipDecode(_) | Self::ZlibDecode(_) | Self::RawDecode(_)
4851- )
4852- }
4853-
4854- /// Workerd's canonical message, matched by its conformance suite.
4855- fn failure(&self) -> &'static str {
4856- if self.decompress() {
4857- "Decompression failed."
4858- } else {
4859- "Compression failed."
4860- }
4861- }
4862-
4863- /// Write one chunk and return whatever output it produced. Decoded
4864- /// output flows per chunk; encoders hold theirs until a full buffer
4865- /// accumulates (matching Workerd, whose suite reads a small message
4866- /// back as one chunk), with the rest arriving from `finish`. A
4867- /// decoder that stops consuming input has hit the end of the
4868- /// compressed stream, so leftover bytes are trailing garbage —
4869- /// Workerd's strict_compression_checks.
4870- fn push(&mut self, mut input: &[u8]) -> Result<Vec<u8>> {
4871- use std::io::Write;
4872- const ENCODER_CHUNK: usize = 32 * 1024;
4873- let failure = self.failure();
4874- let held = if self.decompress() { 0 } else { ENCODER_CHUNK };
4875- zlib_each!(self, w => {
4876- while !input.is_empty() {
4877- let n = w.write(input).map_err(|_| anyhow!(failure))?;
4878- if n == 0 { return Err(anyhow!(failure)); }
4879- input = &input[n..];
4880- }
4881- if w.get_ref().len() < held { return Ok(Vec::new()); }
4882- Ok(std::mem::take(w.get_mut()))
4883- })
4884- }
4885-
4886- /// Terminate the stream and return the final output. For gzip this
4887- /// also validates the trailer, so a truncated stream errors here.
4888- fn finish(self) -> Result<Vec<u8>> {
4889- let failure = self.failure();
4890- zlib_each!(self, w => w.finish().map_err(|_| anyhow!(failure)))
4891- }
4892-}
4893-
4894-thread_local! {
4895- static ZLIB_STREAMS: std::cell::RefCell<
4896- std::collections::HashMap<u64, ZlibStream>> = Default::default();
4897- static ZLIB_STREAM_NEXT: std::cell::Cell<u64> =
4898- const { std::cell::Cell::new(1) };
4899-}
4900-
4901-fn zlib_stream_return(
4902- scope: &mut v8::PinScope,
4903- rv: v8::ReturnValue<v8::Value>,
4904- result: Result<Vec<u8>>,
4905-) {
4906- match result {
4907- Ok(bytes) => webcrypto_return_bytes(scope, rv, &bytes),
4908- Err(error) => {
4909- let message = v8::String::new(scope, &error.to_string()).unwrap();
4910- let exception = v8::Exception::type_error(scope, message);
4911- scope.throw_exception(exception);
4912- }
4913- }
4914-}
4915-
4916-/// `__zlib_stream_new(format, decompress)` -> id. JS validates the format
4917-/// and throws the spec TypeError, so an unknown one here is a bug.
4918-fn op_zlib_stream_new(
4919- scope: &mut v8::PinScope,
4920- args: v8::FunctionCallbackArguments,
4921- mut rv: v8::ReturnValue<v8::Value>,
4922-) {
4923- let format = args.get(0).to_rust_string_lossy(scope);
4924- let decompress = args.get(1).boolean_value(scope);
4925- let stream = ZlibStream::new(&format, decompress).expect("JS validated the compression format");
4926- let id = ZLIB_STREAM_NEXT.with(|next| {
4927- let id = next.get();
4928- next.set(id + 1);
4929- id
4930- });
4931- ZLIB_STREAMS.with(|streams| streams.borrow_mut().insert(id, stream));
4932- rv.set(v8::Number::new(scope, id as f64).into());
4933-}
4934-
4935-/// `__zlib_stream_push(id, view)` -> Uint8Array (possibly empty). An
4936-/// error poisons the stream: its native state is dropped and the
4937-/// TypeError errors both sides of the transform.
4938-fn op_zlib_stream_push(
4939- scope: &mut v8::PinScope,
4940- args: v8::FunctionCallbackArguments,
4941- rv: v8::ReturnValue<v8::Value>,
4942-) {
4943- let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
4944- let bytes = view_bytes(args.get(1)).unwrap_or_default();
4945- let result = ZLIB_STREAMS.with(|streams| {
4946- let mut streams = streams.borrow_mut();
4947- let stream = streams
4948- .get_mut(&id)
4949- .ok_or_else(|| anyhow!("zlib stream already closed"))?;
4950- let out = stream.push(&bytes);
4951- if out.is_err() {
4952- streams.remove(&id);
4953- }
4954- out
4955- });
4956- zlib_stream_return(scope, rv, result);
4957-}
4958-
4959-/// `__zlib_stream_end(id)` -> the final Uint8Array. Consumes the stream.
4960-fn op_zlib_stream_end(
4961- scope: &mut v8::PinScope,
4962- args: v8::FunctionCallbackArguments,
4963- rv: v8::ReturnValue<v8::Value>,
4964-) {
4965- let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
4966- let result = ZLIB_STREAMS.with(|streams| {
4967- streams
4968- .borrow_mut()
4969- .remove(&id)
4970- .ok_or_else(|| anyhow!("zlib stream already closed"))
4971- });
4972- zlib_stream_return(scope, rv, result.and_then(ZlibStream::finish));
4973-}
4974-
4975-/// `__zlib_stream_drop(id)` — cancelled/aborted transform cleanup.
4976-fn op_zlib_stream_drop(
4977- scope: &mut v8::PinScope,
4978- args: v8::FunctionCallbackArguments,
4979- _rv: v8::ReturnValue<v8::Value>,
4980-) {
4981- let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
4982- ZLIB_STREAMS.with(|streams| streams.borrow_mut().remove(&id));
4983-}
4984-
4985-fn op_ws_send(
4986- scope: &mut v8::PinScope,
4987- args: v8::FunctionCallbackArguments,
4988- _rv: v8::ReturnValue<v8::Value>,
4989-) {
4990- let id = args
4991- .get(0)
4992- .to_integer(scope)
4993- .map(|n| n.value() as u64)
4994- .unwrap_or(0);
4995- let data = args.get(1).to_rust_string_lossy(scope);
4996- ws_emit(id, WsOut::Text(data));
4997-}
4998-fn op_ws_send_binary(
4999- scope: &mut v8::PinScope,
5000- args: v8::FunctionCallbackArguments,
5001- _rv: v8::ReturnValue<v8::Value>,
5002-) {
5003- let id = args
5004- .get(0)
5005- .to_integer(scope)
5006- .map(|n| n.value() as u64)
5007- .unwrap_or(0);
5008- let data = view_bytes(args.get(1)).unwrap_or_default();
5009- ws_emit(id, WsOut::Binary(data));
5010-}
5011-fn op_ws_close(
5012- scope: &mut v8::PinScope,
5013- args: v8::FunctionCallbackArguments,
5014- _rv: v8::ReturnValue<v8::Value>,
5015-) {
5016- let id = args
5017- .get(0)
5018- .to_integer(scope)
5019- .map(|n| n.value() as u64)
5020- .unwrap_or(0);
5021- let code = args.get(1).uint32_value(scope).unwrap_or(1000) as u16;
5022- let reason = args.get(2).to_rust_string_lossy(scope);
5023- ws_emit(id, WsOut::Close(code, reason));
5024-}
5025-fn op_ws_alloc(
5026- scope: &mut v8::PinScope,
5027- _args: v8::FunctionCallbackArguments,
5028- mut rv: v8::ReturnValue<v8::Value>,
5029-) {
5030- rv.set(v8::Number::new(scope, ws_next_id() as f64).into());
5031-}
5032-/// `fetch(url, { headers: { Upgrade: "websocket" } })`. Returns a JSON
5033-/// envelope: either an upgraded socket, or the ordinary response a server sent
5034-/// instead, which the caller returns unchanged.
5035-fn op_ws_upgrade(
5036- scope: &mut v8::PinScope,
5037- args: v8::FunctionCallbackArguments,
5038- mut rv: v8::ReturnValue<v8::Value>,
5039-) {
5040- if actor_runtime_state(scope).egress == EgressPolicy::Deny {
5041- return loader_throw(
5042- scope,
5043- "This worker is not permitted to access the internet via global functions.",
5044- );
5045- }
5046- let id = args
5047- .get(0)
5048- .to_integer(scope)
5049- .map(|n| n.value() as u64)
5050- .unwrap_or(0);
5051- let cell = args.get(1).to_rust_string_lossy(scope);
5052- let url = args.get(2).to_rust_string_lossy(scope);
5053- let headers: Vec<(String, String)> =
5054- serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
5055- let protocols: Vec<String> = headers
5056- .iter()
5057- .find(|(name, _)| name.eq_ignore_ascii_case("sec-websocket-protocol"))
5058- .map(|(_, value)| value.split(',').map(|p| p.trim().to_string()).collect())
5059- .unwrap_or_default();
5060- let pull = cell.is_empty().then(|| {
5061- let (pull_tx, pull_rx) = tokio::sync::mpsc::unbounded_channel();
5062- ws_pull_register(id, pull_rx);
5063- ws_region_track(id);
5064- pull_tx
5065- });
5066- let (tx, rx) = tokio::sync::oneshot::channel();
5067- let sent = OUTBOUND_WS_TX.get().is_some_and(|sender| {
5068- sender
5069- .send(OutboundWsReq {
5070- scope: cell,
5071- id,
5072- url,
5073- protocols,
5074- pull,
5075- headers,
5076- want_response: true,
5077- reply: tx,
5078- })
5079- .is_ok()
5080- });
5081- let async_id = asyncrt::enqueue(async move {
5082- if !sent {
5083- return Err("no outbound WebSocket channel".into());
5084- }
5085- let open = match rx.await {
5086- Ok(Ok(open)) => open,
5087- Ok(Err(error)) => return Err(format!("WebSocket upgrade failed: {error}")),
5088- Err(error) => return Err(format!("WebSocket connector dropped: {error}")),
5089- };
5090- Ok(match open.declined {
5091- Some(declined) => serde_json::json!({
5092- "upgraded": false,
5093- "status": declined.status,
5094- "headers": declined.headers,
5095- "body": declined.body,
5096- })
5097- .to_string(),
5098- None => serde_json::json!({
5099- "upgraded": true,
5100- "protocol": open.protocol.unwrap_or_default(),
5101- })
5102- .to_string(),
5103- })
5104- });
5105- rv.set(promise_for(scope, async_id));
5106-}
5107-
5108-/// Await the next inbound event on an isolate-polled socket. Resolves with a
5109-/// tagged buffer; a closed queue resolves as a 1006 close so the JS pump always
5110-/// terminates rather than hanging on a dropped sender.
5111-fn op_ws_next(
5112- scope: &mut v8::PinScope,
5113- args: v8::FunctionCallbackArguments,
5114- mut rv: v8::ReturnValue<v8::Value>,
5115-) {
5116- let id = args
5117- .get(0)
5118- .to_integer(scope)
5119- .map(|n| n.value() as u64)
5120- .unwrap_or(0);
5121- let queue = ws_pull().lock().unwrap().get(&id).cloned();
5122- let async_id = asyncrt::enqueue(async move {
5123- let Some(queue) = queue else {
5124- return Ok(WsPull::Close(1006, "socket is not registered".into(), false).encode());
5125- };
5126- let mut queue = queue.lock().await;
5127- Ok(queue
5128- .recv()
5129- .await
5130- .unwrap_or_else(|| WsPull::Close(1006, String::new(), false))
5131- .encode())
5132- });
5133- rv.set(promise_for(scope, async_id));
5134-}
5135-
5136-fn op_ws_connect(
5137- scope: &mut v8::PinScope,
5138- args: v8::FunctionCallbackArguments,
5139- mut rv: v8::ReturnValue<v8::Value>,
5140-) {
5141- if actor_runtime_state(scope).egress == EgressPolicy::Deny {
5142- return loader_throw(
5143- scope,
5144- "This worker is not permitted to access the internet via global functions.",
5145- );
5146- }
5147- let id = args
5148- .get(0)
5149- .to_integer(scope)
5150- .map(|n| n.value() as u64)
5151- .unwrap_or(0);
5152- let cell = args.get(1).to_rust_string_lossy(scope);
5153- let url = args.get(2).to_rust_string_lossy(scope);
5154- let protocols: Vec<String> =
5155- serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
5156- // No cell means a Worker socket: the isolate polls it, so register the
5157- // queue here on the JS thread and track it against the running region.
5158- let pull = cell.is_empty().then(|| {
5159- let (pull_tx, pull_rx) = tokio::sync::mpsc::unbounded_channel();
5160- ws_pull_register(id, pull_rx);
5161- ws_region_track(id);
5162- pull_tx
5163- });
5164- let (tx, rx) = tokio::sync::oneshot::channel();
5165- let sent = OUTBOUND_WS_TX.get().is_some_and(|sender| {
5166- sender
5167- .send(OutboundWsReq {
5168- scope: cell,
5169- id,
5170- url,
5171- protocols,
5172- pull,
5173- headers: Vec::new(),
5174- want_response: false,
5175- reply: tx,
5176- })
5177- .is_ok()
5178- });
5179- let async_id = asyncrt::enqueue(async move {
5180- if !sent {
5181- return Err("no outbound WebSocket channel".into());
5182- }
5183- match rx.await {
5184- Ok(Ok(open)) => Ok(open.protocol.unwrap_or_default()),
5185- Ok(Err(error)) => Err(format!("WebSocket connection failed: {error}")),
5186- Err(error) => Err(format!("WebSocket connector dropped: {error}")),
5187- }
5188- });
5189- rv.set(promise_for(scope, async_id));
5190-}
5191-fn op_ws_accept(
5192- scope: &mut v8::PinScope,
5193- args: v8::FunctionCallbackArguments,
5194- _rv: v8::ReturnValue<v8::Value>,
5195-) {
5196- let id = args
5197- .get(0)
5198- .to_integer(scope)
5199- .map(|n| n.value() as u64)
5200- .unwrap_or(0);
5201- let cell = args.get(1).to_rust_string_lossy(scope);
5202- let tags: Vec<String> =
5203- serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)).unwrap_or_default();
5204- let replaced_regular_scope = {
5205- let mut registry = ws_registry().lock().unwrap();
5206- let sockets = &mut registry.metadata;
5207- let replaced_regular_scope = sockets
5208- .get(&id)
5209- .filter(|meta| !meta.hibernatable)
5210- .map(|meta| meta.scope.clone());
5211- sockets
5212- .entry(id)
5213- .and_modify(|meta| {
5214- meta.scope = cell.clone();
5215- meta.hibernatable = true;
5216- meta.tags = tags.clone();
5217- })
5218- .or_insert(WsMeta {
5219- scope: cell.clone(),
5220- hibernatable: true,
5221- tags,
5222- attachment: None,
5223- pending: Vec::new(),
5224- });
5225- replaced_regular_scope
5226- };
5227- if let Some(scope) = replaced_regular_scope {
5228- decrement_regular_ws(&scope);
5229- }
5230- tracing::info!(ws_id = id, scope = %cell, "accepted hibernatable WebSocket");
5231-}
5232-fn op_ws_accept_regular(
5233- scope: &mut v8::PinScope,
5234- args: v8::FunctionCallbackArguments,
5235- _rv: v8::ReturnValue<v8::Value>,
5236-) {
5237- let id = args
5238- .get(0)
5239- .to_integer(scope)
5240- .map(|n| n.value() as u64)
5241- .unwrap_or(0);
5242- let cell = args.get(1).to_rust_string_lossy(scope);
5243- let inserted = {
5244- let mut registry = ws_registry().lock().unwrap();
5245- let sockets = &mut registry.metadata;
5246- if let std::collections::hash_map::Entry::Vacant(entry) = sockets.entry(id) {
5247- entry.insert(WsMeta {
5248- scope: cell.clone(),
5249- hibernatable: false,
5250- tags: Vec::new(),
5251- attachment: None,
5252- pending: Vec::new(),
5253- });
5254- true
5255- } else {
5256- false
5257- }
5258- };
5259- if inserted {
5260- increment_regular_ws(&cell);
5261- }
5262- tracing::info!(ws_id = id, scope = %cell, "accepted regular WebSocket");
5263-}
5264-fn op_ws_list(
5265- scope: &mut v8::PinScope,
5266- args: v8::FunctionCallbackArguments,
5267- mut rv: v8::ReturnValue<v8::Value>,
5268-) {
5269- let cell = args.get(0).to_rust_string_lossy(scope);
5270- let tag = args.get(1);
5271- let tag = if tag.is_undefined() || tag.is_null() {
5272- None
5273- } else {
5274- Some(tag.to_rust_string_lossy(scope))
5275- };
5276- let rows = ws_registry()
5277- .lock()
5278- .unwrap()
5279- .metadata
5280- .iter()
5281- .filter(|(_, meta)| {
5282- meta.hibernatable
5283- && meta.scope == cell
5284- && tag.as_ref().is_none_or(|tag| meta.tags.contains(tag))
5285- })
5286- .map(|(id, meta)| {
5287- serde_json::json!({
5288- "id": id,
5289- "tags": meta.tags,
5290- "attachment": meta.attachment,
5291- })
5292- })
5293- .collect::<Vec<_>>();
5294- let json = serde_json::to_string(&rows).unwrap();
5295- rv.set(v8::String::new(scope, &json).unwrap().into());
5296-}
5297-fn op_ws_attachment_set(
5298- scope: &mut v8::PinScope,
5299- args: v8::FunctionCallbackArguments,
5300- _rv: v8::ReturnValue<v8::Value>,
5301-) {
5302- let id = args
5303- .get(0)
5304- .to_integer(scope)
5305- .map(|n| n.value() as u64)
5306- .unwrap_or(0);
5307- let attachment = args.get(1).to_rust_string_lossy(scope);
5308- if let Some(meta) = ws_registry().lock().unwrap().metadata.get_mut(&id) {
5309- meta.attachment = Some(attachment);
5310- }
5311-}
5312-
5313-#[cfg(all(test, celld_internal_tests))]
5314-mod websocket_registry_private {
5315- include!(env!("CELLD_CONFORMANCE_WEBSOCKET_REGISTRY_TESTS"));
5316-}
5317-fn op_storage_get(
5318- scope: &mut v8::PinScope,
5319- args: v8::FunctionCallbackArguments,
5320- mut rv: v8::ReturnValue<v8::Value>,
5321-) {
5322- let scope_s = args.get(0).to_rust_string_lossy(scope);
5323- let key = args.get(1).to_rust_string_lossy(scope);
5324- match storage::get_stored(&scope_s, &key) {
5325- Ok(Some(value)) => {
5326- if let Some((value, _)) = deserialize_stored(scope, value, args.get(2)) {
5327- rv.set(value);
5328- }
5329- }
5330- Ok(None) => rv.set(v8::undefined(scope).into()),
5331- Err(error) => throw_storage_error(scope, "get", error),
5332- }
5333-}
5334-fn op_storage_get_many(
5335- scope: &mut v8::PinScope,
5336- args: v8::FunctionCallbackArguments,
5337- mut rv: v8::ReturnValue<v8::Value>,
5338-) {
5339- let cell = args.get(0).to_rust_string_lossy(scope);
5340- let keys = match storage_string_array(scope, args.get(1)) {
5341- Ok(keys) => keys,
5342- Err(error) => {
5343- throw_storage_error(scope, "get", error);
5344- return;
5345- }
5346- };
5347- match storage::get_many_stored(&cell, &keys) {
5348- Ok(entries) => {
5349- let sentinel = args.get(2);
5350- if let Some((map, tagged)) = storage_entries_map(scope, entries, sentinel) {
5351- rv.set(if tagged {
5352- wrap_stored(scope, sentinel, map.into())
5353- } else {
5354- map.into()
5355- });
5356- }
5357- }
5358- Err(error) => throw_storage_error(scope, "get", error),
5359- }
5360-}
5361-fn op_storage_put(
5362- scope: &mut v8::PinScope,
5363- args: v8::FunctionCallbackArguments,
5364- _rv: v8::ReturnValue<v8::Value>,
5365-) {
5366- let s = args.get(0).to_rust_string_lossy(scope);
5367- let k = args.get(1).to_rust_string_lossy(scope);
5368- let Some(value) = serialize_storage_value(scope, args.get(2)) else {
5369- return;
5370- };
5371- if let Err(error) = storage::put_serialized(&s, &k, &value) {
5372- throw_storage_error(scope, "put", error);
5373- }
5374-}
5375-fn op_storage_put_many(
5376- scope: &mut v8::PinScope,
5377- args: v8::FunctionCallbackArguments,
5378- _rv: v8::ReturnValue<v8::Value>,
5379-) {
5380- let cell = args.get(0).to_rust_string_lossy(scope);
5381- let Ok(entries) = v8::Local::<v8::Array>::try_from(args.get(1)) else {
5382- throw_storage_error(scope, "put", "entries must be an array");
5383- return;
5384- };
5385- let mut serialized = Vec::with_capacity(entries.length() as usize);
5386- for index in 0..entries.length() {
5387- let Some(entry) = entries.get_index(scope, index) else {
5388- return;
5389- };
5390- let Ok(entry) = v8::Local::<v8::Array>::try_from(entry) else {
5391- throw_storage_error(scope, "put", "entry must be a key/value pair");
5392- return;
5393- };
5394- let Some(key) = entry.get_index(scope, 0) else {
5395- return;
5396- };
5397- let Some(value) = entry.get_index(scope, 1) else {
5398- return;
5399- };
5400- let Some(value) = serialize_storage_value(scope, value) else {
5401- return;
5402- };
5403- serialized.push((key.to_rust_string_lossy(scope), value));
5404- }
5405- if let Err(error) = storage::put_many_serialized(&cell, &serialized) {
5406- throw_storage_error(scope, "put", error);
5407- }
5408-}
5409-
5410-/// `__storage_put_serialized(cell, key, bytes)`: write pre-encoded row
5411-/// bytes verbatim — the stored-stub envelope (or a plain clone) built by
5412-/// the JS storage wrapper after a plain clone failed. Never on the fast
5413-/// path.
5414-fn op_storage_put_serialized(
5415- scope: &mut v8::PinScope,
5416- args: v8::FunctionCallbackArguments,
5417- _rv: v8::ReturnValue<v8::Value>,
5418-) {
5419- let cell = args.get(0).to_rust_string_lossy(scope);
5420- let key = args.get(1).to_rust_string_lossy(scope);
5421- let Some(bytes) = view_bytes(args.get(2)) else {
5422- throw_storage_error(scope, "put", "serialized row must be bytes");
5423- return;
5424- };
5425- if let Err(error) = storage::put_serialized(&cell, &key, &bytes) {
5426- throw_storage_error(scope, "put", error);
5427- }
5428-}
5429-
5430-/// The queued flavor of [`op_storage_put_serialized`], joining the same
5431-/// pending-puts batch the plain queue ops feed.
5432-fn op_storage_queue_put_serialized(
5433- scope: &mut v8::PinScope,
5434- args: v8::FunctionCallbackArguments,
5435- _rv: v8::ReturnValue<v8::Value>,
5436-) {
5437- let cell = args.get(0).to_rust_string_lossy(scope);
5438- let key = args.get(1).to_rust_string_lossy(scope);
5439- let Some(bytes) = view_bytes(args.get(2)) else {
5440- throw_storage_error(scope, "put", "serialized row must be bytes");
5441- return;
5442- };
5443- queue_serialized_puts(scope, cell, vec![(key, bytes)]);
5444-}
5445-
5446-fn actor_runtime_state(scope: &mut v8::PinScope) -> Arc<ActorRuntimeState> {
5447- scope
5448- .get_slot::<Arc<ActorRuntimeState>>()
5449- .expect("actor runtime state slot")
5450- .clone()
5451-}
5452-
5453-fn queue_serialized_puts(scope: &mut v8::PinScope, cell: String, entries: Vec<(String, Vec<u8>)>) {
5454- actor_runtime_state(scope)
5455- .pending_puts
5456- .lock()
5457- .expect("pending puts lock poisoned")
5458- .entry(cell)
5459- .or_default()
5460- .extend(entries);
5461-}
5462-
5463-fn op_storage_queue_put(
5464- scope: &mut v8::PinScope,
5465- args: v8::FunctionCallbackArguments,
5466- _rv: v8::ReturnValue<v8::Value>,
5467-) {
5468- let cell = args.get(0).to_rust_string_lossy(scope);
5469- let key = args.get(1).to_rust_string_lossy(scope);
5470- let Some(value) = serialize_storage_value(scope, args.get(2)) else {
5471- return;
5472- };
5473- queue_serialized_puts(scope, cell, vec![(key, value)]);
5474-}
5475-
5476-fn op_storage_queue_put_many(
5477- scope: &mut v8::PinScope,
5478- args: v8::FunctionCallbackArguments,
5479- _rv: v8::ReturnValue<v8::Value>,
5480-) {
5481- let cell = args.get(0).to_rust_string_lossy(scope);
5482- let Ok(entries) = v8::Local::<v8::Array>::try_from(args.get(1)) else {
5483- throw_storage_error(scope, "put", "entries must be an array");
5484- return;
5485- };
5486- let mut serialized = Vec::with_capacity(entries.length() as usize);
5487- for index in 0..entries.length() {
5488- let Some(entry) = entries.get_index(scope, index) else {
5489- return;
5490- };
5491- let Ok(entry) = v8::Local::<v8::Array>::try_from(entry) else {
5492- throw_storage_error(scope, "put", "entry must be a key/value pair");
5493- return;
5494- };
5495- let Some(key) = entry.get_index(scope, 0) else {
5496- return;
5497- };
5498- let Some(value) = entry.get_index(scope, 1) else {
5499- return;
5500- };
5501- let Some(value) = serialize_storage_value(scope, value) else {
5502- return;
5503- };
5504- serialized.push((key.to_rust_string_lossy(scope), value));
5505- }
5506- queue_serialized_puts(scope, cell, serialized);
5507-}
5508-
5509-fn op_storage_flush_pending_puts(
5510- scope: &mut v8::PinScope,
5511- args: v8::FunctionCallbackArguments,
5512- _rv: v8::ReturnValue<v8::Value>,
5513-) {
5514- let cell = args.get(0).to_rust_string_lossy(scope);
5515- let entries = actor_runtime_state(scope)
5516- .pending_puts
5517- .lock()
5518- .expect("pending puts lock poisoned")
5519- .remove(&cell)
5520- .unwrap_or_default();
5521- if entries.is_empty() {
5522- return;
5523- }
5524- if let Err(error) = storage::put_many_serialized(&cell, &entries) {
5525- throw_storage_error(scope, "put", error);
5526- }
5527-}
5528-
5529-fn op_storage_cancel_pending_puts(
5530- scope: &mut v8::PinScope,
5531- args: v8::FunctionCallbackArguments,
5532- _rv: v8::ReturnValue<v8::Value>,
5533-) {
5534- let cell = args.get(0).to_rust_string_lossy(scope);
5535- actor_runtime_state(scope)
5536- .pending_puts
5537- .lock()
5538- .expect("pending puts lock poisoned")
5539- .remove(&cell);
5540-}
5541-
5542-fn op_actor_abort(
5543- scope: &mut v8::PinScope,
5544- args: v8::FunctionCallbackArguments,
5545- _rv: v8::ReturnValue<v8::Value>,
5546-) {
5547- let cell = args.get(0).to_rust_string_lossy(scope);
5548- let reason = args.get(1).to_rust_string_lossy(scope);
5549- let state = actor_runtime_state(scope);
5550- state
5551- .pending_puts
5552- .lock()
5553- .expect("pending puts lock poisoned")
5554- .remove(&cell);
5555- *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
5556- error: format!("__CELLD_ACTOR_ABORT__:{reason}"),
5557- actor_scope: Some(cell),
5558- });
5559- scope.terminate_execution();
5560-}
5561-
5562-fn op_process_exit(
5563- scope: &mut v8::PinScope,
5564- args: v8::FunctionCallbackArguments,
5565- _rv: v8::ReturnValue<v8::Value>,
5566-) {
5567- let code = args.get(0).integer_value(scope).unwrap_or(0);
5568- let actor_scope = args.get(1).to_rust_string_lossy(scope);
5569- let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope);
5570- let state = actor_runtime_state(scope);
5571- if let Some(actor_scope) = actor_scope.as_deref() {
5572- state
5573- .pending_puts
5574- .lock()
5575- .expect("pending puts lock poisoned")
5576- .remove(actor_scope);
5577- } else {
5578- state.worker_exit_requested.store(true, Ordering::Relaxed);
5579- }
5580- *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
5581- error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."),
5582- actor_scope,
5583- });
5584- scope.terminate_execution();
5585-}
5586-
5587-fn op_log(
5588- scope: &mut v8::PinScope,
5589- args: v8::FunctionCallbackArguments,
5590- _rv: v8::ReturnValue<v8::Value>,
5591-) {
5592- let msg: Vec<String> = (0..args.length())
5593- .map(|i| args.get(i).to_rust_string_lossy(scope))
5594- .collect();
5595- tracing::info!(target: "cell_console", "{}", msg.join(" "));
5596-}
5597-fn op_heap_limit_excessively_exceeded(
5598- scope: &mut v8::PinScope,
5599- _args: v8::FunctionCallbackArguments,
5600- mut rv: v8::ReturnValue<v8::Value>,
5601-) {
5602- let exceeded = scope
5603- .get_slot::<Arc<HeapLimitState>>()
5604- .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed));
5605- rv.set(v8::Boolean::new(scope, exceeded).into());
5606-}
5607-#[cfg(all(test, celld_internal_tests))]
5608-fn op_test_set_heap_limit_excessively_exceeded(
5609- scope: &mut v8::PinScope,
5610- args: v8::FunctionCallbackArguments,
5611- _rv: v8::ReturnValue<v8::Value>,
5612-) {
5613- if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
5614- state
5615- .excessively_exceeded
5616- .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
5617- }
5618-}
5619-#[cfg(all(test, celld_internal_tests))]
5620-fn op_test_gc(
5621- scope: &mut v8::PinScope,
5622- _args: v8::FunctionCallbackArguments,
5623- _rv: v8::ReturnValue<v8::Value>,
5624-) {
5625- scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full);
5626-}
5627-/// `ctx.storage.sql.exec(query, ...binds)` — args: scope, query, binds(JSON).
5628-/// Returns a JSON `{columns, rows, rowsWritten}` (or `{error}`).
5629-fn op_sql_exec(
5630- scope: &mut v8::PinScope,
5631- args: v8::FunctionCallbackArguments,
5632- mut rv: v8::ReturnValue<v8::Value>,
5633-) {
5634- let sc = args.get(0).to_rust_string_lossy(scope);
5635- let query = args.get(1).to_rust_string_lossy(scope);
5636- let binds: Vec<serde_json::Value> =
5637- serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)).unwrap_or_default();
5638- let out = match storage::sql_exec(&sc, &query, &binds) {
5639- Ok((columns, rows, rows_written)) => serde_json::json!({
5640- "columns": columns, "rows": rows, "rowsWritten": rows_written,
5641- }),
5642- Err(e) => serde_json::json!({ "error": e }),
5643- };
5644- rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5645-}
5646-fn op_sql_ingest(
5647- scope: &mut v8::PinScope,
5648- args: v8::FunctionCallbackArguments,
5649- mut rv: v8::ReturnValue<v8::Value>,
5650-) {
5651- let cell = args.get(0).to_rust_string_lossy(scope);
5652- let input = args.get(1).to_rust_string_lossy(scope);
5653- let out = match storage::sql_ingest(&cell, &input) {
5654- Ok((remainder, rows_written, statement_count)) => serde_json::json!({
5655- "remainder": remainder,
5656- "rowsWritten": rows_written,
5657- "statementCount": statement_count,
5658- }),
5659- Err(error) => serde_json::json!({ "error": error }),
5660- };
5661- rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5662-}
5663-fn op_sql_cursor_start(
5664- scope: &mut v8::PinScope,
5665- args: v8::FunctionCallbackArguments,
5666- mut rv: v8::ReturnValue<v8::Value>,
5667-) {
5668- let cell = args.get(0).to_rust_string_lossy(scope);
5669- let query = args.get(1).to_rust_string_lossy(scope);
5670- let binds: Vec<serde_json::Value> =
5671- serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)).unwrap_or_default();
5672- let out = match storage::sql_cursor_start(&cell, &query, &binds) {
5673- Ok((cursor, columns, row, rows_written, reused_cached_query)) => serde_json::json!({
5674- "native": true,
5675- "cursorId": cursor,
5676- "columns": columns,
5677- "row": row,
5678- "rowsWritten": rows_written,
5679- "reusedCachedQuery": reused_cached_query,
5680- }),
5681- Err(error) => serde_json::json!({ "error": error }),
5682- };
5683- rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5684-}
5685-fn op_sql_cursor_next(
5686- scope: &mut v8::PinScope,
5687- args: v8::FunctionCallbackArguments,
5688- mut rv: v8::ReturnValue<v8::Value>,
5689-) {
5690- let cursor = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
5691- let out = match storage::sql_cursor_next(cursor) {
5692- Ok((row, rows_written)) => serde_json::json!({
5693- "row": row,
5694- "rowsWritten": rows_written,
5695- }),
5696- Err(error) => serde_json::json!({ "error": error }),
5697- };
5698- rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5699-}
5700-fn op_sql_cursor_close(
5701- scope: &mut v8::PinScope,
5702- args: v8::FunctionCallbackArguments,
5703- _rv: v8::ReturnValue<v8::Value>,
5704-) {
5705- let cursor = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
5706- storage::sql_cursor_close(cursor);
5707-}
5708-fn op_sql_database_size(
5709- scope: &mut v8::PinScope,
5710- args: v8::FunctionCallbackArguments,
5711- mut rv: v8::ReturnValue<v8::Value>,
5712-) {
5713- let cell = args.get(0).to_rust_string_lossy(scope);
5714- match storage::sql_database_size(&cell) {
5715- Ok(bytes) => rv.set(v8::Number::new(scope, bytes as f64).into()),
5716- Err(error) => throw_storage_error(scope, "sql.databaseSize", error),
5717- }
5718-}
5719-#[cfg(all(test, celld_internal_tests))]
5720-fn op_sql_set_max_page_count_for_test(
5721- scope: &mut v8::PinScope,
5722- args: v8::FunctionCallbackArguments,
5723- _rv: v8::ReturnValue<v8::Value>,
5724-) {
5725- let cell = args.get(0).to_rust_string_lossy(scope);
5726- let pages = args.get(1).uint32_value(scope).unwrap_or(0);
5727- if let Err(error) = storage::set_max_page_count_for_test(&cell, pages) {
5728- throw_storage_error(scope, "sql.setMaxPageCountForTest", error);
5729- }
5730-}
5731-#[cfg(all(test, celld_internal_tests))]
5732-fn op_sql_set_write_fault_for_test(
5733- scope: &mut v8::PinScope,
5734- args: v8::FunctionCallbackArguments,
5735- _rv: v8::ReturnValue<v8::Value>,
5736-) {
5737- storage::set_write_fault_for_test(args.get(0).boolean_value(scope));
5738-}
5739-#[cfg(all(test, celld_internal_tests))]
5740-fn op_sql_set_cache_size_for_test(
5741- scope: &mut v8::PinScope,
5742- args: v8::FunctionCallbackArguments,
5743- _rv: v8::ReturnValue<v8::Value>,
5744-) {
5745- let cell = args.get(0).to_rust_string_lossy(scope);
5746- let pages = args.get(1).int32_value(scope).unwrap_or(0);
5747- if let Err(error) = storage::set_cache_size_for_test(&cell, pages) {
5748- throw_storage_error(scope, "sql.setCacheSizeForTest", error);
5749- }
5750-}
5751-#[cfg(all(test, celld_internal_tests))]
5752-fn op_sql_set_interrupt_fault_for_test(
5753- scope: &mut v8::PinScope,
5754- args: v8::FunctionCallbackArguments,
5755- _rv: v8::ReturnValue<v8::Value>,
5756-) {
5757- let cell = args.get(0).to_rust_string_lossy(scope);
5758- let enabled = args.get(1).boolean_value(scope);
5759- if let Err(error) = storage::set_interrupt_fault_for_test(&cell, enabled) {
5760- throw_storage_error(scope, "sql.setInterruptFaultForTest", error);
5761- }
5762-}
5763-#[cfg(all(test, celld_internal_tests))]
5764-fn op_sql_register_nomem_function_for_test(
5765- scope: &mut v8::PinScope,
5766- args: v8::FunctionCallbackArguments,
5767- _rv: v8::ReturnValue<v8::Value>,
5768-) {
5769- let cell = args.get(0).to_rust_string_lossy(scope);
5770- if let Err(error) = storage::register_nomem_function_for_test(&cell) {
5771- throw_storage_error(scope, "sql.registerNomemFunctionForTest", error);
5772- }
5773-}
5774-fn op_storage_transaction_control(
5775- scope: &mut v8::PinScope,
5776- args: v8::FunctionCallbackArguments,
5777- _rv: v8::ReturnValue<v8::Value>,
5778-) {
5779- let cell = args.get(0).to_rust_string_lossy(scope);
5780- let action = args.get(1).to_rust_string_lossy(scope);
5781- let nested = args.get(2).boolean_value(scope);
5782- let savepoint = args.get(3).to_rust_string_lossy(scope);
5783- match storage::transaction_control(&cell, &action, nested, &savepoint) {
5784- Err(error) => throw_storage_error(scope, "transaction", error),
5785- // An outermost commit published a dirty alarm: register its
5786- // wake-entry PUT against the cell's output gate.
5787- Ok(Some(at)) if at >= 0 => spawn_arm_gate(&cell, at),
5788- Ok(_) => {}
5789- }
5790-}
5791-fn op_storage_delete(
5792- scope: &mut v8::PinScope,
5793- args: v8::FunctionCallbackArguments,
5794- mut rv: v8::ReturnValue<v8::Value>,
5795-) {
5796- let s = args.get(0).to_rust_string_lossy(scope);
5797- let k = args.get(1).to_rust_string_lossy(scope);
5798- match storage::delete(&s, &k) {
5799- Ok(deleted) => rv.set(v8::Boolean::new(scope, deleted).into()),
5800- Err(error) => throw_storage_error(scope, "delete", error),
5801- }
5802-}
5803-fn op_storage_delete_many(
5804- scope: &mut v8::PinScope,
5805- args: v8::FunctionCallbackArguments,
5806- mut rv: v8::ReturnValue<v8::Value>,
5807-) {
5808- let cell = args.get(0).to_rust_string_lossy(scope);
5809- let keys = match storage_string_array(scope, args.get(1)) {
5810- Ok(keys) => keys,
5811- Err(error) => {
5812- throw_storage_error(scope, "delete", error);
5813- return;
5814- }
5815- };
5816- match storage::delete_many(&cell, &keys) {
5817- Ok(deleted) => rv.set(v8::Number::new(scope, deleted as f64).into()),
5818- Err(error) => throw_storage_error(scope, "delete", error),
5819- }
5820-}
5821-
5822-#[derive(Default, serde::Deserialize)]
5823-#[serde(default, rename_all = "camelCase")]
5824-struct StorageListOptions {
5825- start: Option<String>,
5826- end: Option<String>,
5827- start_after: Option<String>,
5828- prefix: Option<String>,
5829- limit: Option<usize>,
5830- reverse: bool,
5831-}
5832-
5833-fn op_storage_list(
5834- scope: &mut v8::PinScope,
5835- args: v8::FunctionCallbackArguments,
5836- mut rv: v8::ReturnValue<v8::Value>,
5837-) {
5838- let cell = args.get(0).to_rust_string_lossy(scope);
5839- let options = match serde_json::from_str::<StorageListOptions>(
5840- &args.get(1).to_rust_string_lossy(scope),
5841- ) {
5842- Ok(options) => options,
5843- Err(error) => {
5844- throw_storage_error(scope, "list", error);
5845- return;
5846- }
5847- };
5848- match storage::list_stored_with_options(
5849- &cell,
5850- options.start.as_deref(),
5851- options.end.as_deref(),
5852- options.start_after.as_deref(),
5853- options.prefix.as_deref(),
5854- options.limit,
5855- options.reverse,
5856- ) {
5857- Ok(entries) => {
5858- let sentinel = args.get(2);
5859- if let Some((map, tagged)) = storage_entries_map(scope, entries, sentinel) {
5860- rv.set(if tagged {
5861- wrap_stored(scope, sentinel, map.into())
5862- } else {
5863- map.into()
5864- });
5865- }
5866- }
5867- Err(error) => throw_storage_error(scope, "list", error),
5868- }
5869-}
5870-
5871-fn op_storage_sync_list_start(
5872- scope: &mut v8::PinScope,
5873- args: v8::FunctionCallbackArguments,
5874- mut rv: v8::ReturnValue<v8::Value>,
5875-) {
5876- let cell = args.get(0).to_rust_string_lossy(scope);
5877- let options = match serde_json::from_str::<StorageListOptions>(
5878- &args.get(1).to_rust_string_lossy(scope),
5879- ) {
5880- Ok(options) => options,
5881- Err(error) => {
5882- throw_storage_error(scope, "kv.list", error);
5883- return;
5884- }
5885- };
5886- match storage::sync_list_start(
5887- &cell,
5888- options.start.as_deref(),
5889- options.end.as_deref(),
5890- options.start_after.as_deref(),
5891- options.prefix.as_deref(),
5892- options.limit,
5893- options.reverse,
5894- ) {
5895- Ok(cursor) => rv.set(v8::Number::new(scope, cursor as f64).into()),
5896- Err(error) => throw_storage_error(scope, "kv.list", error),
5897- }
5898-}
5899-
5900-fn op_storage_sync_list_next(
5901- scope: &mut v8::PinScope,
5902- args: v8::FunctionCallbackArguments,
5903- mut rv: v8::ReturnValue<v8::Value>,
5904-) {
5905- let cursor = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
5906- match storage::sync_list_next(cursor) {
5907- Ok(Some((key, value))) => {
5908- let Some((decoded, _)) = deserialize_stored(scope, value, args.get(1)) else {
5909- throw_storage_error(
5910- scope,
5911- "kv.list",
5912- format!("deserialization failed for key {key}"),
5913- );
5914- return;
5915- };
5916- let pair = v8::Array::new(scope, 2);
5917- let key = v8::String::new(scope, &key).unwrap();
5918- pair.set_index(scope, 0, key.into());
5919- pair.set_index(scope, 1, decoded);
5920- rv.set(pair.into());
5921- }
5922- Ok(None) => rv.set(v8::null(scope).into()),
5923- Err(error) => throw_storage_error(scope, "kv.list", error),
5924- }
5925-}
5926-
5927-struct StorageValueDelegate;
5928-
5929-impl v8::ValueSerializerImpl for StorageValueDelegate {
5930- fn throw_data_clone_error(&self, scope: &mut v8::PinScope, message: v8::Local<v8::String>) {
5931- let exception = v8::Exception::type_error(scope, message);
5932- scope.throw_exception(exception);
5933- }
5934-}
5935-
5936-impl v8::ValueDeserializerImpl for StorageValueDelegate {}
5937-
5938-fn serialize_storage_value(
5939- scope: &mut v8::PinScope,
5940- value: v8::Local<v8::Value>,
5941-) -> Option<Vec<u8>> {
5942- let context = scope.get_current_context();
5943- let serializer = v8::ValueSerializer::new(scope, Box::new(StorageValueDelegate));
5944- serializer.write_header();
5945- if !serializer.write_value(context, value).unwrap_or(false) {
5946- return None;
5947- }
5948- let mut bytes = serializer.release();
5949- // Workerd pins persisted actor values to V8 wire version 15 so rolling
5950- // upgrades remain readable by older processes. V8 150 writes version 16;
5951- // for Cells' supported (sub-4GiB) ArrayBuffers its varint encoding is
5952- // byte-compatible, so retain the Workerd on-disk version tag.
5953- if bytes.starts_with(&[0xff, 0x10]) {
5954- bytes[1] = 0x0f;
5955- }
5956- Some(bytes)
5957-}
5958-
5959-fn deserialize_storage_value<'s>(
5960- scope: &mut v8::PinScope<'s, '_>,
5961- value: storage::StoredValue,
5962-) -> Option<v8::Local<'s, v8::Value>> {
5963- match value {
5964- storage::StoredValue::LegacyJson(json) => {
5965- let json = v8::String::new(scope, &json)?;
5966- v8::json::parse(scope, json)
5967- }
5968- storage::StoredValue::V8(bytes) => {
5969- let context = scope.get_current_context();
5970- let deserializer =
5971- v8::ValueDeserializer::new(scope, Box::new(StorageValueDelegate), &bytes);
5972- deserializer.set_supports_legacy_wire_format(true);
5973- if !deserializer.read_header(context).unwrap_or(false) {
5974- return None;
5975- }
5976- deserializer.read_value(context)
5977- }
5978- }
5979-}
5980-
5981-/// First byte of a stored-stub row: a durable stub marker tree follows
5982-/// as an ordinary V8 clone. Plain rows keep V8's own 0xff prefix, so
5983-/// the tag branch never runs for them.
5984-const STORED_STUB_TAG: u8 = 0x01;
5985-
5986-fn wrap_stored<'s>(
5987- scope: &mut v8::PinScope<'s, '_>,
5988- sentinel: v8::Local<v8::Value>,
5989- value: v8::Local<v8::Value>,
5990-) -> v8::Local<'s, v8::Value> {
5991- let pair = v8::Array::new(scope, 2);
5992- pair.set_index(scope, 0, sentinel);
5993- pair.set_index(scope, 1, value);
5994- pair.into()
5995-}
5996-
5997-/// Decode one stored row for JS. A stub-tagged row comes back as
5998-/// `[sentinel, tree]` (plus `true`), which only the storage wrapper —
5999-/// holder of the closure-private sentinel — turns back into live stubs.
6000-fn deserialize_stored<'s>(
6001- scope: &mut v8::PinScope<'s, '_>,
6002- value: storage::StoredValue,
6003- sentinel: v8::Local<v8::Value>,
6004-) -> Option<(v8::Local<'s, v8::Value>, bool)> {
6005- match value {
6006- storage::StoredValue::V8(bytes) if bytes.first() == Some(&STORED_STUB_TAG) => {
6007- let tree =
6008- deserialize_storage_value(scope, storage::StoredValue::V8(bytes[1..].to_vec()))?;
6009- Some((wrap_stored(scope, sentinel, tree), true))
6010- }
6011- value => deserialize_storage_value(scope, value).map(|value| (value, false)),
6012- }
6013-}
6014-
6015-/// `__sc_encode(value)` -> Uint8Array: V8 structured clone, sharing the
6016-/// storage serializer (same delegate, same pinned wire version). The RPC
6017-/// marshalling seam — a failed clone leaves the delegate's throw pending.
6018-fn op_sc_encode(
6019- scope: &mut v8::PinScope,
6020- args: v8::FunctionCallbackArguments,
6021- mut rv: v8::ReturnValue<v8::Value>,
6022-) {
6023- if let Some(bytes) = serialize_storage_value(scope, args.get(0)) {
6024- rv.set(bytes_value(scope, bytes));
6025- }
6026-}
6027-
6028-/// `__sc_decode(bytes)` -> value: inverse of `__sc_encode`.
6029-fn op_sc_decode(
6030- scope: &mut v8::PinScope,
6031- args: v8::FunctionCallbackArguments,
6032- mut rv: v8::ReturnValue<v8::Value>,
6033-) {
6034- let Some(bytes) = view_bytes(args.get(0)) else {
6035- let message = v8::String::new(scope, "__sc_decode expects bytes").unwrap();
6036- let exception = v8::Exception::type_error(scope, message);
6037- scope.throw_exception(exception);
6038- return;
6039- };
6040- match deserialize_storage_value(scope, storage::StoredValue::V8(bytes)) {
6041- Some(value) => rv.set(value),
6042- None => throw_storage_error(scope, "rpc", "corrupt clone payload"),
6043- }
6044-}
6045-
6046-fn storage_string_array(
6047- scope: &mut v8::PinScope,
6048- value: v8::Local<v8::Value>,
6049-) -> std::result::Result<Vec<String>, &'static str> {
6050- let array = v8::Local::<v8::Array>::try_from(value).map_err(|_| "keys must be an array")?;
6051- let mut keys = Vec::with_capacity(array.length() as usize);
6052- for index in 0..array.length() {
6053- let value = array.get_index(scope, index).ok_or("missing key")?;
6054- keys.push(value.to_rust_string_lossy(scope));
6055- }
6056- Ok(keys)
6057-}
6058-
6059-/// The `bool` reports whether any entry was a stored-stub row, so the
6060-/// caller wraps the whole map only then — plain maps cross unwrapped and
6061-/// the JS side never walks them.
6062-fn storage_entries_map<'s>(
6063- scope: &mut v8::PinScope<'s, '_>,
6064- entries: Vec<(String, storage::StoredValue)>,
6065- sentinel: v8::Local<v8::Value>,
6066-) -> Option<(v8::Local<'s, v8::Map>, bool)> {
6067- let map = v8::Map::new(scope);
6068- let mut any_tagged = false;
6069- for (key, value) in entries {
6070- let key = v8::String::new(scope, &key)?;
6071- let (value, tagged) = deserialize_stored(scope, value, sentinel)?;
6072- any_tagged |= tagged;
6073- map.set(scope, key.into(), value)?;
6074- }
6075- Some((map, any_tagged))
6076-}
6077-
6078-fn throw_storage_error(scope: &mut v8::PinScope, operation: &str, error: impl std::fmt::Display) {
6079- let message = v8::String::new(scope, &format!("storage.{operation}: {error}")).unwrap();
6080- let exception = v8::Exception::error(scope, message);
6081- scope.throw_exception(exception);
6082-}
6083-fn op_storage_delete_all(
6084- scope: &mut v8::PinScope,
6085- args: v8::FunctionCallbackArguments,
6086- _rv: v8::ReturnValue<v8::Value>,
6087-) {
6088- let cell = args.get(0).to_rust_string_lossy(scope);
6089- let delete_alarm = args.get(1).boolean_value(scope);
6090- if let Err(error) = storage::delete_all_with_alarm(&cell, delete_alarm) {
6091- let message = v8::String::new(scope, &format!("deleteAll: {error}")).unwrap();
6092- let exception = v8::Exception::error(scope, message);
6093- scope.throw_exception(exception);
6094- }
6095-}
6096-
6097-/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href}
6098-/// Backed by the WHATWG-conformant `url` crate.
6099-fn op_url_parse(
6100- scope: &mut v8::PinScope,
6101- args: v8::FunctionCallbackArguments,
6102- mut rv: v8::ReturnValue<v8::Value>,
6103-) {
6104- let input = args.get(0).to_rust_string_lossy(scope);
6105- let base = args.get(1);
6106- let parsed = if base.is_undefined() {
6107- url::Url::parse(&input)
6108- } else {
6109- url::Url::options()
6110- .base_url(
6111- url::Url::parse(&base.to_rust_string_lossy(scope))
6112- .ok()
6113- .as_ref(),
6114- )
6115- .parse(&input)
6116- };
6117- let u = match parsed {
6118- Ok(u) => u,
6119- Err(e) => {
6120- let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap();
6121- let exc = v8::Exception::type_error(scope, msg);
6122- scope.throw_exception(exc);
6123- return;
6124- }
6125- };
6126- let o = v8::Object::new(scope);
6127- let set = |k: &str, v: &str| {
6128- let key = v8::String::new(scope, k).unwrap();
6129- let val = v8::String::new(scope, v).unwrap();
6130- o.set(scope, key.into(), val.into());
6131- };
6132- set("protocol", u.scheme());
6133- set("username", u.username());
6134- set("password", u.password().unwrap_or(""));
6135- set("host", u.host_str().unwrap_or(""));
6136- set("port", &u.port().map(|p| p.to_string()).unwrap_or_default());
6137- set("pathname", u.path());
6138- set("search", u.query().unwrap_or(""));
6139- set("hash", u.fragment().unwrap_or(""));
6140- set("href", u.as_str());
6141- rv.set(o.into());
6142-}
6143-
6144-// URLPattern host seam, split like Deno's: pattern parsing and match-input
6145-// canonicalization run in Rust via the `urlpattern` crate; per-match regex
6146-// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the
6147-// boundary — both ops run at construct/match-canonicalize time only.
6148-
6149-/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a
6150-/// pattern string or an init object of string components. Returns
6151-/// per-component `{ patternString, regexpString, groupNameList }` plus
6152-/// `hasRegexpGroups`. Throws TypeError on an invalid pattern.
6153-fn op_urlpattern_parse(
6154- scope: &mut v8::PinScope,
6155- args: v8::FunctionCallbackArguments,
6156- mut rv: v8::ReturnValue<v8::Value>,
6157-) {
6158- use urlpattern::quirks;
6159- let input = args.get(0).to_rust_string_lossy(scope);
6160- let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
6161- let base = args.get(1);
6162- let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
6163- let options = urlpattern::UrlPatternOptions {
6164- ignore_case: args.get(2).boolean_value(scope),
6165- };
6166- let pattern = quirks::process_construct_pattern_input(input, base.as_deref())
6167- .and_then(|init| quirks::parse_pattern(init, options));
6168- let p = match pattern {
6169- Ok(p) => p,
6170- Err(e) => {
6171- let msg = v8::String::new(scope, &e.to_string()).unwrap();
6172- let exc = v8::Exception::type_error(scope, msg);
6173- scope.throw_exception(exc);
6174- return;
6175- }
6176- };
6177- let component = |c: &quirks::UrlPatternComponent| {
6178- serde_json::json!({
6179- "patternString": c.pattern_string,
6180- "regexpString": c.regexp_string,
6181- "groupNameList": c.group_name_list,
6182- })
6183- };
6184- let out = serde_json::json!({
6185- "protocol": component(&p.protocol),
6186- "username": component(&p.username),
6187- "password": component(&p.password),
6188- "hostname": component(&p.hostname),
6189- "port": component(&p.port),
6190- "pathname": component(&p.pathname),
6191- "search": component(&p.search),
6192- "hash": component(&p.hash),
6193- "hasRegexpGroups": p.has_regexp_groups,
6194- });
6195- rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
6196-}
6197-
6198-/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in
6199-/// component order (protocol..hash), or `null` when the input does not parse
6200-/// as a URL. Throws TypeError for an init combined with a baseURL argument.
6201-fn op_urlpattern_match_input(
6202- scope: &mut v8::PinScope,
6203- args: v8::FunctionCallbackArguments,
6204- mut rv: v8::ReturnValue<v8::Value>,
6205-) {
6206- use urlpattern::quirks;
6207- let input = args.get(0).to_rust_string_lossy(scope);
6208- let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
6209- let base = args.get(1);
6210- let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
6211- let null = v8::null(scope).into();
6212- let m = match quirks::process_match_input(input, base.as_deref()) {
6213- Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) {
6214- Some(m) => m,
6215- None => return rv.set(null),
6216- },
6217- Ok(None) => return rv.set(null),
6218- Err(e) => {
6219- let msg = v8::String::new(scope, &e.to_string()).unwrap();
6220- let exc = v8::Exception::type_error(scope, msg);
6221- scope.throw_exception(exc);
6222- return;
6223- }
6224- };
6225- let out = serde_json::json!([
6226- m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash,
6227- ]);
6228- rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
6229-}
6230-
6231-fn op_atob(
6232- scope: &mut v8::PinScope,
6233- args: v8::FunctionCallbackArguments,
6234- mut rv: v8::ReturnValue<v8::Value>,
6235-) {
6236- use base64::Engine;
6237- let input = args.get(0).to_rust_string_lossy(scope);
6238- let cleaned: String = input.chars().filter(|c| !c.is_whitespace()).collect();
6239- match base64::engine::general_purpose::STANDARD.decode(cleaned) {
6240- Ok(bytes) => {
6241- // atob returns a binary string (latin1)
6242- let s: String = bytes.iter().map(|&b| b as char).collect();
6243- rv.set(v8::String::new(scope, &s).unwrap().into());
6244- }
6245- Err(_) => {
6246- let msg = v8::String::new(scope, "Invalid base64").unwrap();
6247- let exc = v8::Exception::error(scope, msg);
6248- scope.throw_exception(exc);
6249- }
6250- }
6251-}
6252-
6253-// node:util introspection seam: V8-level queries that JS cannot perform,
6254-// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy
6255-// node:async_hooks prelude calls these. The value is V8's
6256-// continuation-preserved embedder data — the primitive Workerd's
6257-// AsyncContextFrame rides — which V8 itself captures and restores
6258-// around every promise reaction. No promise hooks are installed, and an
6259-// isolate that never touches AsyncLocalStorage never sets the value, so
6260-// a bundle that does not import async_hooks pays nothing per promise.
6261-
6262-fn op_als_get(
6263- scope: &mut v8::PinScope,
6264- _args: v8::FunctionCallbackArguments,
6265- mut rv: v8::ReturnValue<v8::Value>,
6266-) {
6267- rv.set(scope.get_continuation_preserved_embedder_data());
6268-}
6269-
6270-fn op_als_set(
6271- scope: &mut v8::PinScope,
6272- args: v8::FunctionCallbackArguments,
6273- _rv: v8::ReturnValue<v8::Value>,
6274-) {
6275- scope.set_continuation_preserved_embedder_data(args.get(0));
6276-}
6277-
6278-// node:util prelude calls these; registration is the sole per-isolate cost.
6279-
6280-/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js.
6281-fn op_util_type_flags(
6282- _scope: &mut v8::PinScope,
6283- args: v8::FunctionCallbackArguments,
6284- mut rv: v8::ReturnValue<v8::Value>,
6285-) {
6286- let v = args.get(0);
6287- let checks: [bool; 27] = [
6288- v.is_external(),
6289- v.is_date(),
6290- v.is_arguments_object(),
6291- v.is_big_int_object(),
6292- v.is_boolean_object(),
6293- v.is_number_object(),
6294- v.is_string_object(),
6295- v.is_symbol_object(),
6296- v.is_native_error(),
6297- v.is_reg_exp(),
6298- v.is_async_function(),
6299- v.is_generator_function(),
6300- v.is_generator_object(),
6301- v.is_promise(),
6302- v.is_map(),
6303- v.is_set(),
6304- v.is_map_iterator(),
6305- v.is_set_iterator(),
6306- v.is_weak_map(),
6307- v.is_weak_set(),
6308- v.is_array_buffer(),
6309- v.is_data_view(),
6310- v.is_shared_array_buffer(),
6311- v.is_proxy(),
6312- v.is_module_namespace_object(),
6313- v.is_typed_array(),
6314- v.is_array_buffer_view(),
6315- ];
6316- let mut flags: u32 = 0;
6317- for (i, hit) in checks.iter().enumerate() {
6318- if *hit {
6319- flags |= 1 << i;
6320- }
6321- }
6322- rv.set_uint32(flags);
6323-}
6324-
6325-fn op_util_constructor_name(
6326- _scope: &mut v8::PinScope,
6327- args: v8::FunctionCallbackArguments,
6328- mut rv: v8::ReturnValue<v8::Value>,
6329-) {
6330- let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
6331- return; // undefined
6332- };
6333- rv.set(obj.get_constructor_name().into());
6334-}
6335-
6336-/// `[target, handler]` for a proxy, undefined otherwise.
6337-fn op_util_proxy_details(
6338- scope: &mut v8::PinScope,
6339- args: v8::FunctionCallbackArguments,
6340- mut rv: v8::ReturnValue<v8::Value>,
6341-) {
6342- let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else {
6343- return;
6344- };
6345- let target = proxy.get_target(scope);
6346- let handler = proxy.get_handler(scope);
6347- rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into());
6348-}
6349-
6350-/// `[state]` for a pending promise, `[state, result]` otherwise,
6351-/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected.
6352-fn op_util_promise_details(
6353- scope: &mut v8::PinScope,
6354- args: v8::FunctionCallbackArguments,
6355- mut rv: v8::ReturnValue<v8::Value>,
6356-) {
6357- let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else {
6358- return;
6359- };
6360- let state = match promise.state() {
6361- v8::PromiseState::Pending => 0,
6362- v8::PromiseState::Fulfilled => 1,
6363- v8::PromiseState::Rejected => 2,
6364- };
6365- let pending = state == 0;
6366- let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into();
6367- let elements = if pending {
6368- vec![state]
6369- } else {
6370- vec![state, promise.result(scope)]
6371- };
6372- rv.set(v8::Array::new_with_elements(scope, &elements).into());
6373-}
6374-
6375-/// `[entries, isKeyValue]` for collections and their iterators (V8's
6376-/// PreviewEntries), undefined when V8 has no preview.
6377-fn op_util_preview_entries(
6378- scope: &mut v8::PinScope,
6379- args: v8::FunctionCallbackArguments,
6380- mut rv: v8::ReturnValue<v8::Value>,
6381-) {
6382- let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
6383- return;
6384- };
6385- let (entries, is_key_value) = obj.preview_entries(scope);
6386- let Some(entries) = entries else { return };
6387- let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into();
6388- rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into());
6389-}
6390-
6391-fn op_alarm_set(
6392- scope: &mut v8::PinScope,
6393- args: v8::FunctionCallbackArguments,
6394- _rv: v8::ReturnValue<v8::Value>,
6395-) {
6396- let s = args.get(0).to_rust_string_lossy(scope);
6397- let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64;
6398- match storage::set_alarm(&s, at) {
6399- Err(error) => throw_storage_error(scope, "setAlarm", error),
6400- // Committed immediately: register the wake-entry PUT against the
6401- // cell's output gate. Inside an explicit transaction (`Ok(None)`)
6402- // the gate registers at that transaction's commit instead.
6403- Ok(Some(committed)) if committed >= 0 => spawn_arm_gate(&s, committed),
6404- Ok(_) => {}
6405- }
6406-}
6407-fn op_alarm_get(
6408- scope: &mut v8::PinScope,
6409- args: v8::FunctionCallbackArguments,
6410- mut rv: v8::ReturnValue<v8::Value>,
6411-) {
6412- let s = args.get(0).to_rust_string_lossy(scope);
6413- match storage::get_alarm(&s) {
6414- Some(at) => rv.set(v8::Number::new(scope, at as f64).into()),
6415- None => rv.set(v8::null(scope).into()),
6416- }
6417-}
6418-fn op_alarm_delete(
6419- scope: &mut v8::PinScope,
6420- args: v8::FunctionCallbackArguments,
6421- _rv: v8::ReturnValue<v8::Value>,
6422-) {
6423- let s = args.get(0).to_rust_string_lossy(scope);
6424- if let Err(error) = storage::delete_alarm(&s) {
6425- throw_storage_error(scope, "deleteAlarm", error);
6426- }
6427-}
6428-
6429-fn op_btoa(
6430- scope: &mut v8::PinScope,
6431- args: v8::FunctionCallbackArguments,
6432- mut rv: v8::ReturnValue<v8::Value>,
6433-) {
6434- use base64::Engine;
6435- let input = args.get(0).to_rust_string_lossy(scope);
6436- let bytes: Vec<u8> = input.chars().map(|c| c as u8).collect();
6437- let s = base64::engine::general_purpose::STANDARD.encode(bytes);
6438- rv.set(v8::String::new(scope, &s).unwrap().into());
6439-}
6440-
6441-// ---- WHATWG legacy text decoders (encoding_rs) ----
6442-//
6443-// TextDecoder's utf-8/utf-16 hot path stays pure JS in
6444-// src/js/text_encoding.js; these ops back every other WHATWG label
6445-// (windows-1252, Big5, GBK/GB18030, ISO-2022-JP, x-user-defined, …).
6446-// Streaming decoders live in a thread-local table keyed by id; JS frees
6447-// one on the final decode (last=true), on a fatal error (encoding_rs
6448-// poisons an errored decoder), or via FinalizationRegistry when a
6449-// mid-stream decoder is abandoned. Ids are never reused, so a late
6450-// finalizer free of an already-closed id is a no-op.
6451-
6452-thread_local! {
6453- static TEXT_DECODERS: std::cell::RefCell<
6454- std::collections::HashMap<u64, encoding_rs::Decoder>> =
6455- Default::default();
6456- static TEXT_DECODER_NEXT: std::cell::Cell<u64> =
6457- const { std::cell::Cell::new(1) };
6458-}
6459-
6460-/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined
6461-/// for unknown labels and the replacement encoding (RangeError in JS).
6462-fn op_text_decoder_label(
6463- scope: &mut v8::PinScope,
6464- args: v8::FunctionCallbackArguments,
6465- mut rv: v8::ReturnValue<v8::Value>,
6466-) {
6467- let label = args.get(0).to_rust_string_lossy(scope);
6468- if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) {
6469- let name = enc.name().to_ascii_lowercase();
6470- rv.set(v8::String::new(scope, &name).unwrap().into());
6471- }
6472-}
6473-
6474-/// `$$textDecoderNew(name, ignoreBOM)` -> id.
6475-fn op_text_decoder_new(
6476- scope: &mut v8::PinScope,
6477- args: v8::FunctionCallbackArguments,
6478- mut rv: v8::ReturnValue<v8::Value>,
6479-) {
6480- let name = args.get(0).to_rust_string_lossy(scope);
6481- let ignore_bom = args.get(1).boolean_value(scope);
6482- let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
6483- let dec = if ignore_bom {
6484- enc.new_decoder_without_bom_handling()
6485- } else {
6486- enc.new_decoder_with_bom_removal()
6487- };
6488- let id = TEXT_DECODER_NEXT.with(|next| {
6489- let id = next.get();
6490- next.set(id + 1);
6491- id
6492- });
6493- TEXT_DECODERS.with(|table| table.borrow_mut().insert(id, dec));
6494- rv.set(v8::Number::new(scope, id as f64).into());
6495-}
6496-
6497-/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the
6498-/// decoder when `last` is true or on a fatal malformed sequence
6499-/// (TypeError).
6500-fn op_text_decoder_decode(
6501- scope: &mut v8::PinScope,
6502- args: v8::FunctionCallbackArguments,
6503- mut rv: v8::ReturnValue<v8::Value>,
6504-) {
6505- let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
6506- let bytes = view_bytes(args.get(1)).unwrap_or_default();
6507- let fatal = args.get(2).boolean_value(scope);
6508- let last = args.get(3).boolean_value(scope);
6509- // Per spec an empty streaming chunk is a no-op, but encoding_rs
6510- // 0.8 flushes a pending multibyte lead when fed an empty non-last
6511- // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead
6512- // of あ). Skip the decoder entirely.
6513- if bytes.is_empty() && !last {
6514- rv.set(v8::String::empty(scope).into());
6515- return;
6516- }
6517- let mut dec = TEXT_DECODERS
6518- .with(|table| table.borrow_mut().remove(&id))
6519- .expect("JS holds the only live id");
6520- let mut out = String::new();
6521- let ok = if fatal {
6522- let cap = dec
6523- .max_utf8_buffer_length_without_replacement(bytes.len())
6524- .unwrap();
6525- out.reserve(cap);
6526- matches!(
6527- dec.decode_to_string_without_replacement(&bytes, &mut out, last),
6528- (encoding_rs::DecoderResult::InputEmpty, _),
6529- )
6530- } else {
6531- let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap();
6532- out.reserve(cap);
6533- let _ = dec.decode_to_string(&bytes, &mut out, last);
6534- true
6535- };
6536- if !ok {
6537- let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap();
6538- let exc = v8::Exception::type_error(scope, msg);
6539- scope.throw_exception(exc);
6540- return;
6541- }
6542- if !last {
6543- TEXT_DECODERS.with(|table| table.borrow_mut().insert(id, dec));
6544- }
6545- rv.set(v8::String::new(scope, &out).unwrap().into());
6546-}
6547-
6548-/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder
6549-/// abandoned mid-stream.
6550-fn op_text_decoder_free(
6551- scope: &mut v8::PinScope,
6552- args: v8::FunctionCallbackArguments,
6553- _rv: v8::ReturnValue<v8::Value>,
6554-) {
6555- let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
6556- TEXT_DECODERS.with(|table| table.borrow_mut().remove(&id));
6557-}
6558-
6559-// ---- the JS harness: Web API + the DO object model ----
6560-
6561-/// Per-process compiled-bytecode cache for the fixed bootstrap scripts.
6562-/// Every cell wake pays a fresh isolate, and without this each one re-parses
6563-/// and re-compiles the same ~23k lines of prelude + harness — the single
6564-/// largest slice of hibernated-wake latency. The first isolate compiles
6565-/// eagerly and publishes the cache; every later isolate consumes it and only
6566-/// executes.
6567-type BootstrapCache = std::collections::HashMap<&'static str, std::sync::Arc<Vec<u8>>>;
6568-
6569-fn bootstrap_code_cache() -> &'static std::sync::Mutex<BootstrapCache> {
6570- static CACHE: std::sync::OnceLock<std::sync::Mutex<BootstrapCache>> =
6571- std::sync::OnceLock::new();
6572- CACHE.get_or_init(Default::default)
6573-}
6574-
6575-fn run_bootstrap_script(scope: &mut v8::PinScope, name: &'static str, src: &str) -> Result<()> {
6576- use v8::script_compiler::CompileOptions;
6577- use v8::script_compiler::NoCacheReason;
6578- let code = v8::String::new(scope, src).unwrap();
6579- let cached = bootstrap_code_cache().lock().unwrap().get(name).cloned();
6580- let unbound = match cached {
6581- // `CachedData` borrows `bytes`; the Arc binding outlives the Source.
6582- Some(bytes) => {
6583- let data = v8::script_compiler::CachedData::new(&bytes);
6584- let mut source = v8::script_compiler::Source::new_with_cached_data(code, None, data);
6585- let unbound = v8::script_compiler::compile_unbound_script(
6586- scope,
6587- &mut source,
6588- CompileOptions::ConsumeCodeCache,
6589- NoCacheReason::NoReason,
6590- )
6591- .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
6592- debug_assert!(
6593- !source.get_cached_data().is_some_and(|data| data.rejected()),
6594- "code cache rejected for {name}"
6595- );
6596- unbound
6597- }
6598- None => {
6599- let mut source = v8::script_compiler::Source::new(code, None);
6600- // Eager: a lazily-compiled cache would push function-body compile
6601- // cost back into every consumer's first request.
6602- let unbound = v8::script_compiler::compile_unbound_script(
6603- scope,
6604- &mut source,
6605- CompileOptions::EagerCompile,
6606- NoCacheReason::NoReason,
6607- )
6608- .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
6609- if let Some(data) = unbound.create_code_cache() {
6610- bootstrap_code_cache()
6611- .lock()
6612- .unwrap()
6613- .insert(name, std::sync::Arc::new(data.to_vec()));
6614- }
6615- unbound
6616- }
6617- };
6618- unbound
6619- .bind_to_current_context(scope)
6620- .run(scope)
6621- .ok_or_else(|| anyhow!("bootstrap run {name}"))?;
6622- Ok(())
6623-}
6624-
6625-/// WPT-conformant Web APIs: TextEncoder, URL/URLSearchParams, atob/btoa, and
6626-/// Headers. Run once per isolate before the Cells/Cloudflare-specific harness.
6627-fn install_prelude(scope: &mut v8::PinScope) -> Result<()> {
6628- const PRELUDE: &[(&str, &str)] = &[
6629- ("text_encoding.js", include_str!("js/text_encoding.js")),
6630- (
6631- "url_search_params.js",
6632- include_str!("js/url_search_params.js"),
6633- ),
6634- ("url.js", include_str!("js/url.js")),
6635- ("atob_btoa.js", include_str!("js/atob_btoa.js")),
6636- ("headers.js", include_str!("js/headers.js")),
6637- ("streams.js", include_str!("js/streams.js")),
6638- ("writable_stream.js", include_str!("js/writable_stream.js")),
6639- (
6640- "text_encoding_streams.js",
6641- include_str!("js/text_encoding_streams.js"),
6642- ),
6643- ];
6644- for (name, src) in PRELUDE {
6645- run_bootstrap_script(scope, name, src)?;
6646- }
6647- Ok(())
6648-}
6649-
6650-fn install_harness(scope: &mut v8::PinScope) -> Result<()> {
6651- run_bootstrap_script(scope, "harness.js", include_str!("js/harness.js"))?;
6652- run_bootstrap_script(scope, "crypto.js", include_str!("js/crypto.js"))
6653-}
6654-
6655-fn register_class(scope: &mut v8::PinScope, name: &str, cls: v8::Local<v8::Value>) -> Result<()> {
6656- let ctx = scope.get_current_context();
6657- let global = ctx.global(scope);
6658- let ck = v8::String::new(scope, "__cell").unwrap();
6659- let cell = global
6660- .get(scope, ck.into())
6661- .unwrap()
6662- .to_object(scope)
6663- .unwrap();
6664- let clk = v8::String::new(scope, "classes").unwrap();
6665- let classes = cell
6666- .get(scope, clk.into())
6667- .unwrap()
6668- .to_object(scope)
6669- .unwrap();
6670- let nk = v8::String::new(scope, name).unwrap();
6671- classes.set(scope, nk.into(), cls);
6672- Ok(())
6673-}
6674-
6675-/// Populate `cloudflare:workers` `exports` with the worker module's own exports:
6676-/// a Durable Object class is exposed as its namespace (idFromName/get/RPC), any
6677-/// other export by value. `default` is omitted (it is the fetch entrypoint, not
6678-/// an importable export). Mirrors Workerd's `import { exports }` surface.
6679-fn populate_cf_exports(
6680- scope: &mut v8::PinScope,
6681- ns: v8::Local<v8::Object>,
6682- do_classes: &[String],
6683-) -> Result<()> {
6684- let context = scope.get_current_context();
6685- let global = context.global(scope);
6686- let cf = global
6687- .get(scope, v8::String::new(scope, "__cf").unwrap().into())
6688- .and_then(|value| value.to_object(scope))
6689- .ok_or_else(|| anyhow!("missing __cf runtime state"))?;
6690- let exports = cf
6691- .get(scope, v8::String::new(scope, "exports").unwrap().into())
6692- .and_then(|value| value.to_object(scope))
6693- .ok_or_else(|| anyhow!("missing __cf.exports"))?;
6694- let cell = global
6695- .get(scope, v8::String::new(scope, "__cell").unwrap().into())
6696- .and_then(|value| value.to_object(scope))
6697- .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
6698- let make_ns: v8::Local<v8::Function> = cell
6699- .get(
6700- scope,
6701- v8::String::new(scope, "makeNamespace").unwrap().into(),
6702- )
6703- .and_then(|value| value.try_into().ok())
6704- .ok_or_else(|| anyhow!("missing __cell.makeNamespace"))?;
6705- let do_set: std::collections::HashSet<&str> = do_classes.iter().map(String::as_str).collect();
6706- let names = ns
6707- .get_own_property_names(scope, Default::default())
6708- .ok_or_else(|| anyhow!("no module export names"))?;
6709- for index in 0..names.length() {
6710- let name_value = names.get_index(scope, index).unwrap();
6711- let name = name_value.to_rust_string_lossy(scope);
6712- if name == "default" {
6713- continue;
6714- }
6715- let export_value = if do_set.contains(name.as_str()) {
6716- let arg = v8::String::new(scope, &name).unwrap().into();
6717- make_ns
6718- .call(scope, cell.into(), &[arg])
6719- .ok_or_else(|| anyhow!("makeNamespace({name}) failed"))?
6720- } else {
6721- ns.get(scope, name_value)
6722- .ok_or_else(|| anyhow!("export {name}"))?
6723- };
6724- let key = v8::String::new(scope, &name).unwrap();
6725- exports.set(scope, key.into(), export_value);
6726- }
6727- Ok(())
6728-}
6729-
6730-fn inject_namespace_keys(
6731- scope: &mut v8::PinScope,
6732- script_name: &str,
6733- do_classes: &[String],
6734-) -> Result<()> {
6735- let context = scope.get_current_context();
6736- let global = context.global(scope);
6737- let cell_key = v8::String::new(scope, "__cell").unwrap();
6738- let cell = global
6739- .get(scope, cell_key.into())
6740- .and_then(|value| value.to_object(scope))
6741- .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
6742- let keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
6743- let keys = cell
6744- .get(scope, keys_key.into())
6745- .and_then(|value| value.to_object(scope))
6746- .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
6747- let script_key = v8::String::new(scope, "script").unwrap();
6748- let script_value = v8::String::new(scope, script_name).unwrap();
6749- cell.set(scope, script_key.into(), script_value.into());
6750- for class_name in do_classes {
6751- let class_key = v8::String::new(scope, class_name).unwrap();
6752- let namespace_key = format!("cells:v1:{}:{script_name}:{class_name}", script_name.len(),);
6753- let namespace_key = v8::String::new(scope, &namespace_key).unwrap();
6754- if !keys
6755- .set(scope, class_key.into(), namespace_key.into())
6756- .unwrap_or(false)
6757- {
6758- anyhow::bail!("could not register namespace key for {class_name}");
6759- }
6760- }
6761- Ok(())
6762-}
6763-
6764-/// `globalThis.Cloudflare.compatibilityFlags`. Only flags Cells actually
6765-/// honours are listed; a flag Cells does not model is absent (falsy) rather
6766-/// than reported as enabled.
6767-///
6768-/// Built through the V8 object API rather than by compiling a snippet: this
6769-/// runs on every isolate load, and a separate `Script::compile` there cost
6770-/// ~100us per worker.
6771-fn inject_compatibility_flags(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
6772- let context = scope.get_current_context();
6773- let global = context.global(scope);
6774- let flags = v8::Object::new(scope);
6775- let set_flag = |scope: &mut v8::PinScope, name: &str, value: bool| {
6776- let key = v8::String::new(scope, name).unwrap();
6777- let value = v8::Boolean::new(scope, value);
6778- flags.set(scope, key.into(), value.into());
6779- };
6780- set_flag(scope, "upper_case_all_http_methods", true);
6781- // Cells' async stream/pipe methods return rejected promises
6782- // rather than throwing synchronously, which is exactly the
6783- // behavior this flag names.
6784- set_flag(scope, "capture_async_api_throws", true);
6785- set_flag(
6786- scope,
6787- "delete_all_deletes_alarm",
6788- compat.delete_all_deletes_alarm,
6789- );
6790- set_flag(scope, "js_rpc", compat.js_rpc);
6791- set_flag(
6792- scope,
6793- "fetcher_no_get_put_delete",
6794- !compat.fetcher_get_put_delete,
6795- );
6796- let cloudflare = v8::Object::new(scope);
6797- let key = v8::String::new(scope, "compatibilityFlags").unwrap();
6798- cloudflare.set(scope, key.into(), flags.into());
6799- let key = v8::String::new(scope, "Cloudflare").unwrap();
6800- global.set(scope, key.into(), cloudflare.into());
6801- Ok(())
6802-}
6803-
6804-fn build_env(scope: &mut v8::PinScope, config: &WorkerConfig) -> Result<()> {
6805- let script_name = config.script_name.as_str();
6806- let bindings = config.bindings.as_slice();
6807- let r2_bindings = config.r2_bindings.as_slice();
6808- let ai_binding = config.ai_binding.as_deref();
6809- let vars = config.vars.as_slice();
6810- let services = config.services.as_slice();
6811- let asset_binding = config.asset_binding.as_deref();
6812- // call the harness: for each binding, env[bindingName] = makeNamespace(className)
6813- let src = {
6814- let mut lines = String::from("(() => { const e = __cell.env;\n");
6815- for (bname, cname) in bindings {
6816- lines.push_str(&format!(
6817- "e[{:?}] = __cell.makeNamespace({:?});\n",
6818- bname, cname
6819- ));
6820- }
6821- for name in r2_bindings {
6822- lines.push_str(&format!("e[{:?}] = __makeR2Bucket({:?});\n", name, name));
6823- }
6824- if let (Some(name), Ok(url)) = (ai_binding, std::env::var("CELLD_AI_URL")) {
6825- lines.push_str(&format!("e[{:?}] = __makeAiBinding({:?});\n", name, url));
6826- }
6827- for (binding, script, entrypoint) in services {
6828- let entrypoint = match entrypoint {
6829- Some(name) => format!("{name:?}"),
6830- None => "null".to_string(),
6831- };
6832- lines.push_str(&format!(
6833- "e[{:?}] = __makeServiceBinding({:?}, {});\n",
6834- binding, script, entrypoint
6835- ));
6836- }
6837- for (name, value) in vars {
6838- lines.push_str(&format!("e[{:?}] = {:?};\n", name, value));
6839- }
6840- if let Some(name) = asset_binding {
6841- lines.push_str(&format!(
6842- "e[{:?}] = __makeAssetsBinding({:?});\n",
6843- name, script_name
6844- ));
6845- }
6846- if let Some(name) = config.loader_binding.as_deref() {
6847- lines.push_str(&format!("e[{:?}] = __makeLoader();\n", name));
6848- }
6849- // A loaded worker's caller-supplied `env` (plain JSON values only in
6850- // the walking skeleton) merges last, over the declared bindings.
6851- if let Some(env) = config.loader_env.as_deref() {
6852- lines.push_str(&format!("Object.assign(e, {});\n", env));
6853- }
6854- lines.push_str("})();");
6855- lines
6856- };
6857- let code = v8::String::new(scope, &src).unwrap();
6858- let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("env compile"))?;
6859- s.run(scope).ok_or_else(|| anyhow!("env run"))?;
6860- Ok(())
6861-}
6862-
6863-/// Record every exported class deriving from `WorkerEntrypoint` in
6864-/// `__cell.entrypoints`, so a service binding with `entrypoint = "Name"` can
6865-/// resolve it, and every export deriving from `DurableObject` in
6866-/// `__cell.doExports`, so misrouting a DO class as a stateless entrypoint is
6867-/// reported as such (Workerd getExportedHandler()). Runs once per load; the
6868-/// check is a prototype walk, not a call into user code.
6869-fn register_entrypoints(scope: &mut v8::PinScope, ns: v8::Local<v8::Object>) -> Result<()> {
6870- let context = scope.get_current_context();
6871- let global = context.global(scope);
6872- let cell_key = v8::String::new(scope, "__cell").unwrap();
6873- let cell = global
6874- .get(scope, cell_key.into())
6875- .and_then(|value| value.to_object(scope))
6876- .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
6877- let key = v8::String::new(scope, "entrypoints").unwrap();
6878- let entrypoints = cell
6879- .get(scope, key.into())
6880- .and_then(|value| value.to_object(scope))
6881- .ok_or_else(|| anyhow!("missing entrypoint registry"))?;
6882- let key = v8::String::new(scope, "objectEntrypoints").unwrap();
6883- let object_entrypoints = cell
6884- .get(scope, key.into())
6885- .and_then(|value| value.to_object(scope))
6886- .ok_or_else(|| anyhow!("missing object-entrypoint registry"))?;
6887- let key = v8::String::new(scope, "doExports").unwrap();
6888- let do_exports = cell
6889- .get(scope, key.into())
6890- .and_then(|value| value.to_object(scope))
6891- .ok_or_else(|| anyhow!("missing doExports registry"))?;
6892- let cf_key = v8::String::new(scope, "__cf").unwrap();
6893- let cf = global
6894- .get(scope, cf_key.into())
6895- .and_then(|value| value.to_object(scope))
6896- .ok_or_else(|| anyhow!("missing __cf"))?;
6897- let key = v8::String::new(scope, "WorkerEntrypoint").unwrap();
6898- let entrypoint_base = cf
6899- .get(scope, key.into())
6900- .ok_or_else(|| anyhow!("missing WorkerEntrypoint base"))?;
6901- let key = v8::String::new(scope, "DurableObject").unwrap();
6902- let durable_base = cf
6903- .get(scope, key.into())
6904- .ok_or_else(|| anyhow!("missing DurableObject base"))?;
6905- let Some(names) = ns.get_own_property_names(scope, Default::default()) else {
6906- return Ok(());
6907- };
6908- let yes = v8::Boolean::new(scope, true);
6909- for index in 0..names.length() {
6910- let Some(name) = names.get_index(scope, index) else {
6911- continue;
6912- };
6913- let Some(value) = ns.get(scope, name) else {
6914- continue;
6915- };
6916- if !value.is_function() {
6917- // A plain-object export is Workerd's non-class entrypoint; its
6918- // handler functions dispatch as fn(arg, env, ctx).
6919- if value.is_object() {
6920- object_entrypoints.set(scope, name, value);
6921- }
6922- continue;
6923- }
6924- // Walk the prototype chain rather than calling anything.
6925- let mut proto = value.to_object(scope).and_then(|o| o.get_prototype(scope));
6926- while let Some(current) = proto {
6927- if current == entrypoint_base {
6928- entrypoints.set(scope, name, value);
6929- break;
6930- }
6931- if current == durable_base {
6932- do_exports.set(scope, name, yes.into());
6933- break;
6934- }
6935- proto = current
6936- .to_object(scope)
6937- .and_then(|o| o.get_prototype(scope));
6938- }
6939- }
6940- Ok(())
6941-}
6942-
6943-/// Mark which cell scopes are local to this node and record the node id. Every
6944-/// other scope routes cross-node via `__do_call`.
6945-fn inject_routing(scope: &mut v8::PinScope, owned: &[String], node: &str) -> Result<()> {
6946- let mut src = format!("(() => {{ __cell.node = {node:?};\n");
6947- for s in owned {
6948- src.push_str(&format!("__cell.owned[{s:?}] = true;\n"));
6949- }
6950- src.push_str("})();");
6951- let code = v8::String::new(scope, &src).unwrap();
6952- let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("routing compile"))?;
6953- s.run(scope).ok_or_else(|| anyhow!("routing run"))?;
6954- Ok(())
6955-}
6956-
6957-fn inject_storage_compatibility(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
6958- let source = format!(
6959- "__cell.deleteAllDeletesAlarm = {};\n\
6960- __cell.compat.jsRpc = {};\n\
6961- __cell.compat.fetcherGetPutDelete = {};\n\
6962- __cell.compat.websocketStandardBinaryType = {};",
6963- compat.delete_all_deletes_alarm,
6964- compat.js_rpc,
6965- compat.fetcher_get_put_delete,
6966- compat.websocket_standard_binary_type,
6967- );
6968- let code = v8::String::new(scope, &source).unwrap();
6969- let script =
6970- v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compatibility compile"))?;
6971- script
6972- .run(scope)
6973- .ok_or_else(|| anyhow!("compatibility run"))?;
6974- Ok(())
6975-}
6976-
6977-fn harness_env<'s>(scope: &mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>> {
6978- let ctx = scope.get_current_context();
6979- let global = ctx.global(scope);
6980- let ck = v8::String::new(scope, "__cell").unwrap();
6981- let cell = global
6982- .get(scope, ck.into())
6983- .unwrap()
6984- .to_object(scope)
6985- .unwrap();
6986- let ek = v8::String::new(scope, "env").unwrap();
6987- Ok(cell.get(scope, ek.into()).unwrap())
6988-}
6989-
6990-fn begin_event_context<'s>(scope: &mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>> {
6991- let global = scope.get_current_context().global(scope);
6992- let key = v8::String::new(scope, "__beginEvent").unwrap();
6993- let function: v8::Local<v8::Function> = global
6994- .get(scope, key.into())
6995- .ok_or_else(|| anyhow!("no __beginEvent"))?
6996- .try_into()
6997- .map_err(|_| anyhow!("__beginEvent is not a function"))?;
6998- let recv = v8::undefined(scope).into();
6999- function
7000- .call(scope, recv, &[])
7001- .ok_or_else(|| anyhow!("__beginEvent threw"))
7002-}
7003-
7004-fn end_event_context<'s>(
7005- scope: &mut v8::PinScope<'s, '_>,
7006-) -> Result<Option<v8::Local<'s, v8::Promise>>> {
7007- let global = scope.get_current_context().global(scope);
7008- let key = v8::String::new(scope, "__endEvent").unwrap();
7009- let function: v8::Local<v8::Function> = global
7010- .get(scope, key.into())
7011- .ok_or_else(|| anyhow!("no __endEvent"))?
7012- .try_into()
7013- .map_err(|_| anyhow!("__endEvent is not a function"))?;
7014- let recv = v8::undefined(scope).into();
7015- let value = function
7016- .call(scope, recv, &[])
7017- .ok_or_else(|| anyhow!("__endEvent threw"))?;
7018- if value.is_null_or_undefined() {
7019- Ok(None)
7020- } else {
7021- Ok(Some(value.try_into().map_err(|_| {
7022- anyhow!("__endEvent did not return a promise")
7023- })?))
7024- }
7025-}
7026-
7027-// ---- module compilation + request/response marshalling ----
7028-
7029-fn compile_module<'s>(
7030- scope: &mut v8::PinScope<'s, '_>,
7031- name: &str,
7032- src: &str,
7033-) -> Option<v8::Local<'s, v8::Module>> {
7034- let name = v8::String::new(scope, name)?;
7035- let source = v8::String::new(scope, src)?;
7036- let origin = v8::ScriptOrigin::new(
7037- scope,
7038- name.into(),
7039- 0,
7040- 0,
7041- false,
7042- 0,
7043- None,
7044- false,
7045- false,
7046- true,
7047- None,
7048- );
7049- let mut src = v8::script_compiler::Source::new(source, Some(&origin));
7050- v8::script_compiler::compile_module(scope, &mut src)
7051-}
7052-
7053-thread_local! {
7054- // specifier -> pre-compiled stub module, consulted by `resolve_external`
7055- // while V8 statically links a real worker bundle's imports.
7056- static MODREG: RefCell<HashMap<String, v8::Global<v8::Module>>> =
7057- RefCell::new(HashMap::new());
7058-}
7059-
7060-/// Scan a bundle for its external (`cloudflare:*` / `node:*`) imports and the
7061-/// named/default bindings pulled from each. V8 static-links these, so a stub
7062-/// must provide exactly these names; namespace imports (`* as x`) need none.
7063-/// Is `spec` an external builtin (`node:*`, `cloudflare:*`, or a bare node
7064-/// builtin)? esbuild bundles every npm dep inline and leaves only builtins
7065-/// external, so a remaining bare specifier is a node builtin.
7066-fn is_external(spec: &str) -> bool {
7067- const BARE: &[&str] = &[
7068- "path",
7069- "os",
7070- "fs",
7071- "fs/promises",
7072- "crypto",
7073- "stream",
7074- "util",
7075- "util/types",
7076- "assert",
7077- "module",
7078- "process",
7079- "tty",
7080- "url",
7081- "v8",
7082- "constants",
7083- "buffer",
7084- "events",
7085- "zlib",
7086- "child_process",
7087- "http",
7088- "https",
7089- "http2",
7090- "net",
7091- "tls",
7092- "dns",
7093- "readline",
7094- "string_decoder",
7095- "querystring",
7096- "async_hooks",
7097- "perf_hooks",
7098- "worker_threads",
7099- "vm",
7100- "diagnostics_channel",
7101- "timers",
7102- "inspector",
7103- "dgram",
7104- "cluster",
7105- "punycode",
7106- "sqlite",
7107- ];
7108- if spec.starts_with("node:") || spec.starts_with("cloudflare:") {
7109- return true;
7110- }
7111- // bare builtin, or a builtin submodule like `stream/promises`
7112- BARE.contains(&spec) || BARE.contains(&spec.split('/').next().unwrap_or(""))
7113-}
7114-
7115-fn scan_external_imports(
7116- src: &str,
7117-) -> std::collections::BTreeMap<String, std::collections::BTreeSet<String>> {
7118- let re = regex::Regex::new(r#"import\s+([^;]*?)\s*from\s*["']([^"']+)["']"#).unwrap();
7119- let braces = regex::Regex::new(r"\{([^}]*)\}").unwrap();
7120- let mut map: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
7121- Default::default();
7122- for cap in re.captures_iter(src) {
7123- if !is_external(&cap[2]) {
7124- continue;
7125- }
7126- let clause = cap[1].trim();
7127- let set = map.entry(cap[2].to_string()).or_default();
7128- if let Some(b) = braces.captures(clause) {
7129- for part in b[1].split(',') {
7130- let name = part.split_whitespace().next().unwrap_or("");
7131- // A commented-out binding inside the braces is not a name.
7132- if !name.is_empty() && !name.starts_with("//") {
7133- set.insert(name.to_string());
7134- }
7135- }
7136- }
7137- let head = clause
7138- .split(['{', '*'])
7139- .next()
7140- .unwrap_or("")
7141- .trim()
7142- .trim_end_matches(',')
7143- .trim();
7144- if !head.is_empty() {
7145- set.insert("default".into());
7146- } // default import
7147- // `import * as x` consumes the whole namespace; the stub must then
7148- // export the module's full surface, not just the scanned names.
7149- if clause.contains('*') {
7150- set.insert("*".into());
7151- }
7152- }
7153- map
7154-}
7155-
7156-/// A stub ES module for `spec`. `cloudflare:workers` binds the real DO base
7157-/// class from the harness; every other builtin routes to a pass-through proxy
7158-/// so evaluation never crashes on an unsupported node/cf API.
7159-/// A module Cells really implements in JS. Its source is injected into the
7160-/// generated stub module, and `register_stubs` only builds stubs for
7161-/// specifiers a bundle actually imports — so an isolate that never imports it
7162-/// pays nothing at load. `global` is what the source defines and doubles as
7163-/// the redefinition guard when a bundle imports several aliases.
7164-struct LazyModule {
7165- specs: &'static [&'static str],
7166- global: &'static str,
7167- source: &'static str,
7168-}
7169-
7170-const LAZY_MODULES: &[LazyModule] = &[
7171- LazyModule {
7172- specs: &["assert", "node:assert"],
7173- global: "__assertModule",
7174- source: include_str!("js/node_assert.js"),
7175- },
7176- LazyModule {
7177- specs: &["assert/strict", "node:assert/strict"],
7178- global: "__assertStrictModule",
7179- source: include_str!("js/node_assert.js"),
7180- },
7181- LazyModule {
7182- specs: &["timers/promises", "node:timers/promises"],
7183- global: "__timersPromises",
7184- source: include_str!("js/node_timers.js"),
7185- },
7186- LazyModule {
7187- specs: &["test", "node:test", "node:test/reporters"],
7188- global: "__nodeTest",
7189- source: include_str!("js/node_test.js"),
7190- },
7191- LazyModule {
7192- specs: &["util", "node:util"],
7193- global: "__utilModule",
7194- source: include_str!("js/node_util.js"),
7195- },
7196- // Same source, different namespace: node:util/types has the type
7197- // predicates as its named exports. The shared source defines both
7198- // globals, so either entry's guard covers the other.
7199- LazyModule {
7200- specs: &["util/types", "node:util/types"],
7201- global: "__utilTypesModule",
7202- source: include_str!("js/node_util.js"),
7203- },
7204- LazyModule {
7205- specs: &["events", "node:events"],
7206- global: "__eventsModule",
7207- source: include_str!("js/node_events.js"),
7208- },
7209- LazyModule {
7210- specs: &["path", "node:path", "path/posix", "node:path/posix"],
7211- global: "__pathModule",
7212- source: include_str!("js/node_path.js"),
7213- },
7214- // Same source; either entry's guard covers the other.
7215- LazyModule {
7216- specs: &["path/win32", "node:path/win32"],
7217- global: "__pathWin32Module",
7218- source: include_str!("js/node_path.js"),
7219- },
7220- // Shares its source with the `Buffer` LAZY_GLOBALS entry; the script
7221- // is self-guarded, so whichever seam runs first wins and the other
7222- // reuses the same classes.
7223- LazyModule {
7224- specs: &["buffer", "node:buffer"],
7225- global: "__buffer",
7226- source: include_str!("js/node_buffer.js"),
7227- },
7228- LazyModule {
7229- specs: &["crypto", "node:crypto"],
7230- global: "__cryptoModule",
7231- source: include_str!("js/node_crypto.js"),
7232- },
7233- LazyModule {
7234- specs: &["async_hooks", "node:async_hooks"],
7235- global: "__asyncHooksModule",
7236- source: include_str!("js/node_async_hooks.js"),
7237- },
7238- // One source defines the whole stream family; whichever entry runs
7239- // first, its guard covers the others.
7240- LazyModule {
7241- specs: &["stream", "node:stream"],
7242- global: "__streamModule",
7243- source: include_str!("js/node_stream.js"),
7244- },
7245- LazyModule {
7246- specs: &["stream/promises", "node:stream/promises"],
7247- global: "__streamPromises",
7248- source: include_str!("js/node_stream.js"),
7249- },
7250- LazyModule {
7251- specs: &["stream/web", "node:stream/web"],
7252- global: "__streamWeb",
7253- source: include_str!("js/node_stream.js"),
7254- },
7255- LazyModule {
7256- specs: &["stream/consumers", "node:stream/consumers"],
7257- global: "__streamConsumers",
7258- source: include_str!("js/node_stream.js"),
7259- },
7260-];
7261-
7262-/// A global whose definition only compiles when something reads the name.
7263-/// One script may define several names; touching any of them installs them
7264-/// all. A bundle that names none pays only the `SetLazyDataProperty` calls
7265-/// at boot, so this is where a new global belongs unless the prelude has to
7266-/// see it.
7267-struct LazyGlobal {
7268- names: &'static [&'static str],
7269- source: &'static str,
7270-}
7271-
7272-const LAZY_GLOBALS: &[LazyGlobal] = &[
7273- LazyGlobal {
7274- names: &["IdentityTransformStream", "FixedLengthStream"],
7275- source: include_str!("js/identity_transform_stream.js"),
7276- },
7277- LazyGlobal {
7278- names: &["CompressionStream", "DecompressionStream"],
7279- source: include_str!("js/compression_streams.js"),
7280- },
7281- LazyGlobal {
7282- names: &[
7283- "ReadableByteStreamController",
7284- "ReadableStreamBYOBReader",
7285- "ReadableStreamBYOBRequest",
7286- ],
7287- source: include_str!("js/byte_streams.js"),
7288- },
7289- LazyGlobal {
7290- names: &["Buffer"],
7291- source: include_str!("js/node_buffer.js"),
7292- },
7293- LazyGlobal {
7294- names: &["setImmediate", "clearImmediate"],
7295- source: include_str!("js/set_immediate.js"),
7296- },
7297- LazyGlobal {
7298- names: &["URLPattern"],
7299- source: include_str!("js/url_pattern.js"),
7300- },
7301-];
7302-
7303-/// Runs once per group, the first time one of its names is read. V8 then
7304-/// replaces the accessor with the returned value, so the script never
7305-/// compiles twice.
7306-fn lazy_global_getter(
7307- scope: &mut v8::PinScope,
7308- name: v8::Local<v8::Name>,
7309- args: v8::PropertyCallbackArguments,
7310- mut rv: v8::ReturnValue<v8::Value>,
7311-) {
7312- let index = args.data().integer_value(scope).unwrap();
7313- let group = &LAZY_GLOBALS[index as usize];
7314- let code = v8::String::new(scope, group.source).unwrap();
7315- let script = v8::Script::compile(scope, code, None).unwrap();
7316- let exports = script.run(scope).unwrap();
7317- let exports: v8::Local<v8::Object> = exports.try_into().unwrap();
7318- // The group's other names are still lazy; define them now or reading one
7319- // would compile the same script again. Not this one — V8 asserts the
7320- // property is still an accessor when the getter returns.
7321- let global = scope.get_current_context().global(scope);
7322- for other in group.names {
7323- let key = v8::String::new(scope, other).unwrap();
7324- if name.strict_equals(key.into()) {
7325- continue;
7326- }
7327- let value = exports.get(scope, key.into()).unwrap();
7328- global.create_data_property(scope, key.into(), value);
7329- }
7330- rv.set(exports.get(scope, name.into()).unwrap());
7331-}
7332-
7333-fn install_lazy_globals(scope: &mut v8::PinScope) -> Result<()> {
7334- let global = scope.get_current_context().global(scope);
7335- for (i, group) in LAZY_GLOBALS.iter().enumerate() {
7336- let data = v8::Integer::new(scope, i as i32);
7337- for name in group.names {
7338- let key = v8::String::new(scope, name).unwrap();
7339- global.set_lazy_data_property_with_data(
7340- scope,
7341- key.into(),
7342- lazy_global_getter,
7343- data.into(),
7344- v8::PropertyAttribute::NONE,
7345- v8::SideEffectType::HasSideEffect,
7346- v8::SideEffectType::HasSideEffect,
7347- );
7348- }
7349- }
7350- Ok(())
7351-}
7352-
7353-/// Globals already installed by the src/js/harness for partially supported
7354-/// builtins. These cost every isolate, so new modules belong in
7355-/// `LAZY_MODULES` instead.
7356-fn eager_module_global(spec: &str) -> Option<&'static str> {
7357- Some(match spec {
7358- "fs" | "node:fs" | "fs/promises" | "node:fs/promises" => "globalThis.__fs",
7359- "zlib" | "node:zlib" => "globalThis.__zlibModule",
7360- _ => return None,
7361- })
7362-}
7363-
7364-fn stub_source(spec: &str, names: &std::collections::BTreeSet<String>) -> String {
7365- let cf = spec == "cloudflare:workers";
7366- let lazy = LAZY_MODULES.iter().find(|m| m.specs.contains(&spec));
7367- let eager = eager_module_global(spec);
7368- let base = if cf {
7369- "globalThis.__cf".to_string()
7370- } else if let Some(m) = lazy {
7371- format!("globalThis.{}", m.global)
7372- } else if let Some(global) = eager {
7373- global.to_string()
7374- } else {
7375- "globalThis.__nodeStub".to_string()
7376- };
7377- let real = cf || lazy.is_some() || eager.is_some();
7378- let mut out = String::new();
7379- if let Some(m) = lazy {
7380- out.push_str(&format!("if (!globalThis.{}) {{\n", m.global));
7381- out.push_str(m.source);
7382- out.push_str("}\n");
7383- }
7384- for n in names {
7385- if n == "*" {
7386- continue; // namespace imports take the full-surface path
7387- } else if n == "default" {
7388- out.push_str(&format!("export default {base};\n"));
7389- } else if cf
7390- && matches!(
7391- n.as_str(),
7392- "DurableObject" | "RpcTarget" | "WorkerEntrypoint" | "env" | "exports"
7393- )
7394- {
7395- out.push_str(&format!("export const {n} = globalThis.__cf.{n};\n"));
7396- } else if real {
7397- out.push_str(&format!("export const {n} = {base}.{n};\n"));
7398- } else {
7399- out.push_str(&format!("export const {n} = globalThis.__nodeStub;\n"));
7400- }
7401- }
7402- out
7403-}
7404-
7405-/// Compile one stub module per external specifier into MODREG. Run before
7406-/// instantiating a real bundle; `resolve_external` then serves them.
7407-fn register_stubs(scope: &mut v8::PinScope, src: &str, text: &[(String, String)]) {
7408- MODREG.with(|r| r.borrow_mut().clear());
7409- let reg = |spec: String, source: String, scope: &mut v8::PinScope| {
7410- if let Some(m) = compile_module(scope, &spec, &source) {
7411- MODREG.with(|r| r.borrow_mut().insert(spec, v8::Global::new(scope, m)));
7412- } else {
7413- tracing::warn!(%spec, "module stub failed to compile");
7414- }
7415- };
7416- for (spec, names) in scan_external_imports(src) {
7417- // `import * as x` binds the whole namespace, so the stub's exports
7418- // must be the module's full surface — probed from the backing
7419- // object, like dynamic import() — not just the scanned names.
7420- let s = if names.contains("*") {
7421- full_surface_source(scope, &spec, &names).unwrap_or_else(|| stub_source(&spec, &names))
7422- } else {
7423- stub_source(&spec, &names)
7424- };
7425- reg(spec, s, scope);
7426- }
7427- // sibling text modules (wrangler Text rule: `import md from './x.md'`)
7428- for (spec, content) in text {
7429- let s = format!(
7430- "export default {};",
7431- serde_json::to_string(content).unwrap()
7432- );
7433- reg(spec.clone(), s, scope);
7434- }
7435- tracing::debug!(
7436- mods = MODREG.with(|r| r.borrow().len()),
7437- "registered import stubs + text modules"
7438- );
7439-}
7440-
7441-/// Register a loaded worker's sibling JS modules (Worker Loader multi-module
7442-/// bundles), in addition to the builtins `register_stubs` already added for the
7443-/// main module. Each module is registered under its own name and `./name` so
7444-/// both bare and relative sibling imports resolve; the whole graph links when
7445-/// the main module instantiates. Any builtin a sibling imports (and the main
7446-/// module did not) is stubbed too.
7447-fn register_loader_modules(scope: &mut v8::PinScope, modules: &[(String, String)]) {
7448- for (_name, source) in modules {
7449- for (spec, names) in scan_external_imports(source) {
7450- if MODREG.with(|r| r.borrow().contains_key(&spec)) {
7451- continue;
7452- }
7453- let s = if names.contains("*") {
7454- full_surface_source(scope, &spec, &names)
7455- .unwrap_or_else(|| stub_source(&spec, &names))
7456- } else {
7457- stub_source(&spec, &names)
7458- };
7459- if let Some(m) = compile_module(scope, &spec, &s) {
7460- MODREG.with(|r| r.borrow_mut().insert(spec, v8::Global::new(scope, m)));
7461- }
7462- }
7463- }
7464- for (name, source) in modules {
7465- let Some(m) = compile_module(scope, name, source) else {
7466- tracing::warn!(%name, "loader module failed to compile");
7467- continue;
7468- };
7469- let g = v8::Global::new(scope, m);
7470- MODREG.with(|r| {
7471- let mut reg = r.borrow_mut();
7472- reg.insert(name.clone(), g.clone());
7473- reg.insert(format!("./{name}"), g);
7474- });
7475- }
7476-}
7477-
7478-/// Module resolve callback: serve a registered stub for `cloudflare:*`/`node:*`.
7479-/// celld bundles are single-file, so anything else is genuinely unresolvable.
7480-fn resolve_external<'s>(
7481- context: v8::Local<'s, v8::Context>,
7482- specifier: v8::Local<'s, v8::String>,
7483- _a: v8::Local<'s, v8::FixedArray>,
7484- _r: v8::Local<'s, v8::Module>,
7485-) -> Option<v8::Local<'s, v8::Module>> {
7486- v8::callback_scope!(unsafe scope, context);
7487- let spec = specifier.to_rust_string_lossy(scope);
7488- let m = MODREG.with(|r| r.borrow().get(&spec).map(|g| v8::Local::new(scope, g)));
7489- if m.is_none() {
7490- tracing::warn!(%spec, "resolve: no stub for specifier");
7491- }
7492- m
7493-}
7494-
7495-/// The (guarded setup script, backing-object expression) pair for a builtin
7496-/// specifier, or None if `spec` is not one. The setup materializes a lazy
7497-/// module's source at most once; the expression then names its global.
7498-fn builtin_source(spec: &str) -> Option<(String, String)> {
7499- if spec == "cloudflare:workers" {
7500- return Some((String::new(), "globalThis.__cf".into()));
7501- }
7502- if let Some(m) = LAZY_MODULES.iter().find(|m| m.specs.contains(&spec)) {
7503- return Some((
7504- format!("if (!globalThis.{}) {{\n{}}}\n", m.global, m.source),
7505- format!("globalThis.{}", m.global),
7506- ));
7507- }
7508- if let Some(global) = eager_module_global(spec) {
7509- return Some((String::new(), global.to_string()));
7510- }
7511- is_external(spec).then(|| (String::new(), "globalThis.__nodeStub".to_string()))
7512-}
7513-
7514-/// Full-surface module source for a builtin: run the (guarded) setup, probe
7515-/// the backing object's enumerable keys, and re-export each one. Serves both
7516-/// `import * as x` stubs and dynamic import(). `extra` adds statically
7517-/// scanned names the probe may have missed, so mixed named + namespace
7518-/// imports still link. String export names sidestep identifier restrictions.
7519-fn full_surface_source(
7520- scope: &mut v8::PinScope,
7521- spec: &str,
7522- extra: &std::collections::BTreeSet<String>,
7523-) -> Option<String> {
7524- let (setup, expr) = builtin_source(spec)?;
7525- let probe = format!("{setup}JSON.stringify(Object.keys(Object({expr})))");
7526- let code = v8::String::new(scope, &probe)?;
7527- let script = v8::Script::compile(scope, code, None)?;
7528- let keys = script.run(scope)?.to_rust_string_lossy(scope);
7529- let mut names: Vec<String> = serde_json::from_str(&keys).unwrap_or_default();
7530- for name in extra {
7531- if name != "*" && !names.contains(name) {
7532- names.push(name.clone());
7533- }
7534- }
7535- let mut src = format!("const __b = {expr};\nexport default __b;\n");
7536- for (i, name) in names.iter().enumerate() {
7537- if name == "default" {
7538- continue;
7539- }
7540- let name = serde_json::to_string(name).unwrap();
7541- src.push_str(&format!(
7542- "const __e{i} = __b[{name}]; export {{ __e{i} as {name} }};\n"
7543- ));
7544- }
7545- Some(src)
7546-}
7547-
7548-/// `process.getBuiltinModule(id)`: the builtin's backing object, or
7549-/// undefined for anything that is not a node builtin.
7550-fn op_builtin_module(
7551- scope: &mut v8::PinScope,
7552- args: v8::FunctionCallbackArguments,
7553- mut rv: v8::ReturnValue<v8::Value>,
7554-) {
7555- let spec = args.get(0).to_rust_string_lossy(scope);
7556- if spec.starts_with("cloudflare:") {
7557- return; // not a node builtin
7558- }
7559- let Some((setup, expr)) = builtin_source(&spec) else {
7560- return;
7561- };
7562- let code = v8::String::new(scope, &format!("{setup}{expr}")).unwrap();
7563- if let Some(script) = v8::Script::compile(scope, code, None) {
7564- if let Some(value) = script.run(scope) {
7565- rv.set(value);
7566- }
7567- }
7568-}
7569-
7570-/// Evaluate (once per isolate) a full-namespace module for a builtin
7571-/// specifier. Unlike the static stubs, whose exports are the statically
7572-/// scanned import names, this re-exports every enumerable key of the
7573-/// backing object — a dynamic import's consumer can reach for any of them.
7574-/// Cached in MODREG under a `dyn:` key so later import() calls are a
7575-/// table lookup.
7576-fn dynamic_namespace<'s>(
7577- scope: &mut v8::PinScope<'s, '_>,
7578- spec: &str,
7579-) -> Result<v8::Local<'s, v8::Value>> {
7580- let key = format!("dyn:{spec}");
7581- let cached = MODREG.with(|r| r.borrow().get(&key).map(|g| v8::Local::new(scope, g)));
7582- if let Some(module) = cached {
7583- return Ok(module.get_module_namespace());
7584- }
7585- let src = full_surface_source(scope, spec, &Default::default())
7586- .ok_or_else(|| anyhow!("dynamic import of \"{spec}\" is not supported"))?;
7587- let module = compile_module(scope, spec, &src)
7588- .ok_or_else(|| anyhow!("dynamic module for {spec} did not compile"))?;
7589- module
7590- .instantiate_module(scope, resolve_external)
7591- .ok_or_else(|| anyhow!("dynamic module for {spec} did not link"))?;
7592- module
7593- .evaluate(scope)
7594- .ok_or_else(|| anyhow!("dynamic module for {spec} threw"))?;
7595- if module.get_status() != v8::ModuleStatus::Evaluated {
7596- return Err(anyhow!("dynamic module for {spec} failed to evaluate"));
7597- }
7598- MODREG.with(|r| r.borrow_mut().insert(key, v8::Global::new(scope, module)));
7599- Ok(module.get_module_namespace())
7600-}
7601-
7602-/// Dynamic `import()` host hook. Builtin specifiers resolve through the same
7603-/// table static imports use; anything else rejects — celld bundles are
7604-/// single-file, so there is nothing else to load.
7605-fn host_import_module_dynamically<'s>(
7606- scope: &mut v8::PinScope<'s, '_>,
7607- _host_defined_options: v8::Local<'s, v8::Data>,
7608- _resource_name: v8::Local<'s, v8::Value>,
7609- specifier: v8::Local<'s, v8::String>,
7610- _import_attributes: v8::Local<'s, v8::FixedArray>,
7611-) -> Option<v8::Local<'s, v8::Promise>> {
7612- let resolver = v8::PromiseResolver::new(scope)?;
7613- let promise = resolver.get_promise(scope);
7614- let spec = specifier.to_rust_string_lossy(scope);
7615- let tc = std::pin::pin!(v8::TryCatch::new(scope));
7616- let tc = &mut tc.init();
7617- match dynamic_namespace(tc, &spec) {
7618- Ok(namespace) => {
7619- resolver.resolve(tc, namespace);
7620- }
7621- Err(error) => {
7622- let caught = tc.exception();
7623- tc.reset();
7624- let exception = caught.unwrap_or_else(|| {
7625- let message = v8::String::new(tc, &error.to_string()).unwrap();
7626- v8::Exception::error(tc, message)
7627- });
7628- resolver.reject(tc, exception);
7629- }
7630- }
7631- Some(promise)
7632-}
7633-
7634-/// Like `make_request`, but marks the request as incoming. Its signal is
7635-/// registered only if the handler actually suspends, preserving the
7636-/// synchronous request path.
7637-fn make_incoming_request<'s>(
7638- tc: &mut v8::PinScope<'s, '_>,
7639- url: &str,
7640- method: &str,
7641- body: &[u8],
7642- headers: &[(String, String)],
7643-) -> Result<v8::Local<'s, v8::Value>> {
7644- let global = tc.get_current_context().global(tc);
7645- let key = v8::String::new(tc, "__makeIncomingRequest").unwrap();
7646- let f: v8::Local<v8::Function> = global
7647- .get(tc, key.into())
7648- .ok_or_else(|| anyhow!("no __makeIncomingRequest"))?
7649- .try_into()
7650- .map_err(|_| anyhow!("not fn"))?;
7651- let url = v8::String::new(tc, url).unwrap();
7652- let method = v8::String::new(tc, method).unwrap();
7653- let body = bytes_value(tc, body.to_vec());
7654- let headers = v8::String::new(
7655- tc,
7656- &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()),
7657- )
7658- .unwrap();
7659- let recv = v8::undefined(tc).into();
7660- f.call(tc, recv, &[url.into(), method.into(), body, headers.into()])
7661- .ok_or_else(|| anyhow!("__makeIncomingRequest threw"))
7662-}
7663-
7664-fn register_incoming_request(
7665- tc: &mut v8::PinScope,
7666- request_id: RequestId,
7667- request: v8::Local<v8::Value>,
7668-) -> Result<()> {
7669- let global = tc.get_current_context().global(tc);
7670- let key = v8::String::new(tc, "__registerIncomingRequest").unwrap();
7671- let function: v8::Local<v8::Function> = global
7672- .get(tc, key.into())
7673- .ok_or_else(|| anyhow!("no __registerIncomingRequest"))?
7674- .try_into()
7675- .map_err(|_| anyhow!("__registerIncomingRequest is not a function"))?;
7676- let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
7677- let recv = v8::undefined(tc).into();
7678- function
7679- .call(tc, recv, &[id.into(), request])
7680- .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?;
7681- Ok(())
7682-}
7683-
7684-fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) {
7685- let global = tc.get_current_context().global(tc);
7686- let key = v8::String::new(tc, "__finishIncomingRequest").unwrap();
7687- let Some(value) = global.get(tc, key.into()) else {
7688- return;
7689- };
7690- let Ok(function) = value.try_cast::<v8::Function>() else {
7691- return;
7692- };
7693- let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
7694- let recv = v8::undefined(tc).into();
7695- let _ = function.call(tc, recv, &[id.into()]);
7696-}
7697-
7698-fn make_request<'s>(
7699- tc: &mut v8::PinScope<'s, '_>,
7700- url: &str,
7701- method: &str,
7702- body: &[u8],
7703- headers: &[(String, String)],
7704-) -> Result<v8::Local<'s, v8::Value>> {
7705- let g = tc.get_current_context().global(tc);
7706- let k = v8::String::new(tc, "__makeRequest").unwrap();
7707- let f: v8::Local<v8::Function> = g.get(tc, k.into()).unwrap().try_into().unwrap();
7708- let u = v8::String::new(tc, url).unwrap();
7709- let m = v8::String::new(tc, method).unwrap();
7710- let b = bytes_value(tc, body.to_vec());
7711- let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap();
7712- let recv = v8::undefined(tc).into();
7713- f.call(tc, recv, &[u.into(), m.into(), b, h.into()])
7714- .ok_or_else(|| anyhow!("makeRequest threw"))
7715-}
7716-
7717-fn read_response(
7718- scope: &mut v8::PinScope,
7719- ret: v8::Local<v8::Value>,
7720- cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
7721-) -> Result<HttpResponse> {
7722- let ctx = scope.get_current_context();
7723- let global = ctx.global(scope);
7724- let key = v8::String::new(scope, "__readResponse").unwrap();
7725- let f: v8::Local<v8::Function> = global
7726- .get(scope, key.into())
7727- .ok_or_else(|| anyhow!("no __readResponse"))?
7728- .try_into()
7729- .map_err(|_| anyhow!("not fn"))?;
7730- let recv = v8::undefined(scope).into();
7731- let out = f
7732- .call(scope, recv, &[ret])
7733- .ok_or_else(|| anyhow!("readResponse threw"))?;
7734- let out = if let Ok(promise) = out.try_cast::<v8::Promise>() {
7735- run_loop(scope, promise, cell_rx)?
7736- } else {
7737- out
7738- };
7739- let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?;
7740- let sk = v8::String::new(scope, "status").unwrap();
7741- let bk = v8::String::new(scope, "bodyBytes").unwrap();
7742- let tk = v8::String::new(scope, "bodyStreamId").unwrap();
7743- let hk = v8::String::new(scope, "headersJson").unwrap();
7744- let wk = v8::String::new(scope, "wsTargetJson").unwrap();
7745- let status = out
7746- .get(scope, sk.into())
7747- .and_then(|v| v.uint32_value(scope))
7748- .unwrap_or(200) as u16;
7749- // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON
7750- // number array (which was ~4x the bytes to serialize + parse per response).
7751- let body = out
7752- .get(scope, bk.into())
7753- .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok())
7754- .map(|view| {
7755- let mut buf = vec![0u8; view.byte_length()];
7756- view.copy_contents(&mut buf);
7757- buf
7758- })
7759- .unwrap_or_default();
7760- let stream_id = out
7761- .get(scope, tk.into())
7762- .and_then(|value| value.integer_value(scope))
7763- .unwrap_or(0)
7764- .max(0) as u64;
7765- let stream = if stream_id == 0 {
7766- None
7767- } else {
7768- http_streams()
7769- .lock()
7770- .unwrap()
7771- .remove(&stream_id)
7772- .and_then(|stream| stream.source)
7773- .map(http_chunk_stream)
7774- };
7775- if stream_id != 0 && stream.is_none() {
7776- return Err(anyhow!(
7777- "response stream {stream_id} is no longer available"
7778- ));
7779- }
7780- let headers = out
7781- .get(scope, hk.into())
7782- .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok())
7783- .unwrap_or_default();
7784- let ws_json = out
7785- .get(scope, wk.into())
7786- .map(|v| v.to_rust_string_lossy(scope))
7787- .unwrap_or_else(|| "null".into());
7788- let ws = serde_json::from_str(&ws_json).ok();
7789- if status == 101 {
7790- tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response");
7791- }
7792- Ok(HttpResponse {
7793- status,
7794- body,
7795- stream,
7796- headers,
7797- ws,
7798- write_position: None,
7799- })
7800-}
7801-
7802-#[cfg(all(test, celld_internal_tests))]
7803-fn init_engine_for_tests() {
7804- static INIT: std::sync::Once = std::sync::Once::new();
7805- INIT.call_once(|| {
7806- v8::V8::set_flags_from_string("--expose-gc");
7807- Engine::init();
7808- });
7809-}
7810-
7811-/// Externally injected Web-platform tests.
7812-#[cfg(all(test, celld_internal_tests))]
7813-mod conformance_runtime_tests {
7814- include!(env!("CELLD_CONFORMANCE_JS_RUNTIME_TESTS"));
7815-}
7816-
7817-#[cfg(all(test, celld_internal_tests))]
7818-mod conformance_web_platform_tests {
7819- include!(env!("CELLD_CONFORMANCE_WEB_PLATFORM_TESTS"));
13+use anyhow::{anyhow, Context as _, Result};
14+use futures_util::StreamExt as _;
15+use std::cell::RefCell;
16+use std::collections::{HashMap, HashSet};
17+use std::pin::Pin;
18+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
19+use std::sync::{Arc, Mutex, OnceLock};
20+use std::time::{Duration, Instant};
21+use v8::{ValueDeserializerHelper, ValueSerializerHelper};
22+
23+/// The pending exception text from a TryCatch scope (a macro so it needs no
24+/// bound on the crate-private scope traits).
25+macro_rules! exc {
26+ ($tc:expr) => {
27+ $tc.exception()
28+ .map(|e| e.to_rust_string_lossy(&*$tc))
29+ .unwrap_or_else(|| "<none>".into())
30+ };
31+}
32+
33+/// A cross-node dispatch: the isolate hit `env.NS.get(id)` for a cell this node
34+/// does not own. The op hands this to the tokio runtime, which resolves the
35+/// owner and HTTP-proxies the fetch, replying on `reply` (an async oneshot the
36+/// async-op future awaits — the JS thread is never blocked).
37+pub struct DoCallReq {
38+ pub request_id: Option<RequestId>,
39+ pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
40+ /// An explicit JavaScript AbortSignal must reach the target handler, even
41+ /// when it fires before cold routing completes. Transport cancellation has
42+ /// no handler contract and can stop the cold route immediately.
43+ pub deliver_abort_to_handler: bool,
44+ pub scope: String,
45+ pub name: Option<String>,
46+ pub url: String,
47+ pub method: String,
48+ pub body: Vec<u8>,
49+ pub headers: Vec<(String, String)>,
50+ pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
51+ /// Where this call sits in its caller's order for this cell.
52+ pub order: Option<CallOrder>,
53+ /// The dispatching handler's trace context, read from CPED at the
54+ /// call site, so the cell's span joins the caller's trace.
55+ pub parent: Option<crate::telemetry::TraceIds>,
56+}
57+static DO_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<DoCallReq>> = OnceLock::new();
58+
59+/// Delivery order, per caller and per cell.
60+///
61+/// Two calls a script makes back-to-back on one Durable Object stub reach
62+/// the cell in that order. Workerd guarantees it — one pipe per stub — and
63+/// celld did too, while a cell's events came off one channel. Nothing
64+/// between the call and the cell keeps it now: the caller's two ops race to
65+/// the proxy channel, the proxy polls them in a `FuturesUnordered`, and two
66+/// drives race for the isolate. So the order is taken where it is still
67+/// true, synchronously in `op_do_call_impl`, and carried to the one place
68+/// that decides when an event is delivered.
69+///
70+/// It is a chain, not a counter: each call leaves behind the receiver its
71+/// successor waits on, and takes its predecessor's.
72+///
73+/// **The chain lives on the caller.** It was a process-wide map keyed by
74+/// `(context, cell)`, which made every Durable Object call in the node take
75+/// one global lock to record something only its own caller could ever read.
76+/// A shared mutex on a per-request path is a scalability cliff that a small
77+/// machine cannot show you, and the state was never shared to begin with.
78+///
79+/// **Local delivery only.** A call routed to another node crosses HTTP,
80+/// where this order has nowhere to ride, so it is dropped there. Workerd
81+/// has the same seam in a different place, and a cell that moves mid-flight
82+/// reorders under both.
83+pub struct CallOrder {
84+ /// The call before this one, or `None` if this is the first.
85+ ahead: Option<tokio::sync::oneshot::Receiver<Place>>,
86+ /// What the call behind this one waits on.
87+ release: Option<tokio::sync::oneshot::Sender<Place>>,
88+ /// The caller that owns the chain, and this call's place in it.
89+ caller: Arc<IoContext>,
90+ cell: String,
91+ seq: u64,
92+ delivered: bool,
93+}
94+
95+/// What a call hands to the one behind it.
96+///
97+/// `None` once this call has been delivered: the queue has moved on. `Some`
98+/// when it died on the way to a cell and never took its turn, and then it
99+/// is this call's own unfinished place — so the call behind waits for what
100+/// this one was waiting for instead of jumping the queue.
101+///
102+/// Without the handoff a failed call releases its successor immediately,
103+/// and a third call can be delivered ahead of a first that is still in
104+/// flight. Rare, since it needs a call to fail between two that do not, and
105+/// silent, since every call involved still gets an answer.
106+struct Place(Option<Box<tokio::sync::oneshot::Receiver<Place>>>);
107+
108+impl CallOrder {
109+ /// Wait for every call before this one to be delivered.
110+ ///
111+ /// A loop rather than one await because a call that died hands back
112+ /// what *it* was waiting for. `Err` is the chain ahead going away
113+ /// entirely, which is nothing left to wait for.
114+ pub async fn wait(&mut self) {
115+ let mut ahead = self.ahead.take();
116+ while let Some(place) = ahead {
117+ ahead = match place.await {
118+ Ok(Place(forward)) => forward.map(|boxed| *boxed),
119+ Err(_) => None,
120+ };
121+ }
122+ }
123+
124+ /// This call has been delivered; the one behind it may go.
125+ pub fn delivered(&mut self) {
126+ self.delivered = true;
127+ }
128+}
129+
130+impl Drop for CallOrder {
131+ fn drop(&mut self) {
132+ // Nothing followed this call, so the chain is empty and its tail is
133+ // only a leak. A caller's chains outlive its calls otherwise, and a
134+ // cell isolate's default caller outlives everything.
135+ let mut chains = self.caller.call_chains.lock().unwrap();
136+ if chains
137+ .tails
138+ .get(&self.cell)
139+ .is_some_and(|(seq, _)| *seq == self.seq)
140+ {
141+ chains.tails.remove(&self.cell);
142+ }
143+ drop(chains);
144+ if let Some(release) = self.release.take() {
145+ let forward = (!self.delivered).then(|| self.ahead.take()).flatten();
146+ let _ = release.send(Place(forward.map(Box::new)));
147+ }
148+ }
149+}
150+
151+/// One caller's chains, one per cell it has called.
152+#[derive(Default)]
153+struct CallChains {
154+ next_seq: u64,
155+ tails: HashMap<String, (u64, tokio::sync::oneshot::Receiver<Place>)>,
156+}
157+
158+/// Take this call's place in its caller's chain for `cell`. Synchronous, so
159+/// the places are taken in the order the script made the calls.
160+fn enter_call_order(caller: Arc<IoContext>, cell: &str) -> CallOrder {
161+ let (release, next) = tokio::sync::oneshot::channel();
162+ let (seq, ahead) = {
163+ let mut chains = caller.call_chains.lock().unwrap();
164+ chains.next_seq += 1;
165+ let seq = chains.next_seq;
166+ let ahead = chains
167+ .tails
168+ .insert(cell.to_string(), (seq, next))
169+ .map(|(_, ahead)| ahead);
170+ (seq, ahead)
171+ };
172+ CallOrder {
173+ ahead,
174+ release: Some(release),
175+ caller,
176+ cell: cell.to_string(),
177+ seq,
178+ delivered: false,
179+ }
180+}
181+
182+/// An output-gate request for the co-hosted (same-isolate) Durable Object fast
183+/// path. That path runs a resident DO's `fetch` inline, bypassing
184+/// `dispatch_do_call` where the gate lives; the inline handler samples the
185+/// cell's committed-write position and, on a write, asks the actor to hold the
186+/// inline response here until the cell is durable. `position` is the sampled
187+/// committed-write position (the same signal the routed gate uses).
188+pub struct GateReq {
189+ pub scope: String,
190+ pub position: u64,
191+ pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>,
192+}
193+static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new();
194+pub fn set_gate_tx(tx: tokio::sync::mpsc::UnboundedSender<GateReq>) {
195+ let _ = GATE_TX.set(tx);
196+}
197+
198+/// A service-binding call: `env.NAME.fetch()`. Unlike a Durable Object call
199+/// there is no identity to resolve — any isolate running `script` will do — so
200+/// the runtime hands this straight to that script's stateless isolate pool.
201+pub struct SvcCallReq {
202+ /// Fires when the caller's request signal aborts, so the router stops
203+ /// waiting on the target instead of leaving the call outstanding.
204+ pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
205+ pub script: String,
206+ pub url: String,
207+ pub method: String,
208+ pub body: Vec<u8>,
209+ pub headers: Vec<(String, String)>,
210+ pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
211+}
212+static SVC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcCallReq>> = OnceLock::new();
213+
214+/// A Worker assets-binding call. The script name selects the immutable asset
215+/// index loaded for that Worker; unlike ingress this never falls back into the
216+/// Worker and therefore cannot recurse.
217+pub struct AssetCallReq {
218+ pub script: String,
219+ pub url: String,
220+ pub method: String,
221+ pub headers: Vec<(String, String)>,
222+ pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
223+}
224+static ASSET_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<AssetCallReq>> = OnceLock::new();
225+
226+/// An RPC call on a named `WorkerEntrypoint` of another script. Arguments and
227+/// the result cross as V8 structured-clone bytes.
228+pub struct SvcRpcReq {
229+ pub script: String,
230+ pub entrypoint: String,
231+ pub method: String,
232+ pub args: Vec<u8>,
233+ pub reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
234+}
235+static SVC_RPC_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcRpcReq>> = OnceLock::new();
236+pub fn set_svc_rpc_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcRpcReq>) {
237+ let _ = SVC_RPC_TX.set(tx);
238+}
239+pub fn set_svc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcCallReq>) {
240+ let _ = SVC_CALL_TX.set(tx);
241+}
242+pub fn set_asset_call_tx(tx: tokio::sync::mpsc::UnboundedSender<AssetCallReq>) {
243+ let _ = ASSET_CALL_TX.set(tx);
244+}
245+pub fn set_do_call_tx(tx: tokio::sync::mpsc::UnboundedSender<DoCallReq>) {
246+ let _ = DO_CALL_TX.set(tx);
247+}
248+
249+/// Hand a Durable Object call to the dispatcher. Public HTTP ingress uses the
250+/// same queue a Worker's `env.NAME.get(id).fetch()` does, so both resolve
251+/// ownership, forward, and redispatch by one policy rather than two.
252+#[must_use]
253+pub fn submit_do_call(call: DoCallReq) -> bool {
254+ DO_CALL_TX.get().is_some_and(|tx| tx.send(call).is_ok())
255+}
256+
257+/// The arm-time wake-entry gate, output-gate style (matching Durable
258+/// Objects): `setAlarm()` resolves optimistically on the committed local
259+/// write — it never yields the cell's event scheduling to remote I/O — and
260+/// the cell's response edge is withheld until every pending wake-entry PUT
261+/// has landed. Invariant: an arm the caller has OBSERVED acknowledged
262+/// (received the response) is covered by a durable entry.
263+pub struct ArmGate {
264+ pub bucket: crate::bucket::Bucket,
265+ pub flusher: Arc<crate::wake::WakeFlusher>,
266+}
267+static ARM_GATE: OnceLock<ArmGate> = OnceLock::new();
268+pub fn set_arm_gate(gate: ArmGate) {
269+ let _ = ARM_GATE.set(gate);
270+}
271+
272+/// Whether this node still holds a wake entry for `cell`.
273+pub fn wake_entry_tracked(cell: &str) -> bool {
274+ ARM_GATE.get().is_some_and(|gate| gate.flusher.tracks(cell))
275+}
276+
277+/// Drop this node's belief about `cell`'s wake entry — the cell fenced or
278+/// resolved to a remote owner, so the entry is no longer ours to manage.
279+/// Defined since the wake audit and now actually called (it was dead code,
280+/// which meant a node that lost a cell kept believing in its entry).
281+pub fn forget_wake_entry(cell: &str) {
282+ if let Some(gate) = ARM_GATE.get() {
283+ gate.flusher.forget(cell);
284+ }
285+}
286+
287+/// Adopt the wake entry a restored alarm implies, so consuming that alarm
288+/// deletes it rather than orphaning it.
289+pub fn adopt_wake_entry(cell: &str, at_ms: i64) {
290+ if let Some(gate) = ARM_GATE.get() {
291+ gate.flusher.adopt(cell, at_ms);
292+ }
293+}
294+
295+/// Bring the bucket's wake entry for `cell` into line with its alarm.
296+///
297+/// Arming writes an entry; something has to take it away again once the alarm
298+/// has been consumed, or the entry outlives its alarm and every later due scan
299+/// finds it and wakes a cell with nothing to do. `consume_durable` gates that
300+/// final delete on the consuming commit being replicated -- removing the hint
301+/// while the commit that consumed the alarm is still only local would lose
302+/// both the alarm and the record that could have revived it.
303+pub async fn reconcile_wake_entry(cell: &str, next_alarm_ms: i64, consume_durable: bool) {
304+ let Some(gate) = ARM_GATE.get() else {
305+ return;
306+ };
307+ gate.flusher
308+ .reconcile(&gate.bucket, cell, next_alarm_ms, consume_durable)
309+ .await;
310+}
311+
312+type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>;
313+static PENDING_ARM_GATES: OnceLock<Mutex<HashMap<String, Vec<ArmGateRx>>>> = OnceLock::new();
314+fn pending_arm_gates() -> &'static Mutex<HashMap<String, Vec<ArmGateRx>>> {
315+ PENDING_ARM_GATES.get_or_init(Default::default)
316+}
317+
318+/// A committed alarm tightened the durable wake bound: launch the entry PUT
319+/// and register it against the cell's output gate. No-op when the bound
320+/// already covers it or no gate is configured (unit tests).
321+fn spawn_arm_gate(cell: &str, at_ms: i64) {
322+ let Some(gate) = ARM_GATE.get() else { return };
323+ let Some(celld_logic::wake::Op::Put { key, due_ms }) = gate.flusher.arm_op(cell, at_ms) else {
324+ return;
325+ };
326+ let cell_ = cell.to_string();
327+ let (tx, rx) = tokio::sync::oneshot::channel();
328+ {
329+ let mut pending = pending_arm_gates().lock().unwrap();
330+ let gates = pending.entry(cell_.clone()).or_default();
331+ // Arms with no response edge to drain them (alarm handlers,
332+ // WebSocket events) must not accumulate: drop already-settled gates.
333+ gates.retain_mut(|gate| {
334+ matches!(
335+ gate.try_recv(),
336+ Err(tokio::sync::oneshot::error::TryRecvError::Empty)
337+ )
338+ });
339+ gates.push(rx);
340+ }
341+ asyncrt::op_handle().spawn(async move {
342+ let gate = ARM_GATE.get().unwrap();
343+ // The core may have demanded this PUT because the tracked entry's
344+ // consume-delete is already on the wire; the PUT must land after
345+ // that delete, not race it (S3 orders concurrent same-key writes
346+ // arbitrarily).
347+ gate.flusher.await_no_inflight_delete(&cell_).await;
348+ let body = format!("{{\"cell\":{cell_:?},\"due_ms\":{due_ms}}}");
349+ let result = gate
350+ .bucket
351+ .put(&key, body.into_bytes())
352+ .await
353+ .map(|_| gate.flusher.confirm_arm(&cell_, due_ms, key))
354+ .map_err(|e| format!("setAlarm wake entry: {e}"));
355+ let _ = tx.send(result);
356+ });
357+}
358+
359+/// Await the cell's pending wake-entry PUTs — the output-gate drain a
360+/// response edge performs before releasing its reply. An error means an arm
361+/// the response would acknowledge is not durably covered; the caller must
362+/// fail the response rather than lie (the flusher retries the entry).
363+pub async fn drain_arm_gates(cell: &str) -> Result<(), String> {
364+ let gates = pending_arm_gates().lock().unwrap().remove(cell);
365+ let Some(gates) = gates else { return Ok(()) };
366+ for gate in gates {
367+ match gate.await {
368+ Ok(Ok(())) => {}
369+ Ok(Err(error)) => return Err(error),
370+ Err(_) => return Err("wake-entry gate task dropped".into()),
371+ }
372+ }
373+ Ok(())
374+}
375+
376+pub type RequestId = u128;
377+
378+#[derive(Clone, Copy)]
379+pub struct FetchRequest<'a> {
380+ pub url: &'a str,
381+ pub method: &'a str,
382+ pub body: &'a [u8],
383+ pub headers: &'a [(String, String)],
384+ pub request_id: Option<RequestId>,
385+}
386+
387+/// Allocate an id for an ingress or service-binding request so it can be
388+/// aborted mid-flight.
389+pub fn next_request_id() -> RequestId {
390+ next_do_request_id()
391+}
392+
393+static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
394+static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new();
395+static DO_CALL_CANCELS: OnceLock<
396+ std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>>,
397+> = OnceLock::new();
398+fn do_call_cancels(
399+) -> &'static std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>> {
400+ DO_CALL_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
401+}
402+
403+fn next_do_request_id() -> RequestId {
404+ let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| {
405+ let mut bytes = [0; 8];
406+ getrandom::fill(&mut bytes).expect("OS random source unavailable");
407+ u64::from_ne_bytes(bytes)
408+ });
409+ let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
410+ (u128::from(prefix) << 64) | u128::from(sequence)
411+}
412+
413+pub fn request_id_string(request_id: RequestId) -> String {
414+ format!("{request_id:032x}")
415+}
416+
417+pub fn parse_request_id(value: &str) -> Option<RequestId> {
418+ u128::from_str_radix(value, 16).ok()
419+}
420+
421+struct DoCallCancelGuard(Option<RequestId>);
422+
423+impl DoCallCancelGuard {
424+ fn new(request: RequestId) -> Self {
425+ Self(Some(request))
426+ }
427+
428+ fn disarm(&mut self) {
429+ if let Some(request) = self.0.take() {
430+ do_call_cancels().lock().unwrap().remove(&request);
431+ }
432+ }
433+}
434+
435+impl Drop for DoCallCancelGuard {
436+ fn drop(&mut self) {
437+ let Some(request) = self.0.take() else {
438+ return;
439+ };
440+ if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request) {
441+ let _ = cancel.send(());
442+ }
443+ }
444+}
445+
446+/// An RPC payload crossing the host boundary. JS stubs marshal by V8
447+/// structured clone (`V8`); the legacy cross-node JSON envelope and the test
448+/// harness use `Json`. `__dispatchRpc` answers in the flavor it was asked in.
449+pub enum RpcData {
450+ Json(String),
451+ V8(Vec<u8>),
452+}
453+
454+/// A native Durable Object RPC call (`stub.someMethod(...args)`).
455+/// Routing/activation is identical to fetch calls.
456+pub struct RpcCallReq {
457+ pub scope: String,
458+ pub name: Option<String>,
459+ pub method: String,
460+ pub args: RpcData,
461+ pub reply: tokio::sync::oneshot::Sender<Result<RpcData>>,
462+}
463+static RPC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<RpcCallReq>> = OnceLock::new();
464+pub fn set_rpc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<RpcCallReq>) {
465+ let _ = RPC_CALL_TX.set(tx);
466+}
467+
468+pub struct OutboundWsReq {
469+ pub scope: String,
470+ pub id: u64,
471+ pub url: String,
472+ pub protocols: Vec<String>,
473+ /// Present for an isolate-polled (Worker) socket. Created and registered
474+ /// on the JS thread before the request is sent, so `__ws_next` can never
475+ /// run ahead of its own queue.
476+ pub pull: Option<WsPullSender>,
477+ /// Extra request headers, for the `fetch()` upgrade form.
478+ pub headers: Vec<(String, String)>,
479+ /// A `fetch()` upgrade wants the whole handshake outcome, including the
480+ /// ordinary response a server that declines to upgrade sent instead.
481+ pub want_response: bool,
482+ pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>,
483+}
484+
485+/// The ordinary HTTP response a server sent instead of upgrading. `fetch()`
486+/// returns it verbatim rather than turning it into a connection error.
487+pub struct DeclinedUpgrade {
488+ pub status: u16,
489+ pub headers: Vec<(String, String)>,
490+ pub body: Vec<u8>,
491+}
492+
493+/// What an outbound handshake produced.
494+pub struct OutboundWsOpen {
495+ pub protocol: Option<String>,
496+ pub declined: Option<DeclinedUpgrade>,
497+}
498+static OUTBOUND_WS_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> =
499+ OnceLock::new();
500+pub fn set_outbound_ws_tx(tx: tokio::sync::mpsc::UnboundedSender<OutboundWsReq>) {
501+ let _ = OUTBOUND_WS_TX.set(tx);
502+}
503+
504+static NEXT_TIMER_ID: AtomicU64 = AtomicU64::new(1);
505+static TIMER_CANCELS: OnceLock<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>> =
506+ OnceLock::new();
507+fn timer_cancels() -> &'static std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>> {
508+ TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
509+}
510+static NEXT_HTTP_STREAM_ID: AtomicU64 = AtomicU64::new(1);
511+enum HttpStreamSource {
512+ Response(reqwest::Response),
513+ Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>),
514+ Stream(HttpChunkStream),
515+}
516+struct HttpStreamEntry {
517+ created: Instant,
518+ source: Option<HttpStreamSource>,
519+ cancelled: tokio::sync::watch::Sender<bool>,
520+}
521+static HTTP_STREAMS: OnceLock<std::sync::Mutex<HashMap<u64, HttpStreamEntry>>> = OnceLock::new();
522+fn http_streams() -> &'static std::sync::Mutex<HashMap<u64, HttpStreamEntry>> {
523+ HTTP_STREAMS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
524+}
525+fn register_http_stream(stream_id: u64, source: HttpStreamSource) {
526+ let (cancelled, _) = tokio::sync::watch::channel(false);
527+ let mut streams = http_streams().lock().unwrap();
528+ streams.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60));
529+ streams.insert(
530+ stream_id,
531+ HttpStreamEntry {
532+ created: Instant::now(),
533+ source: Some(source),
534+ cancelled,
535+ },
536+ );
537+}
538+struct ResponseStreamWriter {
539+ created: Instant,
540+ writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>,
541+ finished: tokio::sync::watch::Sender<bool>,
542+}
543+static RESPONSE_STREAM_WRITERS: OnceLock<std::sync::Mutex<HashMap<u64, ResponseStreamWriter>>> =
544+ OnceLock::new();
545+fn response_stream_writers() -> &'static std::sync::Mutex<HashMap<u64, ResponseStreamWriter>> {
546+ RESPONSE_STREAM_WRITERS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
547+}
548+
549+pub type HttpChunkStream =
550+ Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>;
551+
552+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
553+pub struct WsTarget {
554+ pub id: u64,
555+ pub scope: String,
556+ #[serde(default, skip_serializing_if = "Option::is_none")]
557+ pub peer_node: Option<String>,
558+ #[serde(default, skip_serializing_if = "Option::is_none")]
559+ pub peer_addr: Option<String>,
560+ #[serde(default, skip_serializing_if = "Option::is_none")]
561+ pub peer_epoch: Option<u64>,
562+}
563+
564+/// Encode a host response for the JS side. A text body crosses as a
565+/// JS string (cheap, lossless), binary as a byte array, and a streaming body
566+/// by id — serializing a Vec<u8> as a JSON number array is the dominant cost
567+/// for real DO responses. `ws_target` is carried only by the DO path.
568+fn encode_http_response(mut response: HttpResponse, ws_target: bool) -> String {
569+ let mut obj = serde_json::json!({
570+ "status": response.status,
571+ "headers": response.headers,
572+ });
573+ if ws_target {
574+ obj["wsTarget"] = serde_json::json!(response.ws);
575+ }
576+ if let Some(stream) = response.stream.take() {
577+ let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
578+ register_http_stream(stream_id, HttpStreamSource::Stream(stream));
579+ obj["streamId"] = serde_json::json!(stream_id);
580+ } else {
581+ match std::str::from_utf8(&response.body) {
582+ Ok(text) => obj["body"] = serde_json::Value::String(text.into()),
583+ Err(_) => obj["bodyBytes"] = serde_json::json!(response.body),
584+ }
585+ }
586+ obj.to_string()
587+}
588+
589+pub struct HttpResponse {
590+ pub status: u16,
591+ pub body: Vec<u8>,
592+ /// A response body forwarded without materializing it in memory.
593+ pub stream: Option<HttpChunkStream>,
594+ pub headers: Vec<(String, String)>,
595+ pub ws: Option<WsTarget>,
596+ /// The cell's committed-write position after the handler ran, for a local
597+ /// Durable Object request. The shell gates the response on durability when
598+ /// this advanced past the cell's last seen position. `None` for responses
599+ /// with no cell storage (Worker, asset, or proxied remote).
600+ pub write_position: Option<u64>,
601+}
602+
603+/// Which alarm a dispatch runs, and who owns its bookkeeping.
604+pub enum AlarmDispatch {
605+ /// Claim whatever is due now, and record the outcome. Production only
606+ /// ever asks for this.
607+ Due,
608+ /// Claim whatever is armed, however far ahead its deadline. Test-only:
609+ /// the corpus asserts on retry accounting without waiting out real
610+ /// deadlines.
611+ Armed,
612+ /// The caller has already claimed it. Dispatch with this retry count and
613+ /// leave the bookkeeping to them. Test-only, so the corpus can assert on
614+ /// the claim and the handler separately.
615+ Claimed(i64),
616+}
617+
618+/// One event a cell receives.
619+///
620+/// Every variant is something the outside world did to the cell, and each
621+/// becomes an `InFlight` entry driven by its own tokio task. Lifecycle —
622+/// taking a cell in, giving it back, cancelling a request — is not here: it
623+/// is a direct call on the isolate, because it is not an event and has no
624+/// handler to run.
625+pub enum CellJob {
626+ Fetch {
627+ request_id: Option<RequestId>,
628+ scope: String,
629+ name: Option<String>,
630+ url: String,
631+ method: String,
632+ body: Vec<u8>,
633+ headers: Vec<(String, String)>,
634+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
635+ /// Where this call sits in its caller's order for this cell, if it
636+ /// came from a script rather than from a peer or the ingress.
637+ order: Option<CallOrder>,
638+ },
639+ Rpc {
640+ scope: String,
641+ name: Option<String>,
642+ method: String,
643+ args: RpcData,
644+ reply: tokio::sync::oneshot::Sender<Result<RpcOutcome>>,
645+ },
646+ WsOpen {
647+ scope: String,
648+ ws_id: u64,
649+ protocol: String,
650+ reply: tokio::sync::oneshot::Sender<Result<()>>,
651+ },
652+ WsMessage {
653+ scope: String,
654+ ws_id: u64,
655+ data: WsIn,
656+ reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>,
657+ },
658+ WsClosed {
659+ scope: String,
660+ ws_id: u64,
661+ code: u16,
662+ reason: String,
663+ was_clean: bool,
664+ reply: tokio::sync::oneshot::Sender<Result<()>>,
665+ },
666+ Alarm {
667+ scope: String,
668+ scheduled_ms: i64,
669+ /// Which alarm to run, and who owns the bookkeeping.
670+ claim: AlarmDispatch,
671+ /// Replies with (next alarm, the handler's write delta). The delta is
672+ /// sampled inside the turn — cell storage must never be reached from
673+ /// the shell — and the shell uses it to prove the consuming commit
674+ /// durable before the core settles. Every answer shape samples it the
675+ /// same way now, in `InFlight::answer_settled`.
676+ reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>,
677+ },
678+}
679+
680+impl CellJob {
681+ /// The cell this event addresses, which is also the realm it runs in.
682+ pub fn scope(&self) -> &str {
683+ match self {
684+ CellJob::Fetch { scope, .. }
685+ | CellJob::Rpc { scope, .. }
686+ | CellJob::WsOpen { scope, .. }
687+ | CellJob::WsMessage { scope, .. }
688+ | CellJob::WsClosed { scope, .. }
689+ | CellJob::Alarm { scope, .. } => scope,
690+ }
691+ }
692+
693+ /// This event's place in its caller's order, taken out so the drive can
694+ /// wait on it and then release the call behind it.
695+ pub fn take_order(&mut self) -> Option<CallOrder> {
696+ match self {
697+ CellJob::Fetch { order, .. } => order.take(),
698+ _ => None,
699+ }
700+ }
701+
702+ /// Fail this event without running it.
703+ pub fn fail(self, error: anyhow::Error) {
704+ match self {
705+ CellJob::Fetch { reply, .. } => drop(reply.send(Err(error))),
706+ CellJob::Rpc { reply, .. } => drop(reply.send(Err(error))),
707+ CellJob::WsOpen { reply, .. } => drop(reply.send(Err(error))),
708+ CellJob::WsMessage { reply, .. } => drop(reply.send(Err(error))),
709+ CellJob::WsClosed { reply, .. } => drop(reply.send(Err(error))),
710+ CellJob::Alarm { reply, .. } => drop(reply.send(Err(error))),
711+ }
712+ }
713+}
714+
715+thread_local! {
716+ // One outbound HTTP client per JS thread — building it per fetch rebuilds
717+ // the TLS stack every call (async-op-hazards.md).
718+ static HTTP: reqwest::Client = reqwest::Client::new();
719+ static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder()
720+ .redirect(reqwest::redirect::Policy::none()).build().unwrap();
721+ static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new());
722+}
723+
724+mod websocket;
725+pub use websocket::*;
726+use websocket::{ws_capture_begin, ws_capture_take};
727+
728+/// Held for the duration of one cell event; pops on every exit path.
729+pub struct EgressGateScope;
730+
731+impl Drop for EgressGateScope {
732+ fn drop(&mut self) {
733+ current_context().egress.lock().unwrap().pop();
734+ }
735+}
736+
737+pub fn egress_gate_enter(cell: &str, position: Option<u64>) -> EgressGateScope {
738+ current_context()
739+ .egress
740+ .lock()
741+ .unwrap()
742+ .push((cell.to_string(), position.unwrap_or(0)));
743+ EgressGateScope
744+}
745+
746+/// What an outbound effect must wait for, if the running handler has written
747+/// anything this event. `None` means there is nothing outstanding and the
748+/// effect may go straight out -- the ordinary read-only case, which must not
749+/// pay a durability round trip.
750+fn egress_gate_pending() -> Option<(String, u64)> {
751+ let context = current_context();
752+ let stack = context.egress.lock().unwrap();
753+ let (cell, before) = stack.last()?;
754+ let position = storage::write_position(cell)?;
755+ (position > *before).then(|| (cell.clone(), position))
756+}
757+
758+/// Wait for the cell's outstanding write to be proven durable before an
759+/// outbound effect leaves the process.
760+///
761+/// This is the output gate applied to egress rather than to the response.
762+/// It cannot deadlock the handler that is awaiting it: the ticket is served by
763+/// `dispatch_gate` on the host's own loop and resolved by the replicator's
764+/// independent task, neither of which needs the isolate's event loop to run.
765+async fn await_egress_gate(pending: Option<(String, u64)>) -> std::result::Result<(), String> {
766+ let Some((cell, position)) = pending else {
767+ return Ok(());
768+ };
769+ let (tx, receive) = tokio::sync::oneshot::channel();
770+ let sent = GATE_TX
771+ .get()
772+ .map(|gate| {
773+ gate.send(GateReq {
774+ scope: cell,
775+ position,
776+ reply: tx,
777+ })
778+ .is_ok()
779+ })
780+ .unwrap_or(false);
781+ if !sent {
782+ return Err("no output-gate channel".into());
783+ }
784+ match receive.await {
785+ Ok(Ok(())) => Ok(()),
786+ Ok(Err(error)) => Err(format!(
787+ "refusing to send: the write this request follows is not durable ({error:?})"
788+ )),
789+ Err(_) => Err("output gate dropped".into()),
790+ }
791+}
792+
793+/// Hold an outbound request until the write it follows is durable, then hand
794+/// it to the host.
795+///
796+/// The send moves inside the future deliberately. These channels dispatch as
797+/// soon as `send` is called, so gating anywhere after it would let the effect
798+/// leave first -- the request would already be on its way while the caller
799+/// waited for a durability answer that no longer decides anything.
800+async fn gated_channel_send<T>(
801+ gate: Option<(String, u64)>,
802+ channel: &'static OnceLock<tokio::sync::mpsc::UnboundedSender<T>>,
803+ request: T,
804+ missing: &'static str,
805+) -> std::result::Result<(), String> {
806+ await_egress_gate(gate).await?;
807+ match channel.get() {
808+ Some(tx) if tx.send(request).is_ok() => Ok(()),
809+ _ => Err(missing.to_string()),
810+ }
811+}
812+
813+/// One `celld_logic::gate::InputGate` per cell.
814+///
815+/// The logic decides; this is only the map and the ids. It replaces the
816+/// promise chain that used to live in `harness.js`, which serialised blocks
817+/// against each other but did nothing about *delivery* — so a second event
818+/// could arrive mid-block, and under real concurrency that wedged the cell.
819+///
820+/// Keyed by cell scope rather than held on the isolate, because a gate
821+/// belongs to a cell and cells share isolates.
822+static CELL_GATES: OnceLock<Mutex<HashMap<String, celld_logic::gate::InputGate>>> = OnceLock::new();
823+static NEXT_GATE_EVENT: AtomicU64 = AtomicU64::new(1);
824+
825+fn cell_gates() -> &'static Mutex<HashMap<String, celld_logic::gate::InputGate>> {
826+ CELL_GATES.get_or_init(|| Mutex::new(HashMap::new()))
827+}
828+
829+/// What a waiting event is told when the gate finally opens: nothing, or
830+/// the reason the holder failed.
831+type GateWake = tokio::sync::oneshot::Sender<Result<(), String>>;
832+
833+static GATE_WAITERS: OnceLock<Mutex<HashMap<String, Vec<GateWake>>>> = OnceLock::new();
834+
835+/// Events waiting for a cell's input gate to open, in arrival order.
836+///
837+/// Step 6 deleted this queue, correctly at the time: an event the gate
838+/// refused stayed on the cell's job channel until a later delivery point
839+/// took it, so the channel *was* the queue and a second one could disagree
840+/// with it. Drives have no channel, so a refused event needs somewhere to
841+/// wait, and workerd keeps the same structure for the same reason
842+/// (`io-gate.h`, `kj::List<Waiter, &Waiter::link> waiters`).
843+///
844+/// In the shell rather than in `celld_logic::gate`, because what waits is a
845+/// tokio task and the core is sans-IO. The core still owns the decision —
846+/// `is_open` — and this owns only the waking.
847+fn gate_waiters() -> &'static Mutex<HashMap<String, Vec<GateWake>>> {
848+ GATE_WAITERS.get_or_init(|| Mutex::new(HashMap::new()))
849+}
850+
851+/// Take a ticket to be woken when `cell`'s gate opens, or `None` if it is
852+/// open now.
853+///
854+/// The gate's lock is held across the check and the enqueue, so a release
855+/// that lands between the two cannot leave an event waiting on a gate that
856+/// is already open.
857+pub fn cell_gate_wait(cell: &str) -> Option<tokio::sync::oneshot::Receiver<Result<(), String>>> {
858+ let gates = cell_gates().lock().unwrap();
859+ if gates.get(cell).is_none_or(|gate| gate.is_open()) {
860+ return None;
861+ }
862+ let (wake, waiter) = tokio::sync::oneshot::channel();
863+ gate_waiters()
864+ .lock()
865+ .unwrap()
866+ .entry(cell.to_string())
867+ .or_default()
868+ .push(wake);
869+ drop(gates);
870+ Some(waiter)
871+}
872+
873+/// Wake everything waiting on `cell`'s gate. Each re-checks and re-queues if
874+/// another block took the gate first, so waking all of them is correct and
875+/// the order they resume in is theirs to lose, not this function's to keep.
876+fn wake_gate_waiters(cell: &str, outcome: Result<(), String>) {
877+ let waiters = gate_waiters().lock().unwrap().remove(cell);
878+ for wake in waiters.into_iter().flatten() {
879+ let _ = wake.send(outcome.clone());
880+ }
881+}
882+
883+/// The event holding this cell's gate died without releasing it.
884+///
885+/// Only execution termination reaches here: every other exit from a block
886+/// runs the `finally` in `harness.js`. Without it a cell whose blocking
887+/// request was killed would refuse every later event forever.
888+fn cell_gate_abandon(scope: &str) {
889+ if let Some(gate) = cell_gates().lock().unwrap().get_mut(scope) {
890+ gate.abandon();
891+ }
892+ // The holder died without running its `finally`, so nobody can say why.
893+ // Refuse the waiters anyway: the cell it queued behind is gone.
894+ wake_gate_waiters(
895+ scope,
896+ Err("the cell's critical section ended without releasing".to_string()),
897+ );
898+}
899+
900+/// JS promise resolvers awaiting an async op, keyed by the op's id.
901+///
902+/// **Per isolate, and shared across threads.** Under D1 a request's turns run
903+/// on whichever tokio worker picks them up, so a resolver registered on one
904+/// thread is resolved from another; a thread-local map loses it, and
905+/// `resolve_res` fails to find the resolver and returns silently, leaving the
906+/// handler awaiting a promise nothing will ever settle. The `Mutex` is what
907+/// makes that safe, not the map's location.
908+///
909+/// It lives on `ActorRuntimeState` — one per isolate, reached from a scope —
910+/// so a resolver is only ever looked up in the heap that owns it. One map for
911+/// the whole process would also work, because op ids come from a single
912+/// counter (`asyncrt::NEXT_ID`) and an id names exactly one resolver. But that
913+/// makes an id-allocation bug into cross-isolate handle confusion, where this
914+/// makes it a miss.
915+type PromiseMap = HashMap<u64, v8::Global<v8::PromiseResolver>>;
916+
917+/// Requests cancelled by a reentrant `AbortFetch`. Global for the same reason
918+/// as [`promises`]: the turn that observes a cancellation need not be on the
919+/// thread that recorded it.
920+static CANCELLED_REQUESTS: OnceLock<Mutex<HashSet<RequestId>>> = OnceLock::new();
921+
922+fn cancelled_requests() -> &'static Mutex<HashSet<RequestId>> {
923+ CANCELLED_REQUESTS.get_or_init(|| Mutex::new(HashSet::new()))
924+}
925+
926+fn promise_store(scope: &mut v8::PinScope, id: u64, r: v8::Global<v8::PromiseResolver>) {
927+ actor_runtime_state(scope)
928+ .promises
929+ .lock()
930+ .unwrap()
931+ .insert(id, r);
932+}
933+
934+/// Resolve or reject op `id`'s promise with its outcome.
935+fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) {
936+ let g = match actor_runtime_state(tc).promises.lock().unwrap().remove(&id) {
937+ Some(g) => g,
938+ None => return,
939+ };
940+ let r = v8::Local::new(tc, g);
941+ match res {
942+ Ok(asyncrt::OpOut::Str(v)) => {
943+ let s = v8::String::new(tc, &v).unwrap();
944+ r.resolve(tc, s.into());
945+ }
946+ Ok(asyncrt::OpOut::Bytes(b)) => {
947+ let v = bytes_value(tc, b);
948+ r.resolve(tc, v);
949+ }
950+ Err(e) => {
951+ let s = v8::String::new(tc, &e).unwrap();
952+ let ex = v8::Exception::error(tc, s);
953+ r.reject(tc, ex);
954+ }
955+ }
956+}
957+
958+/// Move `bytes` into a `Uint8Array` without copying.
959+fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> {
960+ let len = bytes.len();
961+ let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();
962+ let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);
963+ v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into()
964+}
965+
966+pub fn handler_budget() -> Duration {
967+ static BUDGET: OnceLock<Duration> = OnceLock::new();
968+ *BUDGET.get_or_init(|| {
969+ Duration::from_secs(
970+ crate::env_vars::positive_or("CELLD_HANDLER_BUDGET_S", 300)
971+ .expect("validated CELLD_HANDLER_BUDGET_S"),
972+ )
973+ })
974+}
975+
976+/// Aborts raised by an HTTP or service-binding caller disconnecting while the
977+/// target runs in the stateless isolate pool. Durable Object aborts can also
978+/// arrive as a reentrant `CellJob::AbortFetch`, so the abort has to be visible
979+/// from whichever turn observes it.
980+///
981+/// The counter keeps the common path to one relaxed atomic load per loop turn:
982+/// with nothing pending, the mutex is never taken.
983+static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> =
984+ OnceLock::new();
985+static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
986+
987+fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> {
988+ PENDING_ABORTS.get_or_init(Default::default)
989+}
990+
991+/// Mark an in-flight request cancelled from any thread.
992+pub fn abort_request(request_id: RequestId) {
993+ if pending_aborts().lock().unwrap().insert(request_id) {
994+ PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed);
995+ }
996+}
997+
998+fn clear_request_cancellation(request_id: RequestId) {
999+ let _ = take_pending_abort(request_id);
1000+}
1001+
1002+fn take_pending_abort(request_id: RequestId) -> bool {
1003+ if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 {
1004+ return false;
1005+ }
1006+ if pending_aborts().lock().unwrap().remove(&request_id) {
1007+ PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed);
1008+ return true;
1009+ }
1010+ false
1011+}
1012+
1013+pub fn take_request_cancellation(request_id: Option<RequestId>) -> bool {
1014+ request_id.is_some_and(|request_id| {
1015+ cancelled_requests().lock().unwrap().remove(&request_id) || take_pending_abort(request_id)
1016+ })
1017+}
1018+
1019+fn resolved_promise<'s>(
1020+ tc: &mut v8::PinScope<'s, '_>,
1021+ value: v8::Local<'s, v8::Value>,
1022+) -> Result<v8::Local<'s, v8::Promise>> {
1023+ let resolver =
1024+ v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?;
1025+ resolver.resolve(tc, value);
1026+ Ok(resolver.get_promise(tc))
1027+}
1028+
1029+fn abort_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) -> Result<bool> {
1030+ let global = tc.get_current_context().global(tc);
1031+ let key = v8::String::new(tc, "__abortIncomingRequest").unwrap();
1032+ let function: v8::Local<v8::Function> = global
1033+ .get(tc, key.into())
1034+ .ok_or_else(|| anyhow!("no __abortIncomingRequest"))?
1035+ .try_into()
1036+ .map_err(|_| anyhow!("__abortIncomingRequest is not a function"))?;
1037+ let request_id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
1038+ let recv = v8::undefined(tc).into();
1039+ let result = function
1040+ .call(tc, recv, &[request_id.into()])
1041+ .ok_or_else(|| anyhow!("__abortIncomingRequest threw"))?;
1042+ Ok(result.boolean_value(tc))
1043+}
1044+
1045+/// The rejection reason of a settled-rejected promise, with a little stack.
1046+fn reject_reason(tc: &mut v8::PinScope, p: v8::Local<v8::Promise>) -> String {
1047+ let r = p.result(tc);
1048+ let msg = r.to_rust_string_lossy(tc);
1049+ let stk = r
1050+ .to_object(tc)
1051+ .and_then(|o| {
1052+ let k = v8::String::new(tc, "stack")?;
1053+ o.get(tc, k.into())
1054+ })
1055+ .map(|s| s.to_rust_string_lossy(tc))
1056+ .unwrap_or_default();
1057+ let tail = stk
1058+ .lines()
1059+ .skip(1)
1060+ .take(3)
1061+ .map(|l| l.trim())
1062+ .collect::<Vec<_>>()
1063+ .join(" <- ");
1064+ if tail.is_empty() {
1065+ msg
1066+ } else {
1067+ format!("{msg} [{tail}]")
1068+ }
1069+}
1070+
1071+pub struct Engine;
1072+impl Engine {
1073+ pub fn init() {
1074+ // No `v8::icu::set_common_data_78` call: the rusty_v8 152 prebuilt
1075+ // statically links the complete ICU data (full locale tables and
1076+ // regex property-of-strings, e.g. /\p{RGI_Emoji}/v — verified
1077+ // empirically), so overriding it with an embedded icudtl.dat only
1078+ // duplicated 10.8 MB in the binary. A test pins that coverage, so a
1079+ // future v8 bump that reduces the builtin data fails rather than
1080+ // silently narrowing it; the fix would be to re-embed rusty_v8's
1081+ // `third_party/icu/common/icudtl.dat`, 16-byte-aligned.
1082+ let platform = v8::new_default_platform(0, false).make_shared();
1083+ v8::V8::initialize_platform(platform);
1084+ v8::V8::initialize();
1085+ }
1086+}
1087+
1088+/// Per-worker compatibility switches, derived from the manifest's
1089+/// compatibility date and flags (Workerd compatibility-date.capnp). `Default`
1090+/// is every switch off; production derives real values in `main`.
1091+#[derive(Clone, Copy, Default)]
1092+pub struct Compat {
1093+ pub delete_all_deletes_alarm: bool,
1094+ /// `js_rpc`: RPC on a Durable Object class that does not extend
1095+ /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()).
1096+ pub js_rpc: bool,
1097+ /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`,
1098+ /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/
1099+ /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher).
1100+ pub fetcher_get_put_delete: bool,
1101+ /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and
1102+ /// a binary message arrives as a `Blob`, per the WHATWG default. Without
1103+ /// it celld keeps the historical `"arraybuffer"`.
1104+ pub websocket_standard_binary_type: bool,
1105+}
1106+
1107+/// A non-main module the worker's main module may import, tagged by how the
1108+/// runtime materializes it.
1109+pub enum ModuleSource {
1110+ /// UTF-8 content served as `export default "<content>"` (wrangler's Text
1111+ /// rule), registered under the given specifier verbatim.
1112+ Text(String),
1113+ /// JS source compiled as a sibling ES module (Worker Loader multi-module
1114+ /// bundles), registered under both `name` and `./name`.
1115+ EsModule(String),
1116+ /// Wasm bytes served as a module whose default export is the compiled
1117+ /// `WebAssembly.Module` (Wrangler's `CompiledWasm` rule), registered
1118+ /// under both `name` and `./name`.
1119+ Wasm(bytes::Bytes),
1120+}
1121+
1122+pub struct WorkerConfig {
1123+ src: String,
1124+ pub script_name: String,
1125+ do_classes: Vec<String>,
1126+ bindings: Vec<(String, String)>,
1127+ r2_bindings: Vec<String>,
1128+ ai_binding: Option<String>,
1129+ vars: Vec<(String, String)>,
1130+ node: String,
1131+ /// The worker's non-main modules, so the main module can import siblings.
1132+ modules: Vec<(String, ModuleSource)>,
1133+ compat: Compat,
1134+ /// `[[services]]`: (binding name, target script, optional entrypoint).
1135+ /// The target runs in this process; see [[service-bindings]].
1136+ services: Vec<(String, String, Option<String>)>,
1137+ asset_binding: Option<String>,
1138+ /// `env` name of the Worker Loader binding, if this Worker may spawn
1139+ /// dynamic isolates.
1140+ loader_binding: Option<String>,
1141+ /// Ambient outbound authority. Loaded workers may be denied.
1142+ egress: EgressPolicy,
1143+ /// Extra `env` values a loaded worker was handed, as a JSON object string
1144+ /// merged onto its `env`. Loader-only; empty for normal workers.
1145+ loader_env: Option<String>,
1146+}
1147+
1148+pub struct WorkerConfigOptions {
1149+ pub src: String,
1150+ pub script_name: String,
1151+ pub do_classes: Vec<String>,
1152+ pub bindings: Vec<(String, String)>,
1153+ pub r2_bindings: Vec<String>,
1154+ pub ai_binding: Option<String>,
1155+ pub vars: Vec<(String, String)>,
1156+ pub node: String,
1157+ pub modules: Vec<(String, ModuleSource)>,
1158+ pub compat: Compat,
1159+}
1160+
1161+impl WorkerConfig {
1162+ pub fn new(options: WorkerConfigOptions) -> Self {
1163+ let WorkerConfigOptions {
1164+ src,
1165+ script_name,
1166+ do_classes,
1167+ bindings,
1168+ r2_bindings,
1169+ ai_binding,
1170+ vars,
1171+ node,
1172+ modules,
1173+ compat,
1174+ } = options;
1175+ Self {
1176+ src,
1177+ script_name,
1178+ do_classes,
1179+ bindings,
1180+ r2_bindings,
1181+ ai_binding,
1182+ vars,
1183+ node,
1184+ modules,
1185+ compat,
1186+ services: Vec::new(),
1187+ asset_binding: None,
1188+ loader_binding: None,
1189+ egress: EgressPolicy::Allow,
1190+ loader_env: None,
1191+ }
1192+ }
1193+
1194+ /// Grant this Worker a Worker Loader binding at `env` name `binding`.
1195+ pub fn with_loader(mut self, binding: Option<String>) -> Self {
1196+ self.loader_binding = binding;
1197+ self
1198+ }
1199+
1200+ /// Set this Worker's ambient outbound authority (loaded workers only).
1201+ fn with_egress(mut self, egress: EgressPolicy) -> Self {
1202+ self.egress = egress;
1203+ self
1204+ }
1205+
1206+ /// Merge `env` (a JSON object string) onto a loaded worker's `env`.
1207+ fn with_loader_env(mut self, env: Option<String>) -> Self {
1208+ self.loader_env = env;
1209+ self
1210+ }
1211+
1212+ /// Declare the service bindings this Worker may call.
1213+ pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self {
1214+ self.services = services;
1215+ self
1216+ }
1217+
1218+ pub fn with_asset_binding(mut self, binding: Option<String>) -> Self {
1219+ self.asset_binding = binding;
1220+ self
1221+ }
1222+}
1223+
1224+pub struct Worker {
1225+ inner: Option<WorkerIsolate>,
1226+}
1227+
1228+pub struct WorkerIsolate {
1229+ /// Shared rather than owned: under D1 an isolate belongs to no thread,
1230+ /// and a worker enters it by taking its `v8::Locker`
1231+ /// (wiki/designs/isolate-threading.md).
1232+ ///
1233+ /// Every `lock()` below blocks until the current holder releases. That is
1234+ /// only safe because the pool takes an async permit for this isolate
1235+ /// first, so the lock is uncontended by construction; a `lock()` reached
1236+ /// without that permit would be a blocking call on a tokio worker.
1237+ isolate: v8::SharedIsolate,
1238+ /// The one realm this isolate has: its context, and the entry `fetch`
1239+ /// that lives in it.
1240+ ///
1241+ /// It was a `HashMap` keyed by cell, on the premise that a cell needs a
1242+ /// realm of its own. It does not, and nothing ever put a second one in.
1243+ /// The harness already keys instances by scope (`__cell.instances`), and
1244+ /// Durable Objects **share** a context per script rather than getting one
1245+ /// each — a context per cell would also duplicate the compiled module per
1246+ /// cell, which is most of what sharing an isolate saves.
1247+ realm: Realm,
1248+ original_heap_limit: usize,
1249+ /// The storage of the cells this isolate hosts.
1250+ ///
1251+ /// It lives here, and not in a thread-local, because a driven cell's
1252+ /// turns run on whatever tokio worker holds the isolate. See
1253+ /// `storage::Cells`.
1254+ cells: storage::Cells,
1255+}
1256+
1257+/// An isolate's context and the entry `fetch` that lives in it.
1258+///
1259+/// `fetch` is here rather than beside the isolate because a function is a
1260+/// value in the realm that created it.
1261+struct Realm {
1262+ context: v8::Global<v8::Context>,
1263+ fetch: v8::Global<v8::Function>,
1264+}
1265+
1266+impl WorkerIsolate {
1267+ /// Take the isolate for one turn, and make the cells it hosts reachable
1268+ /// while it is held.
1269+ ///
1270+ /// The two belong together. The lock is what makes this thread the only
1271+ /// one that can touch the isolate, and a cell's SQLite handles are part
1272+ /// of what it may touch — so a locker taken without installing them
1273+ /// would let a turn reach no storage at all, or another isolate's.
1274+ /// Pairing them here is why no call site has to remember.
1275+ fn lock(&self) -> (v8::Locker<'_>, storage::Installed) {
1276+ (self.isolate.lock(), self.cells.install())
1277+ }
1278+
1279+ /// Localise the realm for one turn.
1280+ ///
1281+ /// **Taking the scope is the point.** Reaching a realm means touching
1282+ /// `Global` handles, which on a shared isolate is only legal while its
1283+ /// `Locker` is held — and there is no scope to pass until the isolate is
1284+ /// locked. So the requirement is structural rather than a comment asking
1285+ /// callers to remember it. It was a comment, and the one call site that
1286+ /// forgot cloned two `Global`s a line too early; the panic happened
1287+ /// inside a spawned request task, where tokio swallowed it and it
1288+ /// surfaced only as a poisoned mutex on every later request.
1289+ fn realm<'s>(&self, hs: &mut v8::PinScope<'s, '_, ()>) -> Entered<'s> {
1290+ Entered {
1291+ context: v8::Local::new(hs, &self.realm.context),
1292+ fetch: v8::Local::new(hs, &self.realm.fetch),
1293+ }
1294+ }
1295+}
1296+
1297+/// One realm, entered. Valid only for the scope that produced it, which is
1298+/// what ties it to the isolate being locked.
1299+struct Entered<'s> {
1300+ context: v8::Local<'s, v8::Context>,
1301+ fetch: v8::Local<'s, v8::Function>,
1302+}
1303+
1304+impl std::ops::Deref for Worker {
1305+ type Target = WorkerIsolate;
1306+
1307+ fn deref(&self) -> &Self::Target {
1308+ self.inner.as_ref().expect("Worker isolate unavailable")
1309+ }
1310+}
1311+
1312+impl std::ops::DerefMut for Worker {
1313+ fn deref_mut(&mut self) -> &mut Self::Target {
1314+ self.inner.as_mut().expect("Worker isolate unavailable")
1315+ }
1316+}
1317+
1318+const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024;
1319+const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024;
1320+
1321+#[derive(Default)]
1322+struct HeapLimitState {
1323+ excessively_exceeded: AtomicBool,
1324+}
1325+
1326+type SerializedPut = (String, Vec<u8>);
1327+type PendingPuts = HashMap<String, Vec<SerializedPut>>;
1328+
1329+/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a
1330+/// Worker Loader can hand a loaded worker `Deny` (globalOutbound: null) so its
1331+/// global `fetch()` throws and it must reach the world through `env`
1332+/// capabilities.
1333+#[derive(Clone, Copy, Default, PartialEq)]
1334+enum EgressPolicy {
1335+ #[default]
1336+ Allow,
1337+ Deny,
1338+}
1339+
1340+#[derive(Default)]
1341+struct ActorRuntimeState {
1342+ promises: std::sync::Mutex<PromiseMap>,
1343+ termination: std::sync::Mutex<Option<ExecutionTermination>>,
1344+ pending_puts: std::sync::Mutex<PendingPuts>,
1345+ egress: EgressPolicy,
1346+}
1347+
1348+struct ExecutionTermination {
1349+ error: String,
1350+ actor_scope: Option<String>,
1351+}
1352+
1353+fn finish_terminated_actor_event(scope: &mut v8::PinScope, actor_scope: &str) {
1354+ // The one exit from a block that runs no JS, so the `finally` in
1355+ // harness.js never releases. Leave it and the cell refuses everything
1356+ // from here on.
1357+ cell_gate_abandon(actor_scope);
1358+ let global = scope.get_current_context().global(scope);
1359+ let key = v8::String::new(scope, "__endTerminatedActorEvent").unwrap();
1360+ let Some(value) = global.get(scope, key.into()) else {
1361+ return;
1362+ };
1363+ let Ok(function) = v8::Local::<v8::Function>::try_from(value) else {
1364+ return;
1365+ };
1366+ let actor_scope = v8::String::new(scope, actor_scope).unwrap();
1367+ let recv = v8::undefined(scope).into();
1368+ let _ = function.call(scope, recv, &[actor_scope.into()]);
1369+}
1370+
1371+/// Compile and run a JS expression that evaluates to a function.
1372+fn compile_fn<'s>(
1373+ scope: &mut v8::PinScope<'s, '_>,
1374+ src: &str,
1375+) -> Result<v8::Local<'s, v8::Function>> {
1376+ let code = v8::String::new(scope, src).unwrap();
1377+ let script =
1378+ v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compile shim: {src}"))?;
1379+ let value = script
1380+ .run(scope)
1381+ .ok_or_else(|| anyhow!("run shim: {src}"))?;
1382+ value
1383+ .try_into()
1384+ .map_err(|_| anyhow!("shim is not a function: {src}"))
1385+}
1386+
1387+/// Whether `register_entrypoints` put `name` in the `__cell.<registry>`
1388+/// object (e.g. `entrypoints`, `doExports`).
1389+fn cell_registry_has(scope: &mut v8::PinScope, registry: &str, name: &str) -> Result<bool> {
1390+ let context = scope.get_current_context();
1391+ let global = context.global(scope);
1392+ let cell_key = v8::String::new(scope, "__cell").unwrap();
1393+ let registry_key = v8::String::new(scope, registry).unwrap();
1394+ let registry_obj = global
1395+ .get(scope, cell_key.into())
1396+ .and_then(|value| value.to_object(scope))
1397+ .and_then(|cell| cell.get(scope, registry_key.into()))
1398+ .and_then(|value| value.to_object(scope))
1399+ .ok_or_else(|| anyhow!("missing __cell.{registry} registry"))?;
1400+ let name_key = v8::String::new(scope, name).unwrap();
1401+ Ok(registry_obj
1402+ .has_own_property(scope, name_key.into())
1403+ .unwrap_or(false))
1404+}
1405+
1406+fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> {
1407+ let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned();
1408+ let termination = state.and_then(|state| state.termination.lock().ok()?.take());
1409+ let is_terminating = scope.is_execution_terminating();
1410+ if termination.is_some() || is_terminating {
1411+ scope.cancel_terminate_execution();
1412+ }
1413+ if let Some(termination) = termination {
1414+ if let Some(actor_scope) = termination.actor_scope {
1415+ finish_terminated_actor_event(scope, &actor_scope);
1416+ }
1417+ return Some(anyhow!(termination.error));
1418+ }
1419+ is_terminating.then(|| anyhow!("JavaScript execution was terminated"))
1420+}
1421+
1422+extern "C" fn near_heap_limit(
1423+ data: *mut std::ffi::c_void,
1424+ current_heap_limit: usize,
1425+ _initial_heap_limit: usize,
1426+) -> usize {
1427+ // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop
1428+ // removes this callback before the isolate (and its slots) are destroyed.
1429+ let state = unsafe { &*(data as *const HeapLimitState) };
1430+ state.excessively_exceeded.store(true, Ordering::Relaxed);
1431+ // V8 fatally aborts the process if a near-limit callback does not extend
1432+ // the limit. This reserve lets JS observe condemnation and unwind.
1433+ current_heap_limit.saturating_add(V8_HEAP_EMERGENCY_BYTES)
1434+}
1435+
1436+fn v8_heap_limit_bytes() -> usize {
1437+ crate::env_vars::positive::<usize>("CELLD_V8_HEAP_LIMIT_MB")
1438+ .expect("validated CELLD_V8_HEAP_LIMIT_MB")
1439+ .map(|megabytes| {
1440+ megabytes
1441+ .checked_mul(1024 * 1024)
1442+ .expect("validated CELLD_V8_HEAP_LIMIT_MB range")
1443+ })
1444+ .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES)
1445+}
1446+
1447+impl Drop for WorkerIsolate {
1448+ fn drop(&mut self) {
1449+ let limit = self.original_heap_limit;
1450+ let (mut locker, _cells) = self.lock();
1451+ locker.remove_near_heap_limit_callback(near_heap_limit, limit);
1452+ }
1453+}
1454+
1455+/// One in-flight request inside a shared isolate.
1456+///
1457+/// Owned by the request's own tokio task, which is why every field is
1458+/// `Send`: the task suspends between turns and can resume on any worker,
1459+/// then re-enters the isolate it is affiliated with.
1460+/// Where a finished handler's result goes, and in what shape.
1461+///
1462+/// A fetch answers an `HttpResponse` and an entrypoint RPC answers bytes.
1463+/// Everything between — the turn loop, the op region, cancellation, the
1464+/// budget — is identical, so the difference lives here rather than in two
1465+/// copies of `drive`.
1466+pub enum Answer {
1467+ Fetch(tokio::sync::oneshot::Sender<Result<HttpResponse>>),
1468+ Rpc(tokio::sync::oneshot::Sender<Result<Vec<u8>>>),
1469+ /// A DO method call, which answers a value rather than a response.
1470+ CellRpc(tokio::sync::oneshot::Sender<Result<RpcOutcome>>),
1471+ /// A `webSocketMessage`, which answers the frames the output gate held
1472+ /// and the write they are gated on.
1473+ WsMessage(tokio::sync::oneshot::Sender<Result<WsDispatch>>),
1474+ /// An event whose result is that it finished: `webSocketOpen`,
1475+ /// `webSocketClose`.
1476+ Ack(tokio::sync::oneshot::Sender<Result<()>>),
1477+ /// An alarm, which answers whatever alarm the handler left armed.
1478+ Alarm(tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>),
1479+}
1480+
1481+impl Answer {
1482+ /// Send an error, whichever shape the caller is waiting for.
1483+ fn fail(self, error: anyhow::Error) {
1484+ match self {
1485+ Answer::Fetch(reply) => drop(reply.send(Err(error))),
1486+ Answer::Rpc(reply) => drop(reply.send(Err(error))),
1487+ Answer::CellRpc(reply) => drop(reply.send(Err(error))),
1488+ Answer::WsMessage(reply) => drop(reply.send(Err(error))),
1489+ Answer::Ack(reply) => drop(reply.send(Err(error))),
1490+ Answer::Alarm(reply) => drop(reply.send(Err(error))),
1491+ }
1492+ }
1493+}
1494+
1495+pub struct InFlight {
1496+ /// The handler's promise. A `Global` because it outlives the turn that
1497+ /// created it: Locals never cross a turn, exactly as workerd's
1498+ /// `Worker::Lock` never does.
1499+ promise: v8::Global<v8::Promise>,
1500+ context: Arc<IoContext>,
1501+ /// The cell this event belongs to, and `None` for stateless work.
1502+ ///
1503+ /// It is what the storage-shaped parts of settling — the durability
1504+ /// position, a fatal SQL error — are read against.
1505+ scope: Option<String>,
1506+ /// The cell's committed-write position before the handler ran.
1507+ ///
1508+ /// The answer carries a write position only if the handler advanced it,
1509+ /// so the output gate sees a write this event made and ignores celld's
1510+ /// own activation writes (the actor name, alarm bookkeeping).
1511+ writes_before: Option<u64>,
1512+ request_id: Option<RequestId>,
1513+ active_request_id: Option<RequestId>,
1514+ reply: Option<Answer>,
1515+ /// `waitUntil` work still running after the response was sent. The
1516+ /// request stays in flight until it settles, as the single-request loop
1517+ /// keeps driving it.
1518+ background: Option<v8::Global<v8::Promise>>,
1519+ /// Ops this request is waiting on, so a completion can be attributed to
1520+ /// the request whose context must be current while its continuation runs.
1521+ ops: std::collections::HashSet<u64>,
1522+ /// The alarm bookkeeping this entry still owes, if it is one.
1523+ alarm: Option<AlarmClaim>,
1524+ started: Instant,
1525+ /// The sampled trace this entry records into, `None` when telemetry
1526+ /// is off or the trace was not sampled. Installed into the isolate's
1527+ /// CPED slot for every turn, so promise continuations carry it.
1528+ trace: Option<crate::telemetry::TraceIds>,
1529+ /// Why a handler that did not finish failed, captured for the span's
1530+ /// `error` so a query sees the reason, not only that it failed. Set
1531+ /// only when a trace is sampled.
1532+ failure: Option<String>,
1533+ /// The isolate this entry's ops belong to, so `abandon` can drop their
1534+ /// resolvers without a scope to reach the isolate through.
1535+ runtime_state: Arc<ActorRuntimeState>,
1536+}
1537+
1538+impl InFlight {
1539+ /// Read the handler's settled value in the shape this entry answers, end
1540+ /// the event, and reply.
1541+ ///
1542+ /// Every shape ends the event exactly once, whether it produced a value
1543+ /// or an error — ending it is what yields the `waitUntil` work the entry
1544+ /// keeps driving afterwards, and a shape that skipped it on the error
1545+ /// path would leave the context open.
1546+ fn answer_settled<'s>(
1547+ &mut self,
1548+ tc: &mut v8::PinScope<'s, '_>,
1549+ value: v8::Local<'s, v8::Value>,
1550+ ) {
1551+ let Some(reply) = self.reply.take() else {
1552+ return;
1553+ };
1554+ // A cell whose SQL failed fatally cannot answer whatever the handler
1555+ // returned: the storage the handler read may not be what the cell
1556+ // has.
1557+ if let Some(error) = self.scope.as_deref().and_then(storage::sql_critical_error) {
1558+ let _ = end_event_context(tc);
1559+ if self.trace.is_some() {
1560+ self.failure = Some(crate::telemetry::cap_error(error.to_string()));
1561+ }
1562+ reply.fail(anyhow!(error));
1563+ return;
1564+ }
1565+ self.background = match reply {
1566+ Answer::Fetch(reply) => {
1567+ let read = read_response(tc, value).map(|mut response| {
1568+ response.write_position = self.write_delta();
1569+ response
1570+ });
1571+ send_and_end(tc, reply, read)
1572+ }
1573+ Answer::Rpc(reply) => {
1574+ let read =
1575+ view_bytes(value).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes"));
1576+ send_and_end(tc, reply, read)
1577+ }
1578+ Answer::CellRpc(reply) => {
1579+ let outcome = RpcOutcome {
1580+ data: rpc_data_ret(tc, value),
1581+ write_position: self.write_delta(),
1582+ };
1583+ send_and_end(tc, reply, Ok(outcome))
1584+ }
1585+ Answer::WsMessage(reply) => {
1586+ let dispatch = WsDispatch {
1587+ frames: ws_capture_take(),
1588+ write_position: self.write_delta(),
1589+ };
1590+ send_and_end(tc, reply, Ok(dispatch))
1591+ }
1592+ Answer::Ack(reply) => send_and_end(tc, reply, Ok(())),
1593+ Answer::Alarm(reply) => {
1594+ // The handler ran and returned, so close the claim as a
1595+ // success. This is the only path that does: every other
1596+ // `settle_alarm` call site records a failure, and without
1597+ // this one a *successful* alarm was recorded as one to
1598+ // retry — which re-armed it forever, kept the cell busy,
1599+ // and meant an eviction waiting for the cell to go quiet
1600+ // never got its turn.
1601+ self.settle_alarm(true, false);
1602+ // Read what stands *after* that cleanup, and take the delta
1603+ // last so it covers the cleanup's own commit — which is the
1604+ // write the core must prove durable before it settles the
1605+ // alarm.
1606+ let alarm = self
1607+ .scope
1608+ .as_deref()
1609+ .map(storage::get_alarm)
1610+ .unwrap_or(None);
1611+ send_and_end(tc, reply, Ok((alarm, self.write_delta())))
1612+ }
1613+ };
1614+ }
1615+
1616+ /// The write position to gate this answer on: `None` unless the handler
1617+ /// advanced the cell's committed writes past where they were.
1618+ fn write_delta(&self) -> Option<u64> {
1619+ write_delta(
1620+ self.writes_before,
1621+ self.scope.as_deref().and_then(storage::write_position),
1622+ )
1623+ }
1624+
1625+ /// Fail whichever shape is waiting, without knowing which.
1626+ ///
1627+ /// An alarm that fails here failed for a reason that is not the
1628+ /// handler's — a budget overrun, a disconnect — so it does not count
1629+ /// against the retry limit. A handler that threw is recorded by
1630+ /// `settle`, which knows that it did, before it reaches this.
1631+ fn fail(&mut self, error: anyhow::Error) {
1632+ if let Some(reply) = self.reply.take() {
1633+ self.settle_alarm(false, false);
1634+ if self.trace.is_some() {
1635+ self.failure = Some(crate::telemetry::cap_error(error.to_string()));
1636+ }
1637+ reply.fail(error);
1638+ }
1639+ }
1640+
1641+ /// Record how a claimed alarm ended. Runs once; later calls do nothing.
1642+ fn settle_alarm(&mut self, ok: bool, counts_against_limit: bool) {
1643+ let (Some(scope), Some(claim)) = (self.scope.as_deref(), self.alarm.take()) else {
1644+ return;
1645+ };
1646+ if ok {
1647+ storage::finish_alarm_handler(scope, true, claim.now_ms);
1648+ } else {
1649+ storage::finish_alarm_handler_with_retry_policy(
1650+ scope,
1651+ false,
1652+ claim.now_ms,
1653+ counts_against_limit,
1654+ );
1655+ }
1656+ }
1657+
1658+ /// Whether a claimed alarm's outcome is still unrecorded. True only
1659+ /// where the event ended without ever entering the isolate again.
1660+ pub fn owes_alarm(&self) -> bool {
1661+ self.alarm.is_some()
1662+ }
1663+
1664+ /// Done when the response has been sent and nothing is left running.
1665+ pub fn finished(&self) -> bool {
1666+ self.reply.is_none() && self.background.is_none() && self.ops.is_empty()
1667+ }
1668+
1669+ /// Why the handler failed, when a sampled trace captured it.
1670+ pub fn failure(&self) -> Option<&str> {
1671+ self.failure.as_deref()
1672+ }
1673+
1674+ /// How long this handler may still run, or `None` once it has answered.
1675+ ///
1676+ /// The budget bounds the *response*, not the request: `waitUntil` work
1677+ /// continues after the client has been served and is not charged for the
1678+ /// time the handler already spent.
1679+ pub fn remaining(&self, budget: Duration) -> Option<Duration> {
1680+ self.reply
1681+ .is_some()
1682+ .then(|| budget.saturating_sub(self.started.elapsed()))
1683+ }
1684+
1685+ /// Give up on a handler that will not settle.
1686+ pub fn time_out(&mut self, budget: Duration) {
1687+ self.fail(anyhow!("handler exceeded {}s budget", budget.as_secs()));
1688+ }
1689+
1690+ /// Nothing this request awaits can move it, so it will never settle on
1691+ /// its own. Reachable when a handler awaits a promise only some *other*
1692+ /// request could resolve — which the pump concealed, because it settled
1693+ /// every entry on every turn whoever the turn belonged to.
1694+ pub fn stuck(&mut self) {
1695+ self.fail(anyhow!("handler is waiting on nothing"));
1696+ self.background = None;
1697+ }
1698+
1699+ /// Has the client been answered? `waitUntil` work can still be running.
1700+ pub fn answered(&self) -> bool {
1701+ self.reply.is_none()
1702+ }
1703+
1704+ /// Whether a client can still disconnect from this request. A request
1705+ /// with no id is internal and has no client to hang up.
1706+ pub fn cancellable(&self) -> bool {
1707+ self.reply.is_some() && self.request_id.is_some()
1708+ }
1709+
1710+ pub fn request_id(&self) -> Option<RequestId> {
1711+ self.request_id
1712+ }
1713+
1714+ /// The request is over and its remaining ops are being dropped. Purge
1715+ /// their resolvers.
1716+ ///
1717+ /// An op that never completes would otherwise leave its
1718+ /// `Global<PromiseResolver>` in the isolate's map for as long as the
1719+ /// isolate lives. A request that drives itself has to purge them on its
1720+ /// own way out.
1721+ pub fn abandon(&mut self) {
1722+ if self.ops.is_empty() {
1723+ return;
1724+ }
1725+ let mut promises = self.runtime_state.promises.lock().unwrap();
1726+ for id in self.ops.drain() {
1727+ promises.remove(&id);
1728+ }
1729+ }
1730+}
1731+
1732+/// The CPED slot carries two riders in one immutable record: the
1733+/// harness's async-context frame (`__als_get`/`__als_set` — ALS and
1734+/// request-context confinement) and telemetry's trace context. Each
1735+/// write builds a fresh two-element array preserving the other rider,
1736+/// so V8's per-reaction snapshots restore both atomically and neither
1737+/// feature can stomp the other — the collision the trace-join test
1738+/// caught when telemetry first took the whole slot.
1739+///
1740+/// The empty state stays *empty*: when both riders are absent the slot
1741+/// is undefined, which V8 fast-paths, and "off is structural" holds.
1742+fn cped_parts<'s>(
1743+ scope: &mut v8::PinScope<'s, '_>,
1744+) -> (v8::Local<'s, v8::Value>, v8::Local<'s, v8::Value>) {
1745+ let data = scope.get_continuation_preserved_embedder_data();
1746+ if let Ok(record) = v8::Local::<v8::Array>::try_from(data) {
1747+ if record.length() == 2 {
1748+ let undefined = v8::undefined(scope).into();
1749+ return (
1750+ record.get_index(scope, 0).unwrap_or(undefined),
1751+ record.get_index(scope, 1).unwrap_or(undefined),
1752+ );
1753+ }
1754+ }
1755+ // Any non-record value is a bare frame from before this scheme, or
1756+ // the empty slot.
1757+ (data, v8::undefined(scope).into())
1758+}
1759+
1760+fn cped_frame<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
1761+ cped_parts(scope).0
1762+}
1763+
1764+fn cped_trace<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
1765+ cped_parts(scope).1
1766+}
1767+
1768+fn set_cped(scope: &mut v8::PinScope, frame: v8::Local<v8::Value>, trace: v8::Local<v8::Value>) {
1769+ if frame.is_undefined() && trace.is_undefined() {
1770+ let undefined = v8::undefined(scope).into();
1771+ scope.set_continuation_preserved_embedder_data(undefined);
1772+ return;
1773+ }
1774+ let record = v8::Array::new(scope, 2);
1775+ record.set_index(scope, 0, frame);
1776+ record.set_index(scope, 1, trace);
1777+ scope.set_continuation_preserved_embedder_data(record.into());
1778+}
1779+
1780+/// Install a trace context into the isolate's CPED slot for one turn.
1781+///
1782+/// V8 snapshots continuation-preserved embedder data when a promise
1783+/// reaction is registered and restores it while the reaction runs. That
1784+/// is the exactness `console.log` correlation needs: a continuation
1785+/// belonging to a *different* entry that runs during this turn's
1786+/// microtask checkpoint carries its own context, not this turn's
1787+/// (wiki/designs/otel.md). The layout is 16 trace-id bytes then 8
1788+/// span-id bytes in one 24-byte ArrayBuffer, fresh per turn — cheap at
1789+/// sampled rates, and nothing outlives V8's own snapshots.
1790+///
1791+/// Returns the previous slot value *only when something was installed*;
1792+/// the caller restores it before releasing the isolate. An untraced
1793+/// turn touches CPED not at all — every traced turn restores what it
1794+/// found, so the ambient slot between turns is always empty, and "off
1795+/// is structural" stays true at the V8 boundary too (the -13% the
1796+/// always-read version cost at 1% sampling was measured, not guessed).
1797+fn install_trace<'s>(
1798+ scope: &mut v8::PinScope<'s, '_>,
1799+ trace: Option<&crate::telemetry::TraceIds>,
1800+) -> Option<v8::Local<'s, v8::Value>> {
1801+ let ids = trace?;
1802+ let previous = scope.get_continuation_preserved_embedder_data();
1803+ let buffer = v8::ArrayBuffer::new(scope, 24);
1804+ let data = buffer.get_backing_store().data()?;
1805+ let bytes = data.as_ptr() as *mut u8;
1806+ // SAFETY: a freshly created 24-byte buffer, written before any JS
1807+ // can see it.
1808+ unsafe {
1809+ std::ptr::copy_nonoverlapping(ids.trace_id.as_ptr(), bytes, 16);
1810+ std::ptr::copy_nonoverlapping(ids.span_id.as_ptr(), bytes.add(16), 8);
1811+ }
1812+ let frame = cped_frame(scope);
1813+ set_cped(scope, frame, buffer.into());
1814+ Some(previous)
1815+}
1816+
1817+fn restore_trace(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) {
1818+ if let Some(previous) = previous {
1819+ scope.set_continuation_preserved_embedder_data(previous);
1820+ }
1821+}
1822+
1823+/// The trace context current at this exact point of JS execution, read
1824+/// from CPED — the running turn's, or the running continuation's if V8
1825+/// restored one. `None` when telemetry is off, the trace was unsampled,
1826+/// or execution is outside any entry.
1827+pub(crate) fn current_trace_ids(scope: &mut v8::PinScope) -> Option<crate::telemetry::TraceIds> {
1828+ if !crate::telemetry::active() {
1829+ return None;
1830+ }
1831+ let data = cped_trace(scope);
1832+ let buffer = v8::Local::<v8::ArrayBuffer>::try_from(data).ok()?;
1833+ if buffer.byte_length() != 24 {
1834+ return None;
1835+ }
1836+ let data = buffer.get_backing_store().data()?;
1837+ let bytes = data.as_ptr() as *const u8;
1838+ let mut trace_id = [0u8; 16];
1839+ let mut span_id = [0u8; 8];
1840+ // SAFETY: length checked; the buffer is alive for this scope.
1841+ unsafe {
1842+ std::ptr::copy_nonoverlapping(bytes, trace_id.as_mut_ptr(), 16);
1843+ std::ptr::copy_nonoverlapping(bytes.add(16), span_id.as_mut_ptr(), 8);
1844+ }
1845+ Some(crate::telemetry::TraceIds { trace_id, span_id })
1846+}
1847+
1848+/// The isolate, entered for one turn. Everything a request does to a shared
1849+/// isolate goes through one of these, and none of them may be held across an
1850+/// await: the caller takes the pool's async permit first, runs a turn, and
1851+/// leaves. See `wiki/designs/isolate-threading.md`.
1852+impl Worker {
1853+ /// Run a request's first turn.
1854+ ///
1855+ /// Returns what is now in flight — `None` when nothing is, the reply
1856+ /// already carrying the error — and the ops the handler enqueued, which
1857+ /// the caller awaits with no isolate held.
1858+ pub fn turn_begin(
1859+ &mut self,
1860+ job: crate::WorkerJob,
1861+ trace: Option<crate::telemetry::TraceIds>,
1862+ ) -> (Option<InFlight>, Vec<Op>) {
1863+ let Some(inner) = self.inner.as_mut() else {
1864+ return (None, Vec::new());
1865+ };
1866+ let (mut locker, _cells) = inner.lock();
1867+ v8::scope!(let hs, &mut *locker);
1868+ let realm = inner.realm(hs);
1869+ let context = realm.context;
1870+ let cs = &mut v8::ContextScope::new(hs, context);
1871+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
1872+ let tc = &mut tc.init();
1873+
1874+ let previous = install_trace(tc, trace.as_ref());
1875+ let out = match begin(tc, realm.fetch, job) {
1876+ Begun::Running(mut entry) => {
1877+ entry.trace = trace;
1878+ // A handler that returned an already-resolved promise is
1879+ // finished before it ever suspends, and must not wait for an
1880+ // op it will never start.
1881+ let ops = finish_turn(tc, &mut entry);
1882+ (Some(*entry), ops)
1883+ }
1884+ Begun::Threw(answer) => {
1885+ answer.fail(anyhow!("fetch threw: {}", exc!(tc)));
1886+ (None, Vec::new())
1887+ }
1888+ Begun::Nothing => (None, Vec::new()),
1889+ };
1890+ restore_trace(tc, previous);
1891+ out
1892+ }
1893+
1894+ /// Enter the isolate solely to end a request whose client has hung up.
1895+ ///
1896+ /// A suspended request notices the disconnect without any isolate — the
1897+ /// flag is host state — so this is reached only when it has actually
1898+ /// fired, rather than on a timer as the blocking run loop did.
1899+ pub fn turn_cancel(&mut self, entry: &mut InFlight) -> Vec<Op> {
1900+ let Some(inner) = self.inner.as_mut() else {
1901+ return Vec::new();
1902+ };
1903+ let (mut locker, _cells) = inner.lock();
1904+ v8::scope!(let hs, &mut *locker);
1905+ let realm = inner.realm(hs);
1906+ let context = realm.context;
1907+ let cs = &mut v8::ContextScope::new(hs, context);
1908+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
1909+ let tc = &mut tc.init();
1910+
1911+ let previous = install_trace(tc, entry.trace.as_ref());
1912+ cancel(tc, entry);
1913+ let ops = finish_turn(tc, entry);
1914+ restore_trace(tc, previous);
1915+ ops
1916+ }
1917+
1918+ /// Run a later turn: resolve one of this request's ops, drain the
1919+ /// microtasks that follow, and answer if the handler settled.
1920+ pub fn turn_deliver(
1921+ &mut self,
1922+ entry: &mut InFlight,
1923+ op: u64,
1924+ res: Result<asyncrt::OpOut, String>,
1925+ ) -> Vec<Op> {
1926+ let Some(inner) = self.inner.as_mut() else {
1927+ return Vec::new();
1928+ };
1929+ let (mut locker, _cells) = inner.lock();
1930+ v8::scope!(let hs, &mut *locker);
1931+ let realm = inner.realm(hs);
1932+ let context = realm.context;
1933+ let cs = &mut v8::ContextScope::new(hs, context);
1934+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
1935+ let tc = &mut tc.init();
1936+
1937+ let previous = install_trace(tc, entry.trace.as_ref());
1938+ deliver(tc, entry, op, res);
1939+ cancelled(tc, entry);
1940+ let ops = finish_turn(tc, entry);
1941+ restore_trace(tc, previous);
1942+ ops
1943+ }
1944+}
1945+
1946+/// Close a turn, whatever the turn did.
1947+///
1948+/// Every step earns its place and the order is the whole point:
1949+///
1950+/// 1. **settle** — the handler's promise may have resolved, so marshal the
1951+/// response and answer. Marshalling can start a JS-to-host body pump and
1952+/// register it with `waitUntil`.
1953+/// 2. **checkpoint** — that pump's native ops exist only once the microtasks
1954+/// which create them run.
1955+/// 3. **settle again** — the checkpoint may itself have settled the promise,
1956+/// or the `waitUntil` aggregate.
1957+/// 4. **adopt** — only now is the set of ops this request waits on complete.
1958+///
1959+/// Draining before step 2 is the bug that made a streaming handler answer
1960+/// with nothing outstanding and conclude it was waiting on nothing.
1961+/// The checkpoint before adoption is what makes response-body pumps visible.
1962+fn finish_turn(tc: &mut v8::PinScope, entry: &mut InFlight) -> Vec<Op> {
1963+ settle(tc, entry);
1964+ tc.perform_microtask_checkpoint();
1965+ // `abort()` and `process.exit()` terminate execution without settling
1966+ // the handler's promise, so an entry that only watched the promise would
1967+ // wait on it forever and then report that it was waiting on nothing.
1968+ // The blocking loop broke out of its loop here; an entry fails here.
1969+ if let Some(error) = take_execution_termination(tc) {
1970+ entry.fail(error);
1971+ entry.background = None;
1972+ entry.abandon();
1973+ return Vec::new();
1974+ }
1975+ settle(tc, entry);
1976+ adopt(entry)
1977+}
1978+
1979+/// An op the JS enqueued, and the id whose promise it resolves.
1980+pub type Op = (u64, asyncrt::OpFuture);
1981+
1982+/// Take the ops this turn enqueued, recording them as the request's own.
1983+///
1984+/// Drained after `settle`, not before: ending an event runs JS, and anything
1985+/// that starts there belongs to this request too. The pump drained first and
1986+/// so could attribute those to whichever entry it settled next.
1987+fn adopt(entry: &mut InFlight) -> Vec<Op> {
1988+ let spawns = asyncrt::drain_spawns();
1989+ for (id, _) in &spawns {
1990+ entry.ops.insert(*id);
1991+ }
1992+ spawns
1993+}
1994+
1995+/// What starting a request produced.
1996+enum Begun {
1997+ /// In flight. Its ops must be adopted and its promise driven.
1998+ Running(Box<InFlight>),
1999+ /// The handler threw before it could suspend, so nothing is in flight.
2000+ /// The exception belongs to the caller's `TryCatch` — an unnameable type
2001+ /// no signature here can take — so the caller reads it and answers.
2002+ Threw(Answer),
2003+ /// Nothing started: the job was not a fetch, or the reply already
2004+ /// carries the error.
2005+ Nothing,
2006+}
2007+
2008+/// Start a request: build it, call the Worker's `fetch`, and hand back what
2009+/// is now in flight.
2010+///
2011+/// The half of a turn that runs *before* anything can suspend.
2012+fn begin<'s>(
2013+ tc: &mut v8::PinScope<'s, '_>,
2014+ fetch: v8::Local<'s, v8::Function>,
2015+ job: crate::WorkerJob,
2016+) -> Begun {
2017+ let job = match job {
2018+ crate::WorkerJob::Rpc {
2019+ entrypoint,
2020+ method,
2021+ args,
2022+ reply,
2023+ } => return begin_entrypoint_rpc(tc, &entrypoint, &method, args, reply),
2024+ job => job,
2025+ };
2026+ let crate::WorkerJob::Fetch {
2027+ url,
2028+ method,
2029+ body,
2030+ headers,
2031+ request_id,
2032+ reply,
2033+ ..
2034+ } = job
2035+ else {
2036+ return Begun::Nothing;
2037+ };
2038+
2039+ let context = IoContext::new();
2040+ let guard = CurrentGuard::enter(context.clone());
2041+ let started = start_fetch(tc, fetch, &url, &method, &body, &headers, request_id);
2042+ let promise = match started {
2043+ Ok(Started::Running(ret, active)) => match ret.try_cast::<v8::Promise>() {
2044+ Ok(promise) => Ok((promise, active)),
2045+ Err(_) => resolved_promise(tc, ret).map(|promise| (promise, active)),
2046+ },
2047+ Ok(Started::Threw) => {
2048+ drop(guard);
2049+ return Begun::Threw(Answer::Fetch(reply));
2050+ }
2051+ Err(error) => Err(error),
2052+ };
2053+ match promise {
2054+ Ok((promise, active_request_id)) => {
2055+ tc.perform_microtask_checkpoint();
2056+ let entry = InFlight {
2057+ runtime_state: actor_runtime_state(tc),
2058+ promise: v8::Global::new(tc, promise),
2059+ context,
2060+ scope: None,
2061+ writes_before: None,
2062+ request_id,
2063+ active_request_id,
2064+ reply: Some(Answer::Fetch(reply)),
2065+ background: None,
2066+ ops: std::collections::HashSet::new(),
2067+ alarm: None,
2068+ started: Instant::now(),
2069+ trace: None,
2070+ failure: None,
2071+ };
2072+ drop(guard);
2073+ Begun::Running(Box::new(entry))
2074+ }
2075+ Err(error) => {
2076+ drop(guard);
2077+ let _ = reply.send(Err(error));
2078+ Begun::Nothing
2079+ }
2080+ }
2081+}
2082+
2083+/// Start an entrypoint RPC's first turn.
2084+///
2085+/// The same shape as a fetch and deliberately so: call the handler, keep the
2086+/// promise, and let `drive` pump it with no isolate held across the awaits.
2087+/// The old dispatcher blocked until the promise settled, which is why RPC
2088+/// needed a thread of its own and why `WorkerPool` outlived the fetch path.
2089+fn begin_entrypoint_rpc(
2090+ tc: &mut v8::PinScope,
2091+ entrypoint: &str,
2092+ method: &str,
2093+ args: Vec<u8>,
2094+ reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
2095+) -> Begun {
2096+ let context = IoContext::new();
2097+ let guard = CurrentGuard::enter(context.clone());
2098+ let global = tc.get_current_context().global(tc);
2099+ let started = (|| {
2100+ let key = v8::String::new(tc, "__dispatchEntrypointRpc").unwrap();
2101+ let f: v8::Local<v8::Function> = global
2102+ .get(tc, key.into())
2103+ .ok_or_else(|| anyhow!("no __dispatchEntrypointRpc"))?
2104+ .try_into()
2105+ .map_err(|_| anyhow!("__dispatchEntrypointRpc is not a function"))?;
2106+ let entrypoint = v8::String::new(tc, entrypoint).unwrap();
2107+ let method = v8::String::new(tc, method).unwrap();
2108+ let args = bytes_value(tc, args);
2109+ let recv = v8::undefined(tc).into();
2110+ begin_event_context(tc)?;
2111+ let ret = f
2112+ .call(tc, recv, &[entrypoint.into(), method.into(), args])
2113+ .ok_or_else(|| anyhow!("entrypoint RPC threw"))?;
2114+ match ret.try_cast::<v8::Promise>() {
2115+ Ok(promise) => Ok(promise),
2116+ Err(_) => resolved_promise(tc, ret),
2117+ }
2118+ })();
2119+ match started {
2120+ Ok(promise) => {
2121+ tc.perform_microtask_checkpoint();
2122+ let entry = InFlight {
2123+ runtime_state: actor_runtime_state(tc),
2124+ promise: v8::Global::new(tc, promise),
2125+ context,
2126+ scope: None,
2127+ writes_before: None,
2128+ request_id: None,
2129+ active_request_id: None,
2130+ reply: Some(Answer::Rpc(reply)),
2131+ background: None,
2132+ ops: std::collections::HashSet::new(),
2133+ alarm: None,
2134+ started: Instant::now(),
2135+ trace: None,
2136+ failure: None,
2137+ };
2138+ drop(guard);
2139+ Begun::Running(Box::new(entry))
2140+ }
2141+ Err(error) => {
2142+ let _ = end_event_context(tc);
2143+ drop(guard);
2144+ let _ = reply.send(Err(error));
2145+ Begun::Nothing
2146+ }
2147+ }
2148+}
2149+
2150+/// for the JSON flavor, a `Uint8Array` for structured clone.
2151+fn rpc_data_value<'s>(scope: &mut v8::PinScope<'s, '_>, data: RpcData) -> v8::Local<'s, v8::Value> {
2152+ match data {
2153+ RpcData::Json(json) => v8::String::new(scope, &json).unwrap().into(),
2154+ RpcData::V8(bytes) => bytes_value(scope, bytes),
2155+ }
2156+}
2157+
2158+/// The inverse: `__dispatchRpc` answers in the flavor it was asked in.
2159+fn rpc_data_ret(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> RpcData {
2160+ match view_bytes(ret) {
2161+ Some(bytes) => RpcData::V8(bytes),
2162+ None => RpcData::Json(ret.to_rust_string_lossy(scope)),
2163+ }
2164+}
2165+
2166+fn unix_now_ms() -> i64 {
2167+ std::time::SystemTime::now()
2168+ .duration_since(std::time::UNIX_EPOCH)
2169+ .unwrap_or_default()
2170+ .as_millis()
2171+ .min(i64::MAX as u128) as i64
2172+}
2173+
2174+/// End the event, then answer with what the handler produced.
2175+///
2176+/// Ending it is what yields the `waitUntil` aggregate the entry keeps
2177+/// driving after the caller has been served, so it happens for every answer
2178+/// shape and on the error path too.
2179+fn send_and_end<T>(
2180+ tc: &mut v8::PinScope,
2181+ reply: tokio::sync::oneshot::Sender<Result<T>>,
2182+ value: Result<T>,
2183+) -> Option<v8::Global<v8::Promise>> {
2184+ let background = end_event_context(tc).ok().flatten();
2185+ let _ = reply.send(value);
2186+ background.map(|promise| v8::Global::new(tc, promise))
2187+}
2188+
2189+/// A committed-write position only counts when the handler advanced it; celld's
2190+/// own activation writes are already below `before`.
2191+pub(crate) fn write_delta(before: Option<u64>, after: Option<u64>) -> Option<u64> {
2192+ match (before, after) {
2193+ (Some(before), Some(after)) if after > before => Some(after),
2194+ _ => None,
2195+ }
2196+}
2197+
2198+/// What a Durable Object RPC method returned, plus the position its writes
2199+/// reached, so the caller can hold the reply behind durability.
2200+pub struct RpcOutcome {
2201+ pub data: RpcData,
2202+ pub write_position: Option<u64>,
2203+}
2204+
2205+/// What a claimed alarm still owes its bookkeeping.
2206+///
2207+/// `finish_alarm_handler` must run exactly once however the event ends, and
2208+/// an event can now end without running JS at all — a budget overrun, a
2209+/// handler waiting on nothing — so the entry carries the claim rather than
2210+/// the caller that made it.
2211+struct AlarmClaim {
2212+ /// The instant the dispatch was judged due against, so the outcome is
2213+ /// recorded against the same one.
2214+ now_ms: i64,
2215+}
2216+
2217+/// Start one cell event: the half that runs before the handler can suspend.
2218+///
2219+/// Every cell event does the same four things — name the cell it belongs to,
2220+/// sample the writes its answer will be gated on, open an event context, and
2221+/// keep the promise the dispatcher returned. Only the call and the shape of
2222+/// the answer differ, which is what the arguments say.
2223+fn start_cell_event<'s>(
2224+ tc: &mut v8::PinScope<'s, '_>,
2225+ scope: &str,
2226+ answer: Answer,
2227+ request_id: Option<RequestId>,
2228+ capture_frames: bool,
2229+ call: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>>,
2230+) -> Begun {
2231+ let context = IoContext::new();
2232+ let guard = CurrentGuard::enter(context.clone());
2233+ // Sampled before the handler runs so the output gate can tell a write
2234+ // this event made from celld's own activation writes.
2235+ let writes_before = storage::write_position(scope);
2236+ // No guard: this frame is the context's outermost one and the context
2237+ // ends with the event, so there is nothing to pop it before.
2238+ context
2239+ .egress
2240+ .lock()
2241+ .unwrap()
2242+ .push((scope.to_string(), writes_before.unwrap_or(0)));
2243+ if capture_frames {
2244+ ws_capture_begin();
2245+ }
2246+ let started = (|| {
2247+ begin_event_context(tc)?;
2248+ let ret = call(tc)?;
2249+ match ret.try_cast::<v8::Promise>() {
2250+ Ok(promise) => Ok(promise),
2251+ Err(_) => resolved_promise(tc, ret),
2252+ }
2253+ })();
2254+ match started {
2255+ Ok(promise) => {
2256+ tc.perform_microtask_checkpoint();
2257+ let entry = InFlight {
2258+ runtime_state: actor_runtime_state(tc),
2259+ promise: v8::Global::new(tc, promise),
2260+ context,
2261+ scope: Some(scope.to_string()),
2262+ writes_before,
2263+ request_id,
2264+ // A cell's dispatcher registers the incoming request itself,
2265+ // so there is nothing for the shell to finish; `cancel`
2266+ // aborts by the job's own id.
2267+ active_request_id: None,
2268+ reply: Some(answer),
2269+ background: None,
2270+ ops: std::collections::HashSet::new(),
2271+ alarm: None,
2272+ started: Instant::now(),
2273+ trace: None,
2274+ failure: None,
2275+ };
2276+ drop(guard);
2277+ Begun::Running(Box::new(entry))
2278+ }
2279+ Err(error) => {
2280+ let _ = end_event_context(tc);
2281+ drop(guard);
2282+ answer.fail(error);
2283+ Begun::Nothing
2284+ }
2285+ }
2286+}
2287+
2288+/// Look one of the harness dispatchers up on the current realm's global.
2289+fn dispatcher<'s>(
2290+ tc: &mut v8::PinScope<'s, '_>,
2291+ name: &str,
2292+) -> Result<v8::Local<'s, v8::Function>> {
2293+ let global = tc.get_current_context().global(tc);
2294+ let key = v8::String::new(tc, name).unwrap();
2295+ global
2296+ .get(tc, key.into())
2297+ .ok_or_else(|| anyhow!("no {name}"))?
2298+ .try_into()
2299+ .map_err(|_| anyhow!("{name} is not a function"))
2300+}
2301+
2302+/// Start a cell event's first turn.
2303+///
2304+/// The counterpart of `begin` for the events a cell receives. Where the
2305+/// blocking loop ran each of these to completion inside one call — and
2306+/// serviced other cells' events inside *that* — each is now an entry a tokio
2307+/// task drives, so two events of one cell interleave by suspending rather
2308+/// than by nesting. See `wiki/designs/deleting-the-pump.md`.
2309+fn begin_cell(tc: &mut v8::PinScope, job: CellJob) -> Begun {
2310+ match job {
2311+ CellJob::Fetch {
2312+ request_id,
2313+ scope,
2314+ name,
2315+ url,
2316+ method,
2317+ body,
2318+ headers,
2319+ reply,
2320+ order: _,
2321+ } => {
2322+ if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) {
2323+ let _ = reply.send(Err(error));
2324+ return Begun::Nothing;
2325+ }
2326+ start_cell_event(tc, &scope, Answer::Fetch(reply), request_id, false, |tc| {
2327+ let f = dispatcher(tc, "__dispatchTo")?;
2328+ let arguments = [
2329+ v8::String::new(tc, &scope).unwrap().into(),
2330+ v8::String::new(tc, &url).unwrap().into(),
2331+ v8::String::new(tc, &method).unwrap().into(),
2332+ bytes_value(tc, body),
2333+ v8::String::new(tc, &serde_json::to_string(&headers)?)
2334+ .unwrap()
2335+ .into(),
2336+ match request_id {
2337+ Some(id) => v8::String::new(tc, &request_id_string(id)).unwrap().into(),
2338+ None => v8::null(tc).into(),
2339+ },
2340+ ];
2341+ let recv = v8::undefined(tc).into();
2342+ f.call(tc, recv, &arguments)
2343+ .ok_or_else(|| anyhow!("dispatchTo threw"))
2344+ })
2345+ }
2346+ CellJob::Rpc {
2347+ scope,
2348+ name,
2349+ method,
2350+ args,
2351+ reply,
2352+ } => {
2353+ if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) {
2354+ let _ = reply.send(Err(error));
2355+ return Begun::Nothing;
2356+ }
2357+ start_cell_event(tc, &scope, Answer::CellRpc(reply), None, false, |tc| {
2358+ let f = dispatcher(tc, "__dispatchRpc")?;
2359+ let arguments = [
2360+ v8::String::new(tc, &scope).unwrap().into(),
2361+ v8::String::new(tc, &method).unwrap().into(),
2362+ rpc_data_value(tc, args),
2363+ ];
2364+ let recv = v8::undefined(tc).into();
2365+ f.call(tc, recv, &arguments)
2366+ .ok_or_else(|| anyhow!("dispatchRpc threw"))
2367+ })
2368+ }
2369+ CellJob::WsOpen {
2370+ scope,
2371+ ws_id,
2372+ protocol,
2373+ reply,
2374+ } => start_cell_event(tc, &scope, Answer::Ack(reply), None, false, |tc| {
2375+ let f = dispatcher(tc, "__wsOpen")?;
2376+ let arguments = [
2377+ v8::String::new(tc, &scope).unwrap().into(),
2378+ v8::Number::new(tc, ws_id as f64).into(),
2379+ v8::String::new(tc, &protocol).unwrap().into(),
2380+ ];
2381+ let recv = v8::undefined(tc).into();
2382+ f.call(tc, recv, &arguments)
2383+ .ok_or_else(|| anyhow!("wsOpen threw"))
2384+ }),
2385+ CellJob::WsMessage {
2386+ scope,
2387+ ws_id,
2388+ data,
2389+ reply,
2390+ } => start_cell_event(tc, &scope, Answer::WsMessage(reply), None, true, |tc| {
2391+ let (name, data) = match data {
2392+ WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()),
2393+ WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)),
2394+ };
2395+ let f = dispatcher(tc, name)?;
2396+ let arguments = [
2397+ v8::String::new(tc, &scope).unwrap().into(),
2398+ v8::Number::new(tc, ws_id as f64).into(),
2399+ data,
2400+ ];
2401+ let recv = v8::undefined(tc).into();
2402+ f.call(tc, recv, &arguments)
2403+ .ok_or_else(|| anyhow!("WebSocket message dispatch threw"))
2404+ }),
2405+ CellJob::WsClosed {
2406+ scope,
2407+ ws_id,
2408+ code,
2409+ reason,
2410+ was_clean,
2411+ reply,
2412+ } => start_cell_event(tc, &scope, Answer::Ack(reply), None, false, |tc| {
2413+ let f = dispatcher(tc, "__wsClosed")?;
2414+ let arguments = [
2415+ v8::String::new(tc, &scope).unwrap().into(),
2416+ v8::Number::new(tc, ws_id as f64).into(),
2417+ v8::Number::new(tc, f64::from(code)).into(),
2418+ v8::String::new(tc, &reason).unwrap().into(),
2419+ v8::Boolean::new(tc, was_clean).into(),
2420+ ];
2421+ let recv = v8::undefined(tc).into();
2422+ f.call(tc, recv, &arguments)
2423+ .ok_or_else(|| anyhow!("wsClosed threw"))
2424+ }),
2425+ CellJob::Alarm {
2426+ scope,
2427+ scheduled_ms,
2428+ claim,
2429+ reply,
2430+ } => begin_alarm(tc, &scope, scheduled_ms, claim, reply),
2431+ }
2432+}
2433+
2434+/// Start an alarm, claiming the due entry so nothing else fires it.
2435+///
2436+/// The claim is recorded on the entry rather than closed here, because the
2437+/// handler has not run yet: the outcome is known only when the event ends,
2438+/// which is now many turns away.
2439+fn begin_alarm(
2440+ tc: &mut v8::PinScope,
2441+ scope: &str,
2442+ scheduled_ms: i64,
2443+ claim: AlarmDispatch,
2444+ reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>,
2445+) -> Begun {
2446+ let now = unix_now_ms();
2447+ if now < scheduled_ms {
2448+ let _ = reply.send(Err(anyhow!("alarm dispatched before its deadline")));
2449+ return Begun::Nothing;
2450+ }
2451+ if let AlarmDispatch::Claimed(retry) = claim {
2452+ let Some(scheduled_at) = storage::active_alarm_scheduled_time(scope) else {
2453+ let _ = reply.send(Err(anyhow!("alarm dispatched without a claim")));
2454+ return Begun::Nothing;
2455+ };
2456+ return fire_alarm_handler(tc, scope, scheduled_at, retry, None, reply);
2457+ }
2458+ let due_by = match claim {
2459+ AlarmDispatch::Armed => i64::MAX,
2460+ _ => now,
2461+ };
2462+ let Some((scheduled_at, retry)) = storage::due_alarm_entry(scope, due_by) else {
2463+ // Nothing is due: another dispatch already ran it, or the handler
2464+ // that armed it cleared it. Answer what stands now, with no delta —
2465+ // no handler ran, so there is nothing written to prove.
2466+ let _ = reply.send(Ok((storage::get_alarm(scope), None)));
2467+ return Begun::Nothing;
2468+ };
2469+ storage::begin_alarm_handler(scope, scheduled_at);
2470+ fire_alarm_handler(
2471+ tc,
2472+ scope,
2473+ scheduled_at,
2474+ retry,
2475+ Some(AlarmClaim { now_ms: now }),
2476+ reply,
2477+ )
2478+}
2479+
2480+/// Call `alarm()`, carrying whatever claim its outcome must close.
2481+fn fire_alarm_handler(
2482+ tc: &mut v8::PinScope,
2483+ scope: &str,
2484+ scheduled_at: i64,
2485+ retry: i64,
2486+ claim: Option<AlarmClaim>,
2487+ reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>,
2488+) -> Begun {
2489+ let begun = start_cell_event(tc, scope, Answer::Alarm(reply), None, false, |tc| {
2490+ let f = dispatcher(tc, "__fireAlarm")?;
2491+ let arguments = [
2492+ v8::String::new(tc, scope).unwrap().into(),
2493+ v8::Number::new(tc, scheduled_at as f64).into(),
2494+ v8::Number::new(tc, retry as f64).into(),
2495+ ];
2496+ let recv = v8::undefined(tc).into();
2497+ f.call(tc, recv, &arguments)
2498+ .ok_or_else(|| anyhow!("alarm threw"))
2499+ });
2500+ match begun {
2501+ Begun::Running(mut entry) => {
2502+ entry.alarm = claim;
2503+ Begun::Running(entry)
2504+ }
2505+ // The dispatcher never ran, so nothing can have changed the alarm.
2506+ // Give the claim back as a failure that does not count against the
2507+ // retry limit: the handler is not what failed.
2508+ begun => {
2509+ if let Some(claim) = claim {
2510+ storage::finish_alarm_handler_with_retry_policy(scope, false, claim.now_ms, false);
2511+ }
2512+ begun
2513+ }
2514+ }
2515+}
2516+
2517+/// Resolve one completed op and run the microtasks that follow, with the
2518+/// owning request's context current.
2519+///
2520+/// The half of a turn that resumes a suspended request. It knows nothing
2521+/// about any other request: the caller has already established that this op
2522+/// is `entry`'s.
2523+fn deliver(
2524+ tc: &mut v8::PinScope,
2525+ entry: &mut InFlight,
2526+ op: u64,
2527+ res: Result<asyncrt::OpOut, String>,
2528+) {
2529+ entry.ops.remove(&op);
2530+ let guard = CurrentGuard::enter(entry.context.clone());
2531+ resolve_res(tc, op, res);
2532+ tc.perform_microtask_checkpoint();
2533+ drop(guard);
2534+}
2535+
2536+/// End a request whose client has hung up, so its handler stops running.
2537+fn cancelled(tc: &mut v8::PinScope, entry: &mut InFlight) {
2538+ if entry.reply.is_none() || !take_request_cancellation(entry.request_id) {
2539+ return;
2540+ }
2541+ cancel(tc, entry);
2542+}
2543+
2544+/// End a request whose cancellation has already been taken.
2545+///
2546+/// Split from [`cancelled`] because a suspended request observes the
2547+/// cancellation *outside* the isolate — the flag is host state and costs no
2548+/// V8 — and only then enters to act on it.
2549+fn cancel(tc: &mut v8::PinScope, entry: &mut InFlight) {
2550+ let guard = CurrentGuard::enter(entry.context.clone());
2551+ // The id that names this request to the JS side. A stateless handler is
2552+ // registered by the shell, and only once it suspends, so the shell holds
2553+ // the id; a cell's dispatcher registers the request itself, so the job's
2554+ // own id is the one to abort. Aborting the wrong one — or neither —
2555+ // leaves the target's `request.signal` unfired while the caller is told
2556+ // the client has gone.
2557+ if let Some(id) = entry.active_request_id.or(entry.request_id) {
2558+ let _ = abort_incoming_request(tc, id);
2559+ }
2560+ // Finishing is the shell's to undo only where the shell registered.
2561+ if let Some(id) = entry.active_request_id {
2562+ finish_incoming_request(tc, id);
2563+ }
2564+ let background = end_event_context(tc).ok().flatten();
2565+ entry.background = background.map(|promise| v8::Global::new(tc, promise));
2566+ drop(guard);
2567+ entry.fail(anyhow!("The client has disconnected"));
2568+ // A cancelled handler with no waitUntil work has nothing left to drive.
2569+ // Drop its host ops now, so their guards cancel routed work. Explicit
2570+ // waitUntil work keeps its ops and continues after the client disconnects.
2571+ if entry.background.is_none() {
2572+ entry.abandon();
2573+ }
2574+}
2575+
2576+/// Answer a request whose handler promise has settled, and retire its
2577+/// `waitUntil` work once that settles too.
2578+fn settle(tc: &mut v8::PinScope, entry: &mut InFlight) {
2579+ if entry.reply.is_some() {
2580+ let promise = v8::Local::new(tc, &entry.promise);
2581+ match promise.state() {
2582+ v8::PromiseState::Pending => {}
2583+ v8::PromiseState::Fulfilled => {
2584+ let guard = CurrentGuard::enter(entry.context.clone());
2585+ let value = promise.result(tc);
2586+ entry.answer_settled(tc, value);
2587+ if let Some(request_id) = entry.active_request_id {
2588+ finish_incoming_request(tc, request_id);
2589+ }
2590+ drop(guard);
2591+ }
2592+ v8::PromiseState::Rejected => {
2593+ let guard = CurrentGuard::enter(entry.context.clone());
2594+ let reason = reject_reason(tc, promise);
2595+ // The handler is what failed, so an alarm's failure here
2596+ // counts against its retry limit — unlike a budget overrun
2597+ // or a disconnect, which `fail` records as not counting.
2598+ entry.settle_alarm(false, true);
2599+ let _ = end_event_context(tc);
2600+ if let Some(request_id) = entry.active_request_id {
2601+ finish_incoming_request(tc, request_id);
2602+ }
2603+ drop(guard);
2604+ entry.fail(anyhow!("rejected: {reason}"));
2605+ }
2606+ }
2607+ }
2608+ if let Some(background) = &entry.background {
2609+ let promise = v8::Local::new(tc, background);
2610+ if !matches!(promise.state(), v8::PromiseState::Pending) {
2611+ entry.background = None;
2612+ }
2613+ }
2614+}
2615+
2616+/// Begin a stateless request: build it, call the Worker's `fetch`, and hand
2617+/// back the promise it returned.
2618+///
2619+/// The half of a request that runs *before* it can suspend. Split out from
2620+/// driving it to completion so a caller can start several and drive them
2621+/// together; the single-request path starts one and drives it immediately,
2622+/// which is what it always did.
2623+///
2624+/// The caller owns the `IoContext` and must have it current: `__beginEvent`
2625+/// runs here, and the frame it pushes belongs to this request.
2626+fn start_fetch<'s>(
2627+ tc: &mut v8::PinScope<'s, '_>,
2628+ fetch: v8::Local<'s, v8::Function>,
2629+ url: &str,
2630+ method: &str,
2631+ body: &[u8],
2632+ headers: &[(String, String)],
2633+ request_id: Option<RequestId>,
2634+) -> Result<Started<'s>> {
2635+ let req = match request_id {
2636+ Some(_) => make_incoming_request(tc, url, method, body, headers),
2637+ None => make_request(tc, url, method, body, headers),
2638+ }?;
2639+ let env = harness_env(tc)?;
2640+ let recv = v8::undefined(tc).into();
2641+ let f = fetch;
2642+ let execution_ctx = begin_event_context(tc)?;
2643+ let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else {
2644+ // The handler threw synchronously. Termination carries its own error;
2645+ // otherwise the pending exception is on the caller's TryCatch, which
2646+ // is the only scope that can read it, so it formats the message.
2647+ let error = take_execution_termination(tc);
2648+ let _ = end_event_context(tc);
2649+ return match error {
2650+ Some(error) => Err(error),
2651+ None => Ok(Started::Threw),
2652+ };
2653+ };
2654+ // A handler that suspends must be reachable by an abort: register it as an
2655+ // incoming request so a client disconnect can cancel it. One that already
2656+ // settled cannot be cancelled, so its registration is cleared instead.
2657+ let active_request_id = match request_id {
2658+ Some(request_id)
2659+ if ret
2660+ .try_cast::<v8::Promise>()
2661+ .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) =>
2662+ {
2663+ if let Err(error) = register_incoming_request(tc, request_id, req) {
2664+ clear_request_cancellation(request_id);
2665+ let _ = end_event_context(tc);
2666+ return Err(error);
2667+ }
2668+ Some(request_id)
2669+ }
2670+ Some(request_id) => {
2671+ clear_request_cancellation(request_id);
2672+ None
2673+ }
2674+ None => None,
2675+ };
2676+ Ok(Started::Running(ret, active_request_id))
2677+}
2678+
2679+/// What `start_fetch` produced: a running handler, or a synchronous throw
2680+/// whose exception only the caller's `TryCatch` can read.
2681+enum Started<'s> {
2682+ Running(v8::Local<'s, v8::Value>, Option<RequestId>),
2683+ Threw,
2684+}
2685+
2686+impl Worker {
2687+ /// Compile the worker module, wire the DO harness, and extract the entry
2688+ /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding
2689+ /// name to a DO class name (from wrangler metadata).
2690+ ///
2691+ /// The runtime builds a `WorkerConfig` directly; this helper is
2692+ /// test-only.
2693+ #[cfg(test)]
2694+ pub fn load(options: WorkerConfigOptions, owned: &[String]) -> Result<Worker> {
2695+ let config = Arc::new(WorkerConfig::new(options));
2696+ Self::load_config(config, owned)
2697+ }
2698+
2699+ pub fn load_config(config: Arc<WorkerConfig>, owned: &[String]) -> Result<Worker> {
2700+ Self::load_config_owned(config, Arc::from(owned.to_vec()))
2701+ }
2702+
2703+ fn load_config_owned(config: Arc<WorkerConfig>, owned: Arc<[String]>) -> Result<Worker> {
2704+ let src = config.src.as_str();
2705+ let script_name = config.script_name.as_str();
2706+ let do_classes = config.do_classes.as_slice();
2707+ let node = config.node.as_str();
2708+ let compat = config.compat;
2709+ let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes());
2710+ let mut isolate = v8::Isolate::new(params);
2711+ // Dynamic `import()` of builtin specifiers; per-import()-call only.
2712+ isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically);
2713+ let original_heap_limit = isolate.get_heap_statistics().heap_size_limit();
2714+ let heap_limit_state = Arc::new(HeapLimitState::default());
2715+ let runtime_state = Arc::new(ActorRuntimeState {
2716+ promises: std::sync::Mutex::new(PromiseMap::new()),
2717+ egress: config.egress,
2718+ ..Default::default()
2719+ });
2720+ let heap_limit_state_ptr =
2721+ Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void;
2722+ isolate.set_slot(heap_limit_state);
2723+ isolate.set_slot(runtime_state.clone());
2724+ isolate.set_slot(Arc::new(ModuleRegistry::default()));
2725+ isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr);
2726+ let (context, fetch) = {
2727+ v8::scope!(let hs, &mut isolate);
2728+ let context = v8::Context::new(hs, Default::default());
2729+ let cs = &mut v8::ContextScope::new(hs, context);
2730+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2731+ let scope = &mut tc.init();
2732+
2733+ install_ops(scope, context);
2734+ install_prelude(scope)?; // Web Platform APIs
2735+ install_harness(scope)?; // DO object model + minimal Response
2736+ install_lazy_globals(scope)?;
2737+ // A global, so it must exist before the module evaluates: bundles
2738+ // read Cloudflare.compatibilityFlags at module scope.
2739+ inject_compatibility_flags(scope, compat)?;
2740+ inject_storage_compatibility(scope, compat)?;
2741+
2742+ let module = match compile_module(scope, "worker.js", src) {
2743+ Some(m) => m,
2744+ None => return Err(anyhow!("compile: {}", exc!(scope))),
2745+ };
2746+ register_stubs(scope, src, &config.modules); // cloudflare:*/node:* + text modules
2747+ register_wasm_modules(scope, &config.modules);
2748+ register_loader_modules(scope, &config.modules);
2749+ module
2750+ .instantiate_module(scope, resolve_external)
2751+ .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?;
2752+ let ev = match module.evaluate(scope) {
2753+ Some(value) => value,
2754+ None => {
2755+ if let Some(error) = take_execution_termination(scope) {
2756+ return Err(error);
2757+ }
2758+ return Err(anyhow!("evaluate: {}", exc!(scope)));
2759+ }
2760+ };
2761+ if let Some(error) = take_execution_termination(scope) {
2762+ return Err(error);
2763+ }
2764+ if let Ok(p) = ev.try_cast::<v8::Promise>() {
2765+ if p.state() == v8::PromiseState::Rejected {
2766+ let r = p.result(scope);
2767+ let stk = r
2768+ .to_object(scope)
2769+ .and_then(|o| {
2770+ let k = v8::String::new(scope, "stack")?;
2771+ o.get(scope, k.into())
2772+ })
2773+ .map(|s| s.to_rust_string_lossy(scope))
2774+ .unwrap_or_default();
2775+ return Err(anyhow!(
2776+ "top-level rejected: {} | {}",
2777+ r.to_rust_string_lossy(scope),
2778+ stk.lines().take(4).collect::<Vec<_>>().join(" <- ")
2779+ ));
2780+ }
2781+ }
2782+
2783+ let ns = module
2784+ .get_module_namespace()
2785+ .to_object(scope)
2786+ .ok_or_else(|| anyhow!("ns"))?;
2787+
2788+ // register each exported DO class into the harness registry
2789+ for cn in do_classes {
2790+ let key = v8::String::new(scope, cn).unwrap();
2791+ let cls = ns
2792+ .get(scope, key.into())
2793+ .ok_or_else(|| anyhow!("DO class {cn} not exported"))?;
2794+ register_class(scope, cn, cls)?;
2795+ }
2796+ inject_namespace_keys(scope, script_name, do_classes)?;
2797+ populate_cf_exports(scope, ns, do_classes)?;
2798+ register_entrypoints(scope, ns)?;
2799+ // build env from bindings and stash it in the harness
2800+ build_env(scope, &config)?;
2801+ // tell the harness which cells are local (route the rest cross-node)
2802+ inject_routing(scope, owned.as_ref(), node)?;
2803+
2804+ // entry fetch
2805+ let dk = v8::String::new(scope, "default").unwrap();
2806+ let default = ns
2807+ .get(scope, dk.into())
2808+ .ok_or_else(|| anyhow!("no default export"))?
2809+ .to_object(scope)
2810+ .ok_or_else(|| anyhow!("default not object"))?;
2811+ let fk = v8::String::new(scope, "fetch").unwrap();
2812+ let fetch_value = default
2813+ .get(scope, fk.into())
2814+ .ok_or_else(|| anyhow!("no fetch"))?;
2815+ let default_is_entrypoint =
2816+ default.is_function() && cell_registry_has(scope, "entrypoints", "default")?;
2817+ let f: v8::Local<v8::Function> = if fetch_value.is_function() {
2818+ fetch_value.try_into().expect("function casts to Function")
2819+ } else if default_is_entrypoint {
2820+ // A class-based default entrypoint (extends WorkerEntrypoint)
2821+ // keeps fetch on the prototype, so route through the
2822+ // harness's cached instance like a named entrypoint. Only a
2823+ // registered entrypoint dispatches that way — any other
2824+ // callable would load fine and then 500 on every request.
2825+ compile_fn(
2826+ scope,
2827+ "(req) => globalThis.__dispatchEntrypointFetch('default', req)",
2828+ )?
2829+ } else if default.is_function() && cell_registry_has(scope, "doExports", "default")? {
2830+ return Err(anyhow!(
2831+ "the default export is a Durable Object class; export a fetch \
2832+ handler or a WorkerEntrypoint class as the default"
2833+ ));
2834+ } else {
2835+ return Err(anyhow!("fetch not fn"));
2836+ };
2837+
2838+ // Lets a self-targeted service binding invoke the handler in
2839+ // this isolate instead of crossing to a pool thread.
2840+ {
2841+ let cell_key = v8::String::new(scope, "__cell").unwrap();
2842+ if let Some(cell) = context
2843+ .global(scope)
2844+ .get(scope, cell_key.into())
2845+ .and_then(|value| value.to_object(scope))
2846+ {
2847+ let key = v8::String::new(scope, "selfFetch").unwrap();
2848+ cell.set(scope, key.into(), f.into());
2849+ // Optional scheduled handler, reached by a self-targeted
2850+ // service binding's scheduled().
2851+ let sk = v8::String::new(scope, "scheduled").unwrap();
2852+ let key_ = v8::String::new(scope, "selfScheduled").unwrap();
2853+ let own = default
2854+ .get(scope, sk.into())
2855+ .filter(|handler| handler.is_function());
2856+ if let Some(handler) = own {
2857+ cell.set(scope, key_.into(), handler);
2858+ } else if default_is_entrypoint {
2859+ // A class-based default entrypoint keeps scheduled on
2860+ // the prototype; dispatch through the cached instance
2861+ // like fetch above.
2862+ let pk = v8::String::new(scope, "prototype").unwrap();
2863+ let proto_scheduled = default
2864+ .get(scope, pk.into())
2865+ .and_then(|proto| proto.to_object(scope))
2866+ .and_then(|proto| proto.get(scope, sk.into()));
2867+ if proto_scheduled.is_some_and(|handler| handler.is_function()) {
2868+ let shim = compile_fn(
2869+ scope,
2870+ "(ctrl) => globalThis.__dispatchEntrypointScheduled('default', ctrl)",
2871+ )?;
2872+ cell.set(scope, key_.into(), shim.into());
2873+ }
2874+ }
2875+ }
2876+ }
2877+ (v8::Global::new(scope, context), v8::Global::new(scope, f))
2878+ };
2879+ Ok(Worker {
2880+ inner: Some(WorkerIsolate {
2881+ // Every setup scope above has closed, so nothing is entered
2882+ // on top of this isolate and it can be handed over.
2883+ // SAFETY: `into_shared` requires every piece of embedder
2884+ // state hanging off this isolate to be `Send`, because it
2885+ // migrates between threads and is dropped on whichever one
2886+ // holds the lock last. This isolate carries exactly:
2887+ //
2888+ // - three slots, whose types the assertion below pins as
2889+ // `Send + Sync`;
2890+ // - `near_heap_limit`, a bare fn pointer whose only captured
2891+ // state is a raw pointer into the `HeapLimitState` above;
2892+ // - `host_import_module_dynamically`, a bare fn pointer that
2893+ // captures nothing;
2894+ // - a default `CreateParams` allocator, owned by V8.
2895+ //
2896+ // Nothing else is attached, and the assertion fails the build
2897+ // if a slot type ever stops being thread-safe.
2898+ //
2899+ // 152.1.0 made this fallible. None of the four refusals can
2900+ // hold here — this isolate is entered, is not a snapshot
2901+ // creator, has no C++ heap, and has taken no weak handles —
2902+ // so a refusal is a bug in the setup above, not a condition
2903+ // to recover from. It panics with the reason named.
2904+ isolate: unsafe { isolate.try_into_shared() }
2905+ .unwrap_or_else(|error| panic!("cell isolate cannot be shared: {error}")),
2906+ realm: Realm { context, fetch },
2907+ original_heap_limit,
2908+ cells: storage::Cells::default(),
2909+ }),
2910+ })
2911+ }
2912+
2913+ /// Restore an idFromName() actor's human-readable identity before its
2914+ /// constructor runs. The host calls this on activation and before a named
2915+ /// request is dispatched.
2916+ /// Record whether this isolate hosts `cell`, so the harness can dispatch
2917+ /// to it in-isolate instead of going back out through the host.
2918+ ///
2919+ /// Baked in at load time until cells shared isolates, when an isolate
2920+ /// served exactly one cell for its whole life and the list could not
2921+ /// change. Now a cell arrives at an isolate that already exists, so the
2922+ /// list has to move with placement.
2923+ ///
2924+ /// Getting this wrong is not symmetric. A cell missing from the list
2925+ /// still works: the dispatch goes out to the host, which routes it
2926+ /// straight back here, costing a round trip. A cell wrongly *in* the
2927+ /// list is a cell this isolate would try to serve without hosting it, so
2928+ /// the shell sets it when it takes a residency and clears it when the
2929+ /// residency ends.
2930+ pub fn own_cell(
2931+ &mut self,
2932+ cell: &str,
2933+ db_path: Option<&str>,
2934+ owned: bool,
2935+ ) -> Result<Option<i64>> {
2936+ let (mut locker, _cells) = self.lock();
2937+ v8::scope!(let hs, &mut *locker);
2938+ let realm = self.realm(hs);
2939+ let context = realm.context;
2940+ let cs = &mut v8::ContextScope::new(hs, context);
2941+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2942+ adopt_cell(&mut tc.init(), cell, db_path, owned)
2943+ }
2944+
2945+ /// Drain the alarm moves the last turn committed in this isolate.
2946+ ///
2947+ /// An alarm move is a turn output, exactly like the ops a turn starts:
2948+ /// the drive that ran the turn reports it to the host, so a handler
2949+ /// that arms an alarm and then awaits it is schedulable immediately,
2950+ /// not when the request ends. A separate call rather than part of the
2951+ /// turn methods' return because stateless turns cannot move an alarm
2952+ /// and never pay for it.
2953+ pub fn take_alarm_moves(&mut self) -> Vec<(String, i64)> {
2954+ let Some(inner) = self.inner.as_mut() else {
2955+ return Vec::new();
2956+ };
2957+ let (_locker, _cells) = inner.lock();
2958+ storage::take_alarm_moves()
2959+ }
2960+
2961+ pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> {
2962+ let (mut locker, _cells) = self.lock();
2963+ v8::scope!(let hs, &mut *locker);
2964+ let realm = self.realm(hs);
2965+ let context = realm.context;
2966+ let cs = &mut v8::ContextScope::new(hs, context);
2967+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2968+ register_actor_name(&mut tc.init(), scope, Some(name))
2969+ }
2970+
2971+ /// Start a cell event's first turn.
2972+ ///
2973+ /// The cell counterpart of `turn_begin`: it hands back what is now in
2974+ /// flight for `runtime::drive_cell` to pump.
2975+ pub fn turn_begin_cell(
2976+ &mut self,
2977+ job: CellJob,
2978+ trace: Option<crate::telemetry::TraceIds>,
2979+ ) -> (Option<InFlight>, Vec<Op>) {
2980+ let Some(inner) = self.inner.as_mut() else {
2981+ return (None, Vec::new());
2982+ };
2983+ let (mut locker, _cells) = inner.lock();
2984+ v8::scope!(let hs, &mut *locker);
2985+ let realm = inner.realm(hs);
2986+ let context = realm.context;
2987+ let cs = &mut v8::ContextScope::new(hs, context);
2988+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2989+ let tc = &mut tc.init();
2990+
2991+ let previous = install_trace(tc, trace.as_ref());
2992+ let out = match begin_cell(tc, job) {
2993+ Begun::Running(mut entry) => {
2994+ entry.trace = trace;
2995+ let ops = finish_turn(tc, &mut entry);
2996+ (Some(*entry), ops)
2997+ }
2998+ Begun::Threw(answer) => {
2999+ answer.fail(anyhow!("cell event threw: {}", exc!(tc)));
3000+ (None, Vec::new())
3001+ }
3002+ Begun::Nothing => (None, Vec::new()),
3003+ };
3004+ restore_trace(tc, previous);
3005+ out
3006+ }
3007+
3008+ /// Enter the isolate solely to see whether another event settled this
3009+ /// one's promise.
3010+ ///
3011+ /// A promise resolved by a different entry has no waker pointing here,
3012+ /// so the driving task cannot be told and has to look. That is why this
3013+ /// is a poll and not an event, and it is the same reason the blocking
3014+ /// loop woke every 10 ms.
3015+ pub fn turn_poll(&mut self, entry: &mut InFlight) -> Vec<Op> {
3016+ let Some(inner) = self.inner.as_mut() else {
3017+ return Vec::new();
3018+ };
3019+ let (mut locker, _cells) = inner.lock();
3020+ v8::scope!(let hs, &mut *locker);
3021+ let realm = inner.realm(hs);
3022+ let context = realm.context;
3023+ let cs = &mut v8::ContextScope::new(hs, context);
3024+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
3025+ let tc = &mut tc.init();
3026+
3027+ let previous = install_trace(tc, entry.trace.as_ref());
3028+ let ops = finish_turn(tc, entry);
3029+ restore_trace(tc, previous);
3030+ ops
3031+ }
3032+
3033+ /// Enter the isolate solely to record how a claimed alarm ended.
3034+ ///
3035+ /// Reached only when the event ended without running JS again — a budget
3036+ /// overrun, or a handler waiting on nothing. The bookkeeping is storage
3037+ /// the isolate owns, so it cannot be done from the driving task.
3038+ pub fn turn_finish_alarm(&mut self, entry: &mut InFlight) {
3039+ let Some(inner) = self.inner.as_mut() else {
3040+ return;
3041+ };
3042+ let (_locker, _cells) = inner.lock();
3043+ entry.settle_alarm(false, false);
3044+ }
3045+}
3046+
3047+// ---- native ops exposed to JS ----
3048+
3049+/// Host ops, defined non-enumerable. They are runtime internals: a bundle
3050+/// walking `globalThis` must not find them, let alone `new` one — `for (const
3051+/// k in globalThis) new globalThis[k]()` used to reach `__actor_abort` and
3052+/// kill the actor.
3053+macro_rules! ops {
3054+ ($scope:expr, $global:expr, $($name:literal => $op:path),* $(,)?) => {
3055+ $({
3056+ let f = v8::Function::new($scope, $op).unwrap();
3057+ let k = v8::String::new($scope, $name).unwrap();
3058+ $global.define_own_property(
3059+ $scope, k.into(), f.into(), v8::PropertyAttribute::DONT_ENUM);
3060+ })*
3061+ };
3062+}
3063+
3064+fn install_ops(scope: &mut v8::PinScope, context: v8::Local<v8::Context>) {
3065+ let global = context.global(scope);
3066+ ops! { scope, global,
3067+ "__heap_limit_excessively_exceeded" =>
3068+ op_heap_limit_excessively_exceeded,
3069+ "__ws_send" => websocket::op_ws_send,
3070+ "__ws_send_binary" => websocket::op_ws_send_binary,
3071+ "__ws_close" => websocket::op_ws_close,
3072+ "__ws_alloc" => websocket::op_ws_alloc,
3073+ "__ws_accept" => websocket::op_ws_accept,
3074+ "__ws_accept_regular" => websocket::op_ws_accept_regular,
3075+ "__ws_list" => websocket::op_ws_list,
3076+ "__ws_attachment_set" => websocket::op_ws_attachment_set,
3077+ "__ws_auto_response_set" => websocket::op_ws_auto_response_set,
3078+ "__ws_auto_response_get" => websocket::op_ws_auto_response_get,
3079+ "__ws_auto_response_ts" => websocket::op_ws_auto_response_ts,
3080+ "__ws_connect" => websocket::op_ws_connect,
3081+ "__ws_next" => websocket::op_ws_next,
3082+ "__ws_upgrade" => websocket::op_ws_upgrade,
3083+ "__storage_get" => storage_ops::op_storage_get,
3084+ "__storage_get_many" => storage_ops::op_storage_get_many,
3085+ "__sql_exec" => storage_ops::op_sql_exec,
3086+ "__sql_ingest" => storage_ops::op_sql_ingest,
3087+ "__sql_cursor_start" => storage_ops::op_sql_cursor_start,
3088+ "__sql_cursor_next" => storage_ops::op_sql_cursor_next,
3089+ "__sql_cursor_close" => storage_ops::op_sql_cursor_close,
3090+ "__sql_database_size" => storage_ops::op_sql_database_size,
3091+ "__storage_transaction_control" => storage_ops::op_storage_transaction_control,
3092+ "__log" => op_log,
3093+ "__storage_put" => storage_ops::op_storage_put,
3094+ "__storage_put_many" => storage_ops::op_storage_put_many,
3095+ "__storage_queue_put" => storage_ops::op_storage_queue_put,
3096+ "__storage_queue_put_many" => storage_ops::op_storage_queue_put_many,
3097+ "__storage_put_serialized" => storage_ops::op_storage_put_serialized,
3098+ "__storage_queue_put_serialized" => storage_ops::op_storage_queue_put_serialized,
3099+ "__storage_flush_pending_puts" => storage_ops::op_storage_flush_pending_puts,
3100+ "__storage_cancel_pending_puts" => storage_ops::op_storage_cancel_pending_puts,
3101+ "__actor_abort" => op_actor_abort,
3102+ "__process_exit" => op_process_exit,
3103+ "__storage_delete" => storage_ops::op_storage_delete,
3104+ "__storage_delete_many" => storage_ops::op_storage_delete_many,
3105+ "__storage_list" => storage_ops::op_storage_list,
3106+ "__storage_sync_list_start" => storage_ops::op_storage_sync_list_start,
3107+ "__storage_sync_list_next" => storage_ops::op_storage_sync_list_next,
3108+ "__storage_delete_all" => storage_ops::op_storage_delete_all,
3109+ "$$urlParse" => op_url_parse,
3110+ "$$urlPatternParse" => op_urlpattern_parse,
3111+ "$$urlPatternMatchInput" => op_urlpattern_match_input,
3112+ "$$atob" => op_atob,
3113+ "$$btoa" => op_btoa,
3114+ "$$textDecoderLabel" => op_text_decoder_label,
3115+ "$$textDecoderNew" => op_text_decoder_new,
3116+ "$$textDecoderDecode" => op_text_decoder_decode,
3117+ "$$textDecoderFree" => op_text_decoder_free,
3118+ "__alarm_set" => op_alarm_set,
3119+ "__alarm_get" => op_alarm_get,
3120+ "__alarm_delete" => op_alarm_delete,
3121+ "__loader_load" => op_loader_load,
3122+ "__loader_fetch" => op_loader_fetch,
3123+ "__loader_rpc" => op_loader_rpc,
3124+ "__loader_drop" => op_loader_drop,
3125+ "__do_call" => op_do_call,
3126+ "__writePosition" => op_write_position,
3127+ "__gateWrite" => op_gate_write,
3128+ "__svc_call" => op_svc_call,
3129+ "__svc_call_cancellable" => op_svc_call_cancellable,
3130+ "__svc_rpc" => op_svc_rpc,
3131+ "__do_call_cancellable" => op_do_call_cancellable,
3132+ "__do_call_cancel" => op_do_call_cancel,
3133+ "__do_id" => op_do_id,
3134+ "__rpc_call" => op_rpc_call,
3135+ "__sc_encode" => storage_ops::op_sc_encode,
3136+ "__sc_decode" => storage_ops::op_sc_decode,
3137+ "__op_fetch" => op_fetch,
3138+ "__asset_fetch" => op_asset_fetch,
3139+ "__http_stream_read" => op_http_stream_read,
3140+ "__http_stream_cancel" => op_http_stream_cancel,
3141+ "__http_stream_tee" => op_http_stream_tee,
3142+ "__response_stream_create" => op_response_stream_create,
3143+ "__response_stream_write" => op_response_stream_write,
3144+ "__response_stream_closed" => op_response_stream_closed,
3145+ "__response_stream_close" => op_response_stream_close,
3146+ "__op_timer" => op_timer,
3147+ "__timer_alloc" => op_timer_alloc,
3148+ "__gate_acquire" => op_gate_acquire,
3149+ "__gate_wait" => op_gate_wait,
3150+ "__gate_release" => op_gate_release,
3151+ "__timer_cancel" => op_timer_cancel,
3152+ "__crypto_operation" => crypto::op_crypto_operation,
3153+ "$$randomValues" => crypto::op_webcrypto_random,
3154+ "$$digest" => crypto::op_webcrypto_digest,
3155+ "$$hmacSign" => crypto::op_webcrypto_hmac_sign,
3156+ "$$hmacVerify" => crypto::op_webcrypto_hmac_verify,
3157+ "$$aesEncrypt" => crypto::op_webcrypto_aes_encrypt,
3158+ "$$aesDecrypt" => crypto::op_webcrypto_aes_decrypt,
3159+ "$$pbkdf2" => crypto::op_node_pbkdf2,
3160+ "$$hkdf" => crypto::op_node_hkdf,
3161+ "$$timingSafeEqual" => crypto::op_timing_safe_equal,
3162+ "__event_begin" => op_event_begin,
3163+ "__event_end" => op_event_end,
3164+ "__wait_until" => op_wait_until,
3165+ "__event_depth" => op_event_depth,
3166+ "__als_get" => op_als_get,
3167+ "__als_set" => op_als_set,
3168+ "__util_type_flags" => op_util_type_flags,
3169+ "__util_constructor_name" => op_util_constructor_name,
3170+ "__util_proxy_details" => op_util_proxy_details,
3171+ "__util_promise_details" => op_util_promise_details,
3172+ "__util_preview_entries" => op_util_preview_entries,
3173+ "__builtin_module" => op_builtin_module,
3174+ "__zlib" => zlib::op_zlib,
3175+ "__zlib_stream_new" => zlib::op_zlib_stream_new,
3176+ "__zlib_stream_push" => zlib::op_zlib_stream_push,
3177+ "__zlib_stream_end" => zlib::op_zlib_stream_end,
3178+ "__zlib_stream_drop" => zlib::op_zlib_stream_drop,
3179+ }
3180+ #[cfg(all(test, celld_internal_tests))]
3181+ ops! { scope, global,
3182+ "__test_gc" => op_test_gc,
3183+ "__loader_count" => op_loader_count,
3184+ "__test_set_heap_limit_excessively_exceeded" =>
3185+ op_test_set_heap_limit_excessively_exceeded,
3186+ "__sql_set_max_page_count_for_test" =>
3187+ storage_ops::op_sql_set_max_page_count_for_test,
3188+ "__sql_set_write_fault_for_test" => storage_ops::op_sql_set_write_fault_for_test,
3189+ "__sql_set_cache_size_for_test" => storage_ops::op_sql_set_cache_size_for_test,
3190+ "__sql_set_interrupt_fault_for_test" =>
3191+ storage_ops::op_sql_set_interrupt_fault_for_test,
3192+ "__sql_register_nomem_function_for_test" =>
3193+ storage_ops::op_sql_register_nomem_function_for_test,
3194+ }
3195+}
3196+
3197+/// Create a JS promise for an async op `id` and return it to JS.
3198+fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> {
3199+ let resolver = v8::PromiseResolver::new(scope).unwrap();
3200+ let promise = resolver.get_promise(scope);
3201+ promise_store(scope, id, v8::Global::new(scope, resolver));
3202+ promise.into()
3203+}
3204+
3205+/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await
3206+/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON
3207+/// `{status, body, headers}` string the harness turns back into a Response.
3208+/// `__svc_rpc(script, entrypoint, method, argsSc)` -> Promise<Uint8Array>;
3209+/// arguments and result are V8 structured-clone bytes.
3210+fn op_svc_rpc(
3211+ scope: &mut v8::PinScope,
3212+ args: v8::FunctionCallbackArguments,
3213+ mut rv: v8::ReturnValue<v8::Value>,
3214+) {
3215+ let script = args.get(0).to_rust_string_lossy(scope);
3216+ let entrypoint = args.get(1).to_rust_string_lossy(scope);
3217+ let method = args.get(2).to_rust_string_lossy(scope);
3218+ let call_args = view_bytes(args.get(3)).unwrap_or_default();
3219+ let (tx, rx) = tokio::sync::oneshot::channel();
3220+ let gate = egress_gate_pending();
3221+ let request = SvcRpcReq {
3222+ script,
3223+ entrypoint,
3224+ method,
3225+ args: call_args,
3226+ reply: tx,
3227+ };
3228+ let id = asyncrt::enqueue(async move {
3229+ gated_channel_send(gate, &SVC_RPC_TX, request, "no service binding channel").await?;
3230+ match rx.await {
3231+ Ok(Ok(result)) => Ok(result),
3232+ Ok(Err(error)) => Err(format!("{error}")),
3233+ Err(error) => Err(format!("service dropped: {error}")),
3234+ }
3235+ });
3236+ rv.set(promise_for(scope, id));
3237+}
3238+
3239+/// `__svc_call(script, url, method, body, headersJson)` -> Promise<json>.
3240+/// The service-binding equivalent of `__do_call`: no scope to resolve and no
3241+/// cancellation token, just a handoff to the target script's pool.
3242+fn op_svc_call(
3243+ scope: &mut v8::PinScope,
3244+ args: v8::FunctionCallbackArguments,
3245+ mut rv: v8::ReturnValue<v8::Value>,
3246+) {
3247+ op_svc_call_impl(scope, args, &mut rv, false);
3248+}
3249+
3250+fn op_svc_call_cancellable(
3251+ scope: &mut v8::PinScope,
3252+ args: v8::FunctionCallbackArguments,
3253+ mut rv: v8::ReturnValue<v8::Value>,
3254+) {
3255+ op_svc_call_impl(scope, args, &mut rv, true);
3256+}
3257+
3258+fn op_svc_call_impl(
3259+ scope: &mut v8::PinScope,
3260+ args: v8::FunctionCallbackArguments,
3261+ rv: &mut v8::ReturnValue<v8::Value>,
3262+ cancellable: bool,
3263+) {
3264+ let script = args.get(0).to_rust_string_lossy(scope);
3265+ let url = args.get(1).to_rust_string_lossy(scope);
3266+ let method = args.get(2).to_rust_string_lossy(scope);
3267+ let body = view_bytes(args.get(3)).unwrap_or_default();
3268+ let headers =
3269+ serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default();
3270+ let (tx, rx) = tokio::sync::oneshot::channel();
3271+ // Shares the Durable Object cancel registry, so `__do_call_cancel` works
3272+ // unchanged for a service call.
3273+ let (request_id, cancel, cancel_guard) = if cancellable {
3274+ let request_id = next_do_request_id();
3275+ let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
3276+ do_call_cancels()
3277+ .lock()
3278+ .unwrap()
3279+ .insert(request_id, cancel_sender);
3280+ (
3281+ Some(request_id),
3282+ Some(cancel_receiver),
3283+ Some(DoCallCancelGuard::new(request_id)),
3284+ )
3285+ } else {
3286+ (None, None, None)
3287+ };
3288+ let gate = egress_gate_pending();
3289+ let request = SvcCallReq {
3290+ cancel,
3291+ script,
3292+ url,
3293+ method,
3294+ body,
3295+ headers,
3296+ reply: tx,
3297+ };
3298+ let id = asyncrt::enqueue(async move {
3299+ let mut cancel_guard = cancel_guard;
3300+ gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?;
3301+ let result = match rx.await {
3302+ Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3303+ Ok(Err(error)) => Err(format!("{error}")),
3304+ Err(error) => Err(format!("service dropped: {error}")),
3305+ };
3306+ if let Some(cancel_guard) = cancel_guard.as_mut() {
3307+ cancel_guard.disarm();
3308+ }
3309+ result
3310+ });
3311+ let promise = promise_for(scope, id);
3312+ if let Some(request_id) = request_id {
3313+ if let Some(object) = promise.to_object(scope) {
3314+ let key = v8::String::new(scope, "__celldCancelId").unwrap();
3315+ let value = v8::String::new(scope, &request_id.to_string()).unwrap();
3316+ object.set(scope, key.into(), value.into());
3317+ }
3318+ }
3319+ rv.set(promise);
3320+}
3321+
3322+// --- Worker Loader: dynamic isolates for Code Mode ---
3323+// A running Worker creates a fresh isolate from code it supplies at runtime
3324+// and invokes it. The loaded isolate uses the same turn driver as every
3325+// stateless Worker, so an awaited operation holds no thread or isolate.
3326+
3327+// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total
3328+// module bytes, 1 MiB env. Messages match so the conformance cases pass.
3329+const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024;
3330+const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024;
3331+
3332+#[derive(Clone)]
3333+enum LoaderState {
3334+ Loading,
3335+ Ready(Arc<crate::pool::Slot>),
3336+ Failed(Arc<str>),
3337+}
3338+
3339+type LoaderRegistry = HashMap<u64, tokio::sync::watch::Receiver<LoaderState>>;
3340+static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new();
3341+static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1);
3342+
3343+fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> {
3344+ LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
3345+}
3346+
3347+fn loader_throw(scope: &mut v8::PinScope, message: &str) {
3348+ let message = v8::String::new(scope, message).unwrap();
3349+ let exception = v8::Exception::error(scope, message);
3350+ scope.throw_exception(exception);
3351+}
3352+
3353+async fn loaded_worker_slot(
3354+ mut state: tokio::sync::watch::Receiver<LoaderState>,
3355+) -> Result<Arc<crate::pool::Slot>, String> {
3356+ loop {
3357+ match state.borrow().clone() {
3358+ LoaderState::Ready(slot) => return Ok(slot),
3359+ LoaderState::Failed(error) => return Err(error.to_string()),
3360+ LoaderState::Loading => {}
3361+ }
3362+ state
3363+ .changed()
3364+ .await
3365+ .map_err(|_| "worker loader: load task dropped".to_string())?;
3366+ }
3367+}
3368+
3369+/// `__loader_load(codeJson)` -> stub id. Builds a WorkerConfig from the
3370+/// supplied modules and registers its asynchronous load state. Compilation
3371+/// runs on Tokio's blocking pool. Calls wait for that result and then use the
3372+/// normal stateless turn driver.
3373+fn op_loader_load(
3374+ scope: &mut v8::PinScope,
3375+ args: v8::FunctionCallbackArguments,
3376+ mut rv: v8::ReturnValue<v8::Value>,
3377+) {
3378+ let code_json = args.get(0).to_rust_string_lossy(scope);
3379+ let code: serde_json::Value = match serde_json::from_str(&code_json) {
3380+ Ok(code) => code,
3381+ Err(e) => return loader_throw(scope, &format!("worker loader: {e}")),
3382+ };
3383+ let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else {
3384+ return loader_throw(scope, "worker loader: missing mainModule");
3385+ };
3386+ let Some(src) = code
3387+ .get("modules")
3388+ .and_then(|m| m.get(main))
3389+ .and_then(|v| v.as_str())
3390+ .map(str::to_string)
3391+ else {
3392+ return loader_throw(
3393+ scope,
3394+ &format!("worker loader: module {main:?} missing or not a string"),
3395+ );
3396+ };
3397+ // Every module other than the main one is a sibling the main module may
3398+ // import. JS modules arrive in the JSON as strings; anything else there is
3399+ // rejected — JSON.stringify would already have mangled it, and dropping it
3400+ // silently leaves the loaded worker failing instantiation with an
3401+ // unresolved specifier that never names the cause. Wasm modules arrive
3402+ // out of band as the second argument, an array of `[name, Uint8Array]`
3403+ // pairs, which keeps the blobs out of the JSON payload entirely.
3404+ let mut modules: Vec<(String, ModuleSource)> = Vec::new();
3405+ if let Some(map) = code.get("modules").and_then(|m| m.as_object()) {
3406+ for (name, value) in map.iter().filter(|(name, _)| name.as_str() != main) {
3407+ let Some(source) = value.as_str() else {
3408+ return loader_throw(
3409+ scope,
3410+ &format!("worker loader: module {name:?} must be a string or wasm bytes"),
3411+ );
3412+ };
3413+ modules.push((name.clone(), ModuleSource::EsModule(source.to_string())));
3414+ }
3415+ }
3416+ let sideband = args.get(1);
3417+ if !sideband.is_undefined() {
3418+ let Ok(entries) = v8::Local::<v8::Array>::try_from(sideband) else {
3419+ return loader_throw(scope, "worker loader: wasm modules must be an array");
3420+ };
3421+ for index in 0..entries.length() {
3422+ let entry = entries
3423+ .get_index(scope, index)
3424+ .and_then(|entry| v8::Local::<v8::Array>::try_from(entry).ok())
3425+ .and_then(|pair| Some((pair.get_index(scope, 0)?, pair.get_index(scope, 1)?)))
3426+ .filter(|(name, _)| name.is_string())
3427+ .and_then(|(name, value)| {
3428+ let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
3429+ Some((name.to_rust_string_lossy(scope), view))
3430+ });
3431+ let Some((name, view)) = entry else {
3432+ return loader_throw(scope, "worker loader: malformed wasm module entry");
3433+ };
3434+ // A name carried by both the JSON map and the side-band would
3435+ // silently shadow one module with the other in the registry;
3436+ // refuse it the way a non-string JSON module is refused.
3437+ if name == main || modules.iter().any(|(existing, _)| *existing == name) {
3438+ return loader_throw(
3439+ scope,
3440+ &format!("worker loader: duplicate module name {name:?}"),
3441+ );
3442+ }
3443+ let mut bytes = vec![0u8; view.byte_length()];
3444+ view.copy_contents(&mut bytes);
3445+ modules.push((name, ModuleSource::Wasm(bytes.into())));
3446+ }
3447+ }
3448+ // Total module bytes, checked before compiling anything (the oversized
3449+ // module is never parsed) — the extra modules are not yet loaded but do
3450+ // count against the ceiling, as upstream.
3451+ let code_size: usize = src.len()
3452+ + modules
3453+ .iter()
3454+ .map(|(_, source)| match source {
3455+ ModuleSource::Text(source) | ModuleSource::EsModule(source) => source.len(),
3456+ ModuleSource::Wasm(bytes) => bytes.len(),
3457+ })
3458+ .sum::<usize>();
3459+ if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE {
3460+ return loader_throw(
3461+ scope,
3462+ &format!(
3463+ "Dynamic Worker code size ({code_size} bytes) exceeds the \
3464+ maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes."
3465+ ),
3466+ );
3467+ }
3468+ // Plain JSON `env` values merge onto the loaded worker's env; capability
3469+ // stubs are not yet supported and would fail to serialize upstream in JS.
3470+ let loader_env = code
3471+ .get("env")
3472+ .filter(|v| !v.is_null())
3473+ .map(|v| v.to_string());
3474+ if let Some(env) = &loader_env {
3475+ if env.len() > MAX_DYNAMIC_WORKER_ENV_SIZE {
3476+ return loader_throw(
3477+ scope,
3478+ &format!(
3479+ "Dynamic Worker env size ({} bytes) exceeds the maximum \
3480+ allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.",
3481+ env.len()
3482+ ),
3483+ );
3484+ }
3485+ }
3486+ // globalOutbound: absent inherits the caller's authority, null denies
3487+ // ambient egress, a Fetcher (broker) is not implemented yet.
3488+ let egress = match code.get("globalOutbound") {
3489+ None => actor_runtime_state(scope).egress,
3490+ Some(v) if v.is_null() => EgressPolicy::Deny,
3491+ Some(_) => {
3492+ return loader_throw(
3493+ scope,
3494+ "worker loader: globalOutbound broker is not implemented yet",
3495+ );
3496+ }
3497+ };
3498+ // Bound live loaded workers so a runaway agent loop cannot exhaust
3499+ // isolates. Evicted workers (dropped stubs) free their slot.
3500+ let max = crate::env_vars::positive_or("CELLD_MAX_LOADED_WORKERS", 256)
3501+ .expect("validated CELLD_MAX_LOADED_WORKERS");
3502+ if loader_registry().lock().unwrap().len() >= max {
3503+ return loader_throw(
3504+ scope,
3505+ &format!("worker loader: too many loaded workers (limit {max})"),
3506+ );
3507+ }
3508+ // Honor the WorkerCode's declared compatibility (workerd worker_compat
3509+ // reads snake_case keys); Code Mode workers keep RPC on regardless.
3510+ let mut compat = crate::worker_compat(&serde_json::json!({
3511+ "compatibility_date": code.get("compatibilityDate"),
3512+ "compatibility_flags": code.get("compatibilityFlags"),
3513+ }));
3514+ compat.js_rpc = true;
3515+ let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed);
3516+ let config = Arc::new(
3517+ WorkerConfig::new(WorkerConfigOptions {
3518+ src,
3519+ script_name: format!("__loader:{id}"),
3520+ do_classes: Vec::new(),
3521+ bindings: Vec::new(),
3522+ r2_bindings: Vec::new(),
3523+ ai_binding: None,
3524+ vars: Vec::new(),
3525+ node: String::new(),
3526+ modules,
3527+ compat,
3528+ })
3529+ .with_egress(egress)
3530+ .with_loader_env(loader_env),
3531+ );
3532+ let handle = match tokio::runtime::Handle::try_current() {
3533+ Ok(handle) => handle,
3534+ Err(error) => return loader_throw(scope, &format!("worker loader: {error}")),
3535+ };
3536+ let (loaded, state) = tokio::sync::watch::channel(LoaderState::Loading);
3537+ loader_registry().lock().unwrap().insert(id, state);
3538+ handle.spawn(async move {
3539+ let state =
3540+ match tokio::task::spawn_blocking(move || Worker::load_config(config, &[])).await {
3541+ Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::standalone(worker)),
3542+ Ok(Err(error)) => LoaderState::Failed(Arc::from(format!("{error}"))),
3543+ Err(error) => LoaderState::Failed(Arc::from(format!(
3544+ "worker loader: load task failed: {error}"
3545+ ))),
3546+ };
3547+ loaded.send_replace(state);
3548+ });
3549+ rv.set(v8::Number::new(scope, id as f64).into());
3550+}
3551+
3552+/// `__loader_fetch(id, url, method, body, headersJson)` -> Promise<json>. The
3553+/// loaded-worker analog of `__svc_call`: encodes the response the same way.
3554+fn op_loader_fetch(
3555+ scope: &mut v8::PinScope,
3556+ args: v8::FunctionCallbackArguments,
3557+ mut rv: v8::ReturnValue<v8::Value>,
3558+) {
3559+ let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3560+ let url = args.get(1).to_rust_string_lossy(scope);
3561+ let method = args.get(2).to_rust_string_lossy(scope);
3562+ let body = view_bytes(args.get(3)).unwrap_or_default();
3563+ let headers =
3564+ serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default();
3565+ let loaded = loader_registry().lock().unwrap().get(&id).cloned();
3566+ let async_id = asyncrt::enqueue(async move {
3567+ let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?;
3568+ let slot = loaded_worker_slot(state).await?;
3569+ let (reply, receive) = tokio::sync::oneshot::channel();
3570+ let job = crate::WorkerJob::Fetch {
3571+ queued_at: Instant::now(),
3572+ url,
3573+ method,
3574+ body,
3575+ headers,
3576+ request_id: None,
3577+ reply,
3578+ };
3579+ let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
3580+ match receive.await {
3581+ Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3582+ Ok(Err(error)) => Err(format!("{error}")),
3583+ Err(_) => match driving.await {
3584+ Err(error) => Err(format!("loaded worker task died: {error}")),
3585+ Ok(()) => Err("loaded worker dropped response".to_string()),
3586+ },
3587+ }
3588+ });
3589+ rv.set(promise_for(scope, async_id));
3590+}
3591+
3592+/// `__loader_rpc(id, entrypoint, method, argsSc)` -> Promise<Uint8Array>. The
3593+/// loaded-worker analog of `__svc_rpc`: a named-entrypoint method call whose
3594+/// args and result are V8 structured-clone bytes.
3595+fn op_loader_rpc(
3596+ scope: &mut v8::PinScope,
3597+ args: v8::FunctionCallbackArguments,
3598+ mut rv: v8::ReturnValue<v8::Value>,
3599+) {
3600+ let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3601+ let entrypoint = args.get(1).to_rust_string_lossy(scope);
3602+ let method = args.get(2).to_rust_string_lossy(scope);
3603+ let call_args = view_bytes(args.get(3)).unwrap_or_default();
3604+ let loaded = loader_registry().lock().unwrap().get(&id).cloned();
3605+ let async_id = asyncrt::enqueue(async move {
3606+ let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?;
3607+ let slot = loaded_worker_slot(state).await?;
3608+ let (reply, receive) = tokio::sync::oneshot::channel();
3609+ let job = crate::WorkerJob::Rpc {
3610+ entrypoint,
3611+ method,
3612+ args: call_args,
3613+ reply,
3614+ };
3615+ let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
3616+ match receive.await {
3617+ Ok(Ok(result)) => Ok(result),
3618+ Ok(Err(error)) => Err(format!("{error}")),
3619+ Err(_) => match driving.await {
3620+ Err(error) => Err(format!("loaded worker task died: {error}")),
3621+ Ok(()) => Err("loaded worker dropped RPC result".to_string()),
3622+ },
3623+ }
3624+ });
3625+ rv.set(promise_for(scope, async_id));
3626+}
3627+
3628+/// `__loader_drop(id)` — evict a loaded worker. Called from a
3629+/// FinalizationRegistry when its stub is GC'd. Removing the registry entry
3630+/// drops the isolate after any calls that already cloned its load state end.
3631+fn op_loader_drop(
3632+ scope: &mut v8::PinScope,
3633+ args: v8::FunctionCallbackArguments,
3634+ _rv: v8::ReturnValue<v8::Value>,
3635+) {
3636+ let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3637+ if let Some(state) = loader_registry().lock().unwrap().remove(&id) {
3638+ // This op runs while the parent isolate is entered. The load state can
3639+ // own the loaded isolate, and V8 forbids dropping one isolate while a
3640+ // different isolate is entered on the same thread. Hand the final
3641+ // reference to the host scheduler so destruction happens after this
3642+ // turn has left V8.
3643+ asyncrt::op_handle().spawn(async move { drop(state) });
3644+ }
3645+}
3646+
3647+/// `__loader_count()` -> live loaded-worker count, for eviction tests.
3648+#[cfg(all(test, celld_internal_tests))]
3649+fn op_loader_count(
3650+ scope: &mut v8::PinScope,
3651+ _args: v8::FunctionCallbackArguments,
3652+ mut rv: v8::ReturnValue<v8::Value>,
3653+) {
3654+ let n = loader_registry().lock().unwrap().len();
3655+ rv.set(v8::Number::new(scope, n as f64).into());
3656+}
3657+
3658+/// `__writePosition(scope)` -> the cell's committed-write position (a number),
3659+/// or `null` when the scope has no open connection. The co-hosted DO fast path
3660+/// samples this around an inline `fetch` to tell a write from a read.
3661+fn op_write_position(
3662+ scope: &mut v8::PinScope,
3663+ args: v8::FunctionCallbackArguments,
3664+ mut rv: v8::ReturnValue<v8::Value>,
3665+) {
3666+ let cell = args.get(0).to_rust_string_lossy(scope);
3667+ match storage::write_position(&cell) {
3668+ Some(position) => rv.set(v8::Number::new(scope, position as f64).into()),
3669+ None => rv.set(v8::null(scope).into()),
3670+ }
3671+}
3672+
3673+/// `__gateWrite(scope, position)` -> a promise that resolves once the cell is
3674+/// durable and rejects if durability cannot be proved. The co-hosted DO fast
3675+/// path awaits this before returning an inline write's response, so the caller
3676+/// never observes a write the node cannot prove durable — the routed output
3677+/// gate, applied where the inline write actually happens.
3678+fn op_gate_write(
3679+ scope: &mut v8::PinScope,
3680+ args: v8::FunctionCallbackArguments,
3681+ mut rv: v8::ReturnValue<v8::Value>,
3682+) {
3683+ let cell = args.get(0).to_rust_string_lossy(scope);
3684+ let position = args
3685+ .get(1)
3686+ .to_integer(scope)
3687+ .map(|n| n.value() as u64)
3688+ .unwrap_or(0);
3689+ let (tx, receive) = tokio::sync::oneshot::channel();
3690+ let sent = GATE_TX
3691+ .get()
3692+ .map(|gate| {
3693+ gate.send(GateReq {
3694+ scope: cell,
3695+ position,
3696+ reply: tx,
3697+ })
3698+ .is_ok()
3699+ })
3700+ .unwrap_or(false);
3701+ let id = asyncrt::enqueue(async move {
3702+ if !sent {
3703+ return Err("no output-gate channel".into());
3704+ }
3705+ match receive.await {
3706+ Ok(Ok(())) => Ok(String::new()),
3707+ Ok(Err(error)) => Err(format!("{error:?}")),
3708+ Err(_) => Err("output gate dropped".into()),
3709+ }
3710+ });
3711+ rv.set(promise_for(scope, id));
3712+}
3713+
3714+fn op_do_call(
3715+ scope: &mut v8::PinScope,
3716+ args: v8::FunctionCallbackArguments,
3717+ mut rv: v8::ReturnValue<v8::Value>,
3718+) {
3719+ op_do_call_impl(scope, args, &mut rv, false);
3720+}
3721+
3722+fn op_do_call_cancellable(
3723+ scope: &mut v8::PinScope,
3724+ args: v8::FunctionCallbackArguments,
3725+ mut rv: v8::ReturnValue<v8::Value>,
3726+) {
3727+ op_do_call_impl(scope, args, &mut rv, true);
3728+}
3729+
3730+fn op_do_call_impl(
3731+ scope: &mut v8::PinScope,
3732+ args: v8::FunctionCallbackArguments,
3733+ rv: &mut v8::ReturnValue<v8::Value>,
3734+ cancellable: bool,
3735+) {
3736+ let cell = args.get(0).to_rust_string_lossy(scope);
3737+ let name_value = args.get(1);
3738+ let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
3739+ let url = args.get(2).to_rust_string_lossy(scope);
3740+ let method = args.get(3).to_rust_string_lossy(scope);
3741+ let body = view_bytes(args.get(4)).unwrap_or_default();
3742+ let headers =
3743+ serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)).unwrap_or_default();
3744+ let (tx, rx) = tokio::sync::oneshot::channel();
3745+ // Taken here and nowhere later: this is the last point that still runs
3746+ // in the order the script made the calls.
3747+ let order = Some(enter_call_order(current_context(), &cell));
3748+ // Every host op needs an internal cancellation channel. A caller without
3749+ // an AbortSignal cannot cancel from JavaScript, but its enclosing Worker
3750+ // can still disappear and drop this op before routing completes.
3751+ let request_id = next_do_request_id();
3752+ let (cancel_sender, cancel) = tokio::sync::oneshot::channel();
3753+ do_call_cancels()
3754+ .lock()
3755+ .unwrap()
3756+ .insert(request_id, cancel_sender);
3757+ let mut cancel_guard = DoCallCancelGuard::new(request_id);
3758+ let gate = egress_gate_pending();
3759+ let request = DoCallReq {
3760+ request_id: Some(request_id),
3761+ cancel: Some(cancel),
3762+ deliver_abort_to_handler: cancellable,
3763+ scope: cell,
3764+ name,
3765+ url,
3766+ method,
3767+ body,
3768+ headers,
3769+ reply: tx,
3770+ order,
3771+ parent: current_trace_ids(scope),
3772+ };
3773+ let id = asyncrt::enqueue(async move {
3774+ gated_channel_send(gate, &DO_CALL_TX, request, "no proxy channel").await?;
3775+ let result = match rx.await {
3776+ Ok(Ok(response)) => Ok(encode_http_response(response, true)),
3777+ Ok(Err(e)) => Err(format!("{e}")),
3778+ Err(e) => Err(format!("proxy dropped: {e}")),
3779+ };
3780+ cancel_guard.disarm();
3781+ result
3782+ });
3783+ let p = promise_for(scope, id);
3784+ if cancellable {
3785+ if let Some(promise) = p.to_object(scope) {
3786+ let key = v8::String::new(scope, "__celldCancelId").unwrap();
3787+ let request_id = v8::String::new(scope, &request_id_string(request_id)).unwrap();
3788+ promise.set(scope, key.into(), request_id.into());
3789+ }
3790+ }
3791+ rv.set(p);
3792+}
3793+
3794+fn op_do_call_cancel(
3795+ scope: &mut v8::PinScope,
3796+ args: v8::FunctionCallbackArguments,
3797+ _rv: v8::ReturnValue<v8::Value>,
3798+) {
3799+ let request_id = args.get(0).to_rust_string_lossy(scope);
3800+ let Some(request_id) = parse_request_id(&request_id) else {
3801+ return;
3802+ };
3803+ if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) {
3804+ let _ = cancel.send(());
3805+ }
3806+}
3807+
3808+/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>;
3809+/// arguments and result are V8 structured-clone bytes.
3810+fn op_rpc_call(
3811+ scope: &mut v8::PinScope,
3812+ args: v8::FunctionCallbackArguments,
3813+ mut rv: v8::ReturnValue<v8::Value>,
3814+) {
3815+ let cell = args.get(0).to_rust_string_lossy(scope);
3816+ let name_value = args.get(1);
3817+ let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
3818+ let method = args.get(2).to_rust_string_lossy(scope);
3819+ let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default());
3820+ let (tx, rx) = tokio::sync::oneshot::channel();
3821+ let gate = egress_gate_pending();
3822+ let request = RpcCallReq {
3823+ scope: cell,
3824+ name,
3825+ method,
3826+ args,
3827+ reply: tx,
3828+ };
3829+ let id = asyncrt::enqueue(async move {
3830+ gated_channel_send(gate, &RPC_CALL_TX, request, "no RPC channel").await?;
3831+ match rx.await {
3832+ Ok(Ok(RpcData::V8(bytes))) => Ok(bytes),
3833+ Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()),
3834+ Ok(Err(e)) => Err(format!("{e}")),
3835+ Err(e) => Err(format!("RPC proxy dropped: {e}")),
3836+ }
3837+ });
3838+ let p = promise_for(scope, id);
3839+ rv.set(p);
3840+}
3841+
3842+/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON
3843+/// `{status, body, headers}` string. Streaming is a later layer.
3844+fn op_fetch(
3845+ scope: &mut v8::PinScope,
3846+ args: v8::FunctionCallbackArguments,
3847+ mut rv: v8::ReturnValue<v8::Value>,
3848+) {
3849+ // A loaded worker with globalOutbound: null has no ambient egress: it must
3850+ // reach the world through `env` capabilities. Message matches workerd.
3851+ if actor_runtime_state(scope).egress == EgressPolicy::Deny {
3852+ return loader_throw(
3853+ scope,
3854+ "This worker is not permitted to access the internet via global \
3855+ functions like fetch(). It must use capabilities (such as \
3856+ bindings in 'env') to talk to the outside world.",
3857+ );
3858+ }
3859+ let method = args.get(0).to_rust_string_lossy(scope);
3860+ let url = args.get(1).to_rust_string_lossy(scope);
3861+ let b = args.get(2);
3862+ let body: Option<Vec<u8>> = if b.is_undefined() || b.is_null() {
3863+ None
3864+ } else {
3865+ serde_json::from_str(&b.to_rust_string_lossy(scope)).ok()
3866+ };
3867+ let mut headers: Vec<(String, String)> =
3868+ serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
3869+ let redirect = args.get(4).to_rust_string_lossy(scope);
3870+ let client = if redirect == "manual" {
3871+ HTTP_MANUAL.with(|client| client.clone())
3872+ } else {
3873+ HTTP.with(|client| client.clone())
3874+ };
3875+ // The creating context, read here while JS is still running: the op
3876+ // future resolves on whatever worker polls it, far from any CPED.
3877+ let trace = current_trace_ids(scope);
3878+ // The child's ids are minted before the request leaves so the
3879+ // traceparent header carries them: whatever this fetch reaches can
3880+ // join the trace celld is part of.
3881+ let child = trace.as_ref().map(crate::telemetry::child_ids);
3882+ if let Some(child) = child.as_ref() {
3883+ if !headers
3884+ .iter()
3885+ .any(|(name, _)| name.eq_ignore_ascii_case("traceparent"))
3886+ {
3887+ headers.push(("traceparent".into(), crate::telemetry::traceparent(child)));
3888+ }
3889+ }
3890+ let span_url = trace.as_ref().map(|_| url.clone());
3891+ // Whatever this handler has written must be durable before the request
3892+ // leaves: a third party that has acted on a write celld then loses cannot
3893+ // be told to un-act.
3894+ let gate = egress_gate_pending();
3895+ let id = asyncrt::enqueue(async move {
3896+ let span_started = trace.as_ref().map(|_| crate::telemetry::now_unix_us());
3897+ let mut span = trace.as_ref().zip(child).map(|(parent, child)| {
3898+ let mut span =
3899+ crate::telemetry::Span::new(child, "fetch", crate::telemetry::KIND_CLIENT);
3900+ span.parent_span_id = Some(parent.span_id);
3901+ span.parent_remote = Some(false);
3902+ span.url = span_url;
3903+ span
3904+ });
3905+ let mut finish = |ok: bool, status: Option<u16>, error: Option<String>| {
3906+ if let Some(mut span) = span.take() {
3907+ span.start_unix_us = span_started.unwrap_or_default();
3908+ span.duration_us = crate::telemetry::now_unix_us() - span.start_unix_us;
3909+ span.ok = ok;
3910+ span.http_status = status;
3911+ span.error = error;
3912+ crate::telemetry::record(span);
3913+ }
3914+ };
3915+ await_egress_gate(gate).await.inspect_err(|error| {
3916+ finish(false, None, Some(error.clone()));
3917+ })?;
3918+ let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET);
3919+ // a timeout bounds a black-hole host: the future settles (Err) instead
3920+ // of parking run_loop forever — the hang the Drop guard can't catch.
3921+ let fetch_timeout = crate::env_vars::positive_or("CELLD_FETCH_TIMEOUT_S", 120)
3922+ .expect("validated CELLD_FETCH_TIMEOUT_S");
3923+ let mut rb = client
3924+ .request(m, &url)
3925+ .timeout(std::time::Duration::from_secs(fetch_timeout));
3926+ for (name, value) in headers {
3927+ rb = rb.header(name, value);
3928+ }
3929+ if let Some(b) = body {
3930+ rb = rb.body(b);
3931+ }
3932+ match rb.send().await {
3933+ Ok(resp) => {
3934+ let status = resp.status().as_u16();
3935+ finish(true, Some(status), None);
3936+ let headers = resp
3937+ .headers()
3938+ .iter()
3939+ .map(|(name, value)| {
3940+ (
3941+ name.as_str().to_string(),
3942+ value.to_str().unwrap_or_default().to_string(),
3943+ )
3944+ })
3945+ .collect::<Vec<_>>();
3946+ let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3947+ register_http_stream(stream_id, HttpStreamSource::Response(resp));
3948+ Ok(serde_json::json!({
3949+ "status": status, "streamId": stream_id, "headers": headers,
3950+ })
3951+ .to_string())
3952+ }
3953+ Err(e) => {
3954+ finish(false, None, Some(format!("fetch: {e}")));
3955+ Err(format!("fetch: {e}"))
3956+ }
3957+ }
3958+ });
3959+ let p = promise_for(scope, id);
3960+ rv.set(p);
3961+}
3962+
3963+fn op_asset_fetch(
3964+ scope: &mut v8::PinScope,
3965+ args: v8::FunctionCallbackArguments,
3966+ mut rv: v8::ReturnValue<v8::Value>,
3967+) {
3968+ let script = args.get(0).to_rust_string_lossy(scope);
3969+ let method = args.get(1).to_rust_string_lossy(scope);
3970+ let url = args.get(2).to_rust_string_lossy(scope);
3971+ let headers: Vec<(String, String)> =
3972+ serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
3973+ let (tx, rx) = tokio::sync::oneshot::channel();
3974+ let sent = ASSET_CALL_TX.get().is_some_and(|sender| {
3975+ sender
3976+ .send(AssetCallReq {
3977+ script,
3978+ url,
3979+ method,
3980+ headers,
3981+ reply: tx,
3982+ })
3983+ .is_ok()
3984+ });
3985+ let id = asyncrt::enqueue(async move {
3986+ if !sent {
3987+ return Err("no asset resolver channel".to_string());
3988+ }
3989+ match rx.await {
3990+ Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3991+ Ok(Err(error)) => Err(format!("asset fetch: {error}")),
3992+ Err(error) => Err(format!("asset resolver dropped: {error}")),
3993+ }
3994+ });
3995+ rv.set(promise_for(scope, id));
3996+}
3997+
3998+async fn next_http_stream_chunk(source: &mut HttpStreamSource) -> Result<Option<Vec<u8>>, String> {
3999+ match source {
4000+ HttpStreamSource::Response(response) => response
4001+ .chunk()
4002+ .await
4003+ .map(|chunk| chunk.map(|bytes| bytes.to_vec()))
4004+ .map_err(|error| format!("response stream: {error}")),
4005+ HttpStreamSource::Receiver(receiver) => match receiver.recv().await {
4006+ Some(Ok(bytes)) => Ok(Some(bytes)),
4007+ Some(Err(error)) => Err(error),
4008+ None => Ok(None),
4009+ },
4010+ HttpStreamSource::Stream(stream) => stream.next().await.transpose(),
4011+ }
4012+}
4013+
4014+/// Move a host response source into a directly-polled stream. No pump task is
4015+/// needed: the eventual HTTP or JS consumer supplies the backpressure.
4016+fn http_chunk_stream(source: HttpStreamSource) -> HttpChunkStream {
4017+ match source {
4018+ HttpStreamSource::Response(response) => Box::pin(response.bytes_stream().map(|chunk| {
4019+ chunk
4020+ .map(|bytes| bytes.to_vec())
4021+ .map_err(|error| format!("response stream: {error}"))
4022+ })),
4023+ HttpStreamSource::Receiver(receiver) => {
4024+ Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver))
4025+ }
4026+ HttpStreamSource::Stream(stream) => stream,
4027+ }
4028+}
4029+
4030+/// Host-native tee for an outbound response. Both branches are represented by
4031+/// stream IDs, so one can be returned through Axum while JS independently
4032+/// scans the other for observability or usage accounting.
4033+fn tee_http_stream(mut source: HttpStreamSource) -> (u64, u64) {
4034+ let (tx1, rx1) = tokio::sync::mpsc::channel(16);
4035+ let (tx2, rx2) = tokio::sync::mpsc::channel(16);
4036+ let id1 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
4037+ let id2 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
4038+ register_http_stream(id1, HttpStreamSource::Receiver(rx1));
4039+ register_http_stream(id2, HttpStreamSource::Receiver(rx2));
4040+ asyncrt::op_handle().spawn(async move {
4041+ loop {
4042+ match next_http_stream_chunk(&mut source).await {
4043+ Ok(Some(bytes)) => {
4044+ let first = tx1.send(Ok(bytes.clone())).await.is_ok();
4045+ let second = tx2.send(Ok(bytes)).await.is_ok();
4046+ if !first && !second {
4047+ break;
4048+ }
4049+ }
4050+ Ok(None) => break,
4051+ Err(error) => {
4052+ let _ = tx1.send(Err(error.clone())).await;
4053+ let _ = tx2.send(Err(error)).await;
4054+ break;
4055+ }
4056+ }
4057+ }
4058+ });
4059+ (id1, id2)
4060+}
4061+
4062+fn op_http_stream_read(
4063+ scope: &mut v8::PinScope,
4064+ args: v8::FunctionCallbackArguments,
4065+ mut rv: v8::ReturnValue<v8::Value>,
4066+) {
4067+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4068+ let source = http_streams()
4069+ .lock()
4070+ .unwrap()
4071+ .get_mut(&stream_id)
4072+ .and_then(|stream| {
4073+ stream
4074+ .source
4075+ .take()
4076+ .map(|source| (source, stream.cancelled.subscribe()))
4077+ });
4078+ let id = asyncrt::enqueue(async move {
4079+ let Some((mut source, mut cancelled)) = source else {
4080+ return Ok(serde_json::json!({ "done": true }).to_string());
4081+ };
4082+ let next = tokio::select! {
4083+ result = next_http_stream_chunk(&mut source) => Some(result),
4084+ _ = cancelled.changed() => None,
4085+ };
4086+ match next {
4087+ None => Ok(serde_json::json!({ "done": true }).to_string()),
4088+ Some(Ok(Some(bytes))) => {
4089+ if let Some(stream) = http_streams().lock().unwrap().get_mut(&stream_id) {
4090+ stream.created = Instant::now();
4091+ stream.source = Some(source);
4092+ }
4093+ Ok(serde_json::json!({ "done": false, "bytes": bytes }).to_string())
4094+ }
4095+ Some(Ok(None)) => {
4096+ http_streams().lock().unwrap().remove(&stream_id);
4097+ Ok(serde_json::json!({ "done": true }).to_string())
4098+ }
4099+ Some(Err(error)) => {
4100+ http_streams().lock().unwrap().remove(&stream_id);
4101+ Err(error)
4102+ }
4103+ }
4104+ });
4105+ rv.set(promise_for(scope, id));
4106+}
4107+
4108+fn op_http_stream_tee(
4109+ scope: &mut v8::PinScope,
4110+ args: v8::FunctionCallbackArguments,
4111+ mut rv: v8::ReturnValue<v8::Value>,
4112+) {
4113+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4114+ let source = http_streams()
4115+ .lock()
4116+ .unwrap()
4117+ .remove(&stream_id)
4118+ .and_then(|stream| stream.source);
4119+ let Some(source) = source else {
4120+ let message = v8::String::new(scope, "response stream is no longer available").unwrap();
4121+ let exception = v8::Exception::type_error(scope, message);
4122+ scope.throw_exception(exception);
4123+ return;
4124+ };
4125+ let ids = tee_http_stream(source);
4126+ let json = serde_json::to_string(&ids).unwrap();
4127+ rv.set(v8::String::new(scope, &json).unwrap().into());
4128+}
4129+
4130+fn op_http_stream_cancel(
4131+ scope: &mut v8::PinScope,
4132+ args: v8::FunctionCallbackArguments,
4133+ _rv: v8::ReturnValue<v8::Value>,
4134+) {
4135+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4136+ if let Some(stream) = http_streams().lock().unwrap().remove(&stream_id) {
4137+ let _ = stream.cancelled.send(true);
4138+ }
4139+}
4140+
4141+fn op_response_stream_create(
4142+ scope: &mut v8::PinScope,
4143+ _args: v8::FunctionCallbackArguments,
4144+ mut rv: v8::ReturnValue<v8::Value>,
4145+) {
4146+ let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
4147+ let (writer, receiver) = tokio::sync::mpsc::channel(1);
4148+ let (finished, _) = tokio::sync::watch::channel(false);
4149+ let now = Instant::now();
4150+ register_http_stream(stream_id, HttpStreamSource::Receiver(receiver));
4151+ let mut writers = response_stream_writers().lock().unwrap();
4152+ writers.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60));
4153+ writers.insert(
4154+ stream_id,
4155+ ResponseStreamWriter {
4156+ created: now,
4157+ writer,
4158+ finished,
4159+ },
4160+ );
4161+ rv.set(v8::Number::new(scope, stream_id as f64).into());
4162+}
4163+
4164+fn op_response_stream_write(
4165+ scope: &mut v8::PinScope,
4166+ args: v8::FunctionCallbackArguments,
4167+ mut rv: v8::ReturnValue<v8::Value>,
4168+) {
4169+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4170+ let bytes = args
4171+ .get(1)
4172+ .try_cast::<v8::ArrayBufferView>()
4173+ .ok()
4174+ .map(|view| {
4175+ let mut bytes = vec![0; view.byte_length()];
4176+ view.copy_contents(&mut bytes);
4177+ bytes
4178+ });
4179+ let writer = response_stream_writers()
4180+ .lock()
4181+ .unwrap()
4182+ .get_mut(&stream_id)
4183+ .map(|stream| {
4184+ stream.created = Instant::now();
4185+ stream.writer.clone()
4186+ });
4187+ let id = asyncrt::enqueue(async move {
4188+ let Some(bytes) = bytes else {
4189+ return Err("response stream chunks must be ArrayBuffer views".into());
4190+ };
4191+ let Some(writer) = writer else {
4192+ return Err("response stream consumer canceled".into());
4193+ };
4194+ if writer.send(Ok(bytes)).await.is_err() {
4195+ response_stream_writers().lock().unwrap().remove(&stream_id);
4196+ return Err("response stream consumer canceled".into());
4197+ }
4198+ Ok(String::new())
4199+ });
4200+ rv.set(promise_for(scope, id));
4201+}
4202+
4203+fn op_response_stream_closed(
4204+ scope: &mut v8::PinScope,
4205+ args: v8::FunctionCallbackArguments,
4206+ mut rv: v8::ReturnValue<v8::Value>,
4207+) {
4208+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4209+ let (writer, mut finished) = response_stream_writers()
4210+ .lock()
4211+ .unwrap()
4212+ .get(&stream_id)
4213+ .map(|stream| (stream.writer.clone(), stream.finished.subscribe()))
4214+ .unzip();
4215+ let id = asyncrt::enqueue(async move {
4216+ let cancelled = match (writer, finished.as_mut()) {
4217+ (Some(writer), Some(finished)) => tokio::select! {
4218+ biased;
4219+ result = finished.changed() => result.is_err(),
4220+ _ = writer.closed() => true,
4221+ },
4222+ _ => false,
4223+ };
4224+ Ok(String::from(if cancelled {
4225+ "cancelled"
4226+ } else {
4227+ "finished"
4228+ }))
4229+ });
4230+ rv.set(promise_for(scope, id));
4231+}
4232+
4233+fn op_response_stream_close(
4234+ scope: &mut v8::PinScope,
4235+ args: v8::FunctionCallbackArguments,
4236+ mut rv: v8::ReturnValue<v8::Value>,
4237+) {
4238+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4239+ let error = args.get(1).to_rust_string_lossy(scope);
4240+ let stream = response_stream_writers().lock().unwrap().remove(&stream_id);
4241+ let id = asyncrt::enqueue(async move {
4242+ if let Some(stream) = stream {
4243+ let _ = stream.finished.send(true);
4244+ if !error.is_empty() {
4245+ let _ = stream.writer.send(Err(error)).await;
4246+ }
4247+ }
4248+ Ok(String::new())
4249+ });
4250+ rv.set(promise_for(scope, id));
4251+}
4252+
4253+pub fn reqwest_response_stream(response: reqwest::Response) -> HttpChunkStream {
4254+ http_chunk_stream(HttpStreamSource::Response(response))
4255+}
4256+
4257+/// Timer op behind `setTimeout`: a promise resolving after `ms`.
4258+fn op_timer(
4259+ scope: &mut v8::PinScope,
4260+ args: v8::FunctionCallbackArguments,
4261+ mut rv: v8::ReturnValue<v8::Value>,
4262+) {
4263+ let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4264+ let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64;
4265+ let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
4266+ timer_cancels().lock().unwrap().insert(timer_id, cancel_tx);
4267+ let id = asyncrt::enqueue(async move {
4268+ tokio::select! {
4269+ _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {}
4270+ _ = &mut cancel_rx => {}
4271+ }
4272+ timer_cancels().lock().unwrap().remove(&timer_id);
4273+ Ok(String::new())
4274+ });
4275+ let p = promise_for(scope, id);
4276+ rv.set(p);
4277+}
4278+
4279+/// `__gate_acquire(scope)` — take the cell's input gate for a
4280+/// `blockConcurrencyWhile`, waiting if another block holds it.
4281+///
4282+/// Answers a promise of the event id, not the id itself. It was synchronous,
4283+/// and that was right while a cell's events came off one channel: only one
4284+/// ran at a time, a delivery point had already found the gate open, and
4285+/// yielding even one microtask reopened a window in which a nested delivery
4286+/// could wait on a gate nothing would release. Neither half holds now —
4287+/// events are independent tasks, several run at once, and nothing nests —
4288+/// so two blocks can meet and the second must queue.
4289+fn op_gate_acquire(
4290+ scope: &mut v8::PinScope,
4291+ args: v8::FunctionCallbackArguments,
4292+ mut rv: v8::ReturnValue<v8::Value>,
4293+) {
4294+ let cell = args.get(0).to_rust_string_lossy(scope);
4295+ let event = NEXT_GATE_EVENT.fetch_add(1, Ordering::Relaxed);
4296+ // Taken under the gates lock so the test and the take are one step: a
4297+ // release landing between them would leave this block queued behind a
4298+ // gate that is already open.
4299+ let taken = cell_gates()
4300+ .lock()
4301+ .unwrap()
4302+ .entry(cell.clone())
4303+ .or_default()
4304+ .acquire(event);
4305+ if taken {
4306+ let id = asyncrt::enqueue(async move { Ok(event.to_string()) });
4307+ rv.set(promise_for(scope, id));
4308+ return;
4309+ }
4310+ let id = asyncrt::enqueue(async move {
4311+ loop {
4312+ // Ask for a ticket first: `cell_gate_wait` tests and enqueues
4313+ // under the gates lock, so a release landing between the two
4314+ // cannot leave this waiter behind an open gate.
4315+ let waiting = cell_gate_wait(&cell);
4316+ let taken = cell_gates()
4317+ .lock()
4318+ .unwrap()
4319+ .entry(cell.clone())
4320+ .or_default()
4321+ .acquire(event);
4322+ if taken {
4323+ return Ok(event.to_string());
4324+ }
4325+ match waiting {
4326+ Some(open) => match open.await {
4327+ Ok(Ok(())) => {}
4328+ // The block ahead of this one failed and reset the cell,
4329+ // so this block has nothing left to guard.
4330+ Ok(Err(failure)) => return Err(failure),
4331+ Err(_) => {
4332+ return Err("cell stopped while waiting for its input gate".to_string())
4333+ }
4334+ },
4335+ // The gate was open when we asked and shut before we took
4336+ // it: another block won the race. Yield rather than spin —
4337+ // this runs on a tokio worker, and a bare `continue` here
4338+ // starved the runtime.
4339+ None => tokio::task::yield_now().await,
4340+ }
4341+ }
4342+ });
4343+ rv.set(promise_for(scope, id));
4344+}
4345+
4346+/// `__gate_wait(scope)` — settle when the cell's input gate is open.
4347+///
4348+/// The gate's other side. `op_gate_acquire` is for something that wants to
4349+/// *hold* the gate; this is for something that only has to arrive after it,
4350+/// which is every event the gate exists to hold back. A drive does this in
4351+/// Rust before it begins a turn; an RPC stub op does it here, because it is
4352+/// dispatched inside the isolate and never becomes a drive.
4353+///
4354+/// Rejecting matters as much as resolving: a critical section that failed
4355+/// reset the cell, so what waited behind it is refused with the reason
4356+/// rather than run against state that no longer exists.
4357+fn op_gate_wait(
4358+ scope: &mut v8::PinScope,
4359+ args: v8::FunctionCallbackArguments,
4360+ mut rv: v8::ReturnValue<v8::Value>,
4361+) {
4362+ let cell = args.get(0).to_rust_string_lossy(scope);
4363+ let id = asyncrt::enqueue(async move {
4364+ loop {
4365+ match cell_gate_wait(&cell) {
4366+ None => return Ok(String::new()),
4367+ Some(open) => match open.await {
4368+ Ok(Ok(())) => {}
4369+ Ok(Err(failure)) => return Err(failure),
4370+ Err(_) => {
4371+ return Err("cell stopped while waiting for its input gate".to_string())
4372+ }
4373+ },
4374+ }
4375+ }
4376+ });
4377+ rv.set(promise_for(scope, id));
4378+}
4379+
4380+/// `__gate_release(scope, event)` — the block is over. The next delivery
4381+/// point to run takes whatever queued behind it.
4382+fn op_gate_release(
4383+ scope: &mut v8::PinScope,
4384+ args: v8::FunctionCallbackArguments,
4385+ _rv: v8::ReturnValue<v8::Value>,
4386+) {
4387+ let cell = args.get(0).to_rust_string_lossy(scope);
4388+ let event = args.get(1).number_value(scope).unwrap_or_default() as celld_logic::gate::EventId;
4389+ // A third argument means the block failed and the actor was reset, so
4390+ // what queued behind it is refused with that reason rather than
4391+ // delivered to a cell whose state is gone.
4392+ let failure = args.get(2);
4393+ let outcome = if failure.is_null_or_undefined() {
4394+ Ok(())
4395+ } else {
4396+ Err(failure.to_rust_string_lossy(scope))
4397+ };
4398+ if let Some(gate) = cell_gates().lock().unwrap().get_mut(&cell) {
4399+ gate.release(event);
4400+ }
4401+ wake_gate_waiters(&cell, outcome);
4402+}
4403+
4404+fn op_timer_alloc(
4405+ scope: &mut v8::PinScope,
4406+ _args: v8::FunctionCallbackArguments,
4407+ mut rv: v8::ReturnValue<v8::Value>,
4408+) {
4409+ let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64);
4410+ rv.set(id.into());
4411+}
4412+
4413+fn op_timer_cancel(
4414+ scope: &mut v8::PinScope,
4415+ args: v8::FunctionCallbackArguments,
4416+ _rv: v8::ReturnValue<v8::Value>,
4417+) {
4418+ let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4419+ if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) {
4420+ let _ = cancel.send(());
4421+ }
4422+}
4423+
4424+fn durable_object_id_key(namespace_key: &str) -> [u8; 32] {
4425+ DO_ID_KEYS.with(|keys| {
4426+ if let Some(key) = keys.borrow().get(namespace_key) {
4427+ return *key;
4428+ }
4429+ use sha2::Digest;
4430+ let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into();
4431+ keys.borrow_mut().insert(namespace_key.to_string(), key);
4432+ key
4433+ })
4434+}
4435+
4436+fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> {
4437+ use hmac::Mac;
4438+ let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key)
4439+ .expect("SHA-256 accepts any HMAC key");
4440+ mac.update(input);
4441+ mac
4442+}
4443+
4444+/// Ids already derived on this thread, keyed by namespace and name.
4445+///
4446+/// `getByName` costs two HMAC-SHA256 rounds, and a profile of `/c/hello`
4447+/// found them among the largest terms the stateless path does not have —
4448+/// the same name resolving to the same id, recomputed on every request.
4449+///
4450+/// Per thread and unsynchronised, which is sound because the derivation is
4451+/// a pure function of its inputs: a worker that has not seen a name pays
4452+/// for it once, and no answer can differ between threads. Bounded because
4453+/// names come from the application, and cleared wholesale at the cap rather
4454+/// than evicted one at a time — a cache this cheap to refill does not earn
4455+/// an LRU.
4456+const DO_ID_CACHE_MAX: usize = 4096;
4457+
4458+fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] {
4459+ use hmac::Mac;
4460+
4461+ thread_local! {
4462+ static IDS: RefCell<HashMap<(String, String), [u8; 32]>> =
4463+ RefCell::new(HashMap::new());
4464+ }
4465+ let cached = IDS.with(|ids| {
4466+ ids.borrow()
4467+ .get(&(namespace_key.to_string(), name.to_string()))
4468+ .copied()
4469+ });
4470+ if let Some(id) = cached {
4471+ return id;
4472+ }
4473+
4474+ let key = durable_object_id_key(namespace_key);
4475+ let mut id = [0_u8; 32];
4476+ let digest = durable_object_id_hmac(&key, name.as_bytes())
4477+ .finalize()
4478+ .into_bytes();
4479+ id[..16].copy_from_slice(&digest[..16]);
4480+ let digest = durable_object_id_hmac(&key, &id[..16])
4481+ .finalize()
4482+ .into_bytes();
4483+ id[16..].copy_from_slice(&digest[..16]);
4484+
4485+ IDS.with(|ids| {
4486+ let mut ids = ids.borrow_mut();
4487+ if ids.len() >= DO_ID_CACHE_MAX {
4488+ ids.clear();
4489+ }
4490+ ids.insert((namespace_key.to_string(), name.to_string()), id);
4491+ });
4492+ id
4493+}
4494+
4495+fn durable_object_id_hex(bytes: &[u8; 32]) -> String {
4496+ const HEX: &[u8; 16] = b"0123456789abcdef";
4497+ let mut output = String::with_capacity(64);
4498+ for byte in bytes {
4499+ output.push(HEX[(byte >> 4) as usize] as char);
4500+ output.push(HEX[(byte & 0x0f) as usize] as char);
4501+ }
4502+ output
4503+}
4504+
4505+fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> {
4506+ if value.len() != 64 {
4507+ return None;
4508+ }
4509+ let mut output = [0_u8; 32];
4510+ for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
4511+ let nibble = |byte| match byte {
4512+ b'0'..=b'9' => Some(byte - b'0'),
4513+ b'a'..=b'f' => Some(byte - b'a' + 10),
4514+ b'A'..=b'F' => Some(byte - b'A' + 10),
4515+ _ => None,
4516+ };
4517+ output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
4518+ }
4519+ Some(output)
4520+}
4521+
4522+fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) {
4523+ let message = v8::String::new(scope, message).unwrap();
4524+ let exception = v8::Exception::type_error(scope, message);
4525+ scope.throw_exception(exception);
4526+}
4527+
4528+fn register_actor_name(
4529+ scope: &mut v8::PinScope,
4530+ actor_scope: &str,
4531+ name: Option<&str>,
4532+) -> Result<()> {
4533+ let Some(name) = name else {
4534+ return Ok(());
4535+ };
4536+ let context = scope.get_current_context();
4537+ let global = context.global(scope);
4538+ let cell_key = v8::String::new(scope, "__cell").unwrap();
4539+ let cell = global
4540+ .get(scope, cell_key.into())
4541+ .and_then(|value| value.to_object(scope))
4542+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
4543+ let names_key = v8::String::new(scope, "idNames").unwrap();
4544+ let names = cell
4545+ .get(scope, names_key.into())
4546+ .and_then(|value| value.to_object(scope))
4547+ .ok_or_else(|| anyhow!("missing Durable Object name registry"))?;
4548+ let actor_scope_key = v8::String::new(scope, actor_scope).unwrap();
4549+ if let Some(existing) = names.get(scope, actor_scope_key.into()) {
4550+ if !existing.is_undefined() {
4551+ if existing.to_rust_string_lossy(scope) == name {
4552+ return Ok(());
4553+ }
4554+ anyhow::bail!("actor name conflicts with active identity for {actor_scope}");
4555+ }
4556+ }
4557+
4558+ let (class_name, id) = actor_scope
4559+ .split_once(':')
4560+ .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?;
4561+ let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
4562+ let namespace_keys = cell
4563+ .get(scope, namespace_keys_key.into())
4564+ .and_then(|value| value.to_object(scope))
4565+ .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
4566+ let class_name_key = v8::String::new(scope, class_name).unwrap();
4567+ let namespace_key = namespace_keys
4568+ .get(scope, class_name_key.into())
4569+ .filter(|value| value.is_string())
4570+ .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))?
4571+ .to_rust_string_lossy(scope);
4572+ let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name));
4573+ if id != expected {
4574+ anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}");
4575+ }
4576+ storage::set_actor_name(actor_scope, name)?;
4577+
4578+ let name_value = v8::String::new(scope, name).unwrap();
4579+ if !names
4580+ .set(scope, actor_scope_key.into(), name_value.into())
4581+ .unwrap_or(false)
4582+ {
4583+ anyhow::bail!("could not register Durable Object name");
4584+ }
4585+ Ok(())
4586+}
4587+
4588+fn op_do_id(
4589+ scope: &mut v8::PinScope,
4590+ args: v8::FunctionCallbackArguments,
4591+ mut rv: v8::ReturnValue<v8::Value>,
4592+) {
4593+ use hmac::Mac;
4594+
4595+ let namespace_key = args.get(0).to_rust_string_lossy(scope);
4596+ let operation = args.get(1).to_rust_string_lossy(scope);
4597+ let input = args.get(2).to_rust_string_lossy(scope);
4598+ let key = durable_object_id_key(&namespace_key);
4599+ let mut id = [0_u8; 32];
4600+
4601+ match operation.as_str() {
4602+ "name" => {
4603+ id = durable_object_id_for_name(&namespace_key, &input);
4604+ rv.set(
4605+ v8::String::new(scope, &durable_object_id_hex(&id))
4606+ .unwrap()
4607+ .into(),
4608+ );
4609+ return;
4610+ }
4611+ "unique" => {
4612+ if getrandom::fill(&mut id[..16]).is_err() {
4613+ throw_durable_object_id_error(scope, "secure random generation failed");
4614+ return;
4615+ }
4616+ }
4617+ "validate" => {
4618+ let Some(decoded) = decode_durable_object_id(&input) else {
4619+ throw_durable_object_id_error(
4620+ scope,
4621+ "Invalid Durable Object ID: must be 64 hex digits",
4622+ );
4623+ return;
4624+ };
4625+ if durable_object_id_hmac(&key, &decoded[..16])
4626+ .verify_truncated_left(&decoded[16..])
4627+ .is_err()
4628+ {
4629+ throw_durable_object_id_error(
4630+ scope,
4631+ "Durable Object ID is not valid for this namespace",
4632+ );
4633+ return;
4634+ }
4635+ rv.set(
4636+ v8::String::new(scope, &input.to_ascii_lowercase())
4637+ .unwrap()
4638+ .into(),
4639+ );
4640+ return;
4641+ }
4642+ _ => {
4643+ throw_durable_object_id_error(scope, "unknown Durable Object ID operation");
4644+ return;
4645+ }
4646+ }
4647+
4648+ let digest = durable_object_id_hmac(&key, &id[..16])
4649+ .finalize()
4650+ .into_bytes();
4651+ id[16..].copy_from_slice(&digest[..16]);
4652+ rv.set(
4653+ v8::String::new(scope, &durable_object_id_hex(&id))
4654+ .unwrap()
4655+ .into(),
4656+ );
4657+}
4658+
4659+fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> {
4660+ let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
4661+ let mut bytes = vec![0_u8; view.byte_length()];
4662+ view.copy_contents(&mut bytes);
4663+ Some(bytes)
4664+}
4665+
4666+fn webcrypto_return_bytes(
4667+ scope: &mut v8::PinScope,
4668+ mut rv: v8::ReturnValue<v8::Value>,
4669+ bytes: &[u8],
4670+) {
4671+ let buffer = v8::ArrayBuffer::new(scope, bytes.len());
4672+ if !bytes.is_empty() {
4673+ let store = buffer.get_backing_store();
4674+ let destination = unsafe {
4675+ std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len())
4676+ };
4677+ destination.copy_from_slice(bytes);
4678+ }
4679+ let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap();
4680+ rv.set(view.into());
4681+}
4682+
4683+mod crypto;
4684+mod zlib;
4685+
4686+fn op_actor_abort(
4687+ scope: &mut v8::PinScope,
4688+ args: v8::FunctionCallbackArguments,
4689+ _rv: v8::ReturnValue<v8::Value>,
4690+) {
4691+ let cell = args.get(0).to_rust_string_lossy(scope);
4692+ let reason = args.get(1).to_rust_string_lossy(scope);
4693+ let state = actor_runtime_state(scope);
4694+ state
4695+ .pending_puts
4696+ .lock()
4697+ .expect("pending puts lock poisoned")
4698+ .remove(&cell);
4699+ *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
4700+ error: format!("__CELLD_ACTOR_ABORT__:{reason}"),
4701+ actor_scope: Some(cell),
4702+ });
4703+ scope.terminate_execution();
4704+}
4705+
4706+fn op_process_exit(
4707+ scope: &mut v8::PinScope,
4708+ args: v8::FunctionCallbackArguments,
4709+ _rv: v8::ReturnValue<v8::Value>,
4710+) {
4711+ let code = args.get(0).integer_value(scope).unwrap_or(0);
4712+ if current_context().depth() == 0 {
4713+ tracing::warn!(
4714+ code,
4715+ "process.exit called without an active request; ignoring"
4716+ );
4717+ return;
4718+ }
4719+ let actor_scope = args.get(1).to_rust_string_lossy(scope);
4720+ let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope);
4721+ let state = actor_runtime_state(scope);
4722+ if let Some(actor_scope) = actor_scope.as_deref() {
4723+ state
4724+ .pending_puts
4725+ .lock()
4726+ .expect("pending puts lock poisoned")
4727+ .remove(actor_scope);
4728+ }
4729+ *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
4730+ error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."),
4731+ actor_scope,
4732+ });
4733+ scope.terminate_execution();
4734+}
4735+
4736+fn op_log(
4737+ scope: &mut v8::PinScope,
4738+ args: v8::FunctionCallbackArguments,
4739+ _rv: v8::ReturnValue<v8::Value>,
4740+) {
4741+ let msg: Vec<String> = (0..args.length())
4742+ .map(|i| args.get(i).to_rust_string_lossy(scope))
4743+ .collect();
4744+ let body = msg.join(" ");
4745+ // Correlated by CPED, so a continuation logging after an await — or
4746+ // another entry's continuation running in this turn's checkpoint —
4747+ // lands on the trace that owns it, not on whoever holds the isolate.
4748+ if crate::telemetry::active() {
4749+ let ids = current_trace_ids(scope);
4750+ crate::telemetry::record_log(crate::telemetry::Log {
4751+ trace_id: ids.as_ref().map(|ids| ids.trace_id),
4752+ span_id: ids.as_ref().map(|ids| ids.span_id),
4753+ time_unix_us: crate::telemetry::now_unix_us(),
4754+ body: body.clone(),
4755+ });
4756+ }
4757+ tracing::info!(target: "cell_console", "{}", body);
4758+}
4759+fn op_heap_limit_excessively_exceeded(
4760+ scope: &mut v8::PinScope,
4761+ _args: v8::FunctionCallbackArguments,
4762+ mut rv: v8::ReturnValue<v8::Value>,
4763+) {
4764+ let exceeded = scope
4765+ .get_slot::<Arc<HeapLimitState>>()
4766+ .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed));
4767+ rv.set(v8::Boolean::new(scope, exceeded).into());
4768+}
4769+#[cfg(all(test, celld_internal_tests))]
4770+fn op_test_set_heap_limit_excessively_exceeded(
4771+ scope: &mut v8::PinScope,
4772+ args: v8::FunctionCallbackArguments,
4773+ _rv: v8::ReturnValue<v8::Value>,
4774+) {
4775+ if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
4776+ state
4777+ .excessively_exceeded
4778+ .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
4779+ }
4780+}
4781+#[cfg(all(test, celld_internal_tests))]
4782+fn op_test_gc(
4783+ scope: &mut v8::PinScope,
4784+ _args: v8::FunctionCallbackArguments,
4785+ _rv: v8::ReturnValue<v8::Value>,
4786+) {
4787+ scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full);
4788+}
4789+mod storage_ops;
4790+use storage_ops::{actor_runtime_state, throw_storage_error};
4791+
4792+/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href}
4793+/// Backed by the WHATWG-conformant `url` crate.
4794+fn op_url_parse(
4795+ scope: &mut v8::PinScope,
4796+ args: v8::FunctionCallbackArguments,
4797+ mut rv: v8::ReturnValue<v8::Value>,
4798+) {
4799+ let input = args.get(0).to_rust_string_lossy(scope);
4800+ let base = args.get(1);
4801+ let parsed = if base.is_undefined() {
4802+ url::Url::parse(&input)
4803+ } else {
4804+ url::Url::options()
4805+ .base_url(
4806+ url::Url::parse(&base.to_rust_string_lossy(scope))
4807+ .ok()
4808+ .as_ref(),
4809+ )
4810+ .parse(&input)
4811+ };
4812+ let u = match parsed {
4813+ Ok(u) => u,
4814+ Err(e) => {
4815+ let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap();
4816+ let exc = v8::Exception::type_error(scope, msg);
4817+ scope.throw_exception(exc);
4818+ return;
4819+ }
4820+ };
4821+ let o = v8::Object::new(scope);
4822+ let set = |k: &str, v: &str| {
4823+ let key = v8::String::new(scope, k).unwrap();
4824+ let val = v8::String::new(scope, v).unwrap();
4825+ o.set(scope, key.into(), val.into());
4826+ };
4827+ set("protocol", u.scheme());
4828+ set("username", u.username());
4829+ set("password", u.password().unwrap_or(""));
4830+ set("host", u.host_str().unwrap_or(""));
4831+ set("port", &u.port().map(|p| p.to_string()).unwrap_or_default());
4832+ set("pathname", u.path());
4833+ set("search", u.query().unwrap_or(""));
4834+ set("hash", u.fragment().unwrap_or(""));
4835+ set("href", u.as_str());
4836+ rv.set(o.into());
4837+}
4838+
4839+// URLPattern host seam, split like Deno's: pattern parsing and match-input
4840+// canonicalization run in Rust via the `urlpattern` crate; per-match regex
4841+// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the
4842+// boundary — both ops run at construct/match-canonicalize time only.
4843+
4844+/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a
4845+/// pattern string or an init object of string components. Returns
4846+/// per-component `{ patternString, regexpString, groupNameList }` plus
4847+/// `hasRegexpGroups`. Throws TypeError on an invalid pattern.
4848+fn op_urlpattern_parse(
4849+ scope: &mut v8::PinScope,
4850+ args: v8::FunctionCallbackArguments,
4851+ mut rv: v8::ReturnValue<v8::Value>,
4852+) {
4853+ use urlpattern::quirks;
4854+ let input = args.get(0).to_rust_string_lossy(scope);
4855+ let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
4856+ let base = args.get(1);
4857+ let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
4858+ let options = urlpattern::UrlPatternOptions {
4859+ ignore_case: args.get(2).boolean_value(scope),
4860+ };
4861+ let pattern = quirks::process_construct_pattern_input(input, base.as_deref())
4862+ .and_then(|init| quirks::parse_pattern(init, options));
4863+ let p = match pattern {
4864+ Ok(p) => p,
4865+ Err(e) => {
4866+ let msg = v8::String::new(scope, &e.to_string()).unwrap();
4867+ let exc = v8::Exception::type_error(scope, msg);
4868+ scope.throw_exception(exc);
4869+ return;
4870+ }
4871+ };
4872+ let component = |c: &quirks::UrlPatternComponent| {
4873+ serde_json::json!({
4874+ "patternString": c.pattern_string,
4875+ "regexpString": c.regexp_string,
4876+ "groupNameList": c.group_name_list,
4877+ })
4878+ };
4879+ let out = serde_json::json!({
4880+ "protocol": component(&p.protocol),
4881+ "username": component(&p.username),
4882+ "password": component(&p.password),
4883+ "hostname": component(&p.hostname),
4884+ "port": component(&p.port),
4885+ "pathname": component(&p.pathname),
4886+ "search": component(&p.search),
4887+ "hash": component(&p.hash),
4888+ "hasRegexpGroups": p.has_regexp_groups,
4889+ });
4890+ rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
4891+}
4892+
4893+/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in
4894+/// component order (protocol..hash), or `null` when the input does not parse
4895+/// as a URL. Throws TypeError for an init combined with a baseURL argument.
4896+fn op_urlpattern_match_input(
4897+ scope: &mut v8::PinScope,
4898+ args: v8::FunctionCallbackArguments,
4899+ mut rv: v8::ReturnValue<v8::Value>,
4900+) {
4901+ use urlpattern::quirks;
4902+ let input = args.get(0).to_rust_string_lossy(scope);
4903+ let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
4904+ let base = args.get(1);
4905+ let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
4906+ let null = v8::null(scope).into();
4907+ let m = match quirks::process_match_input(input, base.as_deref()) {
4908+ Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) {
4909+ Some(m) => m,
4910+ None => return rv.set(null),
4911+ },
4912+ Ok(None) => return rv.set(null),
4913+ Err(e) => {
4914+ let msg = v8::String::new(scope, &e.to_string()).unwrap();
4915+ let exc = v8::Exception::type_error(scope, msg);
4916+ scope.throw_exception(exc);
4917+ return;
4918+ }
4919+ };
4920+ let out = serde_json::json!([
4921+ m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash,
4922+ ]);
4923+ rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
4924+}
4925+
4926+fn op_atob(
4927+ scope: &mut v8::PinScope,
4928+ args: v8::FunctionCallbackArguments,
4929+ mut rv: v8::ReturnValue<v8::Value>,
4930+) {
4931+ use base64::Engine;
4932+ let input = args.get(0).to_rust_string_lossy(scope);
4933+ let cleaned: String = input.chars().filter(|c| !c.is_whitespace()).collect();
4934+ match base64::engine::general_purpose::STANDARD.decode(cleaned) {
4935+ Ok(bytes) => {
4936+ // atob returns a binary string (latin1)
4937+ let s: String = bytes.iter().map(|&b| b as char).collect();
4938+ rv.set(v8::String::new(scope, &s).unwrap().into());
4939+ }
4940+ Err(_) => {
4941+ let msg = v8::String::new(scope, "Invalid base64").unwrap();
4942+ let exc = v8::Exception::error(scope, msg);
4943+ scope.throw_exception(exc);
4944+ }
4945+ }
4946+}
4947+
4948+// node:util introspection seam: V8-level queries that JS cannot perform,
4949+// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy
4950+// node:async_hooks prelude calls these. The value is V8's
4951+// continuation-preserved embedder data — the primitive Workerd's
4952+// AsyncContextFrame rides — which V8 itself captures and restores
4953+// around every promise reaction. No promise hooks are installed, and an
4954+// isolate that never touches AsyncLocalStorage never sets the value, so
4955+// a bundle that does not import async_hooks pays nothing per promise.
4956+
4957+/// The per-request context: everything a request owns while it is in flight.
4958+///
4959+/// Modelled on workerd's `IoContext`. The host owns it, not JS: a request's
4960+/// event frames and the `waitUntil` promises inside them live here, and JS
4961+/// reaches them only through ops that ask for the *current* context. That
4962+/// inversion is the point. While an isolate serves one request at a time,
4963+/// JS-side per-request state is indistinguishable from isolate-side state,
4964+/// and the two silently diverge the moment requests interleave — one
4965+/// request's `__endEvent` popping another's event, its `waitUntil` work
4966+/// attributed to a request that never asked for it.
4967+///
4968+/// `current()` is a thread-local the host installs for the duration of a
4969+/// turn and restores on the way out, exactly as `threadLocalRequest` is set
4970+/// in `IoContext::runInContextScope` and restored by `SuppressIoContextScope`.
4971+/// An op that needs a context and finds none is a bug in the host, not in
4972+/// the script, so it says so rather than inventing one.
4973+///
4974+/// **It is `Send + Sync`, and that is load-bearing.** Under D1 a request is
4975+/// a tokio task that suspends between turns and can resume on any worker, so
4976+/// the context it carries has to cross threads with it. `Rc` and `RefCell`
4977+/// would forbid that, and the alternative — parking every live context in a
4978+/// map inside the isolate, keyed by request id — rebuilds the very
4979+/// demultiplexing table (`idmap`) that deleting the pump exists to remove.
4980+/// So the interiors are `Mutex` instead. The locks are uncontended by
4981+/// construction, because only the isolate's holder can reach a context, and
4982+/// they are taken about twice per request.
4983+pub struct IoContext {
4984+ /// This caller's delivery order for each cell it has called. See
4985+ /// `CallOrder` — it is here rather than in a process-wide map because
4986+ /// nothing outside this caller ever reads it.
4987+ call_chains: Mutex<CallChains>,
4988+ /// Event frames, innermost last. A frame collects the `waitUntil`
4989+ /// promises registered while it is the innermost one.
4990+ ///
4991+ /// Nesting is per-request and strictly LIFO — a service-binding
4992+ /// dispatch, an RPC entry, or a DO construction pushes its own frame so
4993+ /// its `waitUntil` binds to that dispatch, matching workerd.
4994+ events: Mutex<Vec<Vec<v8::Global<v8::Promise>>>>,
4995+ /// Isolate-polled sockets opened by each nested run loop of this
4996+ /// request, innermost last. `asyncrt` aborts a region's pending ops when
4997+ /// it exits; these are host-side resources abort cannot reach, so the
4998+ /// region closes them itself.
4999+ sockets: Mutex<Vec<Vec<u64>>>,
5000+ /// Sockets opened before any run loop exists. A handler runs
5001+ /// synchronously to its first await before its loop is entered, so a
5002+ /// socket built at the top of a handler has no frame yet; the loop
5003+ /// adopts these when it starts.
5004+ pending_sockets: Mutex<Vec<u64>>,
5005+ /// Output-gate capture. While a `webSocketMessage` runs, the frames it
5006+ /// sends are collected here instead of reaching the wire, so the shell
5007+ /// can hold them until the message's write is durable. A stack, so a
5008+ /// nested dispatch keeps its frames apart from the outer one's.
5009+ ///
5010+ /// On the event and not on the thread, because an event outlives the
5011+ /// turn that began it: capture starts in one turn and is taken in a
5012+ /// later one, which tokio may run on a different worker.
5013+ ws_capture: Mutex<Vec<Vec<(u64, WsOut)>>>,
5014+ /// Which cell an event belongs to, and the committed-write position it
5015+ /// started at, innermost last. An outbound effect raised during the
5016+ /// event consults this: if the handler has advanced the position, the
5017+ /// effect waits for the output gate before it leaves the process.
5018+ ///
5019+ /// Empty for stateless Worker code, which owns no cell and gates
5020+ /// nothing.
5021+ egress: Mutex<Vec<(String, u64)>>,
5022+}
5023+
5024+impl IoContext {
5025+ fn new() -> Arc<Self> {
5026+ Arc::new(Self {
5027+ call_chains: Mutex::new(CallChains::default()),
5028+ events: Mutex::new(Vec::new()),
5029+ sockets: Mutex::new(Vec::new()),
5030+ pending_sockets: Mutex::new(Vec::new()),
5031+ ws_capture: Mutex::new(Vec::new()),
5032+ egress: Mutex::new(Vec::new()),
5033+ })
5034+ }
5035+
5036+ fn begin_event(&self) {
5037+ self.events.lock().unwrap().push(Vec::new());
5038+ }
5039+
5040+ /// Pop the innermost frame and hand back what it collected. `None` when
5041+ /// there is no frame, which is a script calling `waitUntil` outside any
5042+ /// event; the harness turns that into workerd's global-scope error.
5043+ fn end_event(&self) -> Option<Vec<v8::Global<v8::Promise>>> {
5044+ self.events.lock().unwrap().pop()
5045+ }
5046+
5047+ fn register_wait_until(&self, promise: v8::Global<v8::Promise>) {
5048+ if let Some(frame) = self.events.lock().unwrap().last_mut() {
5049+ frame.push(promise);
5050+ }
5051+ }
5052+
5053+ fn depth(&self) -> usize {
5054+ self.events.lock().unwrap().len()
5055+ }
5056+}
5057+
5058+/// What `OwnedIsolate::into_shared` demands of us: every slot value on a
5059+/// shared isolate is reachable, and droppable, from whichever thread holds
5060+/// the lock. The type system cannot check it at the call site, so it is
5061+/// checked here instead.
5062+const _: fn() = || {
5063+ fn assert_send_sync<T: Send + Sync>() {}
5064+ assert_send_sync::<HeapLimitState>();
5065+ assert_send_sync::<ActorRuntimeState>();
5066+ assert_send_sync::<ModuleRegistry>();
5067+};
5068+
5069+/// A request must be able to carry its own context across a suspension. A
5070+/// compile-time check, because losing it would surface as an unrelated
5071+/// `Send` error wherever the request task is spawned.
5072+const _: fn() = || {
5073+ fn assert_send_sync<T: Send + Sync>() {}
5074+ assert_send_sync::<Arc<IoContext>>();
5075+};
5076+
5077+thread_local! {
5078+ /// The request whose turn is running on this thread, or none between
5079+ /// turns. Never set by JS.
5080+ static CURRENT: RefCell<Option<Arc<IoContext>>> =
5081+ const { RefCell::new(None) };
5082+}
5083+
5084+/// Install `context` for the duration of a turn, restoring whatever was
5085+/// current when the guard drops.
5086+///
5087+/// Restoring rather than clearing is what makes nested host dispatch safe: a
5088+/// service binding runs a second handler inside the first one's turn, and the
5089+/// outer request must still be current when it returns.
5090+pub struct CurrentGuard(Option<Arc<IoContext>>);
5091+
5092+impl CurrentGuard {
5093+ pub fn enter(context: Arc<IoContext>) -> Self {
5094+ CurrentGuard(CURRENT.with(|current| current.borrow_mut().replace(context)))
5095+ }
5096+}
5097+
5098+impl Drop for CurrentGuard {
5099+ fn drop(&mut self) {
5100+ CURRENT.with(|current| *current.borrow_mut() = self.0.take());
5101+ }
5102+}
5103+
5104+/// The context this turn belongs to.
5105+///
5106+/// A thread that has not had one installed gets a default: every path that
5107+/// runs JS without an explicit request context — a cell isolate, which the
5108+/// DO contract already serializes, an RPC entry, a DO constructor — keeps
5109+/// exactly the semantics it had when the stack lived in JS, one per isolate.
5110+/// Isolation is a property of *installing* a context, so it arrives with the
5111+/// paths that need it rather than being retrofitted to every caller at once.
5112+fn current_context() -> Arc<IoContext> {
5113+ CURRENT.with(|current| {
5114+ let mut current = current.borrow_mut();
5115+ current.get_or_insert_with(IoContext::new).clone()
5116+ })
5117+}
5118+
5119+fn op_event_begin(
5120+ scope: &mut v8::PinScope,
5121+ _args: v8::FunctionCallbackArguments,
5122+ _rv: v8::ReturnValue<v8::Value>,
5123+) {
5124+ let _ = scope;
5125+ current_context().begin_event();
5126+}
5127+
5128+/// Pop the innermost event and return the aggregate of its `waitUntil`
5129+/// promises, or null when it collected none. The aggregate is built here
5130+/// rather than in JS because the promises live here: the host holds them for
5131+/// the request, and the request is what the frame belongs to.
5132+fn op_event_end<'s>(
5133+ scope: &mut v8::PinScope<'s, '_>,
5134+ _args: v8::FunctionCallbackArguments,
5135+ mut rv: v8::ReturnValue<v8::Value>,
5136+) {
5137+ let Some(frame) = current_context().end_event() else {
5138+ rv.set_null();
5139+ return;
5140+ };
5141+ if frame.is_empty() {
5142+ rv.set_null();
5143+ return;
5144+ }
5145+ let promises: Vec<v8::Local<v8::Value>> = frame
5146+ .iter()
5147+ .map(|promise| v8::Local::new(scope, promise).into())
5148+ .collect();
5149+ let array = v8::Array::new_with_elements(scope, &promises);
5150+ match all_settled(scope, array.into()) {
5151+ Some(aggregate) => rv.set(aggregate),
5152+ None => rv.set_null(),
5153+ }
5154+}
5155+
5156+fn op_wait_until<'s>(
5157+ scope: &mut v8::PinScope<'s, '_>,
5158+ args: v8::FunctionCallbackArguments<'s>,
5159+ _rv: v8::ReturnValue<v8::Value>,
5160+) {
5161+ let value = args.get(0);
5162+ let promise = match value.try_cast::<v8::Promise>() {
5163+ Ok(promise) => promise,
5164+ Err(_) => match resolved_promise(scope, value) {
5165+ Ok(promise) => promise,
5166+ Err(_) => return,
5167+ },
5168+ };
5169+ current_context().register_wait_until(v8::Global::new(scope, promise));
5170+}
5171+
5172+/// How many events are open on the current request. The harness uses it for
5173+/// workerd's global-scope error, which fires when `waitUntil` is imported and
5174+/// called with no event in progress.
5175+fn op_event_depth(
5176+ scope: &mut v8::PinScope,
5177+ _args: v8::FunctionCallbackArguments,
5178+ mut rv: v8::ReturnValue<v8::Value>,
5179+) {
5180+ let depth = current_context().depth();
5181+ rv.set(v8::Integer::new(scope, depth as i32).into());
5182+}
5183+
5184+/// `Promise.allSettled(values)`, from the context's own realm.
5185+fn all_settled<'s>(
5186+ scope: &mut v8::PinScope<'s, '_>,
5187+ values: v8::Local<'s, v8::Value>,
5188+) -> Option<v8::Local<'s, v8::Value>> {
5189+ let global = scope.get_current_context().global(scope);
5190+ let key = v8::String::new(scope, "Promise").unwrap();
5191+ let promise_ctor: v8::Local<v8::Object> = global.get(scope, key.into())?.try_into().ok()?;
5192+ let key = v8::String::new(scope, "allSettled").unwrap();
5193+ let all_settled: v8::Local<v8::Function> =
5194+ promise_ctor.get(scope, key.into())?.try_into().ok()?;
5195+ all_settled.call(scope, promise_ctor.into(), &[values])
5196+}
5197+
5198+fn op_als_get(
5199+ scope: &mut v8::PinScope,
5200+ _args: v8::FunctionCallbackArguments,
5201+ mut rv: v8::ReturnValue<v8::Value>,
5202+) {
5203+ rv.set(cped_frame(scope));
5204+}
5205+
5206+fn op_als_set(
5207+ scope: &mut v8::PinScope,
5208+ args: v8::FunctionCallbackArguments,
5209+ _rv: v8::ReturnValue<v8::Value>,
5210+) {
5211+ let trace = cped_trace(scope);
5212+ set_cped(scope, args.get(0), trace);
5213+}
5214+
5215+// node:util prelude calls these; registration is the sole per-isolate cost.
5216+
5217+/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js.
5218+fn op_util_type_flags(
5219+ _scope: &mut v8::PinScope,
5220+ args: v8::FunctionCallbackArguments,
5221+ mut rv: v8::ReturnValue<v8::Value>,
5222+) {
5223+ let v = args.get(0);
5224+ let checks: [bool; 27] = [
5225+ v.is_external(),
5226+ v.is_date(),
5227+ v.is_arguments_object(),
5228+ v.is_big_int_object(),
5229+ v.is_boolean_object(),
5230+ v.is_number_object(),
5231+ v.is_string_object(),
5232+ v.is_symbol_object(),
5233+ v.is_native_error(),
5234+ v.is_reg_exp(),
5235+ v.is_async_function(),
5236+ v.is_generator_function(),
5237+ v.is_generator_object(),
5238+ v.is_promise(),
5239+ v.is_map(),
5240+ v.is_set(),
5241+ v.is_map_iterator(),
5242+ v.is_set_iterator(),
5243+ v.is_weak_map(),
5244+ v.is_weak_set(),
5245+ v.is_array_buffer(),
5246+ v.is_data_view(),
5247+ v.is_shared_array_buffer(),
5248+ v.is_proxy(),
5249+ v.is_module_namespace_object(),
5250+ v.is_typed_array(),
5251+ v.is_array_buffer_view(),
5252+ ];
5253+ let mut flags: u32 = 0;
5254+ for (i, hit) in checks.iter().enumerate() {
5255+ if *hit {
5256+ flags |= 1 << i;
5257+ }
5258+ }
5259+ rv.set_uint32(flags);
5260+}
5261+
5262+fn op_util_constructor_name(
5263+ _scope: &mut v8::PinScope,
5264+ args: v8::FunctionCallbackArguments,
5265+ mut rv: v8::ReturnValue<v8::Value>,
5266+) {
5267+ let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
5268+ return; // undefined
5269+ };
5270+ rv.set(obj.get_constructor_name().into());
5271+}
5272+
5273+/// `[target, handler]` for a proxy, undefined otherwise.
5274+fn op_util_proxy_details(
5275+ scope: &mut v8::PinScope,
5276+ args: v8::FunctionCallbackArguments,
5277+ mut rv: v8::ReturnValue<v8::Value>,
5278+) {
5279+ let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else {
5280+ return;
5281+ };
5282+ let target = proxy.get_target(scope);
5283+ let handler = proxy.get_handler(scope);
5284+ rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into());
5285+}
5286+
5287+/// `[state]` for a pending promise, `[state, result]` otherwise,
5288+/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected.
5289+fn op_util_promise_details(
5290+ scope: &mut v8::PinScope,
5291+ args: v8::FunctionCallbackArguments,
5292+ mut rv: v8::ReturnValue<v8::Value>,
5293+) {
5294+ let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else {
5295+ return;
5296+ };
5297+ let state = match promise.state() {
5298+ v8::PromiseState::Pending => 0,
5299+ v8::PromiseState::Fulfilled => 1,
5300+ v8::PromiseState::Rejected => 2,
5301+ };
5302+ let pending = state == 0;
5303+ let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into();
5304+ let elements = if pending {
5305+ vec![state]
5306+ } else {
5307+ vec![state, promise.result(scope)]
5308+ };
5309+ rv.set(v8::Array::new_with_elements(scope, &elements).into());
5310+}
5311+
5312+/// `[entries, isKeyValue]` for collections and their iterators (V8's
5313+/// PreviewEntries), undefined when V8 has no preview.
5314+fn op_util_preview_entries(
5315+ scope: &mut v8::PinScope,
5316+ args: v8::FunctionCallbackArguments,
5317+ mut rv: v8::ReturnValue<v8::Value>,
5318+) {
5319+ let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
5320+ return;
5321+ };
5322+ let (entries, is_key_value) = obj.preview_entries(scope);
5323+ let Some(entries) = entries else { return };
5324+ let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into();
5325+ rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into());
5326+}
5327+
5328+fn op_alarm_set(
5329+ scope: &mut v8::PinScope,
5330+ args: v8::FunctionCallbackArguments,
5331+ _rv: v8::ReturnValue<v8::Value>,
5332+) {
5333+ let s = args.get(0).to_rust_string_lossy(scope);
5334+ let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64;
5335+ match storage::set_alarm(&s, at) {
5336+ Err(error) => throw_storage_error(scope, "setAlarm", error),
5337+ // Committed immediately: register the wake-entry PUT against the
5338+ // cell's output gate. Inside an explicit transaction (`Ok(None)`)
5339+ // the gate registers at that transaction's commit instead.
5340+ Ok(Some(committed)) if committed >= 0 => spawn_arm_gate(&s, committed),
5341+ Ok(_) => {}
5342+ }
5343+}
5344+fn op_alarm_get(
5345+ scope: &mut v8::PinScope,
5346+ args: v8::FunctionCallbackArguments,
5347+ mut rv: v8::ReturnValue<v8::Value>,
5348+) {
5349+ let s = args.get(0).to_rust_string_lossy(scope);
5350+ match storage::get_alarm(&s) {
5351+ Some(at) => rv.set(v8::Number::new(scope, at as f64).into()),
5352+ None => rv.set(v8::null(scope).into()),
5353+ }
5354+}
5355+fn op_alarm_delete(
5356+ scope: &mut v8::PinScope,
5357+ args: v8::FunctionCallbackArguments,
5358+ _rv: v8::ReturnValue<v8::Value>,
5359+) {
5360+ let s = args.get(0).to_rust_string_lossy(scope);
5361+ if let Err(error) = storage::delete_alarm(&s) {
5362+ throw_storage_error(scope, "deleteAlarm", error);
5363+ }
5364+}
5365+
5366+fn op_btoa(
5367+ scope: &mut v8::PinScope,
5368+ args: v8::FunctionCallbackArguments,
5369+ mut rv: v8::ReturnValue<v8::Value>,
5370+) {
5371+ use base64::Engine;
5372+ let input = args.get(0).to_rust_string_lossy(scope);
5373+ let bytes: Vec<u8> = input.chars().map(|c| c as u8).collect();
5374+ let s = base64::engine::general_purpose::STANDARD.encode(bytes);
5375+ rv.set(v8::String::new(scope, &s).unwrap().into());
5376+}
5377+
5378+// ---- WHATWG legacy text decoders (encoding_rs) ----
5379+//
5380+// TextDecoder's utf-8/utf-16 hot path stays pure JS in
5381+// src/js/text_encoding.js; these ops back every other WHATWG label
5382+// (windows-1252, Big5, GBK/GB18030, ISO-2022-JP, x-user-defined, …).
5383+// Streaming decoders live in a thread-local table keyed by id; JS frees
5384+// one on the final decode (last=true), on a fatal error (encoding_rs
5385+// poisons an errored decoder), or via FinalizationRegistry when a
5386+// mid-stream decoder is abandoned. Ids are never reused, so a late
5387+// finalizer free of an already-closed id is a no-op.
5388+
5389+/// Live streaming decoders, keyed by an id JS holds across awaits.
5390+///
5391+/// Process-wide for the same reason as [`zlib_streams`]: a `TextDecoder` in
5392+/// streaming mode outlives the turn that made it, and under D1 the next turn
5393+/// can run on a different tokio worker. A per-thread counter would also hand
5394+/// the same id to two requests.
5395+static TEXT_DECODERS: OnceLock<Mutex<HashMap<u64, encoding_rs::Decoder>>> = OnceLock::new();
5396+static TEXT_DECODER_NEXT: AtomicU64 = AtomicU64::new(1);
5397+
5398+fn text_decoders() -> &'static Mutex<HashMap<u64, encoding_rs::Decoder>> {
5399+ TEXT_DECODERS.get_or_init(|| Mutex::new(HashMap::new()))
5400+}
5401+
5402+/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined
5403+/// for unknown labels and the replacement encoding (RangeError in JS).
5404+fn op_text_decoder_label(
5405+ scope: &mut v8::PinScope,
5406+ args: v8::FunctionCallbackArguments,
5407+ mut rv: v8::ReturnValue<v8::Value>,
5408+) {
5409+ let label = args.get(0).to_rust_string_lossy(scope);
5410+ if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) {
5411+ let name = enc.name().to_ascii_lowercase();
5412+ rv.set(v8::String::new(scope, &name).unwrap().into());
5413+ }
5414+}
5415+
5416+/// `$$textDecoderNew(name, ignoreBOM)` -> id.
5417+fn op_text_decoder_new(
5418+ scope: &mut v8::PinScope,
5419+ args: v8::FunctionCallbackArguments,
5420+ mut rv: v8::ReturnValue<v8::Value>,
5421+) {
5422+ let name = args.get(0).to_rust_string_lossy(scope);
5423+ let ignore_bom = args.get(1).boolean_value(scope);
5424+ let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
5425+ let dec = if ignore_bom {
5426+ enc.new_decoder_without_bom_handling()
5427+ } else {
5428+ enc.new_decoder_with_bom_removal()
5429+ };
5430+ let id = TEXT_DECODER_NEXT.fetch_add(1, Ordering::Relaxed);
5431+ text_decoders().lock().unwrap().insert(id, dec);
5432+ rv.set(v8::Number::new(scope, id as f64).into());
5433+}
5434+
5435+/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the
5436+/// decoder when `last` is true or on a fatal malformed sequence
5437+/// (TypeError).
5438+fn op_text_decoder_decode(
5439+ scope: &mut v8::PinScope,
5440+ args: v8::FunctionCallbackArguments,
5441+ mut rv: v8::ReturnValue<v8::Value>,
5442+) {
5443+ let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
5444+ let bytes = view_bytes(args.get(1)).unwrap_or_default();
5445+ let fatal = args.get(2).boolean_value(scope);
5446+ let last = args.get(3).boolean_value(scope);
5447+ // Per spec an empty streaming chunk is a no-op, but encoding_rs
5448+ // 0.8 flushes a pending multibyte lead when fed an empty non-last
5449+ // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead
5450+ // of あ). Skip the decoder entirely.
5451+ if bytes.is_empty() && !last {
5452+ rv.set(v8::String::empty(scope).into());
5453+ return;
5454+ }
5455+ let mut dec = text_decoders()
5456+ .lock()
5457+ .unwrap()
5458+ .remove(&id)
5459+ .expect("JS holds the only live id");
5460+ let mut out = String::new();
5461+ let ok = if fatal {
5462+ let cap = dec
5463+ .max_utf8_buffer_length_without_replacement(bytes.len())
5464+ .unwrap();
5465+ out.reserve(cap);
5466+ matches!(
5467+ dec.decode_to_string_without_replacement(&bytes, &mut out, last),
5468+ (encoding_rs::DecoderResult::InputEmpty, _),
5469+ )
5470+ } else {
5471+ let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap();
5472+ out.reserve(cap);
5473+ let _ = dec.decode_to_string(&bytes, &mut out, last);
5474+ true
5475+ };
5476+ if !ok {
5477+ let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap();
5478+ let exc = v8::Exception::type_error(scope, msg);
5479+ scope.throw_exception(exc);
5480+ return;
5481+ }
5482+ if !last {
5483+ text_decoders().lock().unwrap().insert(id, dec);
5484+ }
5485+ rv.set(v8::String::new(scope, &out).unwrap().into());
5486+}
5487+
5488+/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder
5489+/// abandoned mid-stream.
5490+fn op_text_decoder_free(
5491+ scope: &mut v8::PinScope,
5492+ args: v8::FunctionCallbackArguments,
5493+ _rv: v8::ReturnValue<v8::Value>,
5494+) {
5495+ let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
5496+ text_decoders().lock().unwrap().remove(&id);
5497+}
5498+
5499+// ---- the JS harness: Web API + the DO object model ----
5500+
5501+mod bootstrap;
5502+mod modules;
5503+use bootstrap::{
5504+ adopt_cell, begin_event_context, build_env, end_event_context, harness_env,
5505+ inject_compatibility_flags, inject_namespace_keys, inject_routing,
5506+ inject_storage_compatibility, install_harness, install_prelude, populate_cf_exports,
5507+ register_class, register_entrypoints,
5508+};
5509+use modules::{
5510+ compile_module, host_import_module_dynamically, install_lazy_globals, op_builtin_module,
5511+ register_loader_modules, register_stubs, register_wasm_modules, resolve_external,
5512+ ModuleRegistry,
5513+};
5514+/// Like `make_request`, but marks the request as incoming. Its signal is
5515+/// registered only if the handler actually suspends, preserving the
5516+/// synchronous request path.
5517+fn make_incoming_request<'s>(
5518+ tc: &mut v8::PinScope<'s, '_>,
5519+ url: &str,
5520+ method: &str,
5521+ body: &[u8],
5522+ headers: &[(String, String)],
5523+) -> Result<v8::Local<'s, v8::Value>> {
5524+ let global = tc.get_current_context().global(tc);
5525+ let key = v8::String::new(tc, "__makeIncomingRequest").unwrap();
5526+ let f: v8::Local<v8::Function> = global
5527+ .get(tc, key.into())
5528+ .ok_or_else(|| anyhow!("no __makeIncomingRequest"))?
5529+ .try_into()
5530+ .map_err(|_| anyhow!("not fn"))?;
5531+ let url = v8::String::new(tc, url).unwrap();
5532+ let method = v8::String::new(tc, method).unwrap();
5533+ let body = bytes_value(tc, body.to_vec());
5534+ let headers = v8::String::new(
5535+ tc,
5536+ &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()),
5537+ )
5538+ .unwrap();
5539+ let recv = v8::undefined(tc).into();
5540+ f.call(tc, recv, &[url.into(), method.into(), body, headers.into()])
5541+ .ok_or_else(|| anyhow!("__makeIncomingRequest threw"))
5542+}
5543+
5544+fn register_incoming_request(
5545+ tc: &mut v8::PinScope,
5546+ request_id: RequestId,
5547+ request: v8::Local<v8::Value>,
5548+) -> Result<()> {
5549+ let global = tc.get_current_context().global(tc);
5550+ let key = v8::String::new(tc, "__registerIncomingRequest").unwrap();
5551+ let function: v8::Local<v8::Function> = global
5552+ .get(tc, key.into())
5553+ .ok_or_else(|| anyhow!("no __registerIncomingRequest"))?
5554+ .try_into()
5555+ .map_err(|_| anyhow!("__registerIncomingRequest is not a function"))?;
5556+ let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
5557+ let recv = v8::undefined(tc).into();
5558+ function
5559+ .call(tc, recv, &[id.into(), request])
5560+ .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?;
5561+ Ok(())
5562+}
5563+
5564+fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) {
5565+ let global = tc.get_current_context().global(tc);
5566+ let key = v8::String::new(tc, "__finishIncomingRequest").unwrap();
5567+ let Some(value) = global.get(tc, key.into()) else {
5568+ return;
5569+ };
5570+ let Ok(function) = value.try_cast::<v8::Function>() else {
5571+ return;
5572+ };
5573+ let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
5574+ let recv = v8::undefined(tc).into();
5575+ let _ = function.call(tc, recv, &[id.into()]);
5576+}
5577+
5578+fn make_request<'s>(
5579+ tc: &mut v8::PinScope<'s, '_>,
5580+ url: &str,
5581+ method: &str,
5582+ body: &[u8],
5583+ headers: &[(String, String)],
5584+) -> Result<v8::Local<'s, v8::Value>> {
5585+ let g = tc.get_current_context().global(tc);
5586+ let k = v8::String::new(tc, "__makeRequest").unwrap();
5587+ let f: v8::Local<v8::Function> = g.get(tc, k.into()).unwrap().try_into().unwrap();
5588+ let u = v8::String::new(tc, url).unwrap();
5589+ let m = v8::String::new(tc, method).unwrap();
5590+ let b = bytes_value(tc, body.to_vec());
5591+ let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap();
5592+ let recv = v8::undefined(tc).into();
5593+ f.call(tc, recv, &[u.into(), m.into(), b, h.into()])
5594+ .ok_or_else(|| anyhow!("makeRequest threw"))
5595+}
5596+
5597+fn read_response(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> Result<HttpResponse> {
5598+ let ctx = scope.get_current_context();
5599+ let global = ctx.global(scope);
5600+ let key = v8::String::new(scope, "__readResponse").unwrap();
5601+ let f: v8::Local<v8::Function> = global
5602+ .get(scope, key.into())
5603+ .ok_or_else(|| anyhow!("no __readResponse"))?
5604+ .try_into()
5605+ .map_err(|_| anyhow!("not fn"))?;
5606+ let recv = v8::undefined(scope).into();
5607+ let out = f
5608+ .call(scope, recv, &[ret])
5609+ .ok_or_else(|| anyhow!("readResponse threw"))?;
5610+ // The harness response reader is synchronous. Keeping this assertion at
5611+ // the native boundary prevents a future harness change from quietly
5612+ // reintroducing a nested async runtime while an isolate is entered.
5613+ if out.is_promise() {
5614+ return Err(anyhow!("__readResponse returned a promise"));
5615+ }
5616+ let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?;
5617+ let sk = v8::String::new(scope, "status").unwrap();
5618+ let bk = v8::String::new(scope, "bodyBytes").unwrap();
5619+ let tk = v8::String::new(scope, "bodyStreamId").unwrap();
5620+ let hk = v8::String::new(scope, "headersJson").unwrap();
5621+ let wk = v8::String::new(scope, "wsTargetJson").unwrap();
5622+ let status = out
5623+ .get(scope, sk.into())
5624+ .and_then(|v| v.uint32_value(scope))
5625+ .unwrap_or(200) as u16;
5626+ // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON
5627+ // number array (which was ~4x the bytes to serialize + parse per response).
5628+ let body = out
5629+ .get(scope, bk.into())
5630+ .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok())
5631+ .map(|view| {
5632+ let mut buf = vec![0u8; view.byte_length()];
5633+ view.copy_contents(&mut buf);
5634+ buf
5635+ })
5636+ .unwrap_or_default();
5637+ let stream_id = out
5638+ .get(scope, tk.into())
5639+ .and_then(|value| value.integer_value(scope))
5640+ .unwrap_or(0)
5641+ .max(0) as u64;
5642+ let stream = if stream_id == 0 {
5643+ None
5644+ } else {
5645+ http_streams()
5646+ .lock()
5647+ .unwrap()
5648+ .remove(&stream_id)
5649+ .and_then(|stream| stream.source)
5650+ .map(http_chunk_stream)
5651+ };
5652+ if stream_id != 0 && stream.is_none() {
5653+ return Err(anyhow!(
5654+ "response stream {stream_id} is no longer available"
5655+ ));
5656+ }
5657+ let headers = out
5658+ .get(scope, hk.into())
5659+ .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok())
5660+ .unwrap_or_default();
5661+ let ws_json = out
5662+ .get(scope, wk.into())
5663+ .map(|v| v.to_rust_string_lossy(scope))
5664+ .unwrap_or_else(|| "null".into());
5665+ let ws = serde_json::from_str(&ws_json).ok();
5666+ if status == 101 {
5667+ tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response");
5668+ }
5669+ Ok(HttpResponse {
5670+ status,
5671+ body,
5672+ stream,
5673+ headers,
5674+ ws,
5675+ write_position: None,
5676+ })
5677+}
5678+
5679+#[cfg(all(test, celld_internal_tests))]
5680+fn init_engine_for_tests() {
5681+ static INIT: std::sync::Once = std::sync::Once::new();
5682+ INIT.call_once(|| {
5683+ v8::V8::set_flags_from_string("--expose-gc");
5684+ Engine::init();
5685+ });
5686+}
5687+
5688+/// Externally injected Web-platform tests.
5689+#[cfg(all(test, celld_internal_tests))]
5690+mod conformance_runtime_tests {
5691+ include!(env!("CELLD_CONFORMANCE_JS_RUNTIME_TESTS"));
5692+}
5693+
5694+#[cfg(all(test, celld_internal_tests))]
5695+mod conformance_web_platform_tests {
5696+ include!(env!("CELLD_CONFORMANCE_WEB_PLATFORM_TESTS"));
5697+}
5698+
5699+#[cfg(all(test, celld_internal_tests))]
5700+mod call_order_private {
5701+ include!(env!("CELLD_CONFORMANCE_CALL_ORDER_TESTS"));
78205702 }
addedcrates/celld/js/bootstrap.rs+553−0View file
@@ -1,0 +1,553 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! Isolate bootstrap: what a fresh context needs before user code runs.
4+//!
5+//! The prelude and the harness compile once per process and are cached, so a
6+//! new isolate pays for execution but not for compilation. On top of those go
7+//! the bindings — `env`, the routing table, the compatibility flags — which
8+//! differ per worker and are therefore built every time.
9+use super::*;
10+
11+/// Per-process compiled-bytecode cache for the fixed bootstrap scripts.
12+/// Every cell wake pays a fresh isolate, and without this each one re-parses
13+/// and re-compiles the same ~23k lines of prelude + harness — the single
14+/// largest slice of cold-wake latency. The first isolate compiles
15+/// eagerly and publishes the cache; every later isolate consumes it and only
16+/// executes.
17+type BootstrapCache = std::collections::HashMap<&'static str, std::sync::Arc<Vec<u8>>>;
18+
19+fn bootstrap_code_cache() -> &'static std::sync::Mutex<BootstrapCache> {
20+ static CACHE: std::sync::OnceLock<std::sync::Mutex<BootstrapCache>> =
21+ std::sync::OnceLock::new();
22+ CACHE.get_or_init(Default::default)
23+}
24+
25+fn run_bootstrap_script(scope: &mut v8::PinScope, name: &'static str, src: &str) -> Result<()> {
26+ use v8::script_compiler::CompileOptions;
27+ use v8::script_compiler::NoCacheReason;
28+ let code = v8::String::new(scope, src).unwrap();
29+ let cached = bootstrap_code_cache().lock().unwrap().get(name).cloned();
30+ let unbound = match cached {
31+ // `CachedData` borrows `bytes`; the Arc binding outlives the Source.
32+ Some(bytes) => {
33+ let data = v8::script_compiler::CachedData::new(&bytes);
34+ let mut source = v8::script_compiler::Source::new_with_cached_data(code, None, data);
35+ let unbound = v8::script_compiler::compile_unbound_script(
36+ scope,
37+ &mut source,
38+ CompileOptions::ConsumeCodeCache,
39+ NoCacheReason::NoReason,
40+ )
41+ .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
42+ debug_assert!(
43+ !source.get_cached_data().is_some_and(|data| data.rejected()),
44+ "code cache rejected for {name}"
45+ );
46+ unbound
47+ }
48+ None => {
49+ let mut source = v8::script_compiler::Source::new(code, None);
50+ // Eager: a lazily-compiled cache would push function-body compile
51+ // cost back into every consumer's first request.
52+ let unbound = v8::script_compiler::compile_unbound_script(
53+ scope,
54+ &mut source,
55+ CompileOptions::EagerCompile,
56+ NoCacheReason::NoReason,
57+ )
58+ .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
59+ if let Some(data) = unbound.create_code_cache() {
60+ bootstrap_code_cache()
61+ .lock()
62+ .unwrap()
63+ .insert(name, std::sync::Arc::new(data.to_vec()));
64+ }
65+ unbound
66+ }
67+ };
68+ unbound
69+ .bind_to_current_context(scope)
70+ .run(scope)
71+ .ok_or_else(|| anyhow!("bootstrap run {name}"))?;
72+ Ok(())
73+}
74+
75+/// WPT-conformant Web APIs: TextEncoder, URL/URLSearchParams, atob/btoa, and
76+/// Headers. Run once per isolate before the Cells/Cloudflare-specific harness.
77+pub(super) fn install_prelude(scope: &mut v8::PinScope) -> Result<()> {
78+ const PRELUDE: &[(&str, &str)] = &[
79+ ("text_encoding.js", include_str!("text_encoding.js")),
80+ ("url_search_params.js", include_str!("url_search_params.js")),
81+ ("url.js", include_str!("url.js")),
82+ ("atob_btoa.js", include_str!("atob_btoa.js")),
83+ ("headers.js", include_str!("headers.js")),
84+ ("streams.js", include_str!("streams.js")),
85+ ("writable_stream.js", include_str!("writable_stream.js")),
86+ (
87+ "text_encoding_streams.js",
88+ include_str!("text_encoding_streams.js"),
89+ ),
90+ ];
91+ for (name, src) in PRELUDE {
92+ run_bootstrap_script(scope, name, src)?;
93+ }
94+ Ok(())
95+}
96+
97+pub(super) fn install_harness(scope: &mut v8::PinScope) -> Result<()> {
98+ run_bootstrap_script(scope, "harness.js", include_str!("harness.js"))?;
99+ run_bootstrap_script(scope, "crypto.js", include_str!("crypto.js"))
100+}
101+
102+pub(super) fn register_class(
103+ scope: &mut v8::PinScope,
104+ name: &str,
105+ cls: v8::Local<v8::Value>,
106+) -> Result<()> {
107+ let ctx = scope.get_current_context();
108+ let global = ctx.global(scope);
109+ let ck = v8::String::new(scope, "__cell").unwrap();
110+ let cell = global
111+ .get(scope, ck.into())
112+ .unwrap()
113+ .to_object(scope)
114+ .unwrap();
115+ let clk = v8::String::new(scope, "classes").unwrap();
116+ let classes = cell
117+ .get(scope, clk.into())
118+ .unwrap()
119+ .to_object(scope)
120+ .unwrap();
121+ let nk = v8::String::new(scope, name).unwrap();
122+ classes.set(scope, nk.into(), cls);
123+ Ok(())
124+}
125+
126+/// Populate `cloudflare:workers` `exports` with the worker module's own exports:
127+/// a Durable Object class is exposed as its namespace (idFromName/get/RPC), any
128+/// other export by value. `default` is omitted (it is the fetch entrypoint, not
129+/// an importable export). Mirrors Workerd's `import { exports }` surface.
130+pub(super) fn populate_cf_exports(
131+ scope: &mut v8::PinScope,
132+ ns: v8::Local<v8::Object>,
133+ do_classes: &[String],
134+) -> Result<()> {
135+ let context = scope.get_current_context();
136+ let global = context.global(scope);
137+ let cf = global
138+ .get(scope, v8::String::new(scope, "__cf").unwrap().into())
139+ .and_then(|value| value.to_object(scope))
140+ .ok_or_else(|| anyhow!("missing __cf runtime state"))?;
141+ let exports = cf
142+ .get(scope, v8::String::new(scope, "exports").unwrap().into())
143+ .and_then(|value| value.to_object(scope))
144+ .ok_or_else(|| anyhow!("missing __cf.exports"))?;
145+ let cell = global
146+ .get(scope, v8::String::new(scope, "__cell").unwrap().into())
147+ .and_then(|value| value.to_object(scope))
148+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
149+ let make_ns: v8::Local<v8::Function> = cell
150+ .get(
151+ scope,
152+ v8::String::new(scope, "makeNamespace").unwrap().into(),
153+ )
154+ .and_then(|value| value.try_into().ok())
155+ .ok_or_else(|| anyhow!("missing __cell.makeNamespace"))?;
156+ let do_set: std::collections::HashSet<&str> = do_classes.iter().map(String::as_str).collect();
157+ let names = ns
158+ .get_own_property_names(scope, Default::default())
159+ .ok_or_else(|| anyhow!("no module export names"))?;
160+ for index in 0..names.length() {
161+ let name_value = names.get_index(scope, index).unwrap();
162+ let name = name_value.to_rust_string_lossy(scope);
163+ if name == "default" {
164+ continue;
165+ }
166+ let export_value = if do_set.contains(name.as_str()) {
167+ let arg = v8::String::new(scope, &name).unwrap().into();
168+ make_ns
169+ .call(scope, cell.into(), &[arg])
170+ .ok_or_else(|| anyhow!("makeNamespace({name}) failed"))?
171+ } else {
172+ ns.get(scope, name_value)
173+ .ok_or_else(|| anyhow!("export {name}"))?
174+ };
175+ let key = v8::String::new(scope, &name).unwrap();
176+ exports.set(scope, key.into(), export_value);
177+ }
178+ Ok(())
179+}
180+
181+pub(super) fn inject_namespace_keys(
182+ scope: &mut v8::PinScope,
183+ script_name: &str,
184+ do_classes: &[String],
185+) -> Result<()> {
186+ let context = scope.get_current_context();
187+ let global = context.global(scope);
188+ let cell_key = v8::String::new(scope, "__cell").unwrap();
189+ let cell = global
190+ .get(scope, cell_key.into())
191+ .and_then(|value| value.to_object(scope))
192+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
193+ let keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
194+ let keys = cell
195+ .get(scope, keys_key.into())
196+ .and_then(|value| value.to_object(scope))
197+ .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
198+ let script_key = v8::String::new(scope, "script").unwrap();
199+ let script_value = v8::String::new(scope, script_name).unwrap();
200+ cell.set(scope, script_key.into(), script_value.into());
201+ for class_name in do_classes {
202+ let class_key = v8::String::new(scope, class_name).unwrap();
203+ let namespace_key = format!("cells:v1:{}:{script_name}:{class_name}", script_name.len(),);
204+ let namespace_key = v8::String::new(scope, &namespace_key).unwrap();
205+ if !keys
206+ .set(scope, class_key.into(), namespace_key.into())
207+ .unwrap_or(false)
208+ {
209+ anyhow::bail!("could not register namespace key for {class_name}");
210+ }
211+ }
212+ Ok(())
213+}
214+
215+/// `globalThis.Cloudflare.compatibilityFlags`. Only flags Cells actually
216+/// honours are listed; a flag Cells does not model is absent (falsy) rather
217+/// than reported as enabled.
218+///
219+/// Built through the V8 object API rather than by compiling a snippet: this
220+/// runs on every isolate load, and a separate `Script::compile` there cost
221+/// ~100us per worker.
222+pub(super) fn inject_compatibility_flags(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
223+ let context = scope.get_current_context();
224+ let global = context.global(scope);
225+ let flags = v8::Object::new(scope);
226+ let set_flag = |scope: &mut v8::PinScope, name: &str, value: bool| {
227+ let key = v8::String::new(scope, name).unwrap();
228+ let value = v8::Boolean::new(scope, value);
229+ flags.set(scope, key.into(), value.into());
230+ };
231+ set_flag(scope, "upper_case_all_http_methods", true);
232+ // Cells' async stream/pipe methods return rejected promises
233+ // rather than throwing synchronously, which is exactly the
234+ // behavior this flag names.
235+ set_flag(scope, "capture_async_api_throws", true);
236+ set_flag(
237+ scope,
238+ "delete_all_deletes_alarm",
239+ compat.delete_all_deletes_alarm,
240+ );
241+ set_flag(scope, "js_rpc", compat.js_rpc);
242+ set_flag(
243+ scope,
244+ "fetcher_no_get_put_delete",
245+ !compat.fetcher_get_put_delete,
246+ );
247+ let cloudflare = v8::Object::new(scope);
248+ let key = v8::String::new(scope, "compatibilityFlags").unwrap();
249+ cloudflare.set(scope, key.into(), flags.into());
250+ let key = v8::String::new(scope, "Cloudflare").unwrap();
251+ global.set(scope, key.into(), cloudflare.into());
252+ Ok(())
253+}
254+
255+pub(super) fn build_env(scope: &mut v8::PinScope, config: &WorkerConfig) -> Result<()> {
256+ let script_name = config.script_name.as_str();
257+ let bindings = config.bindings.as_slice();
258+ let r2_bindings = config.r2_bindings.as_slice();
259+ let ai_binding = config.ai_binding.as_deref();
260+ let vars = config.vars.as_slice();
261+ let services = config.services.as_slice();
262+ let asset_binding = config.asset_binding.as_deref();
263+ // call the harness: for each binding, env[bindingName] = makeNamespace(className)
264+ let src = {
265+ let mut lines = String::from("(() => { const e = __cell.env;\n");
266+ for (bname, cname) in bindings {
267+ lines.push_str(&format!(
268+ "e[{:?}] = __cell.makeNamespace({:?});\n",
269+ bname, cname
270+ ));
271+ }
272+ for name in r2_bindings {
273+ lines.push_str(&format!("e[{:?}] = __makeR2Bucket({:?});\n", name, name));
274+ }
275+ if let (Some(name), Ok(url)) = (ai_binding, std::env::var("CELLD_AI_URL")) {
276+ lines.push_str(&format!("e[{:?}] = __makeAiBinding({:?});\n", name, url));
277+ }
278+ for (binding, script, entrypoint) in services {
279+ let entrypoint = match entrypoint {
280+ Some(name) => format!("{name:?}"),
281+ None => "null".to_string(),
282+ };
283+ lines.push_str(&format!(
284+ "e[{:?}] = __makeServiceBinding({:?}, {});\n",
285+ binding, script, entrypoint
286+ ));
287+ }
288+ for (name, value) in vars {
289+ lines.push_str(&format!("e[{:?}] = {:?};\n", name, value));
290+ }
291+ if let Some(name) = asset_binding {
292+ lines.push_str(&format!(
293+ "e[{:?}] = __makeAssetsBinding({:?});\n",
294+ name, script_name
295+ ));
296+ }
297+ if let Some(name) = config.loader_binding.as_deref() {
298+ lines.push_str(&format!("e[{:?}] = __makeLoader();\n", name));
299+ }
300+ // A loaded worker's caller-supplied `env` (plain JSON values only in
301+ // the walking skeleton) merges last, over the declared bindings.
302+ if let Some(env) = config.loader_env.as_deref() {
303+ lines.push_str(&format!("Object.assign(e, {});\n", env));
304+ }
305+ lines.push_str("})();");
306+ lines
307+ };
308+ let code = v8::String::new(scope, &src).unwrap();
309+ let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("env compile"))?;
310+ s.run(scope).ok_or_else(|| anyhow!("env run"))?;
311+ Ok(())
312+}
313+
314+/// Record every exported class deriving from `WorkerEntrypoint` in
315+/// `__cell.entrypoints`, so a service binding with `entrypoint = "Name"` can
316+/// resolve it, and every export deriving from `DurableObject` in
317+/// `__cell.doExports`, so misrouting a DO class as a stateless entrypoint is
318+/// reported as such (Workerd getExportedHandler()). Runs once per load; the
319+/// check is a prototype walk, not a call into user code.
320+pub(super) fn register_entrypoints(
321+ scope: &mut v8::PinScope,
322+ ns: v8::Local<v8::Object>,
323+) -> Result<()> {
324+ let context = scope.get_current_context();
325+ let global = context.global(scope);
326+ let cell_key = v8::String::new(scope, "__cell").unwrap();
327+ let cell = global
328+ .get(scope, cell_key.into())
329+ .and_then(|value| value.to_object(scope))
330+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
331+ let key = v8::String::new(scope, "entrypoints").unwrap();
332+ let entrypoints = cell
333+ .get(scope, key.into())
334+ .and_then(|value| value.to_object(scope))
335+ .ok_or_else(|| anyhow!("missing entrypoint registry"))?;
336+ let key = v8::String::new(scope, "objectEntrypoints").unwrap();
337+ let object_entrypoints = cell
338+ .get(scope, key.into())
339+ .and_then(|value| value.to_object(scope))
340+ .ok_or_else(|| anyhow!("missing object-entrypoint registry"))?;
341+ let key = v8::String::new(scope, "doExports").unwrap();
342+ let do_exports = cell
343+ .get(scope, key.into())
344+ .and_then(|value| value.to_object(scope))
345+ .ok_or_else(|| anyhow!("missing doExports registry"))?;
346+ let cf_key = v8::String::new(scope, "__cf").unwrap();
347+ let cf = global
348+ .get(scope, cf_key.into())
349+ .and_then(|value| value.to_object(scope))
350+ .ok_or_else(|| anyhow!("missing __cf"))?;
351+ let key = v8::String::new(scope, "WorkerEntrypoint").unwrap();
352+ let entrypoint_base = cf
353+ .get(scope, key.into())
354+ .ok_or_else(|| anyhow!("missing WorkerEntrypoint base"))?;
355+ let key = v8::String::new(scope, "DurableObject").unwrap();
356+ let durable_base = cf
357+ .get(scope, key.into())
358+ .ok_or_else(|| anyhow!("missing DurableObject base"))?;
359+ let Some(names) = ns.get_own_property_names(scope, Default::default()) else {
360+ return Ok(());
361+ };
362+ let yes = v8::Boolean::new(scope, true);
363+ let extends = compile_fn(scope, EXTENDS_SRC)?;
364+ for index in 0..names.length() {
365+ let Some(name) = names.get_index(scope, index) else {
366+ continue;
367+ };
368+ let Some(value) = ns.get(scope, name) else {
369+ continue;
370+ };
371+ if !value.is_function() {
372+ // A plain-object export is Workerd's non-class entrypoint; its
373+ // handler functions dispatch as fn(arg, env, ctx).
374+ if value.is_object() {
375+ object_entrypoints.set(scope, name, value);
376+ }
377+ continue;
378+ }
379+ // Walk the prototype chain rather than calling anything. The walk
380+ // runs in JS: Reflect.getPrototypeOf honors Proxy exports (SDK shims
381+ // like workers-rs wrap their classes), which the host-side
382+ // Object::GetPrototype does not.
383+ if call_extends(scope, extends, value, entrypoint_base)? {
384+ entrypoints.set(scope, name, value);
385+ } else if call_extends(scope, extends, value, durable_base)? {
386+ do_exports.set(scope, name, yes.into());
387+ }
388+ }
389+ Ok(())
390+}
391+
392+/// `(cls, base) => base is on cls's prototype chain`, via Reflect so Proxy
393+/// wrappers report the prototype their handler exposes. A getPrototypeOf trap
394+/// also makes the chain user-controlled (a cycle, or a fresh Proxy per hop,
395+/// is spec-legal on an extensible target), so track visited links and cap the
396+/// walk rather than let it hang the load.
397+const EXTENDS_SRC: &str = "((cls, base) => { \
398+ const seen = new Set(); \
399+ for (let p = Reflect.getPrototypeOf(cls); p; p = Reflect.getPrototypeOf(p)) { \
400+ if (p === base) return true; \
401+ if (seen.has(p) || seen.size >= 1000) return false; \
402+ seen.add(p); \
403+ } \
404+ return false; })";
405+
406+/// The walk crosses into user code when an export is a Proxy, so it can throw
407+/// (a revoked Proxy, a throwing getPrototypeOf trap). Pin a TryCatch and
408+/// surface that as a load error rather than misclassifying the export.
409+fn call_extends(
410+ scope: &mut v8::PinScope,
411+ extends: v8::Local<v8::Function>,
412+ class: v8::Local<v8::Value>,
413+ base: v8::Local<v8::Value>,
414+) -> Result<bool> {
415+ let tc = std::pin::pin!(v8::TryCatch::new(scope));
416+ let scope = &mut tc.init();
417+ let recv = v8::undefined(scope).into();
418+ match extends.call(scope, recv, &[class, base]) {
419+ Some(result) => Ok(result.is_true()),
420+ None => Err(anyhow!("inspect export prototype chain: {}", exc!(scope))),
421+ }
422+}
423+
424+/// Mark which cell scopes are local to this node and record the node id. Every
425+/// other scope routes cross-node via `__do_call`.
426+pub(super) fn inject_routing(scope: &mut v8::PinScope, owned: &[String], node: &str) -> Result<()> {
427+ let mut src = format!("(() => {{ __cell.node = {node:?};\n");
428+ for s in owned {
429+ src.push_str(&format!("__cell.owned[{s:?}] = true;\n"));
430+ }
431+ src.push_str("})();");
432+ let code = v8::String::new(scope, &src).unwrap();
433+ let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("routing compile"))?;
434+ s.run(scope).ok_or_else(|| anyhow!("routing run"))?;
435+ Ok(())
436+}
437+
438+/// Amend `inject_routing` for one cell, and restore its id name.
439+///
440+/// The isolate-side half of taking a cell in or giving it back. Kept beside
441+/// `inject_routing` because it edits the table that function builds.
442+pub(super) fn adopt_cell(
443+ tc: &mut v8::PinScope,
444+ cell: &str,
445+ db_path: Option<&str>,
446+ owned: bool,
447+) -> Result<Option<i64>> {
448+ if owned {
449+ if let Some(path) = db_path {
450+ storage::open(cell, path).context("cell storage open failed")?;
451+ }
452+ }
453+ // NOT marked local, deliberately. `__cell.owned[scope]` turns a cell
454+ // dispatch into an in-isolate call, and with one cell per isolate the
455+ // only reachable case was a cell calling itself. Now that cells share an
456+ // isolate the same flag makes A->B run B's handler *nested inside* A's,
457+ // and a cycle back to A nests again on one thread — which times out
458+ // (`actor lab self and cycle paths`).
459+ //
460+ // So every cell dispatch goes back out through the host and arrives as
461+ // an ordinary reentrant `CellJob::Fetch`, which the run loop already
462+ // supports. That costs a round trip and is the behaviour cells had
463+ // before they shared isolates. Re-enabling the fast path needs the
464+ // target checked against what is already on the stack; correctness
465+ // first.
466+ let source = format!("(() => {{ delete __cell.owned[{cell:?}]; }})();");
467+ let code = v8::String::new(tc, &source).unwrap();
468+ let script = v8::Script::compile(tc, code, None).ok_or_else(|| anyhow!("adopt compile"))?;
469+ script.run(tc).ok_or_else(|| anyhow!("adopt run"))?;
470+ if !owned {
471+ storage::close(cell);
472+ return Ok(None);
473+ }
474+ let name = storage::get_actor_name(cell).context("read actor name")?;
475+ register_actor_name(tc, cell, name.as_deref())?;
476+ Ok(storage::get_alarm(cell))
477+}
478+
479+pub(super) fn inject_storage_compatibility(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
480+ let source = format!(
481+ "__cell.deleteAllDeletesAlarm = {};\n\
482+ __cell.compat.jsRpc = {};\n\
483+ __cell.compat.fetcherGetPutDelete = {};\n\
484+ __cell.compat.websocketStandardBinaryType = {};",
485+ compat.delete_all_deletes_alarm,
486+ compat.js_rpc,
487+ compat.fetcher_get_put_delete,
488+ compat.websocket_standard_binary_type,
489+ );
490+ let code = v8::String::new(scope, &source).unwrap();
491+ let script =
492+ v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compatibility compile"))?;
493+ script
494+ .run(scope)
495+ .ok_or_else(|| anyhow!("compatibility run"))?;
496+ Ok(())
497+}
498+
499+pub(super) fn harness_env<'s>(
500+ scope: &mut v8::PinScope<'s, '_>,
501+) -> Result<v8::Local<'s, v8::Value>> {
502+ let ctx = scope.get_current_context();
503+ let global = ctx.global(scope);
504+ let ck = v8::String::new(scope, "__cell").unwrap();
505+ let cell = global
506+ .get(scope, ck.into())
507+ .unwrap()
508+ .to_object(scope)
509+ .unwrap();
510+ let ek = v8::String::new(scope, "env").unwrap();
511+ Ok(cell.get(scope, ek.into()).unwrap())
512+}
513+
514+pub(super) fn begin_event_context<'s>(
515+ scope: &mut v8::PinScope<'s, '_>,
516+) -> Result<v8::Local<'s, v8::Value>> {
517+ let global = scope.get_current_context().global(scope);
518+ let key = v8::String::new(scope, "__beginEvent").unwrap();
519+ let function: v8::Local<v8::Function> = global
520+ .get(scope, key.into())
521+ .ok_or_else(|| anyhow!("no __beginEvent"))?
522+ .try_into()
523+ .map_err(|_| anyhow!("__beginEvent is not a function"))?;
524+ let recv = v8::undefined(scope).into();
525+ function
526+ .call(scope, recv, &[])
527+ .ok_or_else(|| anyhow!("__beginEvent threw"))
528+}
529+
530+pub(super) fn end_event_context<'s>(
531+ scope: &mut v8::PinScope<'s, '_>,
532+) -> Result<Option<v8::Local<'s, v8::Promise>>> {
533+ let global = scope.get_current_context().global(scope);
534+ let key = v8::String::new(scope, "__endEvent").unwrap();
535+ let function: v8::Local<v8::Function> = global
536+ .get(scope, key.into())
537+ .ok_or_else(|| anyhow!("no __endEvent"))?
538+ .try_into()
539+ .map_err(|_| anyhow!("__endEvent is not a function"))?;
540+ let recv = v8::undefined(scope).into();
541+ let value = function
542+ .call(scope, recv, &[])
543+ .ok_or_else(|| anyhow!("__endEvent threw"))?;
544+ if value.is_null_or_undefined() {
545+ Ok(None)
546+ } else {
547+ Ok(Some(value.try_into().map_err(|_| {
548+ anyhow!("__endEvent did not return a promise")
549+ })?))
550+ }
551+}
552+
553+// ---- module compilation + request/response marshalling ----
modifiedcrates/celld/js/crypto.js+333−13View file
@@ -11,10 +11,32 @@
1111 const _aesEncrypt = $$aesEncrypt;
1212 const _aesDecrypt = $$aesDecrypt;
1313
14+ // MD5 is not in the Web Crypto spec; Cloudflare accepts it for `digest`
15+ // and DigestStream, and the host op has always implemented it.
16+ const _CRC_ALGS = new Set(["CRC32", "CRC32C", "CRC64NVME"]);
1417 const _DIGEST_ALGS = new Set([
15- "SHA-1", "SHA-256", "SHA-384", "SHA-512",
18+ "SHA-1", "SHA-256", "SHA-384", "SHA-512", "MD5",
1619 ]);
17- const _SECRET_KEY_ALGS = new Set(["HMAC", "AES-GCM", "AES-CBC"]);
20+ const _SECRET_KEY_ALGS = new Set(
21+ ["HMAC", "AES-GCM", "AES-CBC", "AES-CTR"],
22+ );
23+ // Algorithms whose keys are asymmetric, whatever celld can then *do* with
24+ // them: import validates the key, and an unsupported operation throws
25+ // later at sign/verify/encrypt rather than here.
26+ // Cloudflare accepts its own pre-standard curve spellings beside the
27+ // standard ones.
28+ const _curveName = (curve) =>
29+ curve === "NODE-ED25519" ? "Ed25519" : String(curve ?? "");
30+ // The curves celld carries, under every spelling Web Crypto and Node use.
31+ const _EC_CURVES = {
32+ "P-256": "P-256", "prime256v1": "P-256", "secp256r1": "P-256",
33+ "P-384": "P-384", "secp384r1": "P-384",
34+ "P-521": "P-521", "secp521r1": "P-521",
35+ };
36+ const _ASYM_ALGS = new Set([
37+ "RSASSA-PKCS1-V1_5", "RSA-OAEP", "RSA-PSS", "ECDSA", "ECDH",
38+ "ED25519", "X25519",
39+ ]);
1840
1941 function _toBuf(data) {
2042 if (data instanceof ArrayBuffer) return new Uint8Array(data);
@@ -65,6 +87,27 @@
6587 return JSON.parse(__crypto_operation(operation, JSON.stringify(input)));
6688 }
6789
90+ // AES-CBC and AES-CTR run through the host ops. CBC is PKCS#7-padded and
91+ // CTR is its own inverse, so `encrypting` only matters for CBC.
92+ function _aesBlockMode(name, algorithm, key, data, encrypting) {
93+ const bytes = Array.from(_toBuf(key.__celldMaterial.bytes));
94+ const input = Array.from(_toBuf(data));
95+ if (name === "AES-CTR") {
96+ // The counter is copied on the way in -- it is the caller's, and
97+ // incrementing it in place is the bug aesCounterOverflowTest pins.
98+ return _extra("aes-ctr", {
99+ key: bytes,
100+ counter: Array.from(_toBuf(algorithm.counter)),
101+ data: input,
102+ }).bytes;
103+ }
104+ return _extra(encrypting ? "aes-cbc-encrypt" : "aes-cbc-decrypt", {
105+ key: bytes,
106+ iv: Array.from(_toBuf(algorithm.iv)),
107+ data: input,
108+ }).bytes;
109+ }
110+
68111 class SubtleCrypto {
69112 get [Symbol.toStringTag]() { return "SubtleCrypto"; }
70113
@@ -88,10 +131,45 @@
88131 "secret", normalized, extractable, usages, { bytes: raw },
89132 );
90133 }
91- if (format === "pkcs8" && (name === "ED25519" || name === "ECDSA")) {
92- return _makeKey(
93- "private", algorithm, extractable, usages,
94- { bytes: _toBuf(keyData).slice() },
134+ // Asymmetric keys go through the same host import node:crypto uses, so
135+ // the CryptoKey carries the key type and details beside its bytes.
136+ // KeyObject.from() then sees a real asymmetric key rather than opaque
137+ // material, and the key is validated at import instead of at first use.
138+ if (
139+ (format === "spki" || format === "pkcs8" ||
140+ (format === "jwk" && name !== "RSA-OAEP")) &&
141+ _ASYM_ALGS.has(name)
142+ ) {
143+ const jwk = format === "jwk";
144+ const visibility =
145+ format === "pkcs8" || (jwk && keyData?.d !== undefined)
146+ ? "private"
147+ : "public";
148+ const imported = _extra("asym-key-import", {
149+ key: jwk ? keyData : Array.from(_toBuf(keyData)),
150+ format: jwk ? "jwk" : "der",
151+ type: jwk ? null : format,
152+ visibility,
153+ passphrase: null,
154+ });
155+ return _makeKey(visibility, algorithm, extractable, usages, {
156+ bytes: Uint8Array.from(imported.der),
157+ keyType: imported.keyType,
158+ details: imported.details,
159+ });
160+ }
161+ // An RSA-OAEP JWK keeps its JWK form: `rsa-oaep-decrypt` reads the
162+ // components directly rather than re-deriving them from DER.
163+ // A JWK's `alg` names the algorithm it was made for. Anything that is
164+ // not a string is not an algorithm name, and importing it would leave
165+ // a key claiming to be something it cannot be. (Web Crypto ignores a
166+ // *mismatched* alg on EC keys -- cloudflare/workerd#1403 -- so only
167+ // the type is checked, not the value.)
168+ if (format === "jwk" && keyData?.alg !== undefined &&
169+ typeof keyData.alg !== "string") {
170+ throw new DOMException(
171+ `Unrecognized or unimplemented algorithm "${String(keyData.alg)}"`,
172+ "NotSupportedError",
95173 );
96174 }
97175 if (format === "jwk" && name === "RSA-OAEP") {
@@ -120,9 +198,76 @@
120198 }
121199 return structuredClone(key.__celldMaterial.jwk);
122200 }
201+ // Asymmetric keys export from their normalized DER: spki and pkcs8 as
202+ // they are stored, jwk through the host.
203+ const material = key?.__celldMaterial;
204+ if (material?.keyType !== undefined) {
205+ if (!key.extractable) {
206+ throw new DOMException("key is not extractable", "InvalidAccessError");
207+ }
208+ const visibility = key.type;
209+ if (format === "jwk") {
210+ return _extra("asym-key-export", {
211+ der: Array.from(material.bytes),
212+ visibility,
213+ }).jwk;
214+ }
215+ if ((format === "spki" && visibility === "public") ||
216+ (format === "pkcs8" && visibility === "private")) {
217+ const der = material.bytes;
218+ return der.buffer.slice(der.byteOffset, der.byteOffset + der.byteLength);
219+ }
220+ }
123221 throw _notSupported("unsupported key export");
124222 }
125223
224+ // Cloudflare's extension, not Web Crypto: a constant-time compare for
225+ // signatures and MACs, where `===` on a decoded string leaks by timing.
226+ // Equal lengths are required, so this cannot be used to probe length.
227+ timingSafeEqual(a, b) {
228+ const left = _toBuf(a), right = _toBuf(b);
229+ if (left.byteLength !== right.byteLength) {
230+ throw new TypeError(
231+ "Input buffers must have the same byte length");
232+ }
233+ return $$timingSafeEqual(left, right);
234+ }
235+
236+ // ECDH. `length` may be null or undefined, a recent spec change: the
237+ // shared secret is the curve's field size, so there is a right answer
238+ // without being told one. A shorter length truncates, as the spec says.
239+ async deriveBits(algorithm, baseKey, length) {
240+ const name = _algorithmName(algorithm);
241+ if (name !== "ECDH") {
242+ throw _notSupported("unsupported derive algorithm: " + name);
243+ }
244+ const publicKey = algorithm?.public;
245+ if (!publicKey || publicKey.type !== "public") {
246+ throw new TypeError("ECDH requires a public key in algorithm.public");
247+ }
248+ const shared = Uint8Array.from(_extra("ecdh-derive", {
249+ private: Array.from(_toBuf(baseKey.__celldMaterial.bytes)),
250+ public: Array.from(_toBuf(publicKey.__celldMaterial.bytes)),
251+ }).bytes);
252+ if (length === null || length === undefined) return shared.buffer;
253+ const bytes = Number(length) / 8;
254+ if (!Number.isInteger(bytes) || bytes < 0 || bytes > shared.byteLength) {
255+ throw _operationError("requested length exceeds the derived secret");
256+ }
257+ return shared.slice(0, bytes).buffer;
258+ }
259+
260+ async deriveKey(algorithm, baseKey, derived, extractable, usages) {
261+ const name = _algorithmName(derived);
262+ const length = derived?.length ??
263+ (name === "AES-GCM" || name === "AES-CBC" || name === "AES-CTR"
264+ ? 256
265+ : null);
266+ const bits = await this.deriveBits(algorithm, baseKey, length);
267+ return this.importKey(
268+ "raw", bits, derived, extractable, usages);
269+ }
270+
126271 async generateKey(algorithm, extractable, usages) {
127272 const name = _algorithmName(algorithm);
128273 if (_SECRET_KEY_ALGS.has(name)) {
@@ -178,6 +323,69 @@
178323 ),
179324 };
180325 }
326+ // Asymmetric signing keys. `NODE-ED25519` is Cloudflare's pre-standard
327+ // spelling of Ed25519 and stays as the reported algorithm name, because
328+ // the caller matched on what it asked for.
329+ const ASYM_GENERATE = {
330+ "RSASSA-PKCS1-V1_5": "rsa",
331+ "RSA-PSS": "rsa",
332+ "ED25519": "ed25519",
333+ "NODE-ED25519": "ed25519",
334+ "ECDSA": "ec",
335+ "ECDH": "ec",
336+ };
337+ const kind = ASYM_GENERATE[name];
338+ if (kind !== undefined) {
339+ const options = { type: kind };
340+ if (kind === "rsa") {
341+ // Only 3 and 65537 are legal exponents, and celld generates with
342+ // 65537. Rejecting the rest here is what stops a pathological
343+ // exponent reaching the prime search at all.
344+ const raw = algorithm?.publicExponent;
345+ const bytes = raw ? Array.from(_toBuf(raw)) : [1, 0, 1];
346+ let exponent = 0;
347+ for (const byte of bytes) exponent = exponent * 256 + byte;
348+ if (exponent !== 3 && exponent !== 65537) {
349+ throw new DOMException(
350+ `The "publicExponent" must be either 3 or 65537, but got ` +
351+ `${exponent}.`,
352+ "OperationError",
353+ );
354+ }
355+ if (exponent !== 65537) {
356+ throw _notSupported("publicExponent 3 is not implemented");
357+ }
358+ options.modulusLength = Number(algorithm?.modulusLength ?? 2048);
359+ }
360+ if (kind === "ec") {
361+ const curve = _EC_CURVES[_curveName(algorithm?.namedCurve)];
362+ if (curve === undefined)
363+ throw _notSupported("unsupported curve: " + algorithm?.namedCurve);
364+ options.namedCurve = curve;
365+ }
366+ const pair = _extra("asym-key-generate", options);
367+ // The algorithm is echoed back with the exponent as a Uint8Array,
368+ // which is what `crypto_preserve_public_exponent` fixed upstream --
369+ // an ArrayBuffer there is the bug that flag names.
370+ const reported = { ...algorithm, name };
371+ if (kind === "rsa") {
372+ reported.publicExponent = Uint8Array.from(
373+ algorithm?.publicExponent ? _toBuf(algorithm.publicExponent) : [1, 0, 1],
374+ );
375+ }
376+ const half = (der, type, allowed) =>
377+ _makeKey(type, reported, type === "public" ? true : extractable,
378+ (usages || []).filter((usage) => allowed.includes(usage)), {
379+ bytes: Uint8Array.from(der),
380+ keyType: pair.keyType,
381+ details: pair.details,
382+ });
383+ return {
384+ publicKey: half(pair.publicDer, "public", ["verify", "encrypt"]),
385+ privateKey: half(pair.privateDer, "private",
386+ ["sign", "decrypt", "deriveKey", "deriveBits"]),
387+ };
388+ }
181389 throw _notSupported("unsupported key algorithm: " + name);
182390 }
183391
@@ -205,19 +413,46 @@
205413
206414 async verify(algorithm, key, signature, data) {
207415 const name = _algorithmName(algorithm || key?.algorithm);
208- if (name !== "HMAC") {
416+ if (name === "HMAC") {
417+ return _hmacVerify(
418+ _hashName(key?.algorithm?.hash),
419+ key.__celldMaterial.bytes,
420+ _toBuf(signature),
421+ _toBuf(data),
422+ );
423+ }
424+ const operation = name === "ECDSA"
425+ ? "p256-verify"
426+ : name === "RSASSA-PKCS1-V1_5"
427+ ? "rsa-pkcs1-verify"
428+ : null;
429+ if (!operation) {
209430 throw _notSupported("unsupported verify algorithm: " + name);
210431 }
211- return _hmacVerify(
212- _hashName(key?.algorithm?.hash),
213- key.__celldMaterial.bytes,
214- _toBuf(signature),
215- _toBuf(data),
216- );
432+ const material = key?.__celldMaterial?.bytes;
433+ if (!material) throw _notSupported("verify needs an spki public key");
434+ return _extra(operation, {
435+ key: Array.from(material),
436+ data: Array.from(_toBuf(data)),
437+ signature: Array.from(_toBuf(signature)),
438+ // ECDSA carries its hash on the call, RSASSA on the key.
439+ hash: _hashName(
440+ name === "ECDSA" ? algorithm?.hash : key?.algorithm?.hash,
441+ ),
442+ }).ok;
217443 }
218444
219445 async encrypt(algorithm, key, data) {
220446 const name = _algorithmName(algorithm);
447+ if (name === "AES-GCM" && _toBuf(algorithm.iv).byteLength === 0) {
448+ throw new DOMException(
449+ "AES-GCM IV must not be empty.", "OperationError");
450+ }
451+ if (name === "AES-CBC" || name === "AES-CTR") {
452+ const out = Uint8Array.from(
453+ _aesBlockMode(name, algorithm, key, data, true));
454+ return out.buffer;
455+ }
221456 if (name !== "AES-GCM") {
222457 throw _notSupported("unsupported encrypt algorithm: " + name);
223458 }
@@ -232,6 +467,15 @@
232467
233468 async decrypt(algorithm, key, data) {
234469 const name = _algorithmName(algorithm);
470+ if (name === "AES-GCM" && _toBuf(algorithm.iv).byteLength === 0) {
471+ throw new DOMException(
472+ "AES-GCM IV must not be empty.", "OperationError");
473+ }
474+ if (name === "AES-CBC" || name === "AES-CTR") {
475+ const out = Uint8Array.from(
476+ _aesBlockMode(name, algorithm, key, data, false));
477+ return out.buffer;
478+ }
235479 if (name === "AES-GCM") {
236480 const out = _aesDecrypt(
237481 key.__celldMaterial.bytes,
@@ -299,6 +543,82 @@
299543 get [Symbol.toStringTag]() { return "Crypto"; },
300544 };
301545
546+ // Cloudflare's DigestStream: a WritableStream that hashes what is written
547+ // to it and resolves `digest` when the stream closes. Not Web Crypto, and
548+ // the reason a Worker can hash a body it never has to hold whole -- though
549+ // celld buffers here, as its Hash already does.
550+ class DigestStream extends WritableStream {
551+ constructor(algorithm) {
552+ const name = _algorithmName(algorithm);
553+ // DigestStream takes the CRC checksums too; `subtle.digest` does not.
554+ if (!_DIGEST_ALGS.has(name) && !_CRC_ALGS.has(name)) {
555+ throw _notSupported("unsupported digest algorithm: " + name);
556+ }
557+ const state = { chunks: [], written: 0, resolve: null, reject: null };
558+ const digest = new Promise((resolve, reject) => {
559+ state.resolve = resolve;
560+ state.reject = reject;
561+ });
562+ super({
563+ write(chunk) {
564+ // A string is written as its UTF-8 bytes, as workerd does; every
565+ // other chunk must already be binary.
566+ if (typeof chunk !== "string" && !ArrayBuffer.isView(chunk) &&
567+ !(chunk instanceof ArrayBuffer)) {
568+ throw new TypeError(
569+ "DigestStream is a byte stream but received an object of " +
570+ "non-ArrayBuffer/ArrayBufferView/string type on its " +
571+ "writable side.");
572+ }
573+ const bytes = typeof chunk === "string"
574+ ? new TextEncoder().encode(chunk)
575+ : _toBuf(chunk);
576+ state.chunks.push(bytes);
577+ state.written += bytes.byteLength;
578+ },
579+ close() {
580+ const joined = new Uint8Array(state.written);
581+ let offset = 0;
582+ for (const chunk of state.chunks) {
583+ joined.set(chunk, offset);
584+ offset += chunk.byteLength;
585+ }
586+ state.chunks.length = 0;
587+ const out = _digest(name, joined);
588+ state.resolve(
589+ out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength));
590+ },
591+ abort(reason) {
592+ state.chunks.length = 0;
593+ state.reject(reason);
594+ },
595+ });
596+ // A stream that is written to and never closed is legal, and so is one
597+ // that is disposed. Neither should raise an unhandled rejection just
598+ // because nobody awaited `digest`.
599+ digest.catch(() => {});
600+ Object.defineProperties(this, {
601+ digest: { value: digest, enumerable: true },
602+ bytesWritten: { get: () => BigInt(state.written), enumerable: true },
603+ });
604+ this.__celldDigestState = state;
605+ }
606+ get [Symbol.toStringTag]() { return "DigestStream"; }
607+ [Symbol.dispose]() {
608+ const state = this.__celldDigestState;
609+ if (state.disposed) return; // disposing twice is a no-op
610+ state.disposed = true;
611+ state.chunks.length = 0;
612+ const error = new Error("The DigestStream was disposed.");
613+ state.reject(error);
614+ // Error the stream itself, so a later write() rejects with the same
615+ // reason rather than succeeding into a digest nobody will resolve.
616+ this.abort(error).catch(() => {});
617+ }
618+ }
619+
620+ crypto.DigestStream = DigestStream;
621+ globalThis.DigestStream = DigestStream;
302622 globalThis.CryptoKey = CryptoKey;
303623 globalThis.SubtleCrypto = SubtleCrypto;
304624 globalThis.crypto = crypto;
addedcrates/celld/js/crypto.rs+1528−0View file
@@ -1,0 +1,1528 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! Web Crypto and node:crypto: the key formats and the primitives.
4+//!
5+//! The JS layer in `crypto.js` and `node_crypto.js` validates the arguments,
6+//! so what arrives here is already well formed. This module holds the key
7+//! formats — SPKI, PKCS#8, JWK, raw — and the operations that use them. It
8+//! touches V8 only in its ops.
9+use super::*;
10+
11+fn crypto_bytes(value: &serde_json::Value, name: &str) -> Result<Vec<u8>> {
12+ serde_json::from_value(value.get(name).cloned().unwrap_or_default())
13+ .map_err(|_| anyhow!("invalid {name} bytes"))
14+}
15+
16+fn rsa_jwk_uint(value: &serde_json::Value, name: &str) -> Result<rsa::BigUint> {
17+ use base64::Engine;
18+ let encoded = value
19+ .get(name)
20+ .and_then(|value| value.as_str())
21+ .ok_or_else(|| anyhow!("RSA JWK missing {name} parameter"))?;
22+ let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
23+ .decode(encoded)
24+ .map_err(|_| anyhow!("invalid RSA JWK {name}"))?;
25+ Ok(rsa::BigUint::from_bytes_be(&bytes))
26+}
27+
28+fn rsa_jwk_encode(value: &rsa::BigUint) -> String {
29+ use base64::Engine;
30+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value.to_bytes_be())
31+}
32+
33+/// Algorithm OIDs, so a parsed key can say what it is. Same constants as
34+/// Node's, via deno's `ext/node_crypto/keys.rs`.
35+const RSA_ENCRYPTION_OID: rsa::pkcs8::ObjectIdentifier =
36+ rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
37+const EC_PUBLIC_KEY_OID: rsa::pkcs8::ObjectIdentifier =
38+ rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
39+const SECP256R1_OID: rsa::pkcs8::ObjectIdentifier =
40+ rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
41+const SECP384R1_OID: rsa::pkcs8::ObjectIdentifier =
42+ rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.132.0.34");
43+const SECP521R1_OID: rsa::pkcs8::ObjectIdentifier =
44+ rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.132.0.35");
45+
46+/// The NIST curves celld reads, as (OID, Node's `namedCurve`, JWK `crv`).
47+/// Signing stays on P-256; these three are for parsing and JWK.
48+const EC_CURVES: &[(rsa::pkcs8::ObjectIdentifier, &str, &str)] = &[
49+ (SECP256R1_OID, "prime256v1", "P-256"),
50+ (SECP384R1_OID, "secp384r1", "P-384"),
51+ (SECP521R1_OID, "secp521r1", "P-521"),
52+];
53+
54+/// Run `$body!(crate)` against whichever curve crate `$crv` names. The three
55+/// crates share an API, so this is the alternative to writing every EC arm
56+/// out three times.
57+macro_rules! ec_curve {
58+ ($crv:expr, $body:ident) => {
59+ match $crv {
60+ "P-256" => $body!(p256),
61+ "P-384" => $body!(p384),
62+ "P-521" => $body!(p521),
63+ other => return Err(anyhow!("unsupported EC curve {other}")),
64+ }
65+ };
66+}
67+const ED25519_OID: rsa::pkcs8::ObjectIdentifier =
68+ rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.101.112");
69+const X25519_OID: rsa::pkcs8::ObjectIdentifier =
70+ rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.101.110");
71+const DSA_OID: rsa::pkcs8::ObjectIdentifier =
72+ rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10040.4.1");
73+
74+/// A key normalized to one DER encoding: PKCS#8 for private, SPKI for public.
75+/// Every consumer — the sign and verify ops, `toCryptoKey`, export — then
76+/// reads one shape rather than five.
77+struct ParsedKey {
78+ kind: &'static str,
79+ der: Vec<u8>,
80+ details: serde_json::Value,
81+}
82+
83+/// X25519 has no DER codec in `x25519-dalek`, and both structures are a
84+/// fixed shape for a 32-byte key, so they are written out directly. Verified
85+/// against the `x25519_private.pem` / `x25519_public.pem` fixtures.
86+fn x25519_pkcs8(scalar: &[u8; 32]) -> Vec<u8> {
87+ let mut der = vec![
88+ 0x30, 0x2e, // SEQUENCE, 46 bytes
89+ 0x02, 0x01, 0x00, // version 0
90+ 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, // AlgorithmIdentifier, X25519
91+ 0x04, 0x22, 0x04, 0x20, // OCTET STRING(34) wrapping OCTET STRING(32)
92+ ];
93+ der.extend_from_slice(scalar);
94+ der
95+}
96+
97+fn x25519_spki(point: &[u8; 32]) -> Vec<u8> {
98+ let mut der = vec![
99+ 0x30, 0x2a, // SEQUENCE, 42 bytes
100+ 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, // AlgorithmIdentifier, X25519
101+ 0x03, 0x21, 0x00, // BIT STRING(33), no unused bits
102+ ];
103+ der.extend_from_slice(point);
104+ der
105+}
106+
107+/// The JWK `crv` for a parsed EC key, from the `namedCurve` its details
108+/// already carry.
109+fn ec_jwk_crv(parsed: &ParsedKey) -> Result<&'static str> {
110+ let named = parsed.details["namedCurve"]
111+ .as_str()
112+ .ok_or_else(|| anyhow!("EC key has no named curve"))?;
113+ EC_CURVES
114+ .iter()
115+ .find(|(_, node, _)| *node == named)
116+ .map(|(.., crv)| *crv)
117+ .ok_or_else(|| anyhow!("unsupported EC curve {named}"))
118+}
119+
120+/// PEM armour: 64-character base64 lines between the labelled delimiters.
121+fn pem_wrap(label: &str, bytes: &[u8]) -> String {
122+ use base64::Engine;
123+ let body = base64::engine::general_purpose::STANDARD.encode(bytes);
124+ let mut out = format!("-----BEGIN {label}-----\n");
125+ for line in body.as_bytes().chunks(64) {
126+ out.push_str(std::str::from_utf8(line).unwrap());
127+ out.push('\n');
128+ }
129+ out.push_str(&format!("-----END {label}-----\n"));
130+ out
131+}
132+
133+fn base64url(value: &[u8]) -> String {
134+ use base64::Engine;
135+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value)
136+}
137+
138+fn jwk_bytes(value: &serde_json::Value, kty: &str, name: &str) -> Result<Vec<u8>> {
139+ use base64::Engine;
140+ let encoded = value
141+ .get(name)
142+ .and_then(serde_json::Value::as_str)
143+ .ok_or_else(|| anyhow!("{kty} JWK missing {name} parameter"))?;
144+ base64::engine::general_purpose::URL_SAFE_NO_PAD
145+ .decode(encoded)
146+ .map_err(|_| anyhow!("invalid JWK {name}"))
147+}
148+
149+/// Identify an already-normalized PKCS#8 or SPKI blob and describe it. Node
150+/// reports `asymmetricKeyType` and `asymmetricKeyDetails` from exactly this.
151+fn describe_key(der: &[u8], private: bool) -> Result<ParsedKey> {
152+ use rsa::pkcs8::der::Decode;
153+ use rsa::traits::PublicKeyParts;
154+
155+ let (algorithm, curve) = if private {
156+ let info = rsa::pkcs8::PrivateKeyInfo::from_der(der)
157+ .map_err(|_| anyhow!("invalid PKCS#8 private key"))?;
158+ (info.algorithm.oid, info.algorithm.parameters_oid().ok())
159+ } else {
160+ let info = rsa::pkcs8::SubjectPublicKeyInfoRef::from_der(der)
161+ .map_err(|_| anyhow!("invalid SPKI public key"))?;
162+ (info.algorithm.oid, info.algorithm.parameters_oid().ok())
163+ };
164+
165+ match algorithm {
166+ RSA_ENCRYPTION_OID => {
167+ // Node reports the modulus length and exponent, so the key has to
168+ // be parsed rather than merely recognized.
169+ let (modulus, exponent) = if private {
170+ use rsa::pkcs8::DecodePrivateKey;
171+ let key = rsa::RsaPrivateKey::from_pkcs8_der(der)
172+ .map_err(|_| anyhow!("invalid RSA private key"))?;
173+ (key.n().bits(), key.e().clone())
174+ } else {
175+ use rsa::pkcs8::DecodePublicKey;
176+ let key = rsa::RsaPublicKey::from_public_key_der(der)
177+ .map_err(|_| anyhow!("invalid RSA public key"))?;
178+ (key.n().bits(), key.e().clone())
179+ };
180+ Ok(ParsedKey {
181+ kind: "rsa",
182+ der: der.to_vec(),
183+ details: serde_json::json!({
184+ "modulusLength": modulus,
185+ "publicExponent": exponent.to_string(),
186+ }),
187+ })
188+ }
189+ EC_PUBLIC_KEY_OID => {
190+ // celld carries P-256 only, matching its Web Crypto surface. A
191+ // P-384 key parses far enough to be named, then is refused here
192+ // rather than silently treated as something else.
193+ let curve = curve.ok_or_else(|| anyhow!("EC key has no named curve"))?;
194+ let named = EC_CURVES
195+ .iter()
196+ .find(|(oid, ..)| *oid == curve)
197+ .ok_or_else(|| anyhow!("unsupported EC curve {curve}"))?
198+ .1;
199+ Ok(ParsedKey {
200+ kind: "ec",
201+ der: der.to_vec(),
202+ details: serde_json::json!({ "namedCurve": named }),
203+ })
204+ }
205+ ED25519_OID => Ok(ParsedKey {
206+ kind: "ed25519",
207+ der: der.to_vec(),
208+ details: serde_json::json!({}),
209+ }),
210+ DSA_OID => {
211+ use dsa::pkcs8::DecodePrivateKey;
212+ use dsa::pkcs8::DecodePublicKey;
213+ use dsa::Components;
214+ let sizes = |components: &Components| (components.p().bits(), components.q().bits());
215+ let (modulus, divisor) = if private {
216+ let key = dsa::SigningKey::from_pkcs8_der(der)
217+ .map_err(|_| anyhow!("invalid DSA private key"))?;
218+ sizes(key.verifying_key().components())
219+ } else {
220+ let key = dsa::VerifyingKey::from_public_key_der(der)
221+ .map_err(|_| anyhow!("invalid DSA public key"))?;
222+ sizes(key.components())
223+ };
224+ Ok(ParsedKey {
225+ kind: "dsa",
226+ der: der.to_vec(),
227+ details: serde_json::json!({
228+ "modulusLength": modulus,
229+ "divisorLength": divisor,
230+ }),
231+ })
232+ }
233+ X25519_OID => Ok(ParsedKey {
234+ kind: "x25519",
235+ der: der.to_vec(),
236+ details: serde_json::json!({}),
237+ }),
238+ other => Err(anyhow!(
239+ "unsupported key algorithm {other}; celld implements RSA, EC P-256 and Ed25519"
240+ )),
241+ }
242+}
243+
244+/// PEM label -> the DER structure inside it. Node keys the whole import off
245+/// this, because the label is the only self-description a PEM file carries.
246+fn pem_structure(label: &str) -> Result<&'static str> {
247+ Ok(match label {
248+ "PRIVATE KEY" => "pkcs8",
249+ "RSA PRIVATE KEY" => "pkcs1",
250+ "EC PRIVATE KEY" => "sec1",
251+ "DSA PRIVATE KEY" => "dsa-traditional",
252+ "PUBLIC KEY" => "spki",
253+ "RSA PUBLIC KEY" => "pkcs1-public",
254+ // Handled before this point, where the passphrase is in scope.
255+ "ENCRYPTED PRIVATE KEY" => "pkcs8",
256+ other => return Err(anyhow!("unsupported PEM label \"{other}\"")),
257+ })
258+}
259+
260+/// Re-encode any accepted private structure as PKCS#8, and any public one as
261+/// SPKI.
262+fn normalize_key(der: &[u8], structure: &str) -> Result<(Vec<u8>, bool)> {
263+ use rsa::pkcs8::EncodePrivateKey;
264+ use rsa::pkcs8::EncodePublicKey;
265+ match structure {
266+ "pkcs8" => Ok((der.to_vec(), true)),
267+ "spki" => Ok((der.to_vec(), false)),
268+ "pkcs1" => {
269+ use rsa::pkcs1::DecodeRsaPrivateKey;
270+ let key = rsa::RsaPrivateKey::from_pkcs1_der(der)
271+ .map_err(|_| anyhow!("invalid PKCS#1 RSA private key"))?;
272+ Ok((key.to_pkcs8_der()?.as_bytes().to_vec(), true))
273+ }
274+ "pkcs1-public" => {
275+ use rsa::pkcs1::DecodeRsaPublicKey;
276+ let key = rsa::RsaPublicKey::from_pkcs1_der(der)
277+ .map_err(|_| anyhow!("invalid PKCS#1 RSA public key"))?;
278+ Ok((key.to_public_key_der()?.as_bytes().to_vec(), false))
279+ }
280+ // OpenSSL's traditional DSA key: a bare SEQUENCE of six INTEGERs
281+ // with no algorithm identifier, so it has to be read field by field
282+ // and rebuilt as PKCS#8. Same shape deno parses.
283+ "dsa-traditional" => {
284+ use dsa::pkcs8::der::asn1::UintRef;
285+ use dsa::pkcs8::der::{Decode, Reader, SliceReader};
286+ use dsa::pkcs8::EncodePrivateKey;
287+ let mut reader =
288+ SliceReader::new(der).map_err(|_| anyhow!("invalid DSA private key"))?;
289+ let key = reader
290+ .sequence(|seq| {
291+ let _version = UintRef::decode(seq)?;
292+ let mut field = || -> Result<rsa::BigUint, dsa::pkcs8::der::Error> {
293+ Ok(rsa::BigUint::from_bytes_be(
294+ UintRef::decode(seq)?.as_bytes(),
295+ ))
296+ };
297+ let (p, q, g, y, x) = (field()?, field()?, field()?, field()?, field()?);
298+ let bad = || dsa::pkcs8::der::Tag::Sequence.value_error();
299+ let components =
300+ dsa::Components::from_components(p, q, g).map_err(|_| bad())?;
301+ let verifying =
302+ dsa::VerifyingKey::from_components(components, y).map_err(|_| bad())?;
303+ dsa::SigningKey::from_components(verifying, x).map_err(|_| bad())
304+ })
305+ .map_err(|_| anyhow!("invalid DSA private key"))?;
306+ Ok((key.to_pkcs8_der()?.as_bytes().to_vec(), true))
307+ }
308+ "sec1" => {
309+ // SEC1 names no algorithm, so P-256 is the only reading celld has.
310+ let key = p256::SecretKey::from_sec1_der(der)
311+ .map_err(|_| anyhow!("invalid SEC1 EC private key (celld implements P-256)"))?;
312+ Ok((
313+ p256::pkcs8::EncodePrivateKey::to_pkcs8_der(&key)?
314+ .as_bytes()
315+ .to_vec(),
316+ true,
317+ ))
318+ }
319+ other => Err(anyhow!("unsupported key structure \"{other}\"")),
320+ }
321+}
322+
323+/// Node does not trust the caller's `type` for DER input — it sniffs, so the
324+/// same PKCS#1 blob imports whether the caller says `pkcs1`, `pkcs8` or
325+/// `sec1`. `crypto-keys-test.js` asserts exactly that ("All three of these
326+/// variations should work, despite the type being different"), so the stated
327+/// structure is only a hint about which decoder to try first.
328+fn normalize_key_sniffing(der: &[u8], stated: Option<&str>, want_private: bool) -> Result<Vec<u8>> {
329+ // `pkcs8` is exact; every other hint falls back. The suite pins both
330+ // halves: a PKCS#8 blob imports whether it is called pkcs1, pkcs8 or
331+ // sec1, but a PKCS#1 blob called `pkcs8` must fail -- "just like with
332+ // Node.js ... tho oddly sec1 is ok. Silly software."
333+ let candidates: &[&str] = match (want_private, stated) {
334+ (true, Some("pkcs8")) => &["pkcs8"],
335+ (true, _) => &["pkcs8", "pkcs1", "sec1"],
336+ (false, _) => &["spki", "pkcs1-public"],
337+ };
338+ let mut order: Vec<&str> = stated
339+ .into_iter()
340+ .filter(|s| candidates.contains(s))
341+ .collect();
342+ order.extend(candidates.iter().filter(|s| Some(**s) != stated));
343+
344+ let mut last = None;
345+ for structure in order {
346+ // A structure that decodes but yields the wrong visibility is not a
347+ // match either, so validate all the way through identification.
348+ if let Ok((der, is_private)) = normalize_key(der, structure) {
349+ if is_private == want_private && describe_key(&der, is_private).is_ok() {
350+ return Ok(der);
351+ }
352+ }
353+ last = Some(structure);
354+ }
355+ let _ = last;
356+ // Node's wording, which the suite matches on exactly.
357+ Err(anyhow!("Failed to parse private key"))
358+}
359+
360+/// A JWK becomes the same normalized DER, so JWK input costs nothing extra
361+/// downstream.
362+fn key_from_jwk(jwk: &serde_json::Value, want_private: bool) -> Result<Vec<u8>> {
363+ use rsa::pkcs8::EncodePrivateKey;
364+ use rsa::pkcs8::EncodePublicKey;
365+ let kty = jwk
366+ .get("kty")
367+ .and_then(serde_json::Value::as_str)
368+ .unwrap_or("");
369+ let curve = jwk.get("crv").and_then(serde_json::Value::as_str);
370+ // A curve-bearing kty with no `crv` is a malformed JWK, not an
371+ // unsupported one, and Node distinguishes the two by message.
372+ if matches!(kty, "EC" | "OKP") && curve.is_none() {
373+ return Err(anyhow!("{kty} JWK missing crv parameter"));
374+ }
375+ match (kty, curve) {
376+ ("RSA", _) => {
377+ let n = rsa_jwk_uint(jwk, "n")?;
378+ let e = rsa_jwk_uint(jwk, "e")?;
379+ if want_private {
380+ // The CRT primes are required: RSA private operations need
381+ // them, and a JWK carrying only `d` cannot be completed here.
382+ let d = rsa_jwk_uint(jwk, "d")?;
383+ let p = rsa_jwk_uint(jwk, "p")?;
384+ let q = rsa_jwk_uint(jwk, "q")?;
385+ let mut key = rsa::RsaPrivateKey::from_components(n, e, d, vec![p, q])?;
386+ key.precompute()?;
387+ Ok(key.to_pkcs8_der()?.as_bytes().to_vec())
388+ } else {
389+ let key = rsa::RsaPublicKey::new(n, e)?;
390+ Ok(key.to_public_key_der()?.as_bytes().to_vec())
391+ }
392+ }
393+ ("EC", Some(crv)) => {
394+ // x and y are checked even for a private key, and before d,
395+ // because that is the order Node reports missing parameters in.
396+ let x = jwk_bytes(jwk, "EC", "x")?;
397+ let y = jwk_bytes(jwk, "EC", "y")?;
398+ macro_rules! import {
399+ ($c:ident) => {{
400+ if want_private {
401+ let d = jwk_bytes(jwk, "EC", "d")?;
402+ let key = $c::SecretKey::from_slice(&d)
403+ .map_err(|_| anyhow!("invalid {} JWK private scalar", crv))?;
404+ // x and y are not decoration: a JWK whose public
405+ // point does not match its scalar describes two
406+ // different keys, and signing with it would produce
407+ // signatures nobody can verify against the x/y the
408+ // caller believes they imported.
409+ use $c::elliptic_curve::sec1::ToEncodedPoint;
410+ let point = key.public_key().to_encoded_point(false);
411+ if point.x().map(|v| v.as_slice()) != Some(x.as_slice())
412+ || point.y().map(|v| v.as_slice()) != Some(y.as_slice())
413+ {
414+ return Err(anyhow!(
415+ "{} JWK private key is inconsistent with its public point",
416+ crv
417+ ));
418+ }
419+ $c::pkcs8::EncodePrivateKey::to_pkcs8_der(&key)?
420+ .as_bytes()
421+ .to_vec()
422+ } else {
423+ let mut sec1 = Vec::with_capacity(1 + x.len() + y.len());
424+ sec1.push(0x04); // uncompressed point
425+ sec1.extend_from_slice(&x);
426+ sec1.extend_from_slice(&y);
427+ let key = $c::PublicKey::from_sec1_bytes(&sec1)
428+ .map_err(|_| anyhow!("invalid {} JWK public point", crv))?;
429+ $c::pkcs8::EncodePublicKey::to_public_key_der(&key)?
430+ .as_bytes()
431+ .to_vec()
432+ }
433+ }};
434+ }
435+ Ok(ec_curve!(crv, import))
436+ }
437+ ("OKP", Some("X25519")) => {
438+ // x25519-dalek has no DER codec, so the 32 raw bytes are wrapped
439+ // by hand. Both structures are fixed-shape for this algorithm:
440+ // PKCS#8 carries the scalar in an OCTET STRING inside an OCTET
441+ // STRING, SPKI the public point as a BIT STRING.
442+ let _ = jwk_bytes(jwk, "OKP", "x")?;
443+ if want_private {
444+ let d = jwk_bytes(jwk, "OKP", "d")?;
445+ let seed: [u8; 32] = d
446+ .as_slice()
447+ .try_into()
448+ .map_err(|_| anyhow!("X25519 JWK private key must be 32 bytes"))?;
449+ Ok(x25519_pkcs8(&seed))
450+ } else {
451+ let x = jwk_bytes(jwk, "OKP", "x")?;
452+ let point: [u8; 32] = x
453+ .as_slice()
454+ .try_into()
455+ .map_err(|_| anyhow!("X25519 JWK public key must be 32 bytes"))?;
456+ Ok(x25519_spki(&point))
457+ }
458+ }
459+ ("OKP", Some("Ed25519")) => {
460+ let _ = jwk_bytes(jwk, "OKP", "x")?;
461+ if want_private {
462+ let d = jwk_bytes(jwk, "OKP", "d")?;
463+ let seed: [u8; 32] = d
464+ .as_slice()
465+ .try_into()
466+ .map_err(|_| anyhow!("Ed25519 JWK private key must be 32 bytes"))?;
467+ let key = ed25519_dalek::SigningKey::from_bytes(&seed);
468+ use ed25519_dalek::pkcs8::EncodePrivateKey;
469+ Ok(key.to_pkcs8_der()?.as_bytes().to_vec())
470+ } else {
471+ let x = jwk_bytes(jwk, "OKP", "x")?;
472+ let point: [u8; 32] = x
473+ .as_slice()
474+ .try_into()
475+ .map_err(|_| anyhow!("Ed25519 JWK public key must be 32 bytes"))?;
476+ let key = ed25519_dalek::VerifyingKey::from_bytes(&point)
477+ .map_err(|_| anyhow!("invalid Ed25519 JWK public key"))?;
478+ use ed25519_dalek::pkcs8::EncodePublicKey;
479+ Ok(key.to_public_key_der()?.as_bytes().to_vec())
480+ }
481+ }
482+ _ => Err(anyhow!(
483+ "JWK {} key import is not implemented for this key type",
484+ if want_private { "private" } else { "public" }
485+ )),
486+ }
487+}
488+
489+fn crypto_operation(operation: &str, args: &serde_json::Value) -> Result<serde_json::Value> {
490+ match operation {
491+ "hmac-sign" => {
492+ use hmac::Mac;
493+ let key = crypto_bytes(args, "key")?;
494+ let data = crypto_bytes(args, "data")?;
495+ let hash = args
496+ .get("hash")
497+ .and_then(|value| value.as_str())
498+ .unwrap_or("SHA-256");
499+ if !hash.eq_ignore_ascii_case("SHA-256") && !hash.eq_ignore_ascii_case("SHA256") {
500+ return Err(anyhow!("unsupported HMAC hash"));
501+ }
502+ let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(&key)
503+ .map_err(|_| anyhow!("invalid HMAC key"))?;
504+ mac.update(&data);
505+ Ok(serde_json::json!({ "bytes": mac.finalize().into_bytes().to_vec() }))
506+ }
507+ // AES-CBC with PKCS#7 padding, and AES-CTR. Both take 128- or
508+ // 256-bit keys.
509+ "aes-cbc-encrypt" | "aes-cbc-decrypt" => {
510+ use cbc::cipher::block_padding::Pkcs7;
511+ use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
512+ let key = crypto_bytes(args, "key")?;
513+ let iv = crypto_bytes(args, "iv")?;
514+ let data = crypto_bytes(args, "data")?;
515+ if iv.len() != 16 {
516+ return Err(anyhow!("AES-CBC requires a 16-byte IV"));
517+ }
518+ let encrypting = operation == "aes-cbc-encrypt";
519+ macro_rules! run {
520+ ($aes:ty) => {{
521+ if encrypting {
522+ cbc::Encryptor::<$aes>::new_from_slices(&key, &iv)
523+ .map_err(|_| anyhow!("invalid AES-CBC key or IV"))?
524+ .encrypt_padded_vec_mut::<Pkcs7>(&data)
525+ } else {
526+ cbc::Decryptor::<$aes>::new_from_slices(&key, &iv)
527+ .map_err(|_| anyhow!("invalid AES-CBC key or IV"))?
528+ .decrypt_padded_vec_mut::<Pkcs7>(&data)
529+ .map_err(|_| anyhow!("AES-CBC decryption failed"))?
530+ }
531+ }};
532+ }
533+ let bytes = match key.len() {
534+ 16 => run!(aes::Aes128),
535+ 32 => run!(aes::Aes256),
536+ other => {
537+ return Err(anyhow!(
538+ "AES-CBC requires a 128- or 256-bit key, got {other} bytes"
539+ ))
540+ }
541+ };
542+ Ok(serde_json::json!({ "bytes": bytes }))
543+ }
544+ // CTR is its own inverse, so one arm serves both directions. The
545+ // counter block is copied before use: it belongs to the caller, and
546+ // `aesCounterOverflowTest` exists because incrementing it in place is
547+ // an easy and invisible mistake.
548+ "aes-ctr" => {
549+ use ctr::cipher::{KeyIvInit, StreamCipher};
550+ let key = crypto_bytes(args, "key")?;
551+ let counter = crypto_bytes(args, "counter")?;
552+ let mut data = crypto_bytes(args, "data")?;
553+ if counter.len() != 16 {
554+ return Err(anyhow!("AES-CTR requires a 16-byte counter block"));
555+ }
556+ macro_rules! run {
557+ ($aes:ty) => {{
558+ let mut cipher = ctr::Ctr128BE::<$aes>::new_from_slices(&key, &counter)
559+ .map_err(|_| anyhow!("invalid AES-CTR key or counter"))?;
560+ cipher.apply_keystream(&mut data);
561+ }};
562+ }
563+ match key.len() {
564+ 16 => run!(aes::Aes128),
565+ 32 => run!(aes::Aes256),
566+ other => {
567+ return Err(anyhow!(
568+ "AES-CTR requires a 128- or 256-bit key, got {other} bytes"
569+ ))
570+ }
571+ }
572+ Ok(serde_json::json!({ "bytes": data }))
573+ }
574+ // ECDH. Web Crypto's deriveBits returns the raw shared secret -- the
575+ // x coordinate of the shared point -- with no KDF applied. Its length
576+ // is the curve's field size, which is why a null `length` is
577+ // answerable at all.
578+ "ecdh-derive" => {
579+ let private = crypto_bytes(args, "private")?;
580+ let public = crypto_bytes(args, "public")?;
581+ let crv = ec_jwk_crv(&describe_key(&private, true)?)?;
582+ if crv != ec_jwk_crv(&describe_key(&public, false)?)? {
583+ return Err(anyhow!("ECDH keys are on different curves"));
584+ }
585+ macro_rules! derive {
586+ ($c:ident) => {{
587+ use $c::pkcs8::DecodePrivateKey;
588+ use $c::pkcs8::DecodePublicKey;
589+ let secret = $c::SecretKey::from_pkcs8_der(&private)
590+ .map_err(|_| anyhow!("invalid ECDH private key"))?;
591+ let point = $c::PublicKey::from_public_key_der(&public)
592+ .map_err(|_| anyhow!("invalid ECDH public key"))?;
593+ $c::elliptic_curve::ecdh::diffie_hellman(
594+ secret.to_nonzero_scalar(),
595+ point.as_affine(),
596+ )
597+ .raw_secret_bytes()
598+ .to_vec()
599+ }};
600+ }
601+ Ok(serde_json::json!({ "bytes": ec_curve!(crv, derive) }))
602+ }
603+ "ed25519-sign" => {
604+ use ed25519_dalek::pkcs8::DecodePrivateKey;
605+ use ed25519_dalek::Signer;
606+ let key = crypto_bytes(args, "key")?;
607+ let data = crypto_bytes(args, "data")?;
608+ let key = ed25519_dalek::SigningKey::from_pkcs8_der(&key)
609+ .map_err(|_| anyhow!("invalid Ed25519 PKCS#8 key"))?;
610+ Ok(serde_json::json!({ "bytes": key.sign(&data).to_bytes().to_vec() }))
611+ }
612+ "p256-sign" => {
613+ use p256::ecdsa::signature::Signer;
614+ use p256::pkcs8::DecodePrivateKey;
615+ let key = crypto_bytes(args, "key")?;
616+ let data = crypto_bytes(args, "data")?;
617+ let key = p256::ecdsa::SigningKey::from_pkcs8_der(&key)
618+ .map_err(|_| anyhow!("invalid P-256 PKCS#8 key"))?;
619+ let signature: p256::ecdsa::Signature = key.sign(&data);
620+ Ok(serde_json::json!({ "bytes": signature.to_bytes().to_vec() }))
621+ }
622+ // JWT verification is the reason these exist: RS256 and ES256 are what
623+ // token issuers sign with (denoland/celld#124). Both take an SPKI
624+ // public key, matching `importKey("spki", ...)`.
625+ // node:crypto's one-shot sign()/verify(). Web Crypto's ops above take
626+ // raw r||s for ECDSA; Node defaults to DER, so these are separate
627+ // entry points rather than flags on those.
628+ "ed25519-verify" => {
629+ use ed25519_dalek::pkcs8::DecodePublicKey;
630+ use ed25519_dalek::Verifier;
631+ let key = crypto_bytes(args, "key")?;
632+ let data = crypto_bytes(args, "data")?;
633+ let signature = crypto_bytes(args, "signature")?;
634+ let key = ed25519_dalek::VerifyingKey::from_public_key_der(&key)
635+ .map_err(|_| anyhow!("invalid Ed25519 SPKI key"))?;
636+ let ok = ed25519_dalek::Signature::from_slice(&signature)
637+ .map(|signature| key.verify(&data, &signature).is_ok())
638+ .unwrap_or(false);
639+ Ok(serde_json::json!({ "ok": ok }))
640+ }
641+ "rsa-pkcs1-sign" => {
642+ use rsa::pkcs8::DecodePrivateKey;
643+ use rsa::signature::{SignatureEncoding, Signer};
644+ let key = crypto_bytes(args, "key")?;
645+ let data = crypto_bytes(args, "data")?;
646+ let hash = args
647+ .get("hash")
648+ .and_then(serde_json::Value::as_str)
649+ .unwrap_or("SHA-256");
650+ let key = rsa::RsaPrivateKey::from_pkcs8_der(&key)
651+ .map_err(|_| anyhow!("invalid RSA private key"))?;
652+ macro_rules! sign {
653+ ($hash:ty) => {
654+ rsa::pkcs1v15::SigningKey::<$hash>::new(key)
655+ .sign(&data)
656+ .to_vec()
657+ };
658+ }
659+ let bytes = match hash {
660+ "SHA-256" => sign!(sha2::Sha256),
661+ "SHA-384" => sign!(sha2::Sha384),
662+ "SHA-512" => sign!(sha2::Sha512),
663+ other => return Err(anyhow!("unsupported RSA sign hash {other}")),
664+ };
665+ Ok(serde_json::json!({ "bytes": bytes }))
666+ }
667+ // Node's ECDSA signatures are DER by default (`dsaEncoding`), where
668+ // Web Crypto's are raw r||s.
669+ "p256-sign-der" => {
670+ use p256::ecdsa::signature::Signer;
671+ use p256::pkcs8::DecodePrivateKey;
672+ let key = crypto_bytes(args, "key")?;
673+ let data = crypto_bytes(args, "data")?;
674+ let key = p256::ecdsa::SigningKey::from_pkcs8_der(&key)
675+ .map_err(|_| anyhow!("invalid P-256 PKCS#8 key"))?;
676+ let signature: p256::ecdsa::Signature = key.sign(&data);
677+ Ok(serde_json::json!({ "bytes": signature.to_der().as_bytes().to_vec() }))
678+ }
679+ "p256-verify-der" => {
680+ use p256::ecdsa::signature::Verifier;
681+ use p256::pkcs8::DecodePublicKey;
682+ let key = crypto_bytes(args, "key")?;
683+ let data = crypto_bytes(args, "data")?;
684+ let signature = crypto_bytes(args, "signature")?;
685+ let key = p256::ecdsa::VerifyingKey::from_public_key_der(&key)
686+ .map_err(|_| anyhow!("invalid P-256 SPKI key"))?;
687+ let ok = p256::ecdsa::DerSignature::try_from(signature.as_slice())
688+ .map(|signature| key.verify(&data, &signature).is_ok())
689+ .unwrap_or(false);
690+ Ok(serde_json::json!({ "ok": ok }))
691+ }
692+ "p256-verify" => {
693+ use p256::ecdsa::signature::Verifier;
694+ use p256::pkcs8::DecodePublicKey;
695+ let key = crypto_bytes(args, "key")?;
696+ let data = crypto_bytes(args, "data")?;
697+ let signature = crypto_bytes(args, "signature")?;
698+ let key = p256::ecdsa::VerifyingKey::from_public_key_der(&key)
699+ .map_err(|_| anyhow!("invalid P-256 SPKI key"))?;
700+ // WebCrypto passes ECDSA signatures as raw r||s, not DER.
701+ let ok = p256::ecdsa::Signature::from_slice(&signature)
702+ .map(|signature| key.verify(&data, &signature).is_ok())
703+ .unwrap_or(false);
704+ Ok(serde_json::json!({ "ok": ok }))
705+ }
706+ "rsa-pkcs1-verify" => {
707+ use rsa::pkcs8::DecodePublicKey;
708+ use rsa::signature::Verifier;
709+ let key = crypto_bytes(args, "key")?;
710+ let data = crypto_bytes(args, "data")?;
711+ let signature = crypto_bytes(args, "signature")?;
712+ let hash = args
713+ .get("hash")
714+ .and_then(serde_json::Value::as_str)
715+ .unwrap_or("SHA-256")
716+ .to_string();
717+ let key = rsa::RsaPublicKey::from_public_key_der(&key)
718+ .map_err(|_| anyhow!("invalid RSA SPKI key"))?;
719+ macro_rules! verify {
720+ ($hash:ty) => {{
721+ let key = rsa::pkcs1v15::VerifyingKey::<$hash>::new(key);
722+ rsa::pkcs1v15::Signature::try_from(signature.as_slice())
723+ .map(|signature| key.verify(&data, &signature).is_ok())
724+ .unwrap_or(false)
725+ }};
726+ }
727+ let ok = match hash.as_str() {
728+ "SHA-256" => verify!(sha2::Sha256),
729+ "SHA-384" => verify!(sha2::Sha384),
730+ "SHA-512" => verify!(sha2::Sha512),
731+ other => return Err(anyhow!("unsupported RSA verify hash {other}")),
732+ };
733+ Ok(serde_json::json!({ "ok": ok }))
734+ }
735+ "rsa-generate" => {
736+ use rsa::traits::{PrivateKeyParts, PublicKeyParts};
737+ let mut rng = rand::rngs::OsRng;
738+ let mut private = rsa::RsaPrivateKey::new(&mut rng, 2048)?;
739+ private.precompute()?;
740+ let public = rsa::RsaPublicKey::from(&private);
741+ let public_jwk = serde_json::json!({
742+ "kty": "RSA",
743+ "n": rsa_jwk_encode(public.n()),
744+ "e": rsa_jwk_encode(public.e()),
745+ "alg": "RSA-OAEP-256",
746+ "ext": true,
747+ "key_ops": ["encrypt"],
748+ });
749+ let private_jwk = serde_json::json!({
750+ "kty": "RSA",
751+ "n": rsa_jwk_encode(private.n()),
752+ "e": rsa_jwk_encode(private.e()),
753+ "d": rsa_jwk_encode(private.d()),
754+ "p": rsa_jwk_encode(&private.primes()[0]),
755+ "q": rsa_jwk_encode(&private.primes()[1]),
756+ "alg": "RSA-OAEP-256",
757+ "ext": true,
758+ "key_ops": ["decrypt"],
759+ });
760+ Ok(serde_json::json!({ "publicKey": public_jwk, "privateKey": private_jwk }))
761+ }
762+ "rsa-oaep-decrypt" => {
763+ let jwk = args.get("jwk").ok_or_else(|| anyhow!("missing RSA JWK"))?;
764+ let n = rsa_jwk_uint(jwk, "n")?;
765+ let e = rsa_jwk_uint(jwk, "e")?;
766+ let d = rsa_jwk_uint(jwk, "d")?;
767+ let p = rsa_jwk_uint(jwk, "p")?;
768+ let q = rsa_jwk_uint(jwk, "q")?;
769+ let mut key = rsa::RsaPrivateKey::from_components(n, e, d, vec![p, q])?;
770+ key.precompute()?;
771+ let data = crypto_bytes(args, "data")?;
772+ let bytes = key.decrypt(rsa::Oaep::new::<sha2::Sha256>(), &data)?;
773+ Ok(serde_json::json!({ "bytes": bytes }))
774+ }
775+ // `createPublicKey` / `createPrivateKey`. Accepts every input shape
776+ // Node does — PEM, bare DER with a stated structure, or a JWK — and
777+ // answers with one normalized DER plus what Node reports as
778+ // `asymmetricKeyType` and `asymmetricKeyDetails`.
779+ "asym-key-import" => {
780+ let format = args
781+ .get("format")
782+ .and_then(serde_json::Value::as_str)
783+ .unwrap_or("pem");
784+ let want_private = args
785+ .get("visibility")
786+ .and_then(serde_json::Value::as_str)
787+ .is_some_and(|visibility| visibility == "private");
788+
789+ let (der, is_private) = if format == "jwk" {
790+ let jwk = args.get("key").ok_or_else(|| anyhow!("missing JWK"))?;
791+ (key_from_jwk(jwk, want_private)?, want_private)
792+ } else {
793+ let key = crypto_bytes(args, "key")?;
794+ let stated = args.get("type").and_then(serde_json::Value::as_str);
795+ if format == "pem" {
796+ let text = std::str::from_utf8(&key)
797+ .map_err(|_| anyhow!("PEM key is not valid UTF-8"))?;
798+ let passphrase = args
799+ .get("passphrase")
800+ .filter(|value| !value.is_null())
801+ .map(|_| crypto_bytes(args, "passphrase"))
802+ .transpose()?;
803+ if text.contains("ENCRYPTED PRIVATE KEY") {
804+ let passphrase = passphrase
805+ .ok_or_else(|| anyhow!("Passphrase required for encrypted key"))?;
806+ use pkcs8::DecodePrivateKey as _;
807+ let document =
808+ pkcs8::SecretDocument::from_pkcs8_encrypted_pem(text, &passphrase)
809+ .map_err(|_| anyhow!("Failed to decrypt private key"))?;
810+ (document.as_bytes().to_vec(), true)
811+ } else {
812+ let (label, document) = rsa::pkcs8::Document::from_pem(text)
813+ .map_err(|_| anyhow!("invalid PEM key"))?;
814+ normalize_key(document.as_bytes(), pem_structure(label)?)?
815+ }
816+ } else {
817+ (
818+ normalize_key_sniffing(&key, stated, want_private)?,
819+ want_private,
820+ )
821+ }
822+ };
823+
824+ if is_private != want_private {
825+ return Err(anyhow!(
826+ "expected a {} key, got a {} key",
827+ if want_private { "private" } else { "public" },
828+ if is_private { "private" } else { "public" }
829+ ));
830+ }
831+ let parsed = describe_key(&der, is_private)?;
832+ Ok(serde_json::json!({
833+ "keyType": parsed.kind,
834+ "der": parsed.der,
835+ "details": parsed.details,
836+ }))
837+ }
838+ // `createPublicKey(privateKeyObject)`: derive the public half from an
839+ // already-normalized PKCS#8 key, so the caller never re-parses.
840+ "asym-key-public-from-private" => {
841+ use rsa::pkcs8::EncodePublicKey;
842+ let der = crypto_bytes(args, "der")?;
843+ let parsed = describe_key(&der, true)?;
844+ let public = match parsed.kind {
845+ "rsa" => {
846+ use rsa::pkcs8::DecodePrivateKey;
847+ let key = rsa::RsaPrivateKey::from_pkcs8_der(&der)
848+ .map_err(|_| anyhow!("invalid RSA private key"))?;
849+ rsa::RsaPublicKey::from(&key)
850+ .to_public_key_der()?
851+ .as_bytes()
852+ .to_vec()
853+ }
854+ "ec" => {
855+ use p256::pkcs8::DecodePrivateKey;
856+ let key = p256::SecretKey::from_pkcs8_der(&der)
857+ .map_err(|_| anyhow!("invalid P-256 private key"))?;
858+ key.public_key().to_public_key_der()?.as_bytes().to_vec()
859+ }
860+ "ed25519" => {
861+ use ed25519_dalek::pkcs8::DecodePrivateKey;
862+ use ed25519_dalek::pkcs8::EncodePublicKey;
863+ let key = ed25519_dalek::SigningKey::from_pkcs8_der(&der)
864+ .map_err(|_| anyhow!("invalid Ed25519 private key"))?;
865+ key.verifying_key().to_public_key_der()?.as_bytes().to_vec()
866+ }
867+ "x25519" => {
868+ let scalar: [u8; 32] = der[der.len() - 32..]
869+ .try_into()
870+ .expect("X25519 PKCS#8 ends with the 32-byte scalar");
871+ let secret = x25519_dalek::StaticSecret::from(scalar);
872+ x25519_spki(x25519_dalek::PublicKey::from(&secret).as_bytes())
873+ }
874+ other => return Err(anyhow!("cannot derive a public key for {other}")),
875+ };
876+ let parsed = describe_key(&public, false)?;
877+ Ok(serde_json::json!({
878+ "keyType": parsed.kind,
879+ "der": parsed.der,
880+ "details": parsed.details,
881+ }))
882+ }
883+ // `generateKeyPairSync`. Answers in the same normalized encodings as
884+ // import — PKCS#8 and SPKI — so the two paths share everything
885+ // downstream.
886+ "asym-key-generate" => {
887+ use ed25519_dalek::pkcs8::EncodePublicKey as _;
888+ use p256::pkcs8::EncodePrivateKey as _;
889+ let kind = args
890+ .get("type")
891+ .and_then(serde_json::Value::as_str)
892+ .ok_or_else(|| anyhow!("missing key type"))?;
893+ let mut rng = rand::rngs::OsRng;
894+ let (private, public) = match kind {
895+ "rsa" => {
896+ let bits = args
897+ .get("modulusLength")
898+ .and_then(serde_json::Value::as_u64)
899+ .ok_or_else(|| anyhow!("missing modulusLength"))?
900+ as usize;
901+ let mut key = rsa::RsaPrivateKey::new(&mut rng, bits)?;
902+ key.precompute()?;
903+ let public = rsa::RsaPublicKey::from(&key);
904+ (
905+ key.to_pkcs8_der()?.as_bytes().to_vec(),
906+ public.to_public_key_der()?.as_bytes().to_vec(),
907+ )
908+ }
909+ "ec" => {
910+ // The JS layer maps Node's curve aliases and rejects
911+ // anything not in EC_CURVES before reaching here.
912+ let crv = args
913+ .get("namedCurve")
914+ .and_then(serde_json::Value::as_str)
915+ .unwrap_or("P-256");
916+ macro_rules! generate {
917+ ($c:ident) => {{
918+ let key = $c::SecretKey::random(&mut rng);
919+ (
920+ $c::pkcs8::EncodePrivateKey::to_pkcs8_der(&key)?
921+ .as_bytes()
922+ .to_vec(),
923+ $c::pkcs8::EncodePublicKey::to_public_key_der(&key.public_key())?
924+ .as_bytes()
925+ .to_vec(),
926+ )
927+ }};
928+ }
929+ ec_curve!(crv, generate)
930+ }
931+ "ed25519" => {
932+ use ed25519_dalek::pkcs8::EncodePrivateKey as _;
933+ // No `generate` on this build of ed25519-dalek (its
934+ // `rand_core` feature is off); the seed is 32 random
935+ // bytes either way.
936+ let mut seed = [0u8; 32];
937+ rand::RngCore::fill_bytes(&mut rng, &mut seed);
938+ let key = ed25519_dalek::SigningKey::from_bytes(&seed);
939+ (
940+ key.to_pkcs8_der()?.as_bytes().to_vec(),
941+ key.verifying_key().to_public_key_der()?.as_bytes().to_vec(),
942+ )
943+ }
944+ "x25519" => {
945+ let secret = x25519_dalek::StaticSecret::random_from_rng(rng);
946+ let public = x25519_dalek::PublicKey::from(&secret);
947+ (
948+ x25519_pkcs8(&secret.to_bytes()),
949+ x25519_spki(public.as_bytes()),
950+ )
951+ }
952+ other => return Err(anyhow!("cannot generate a {other} key pair")),
953+ };
954+ let described = describe_key(&private, true)?;
955+ Ok(serde_json::json!({
956+ "keyType": described.kind,
957+ "privateDer": private,
958+ "publicDer": public,
959+ "details": described.details,
960+ }))
961+ }
962+ // Re-encode a normalized key into one of Node's export structures.
963+ // Import converts every structure *to* PKCS#8/SPKI; this is the
964+ // inverse, and `generateKeyPairSync`'s encoding options need it.
965+ "asym-key-reencode" => {
966+ use rsa::pkcs1::EncodeRsaPrivateKey as _;
967+ use rsa::pkcs1::EncodeRsaPublicKey as _;
968+ let der = crypto_bytes(args, "der")?;
969+ let private = args
970+ .get("visibility")
971+ .and_then(serde_json::Value::as_str)
972+ .is_some_and(|visibility| visibility == "private");
973+ let structure = args
974+ .get("type")
975+ .and_then(serde_json::Value::as_str)
976+ .unwrap_or(if private { "pkcs8" } else { "spki" });
977+ let described = describe_key(&der, private)?;
978+ // A passphrase turns the export into encrypted PKCS#8, whatever
979+ // structure was asked for -- that is the only structure the
980+ // encryption wrapper defines.
981+ if let Some(passphrase) = args
982+ .get("passphrase")
983+ .filter(|value| !value.is_null())
984+ .map(|_| crypto_bytes(args, "passphrase"))
985+ .transpose()?
986+ {
987+ if !private {
988+ return Err(anyhow!("only a private key can be encrypted"));
989+ }
990+ let info = pkcs8::PrivateKeyInfo::try_from(der.as_slice())
991+ .map_err(|_| anyhow!("invalid PKCS#8 private key"))?;
992+ let mut rng = rand::rngs::OsRng;
993+ let document = info
994+ .encrypt(&mut rng, &passphrase)
995+ .map_err(|_| anyhow!("could not encrypt the private key"))?;
996+ let pem = args
997+ .get("format")
998+ .and_then(serde_json::Value::as_str)
999+ .is_some_and(|format| format == "pem");
1000+ return Ok(if pem {
1001+ serde_json::json!({
1002+ "pem": pem_wrap("ENCRYPTED PRIVATE KEY", document.as_bytes()),
1003+ })
1004+ } else {
1005+ serde_json::json!({ "der": document.as_bytes() })
1006+ });
1007+ }
1008+ let (label, bytes) = match (structure, described.kind) {
1009+ ("pkcs8", _) => ("PRIVATE KEY", der.clone()),
1010+ ("spki", _) => ("PUBLIC KEY", der.clone()),
1011+ ("pkcs1", "rsa") if private => {
1012+ use rsa::pkcs8::DecodePrivateKey;
1013+ let key = rsa::RsaPrivateKey::from_pkcs8_der(&der)?;
1014+ ("RSA PRIVATE KEY", key.to_pkcs1_der()?.as_bytes().to_vec())
1015+ }
1016+ ("pkcs1", "rsa") => {
1017+ use rsa::pkcs8::DecodePublicKey;
1018+ let key = rsa::RsaPublicKey::from_public_key_der(&der)?;
1019+ ("RSA PUBLIC KEY", key.to_pkcs1_der()?.as_bytes().to_vec())
1020+ }
1021+ ("sec1", "ec") if private => {
1022+ use p256::elliptic_curve::sec1::ToEncodedPoint;
1023+ use p256::pkcs8::DecodePrivateKey;
1024+ let key = p256::SecretKey::from_pkcs8_der(&der)?;
1025+ let _ = key.public_key().to_encoded_point(false);
1026+ ("EC PRIVATE KEY", key.to_sec1_der()?.to_vec())
1027+ }
1028+ (structure, kind) => {
1029+ return Err(anyhow!("cannot export a {kind} key as {structure}"))
1030+ }
1031+ };
1032+ let pem = args
1033+ .get("format")
1034+ .and_then(serde_json::Value::as_str)
1035+ .is_some_and(|format| format == "pem");
1036+ if pem {
1037+ Ok(serde_json::json!({ "pem": pem_wrap(label, &bytes) }))
1038+ } else {
1039+ Ok(serde_json::json!({ "der": bytes }))
1040+ }
1041+ }
1042+ // Export a normalized key back out. `jwk` is the shape `toCryptoKey`
1043+ // and Node's `export({format:"jwk"})` both want.
1044+ "asym-key-export" => {
1045+ let der = crypto_bytes(args, "der")?;
1046+ let private = args
1047+ .get("visibility")
1048+ .and_then(serde_json::Value::as_str)
1049+ .is_some_and(|visibility| visibility == "private");
1050+ let parsed = describe_key(&der, private)?;
1051+ let jwk = match (parsed.kind, private) {
1052+ ("rsa", false) => {
1053+ use rsa::pkcs8::DecodePublicKey;
1054+ use rsa::traits::PublicKeyParts;
1055+ let key = rsa::RsaPublicKey::from_public_key_der(&der)?;
1056+ serde_json::json!({
1057+ "kty": "RSA",
1058+ "n": rsa_jwk_encode(key.n()),
1059+ "e": rsa_jwk_encode(key.e()),
1060+ })
1061+ }
1062+ ("rsa", true) => {
1063+ use rsa::pkcs8::DecodePrivateKey;
1064+ use rsa::traits::{PrivateKeyParts, PublicKeyParts};
1065+ let key = rsa::RsaPrivateKey::from_pkcs8_der(&der)?;
1066+ // The CRT parameters are part of the JWK, not an
1067+ // optimization detail: Node emits all of dp, dq and qi.
1068+ let missing = || anyhow!("RSA key has no CRT parameters");
1069+ serde_json::json!({
1070+ "kty": "RSA",
1071+ "n": rsa_jwk_encode(key.n()),
1072+ "e": rsa_jwk_encode(key.e()),
1073+ "d": rsa_jwk_encode(key.d()),
1074+ "p": rsa_jwk_encode(&key.primes()[0]),
1075+ "q": rsa_jwk_encode(&key.primes()[1]),
1076+ "dp": rsa_jwk_encode(key.dp().ok_or_else(missing)?),
1077+ "dq": rsa_jwk_encode(key.dq().ok_or_else(missing)?),
1078+ "qi": rsa_jwk_encode(&key.crt_coefficient().ok_or_else(missing)?),
1079+ })
1080+ }
1081+ ("ec", false) => {
1082+ let crv = ec_jwk_crv(&parsed)?;
1083+ macro_rules! export {
1084+ ($c:ident) => {{
1085+ use $c::elliptic_curve::sec1::ToEncodedPoint;
1086+ use $c::pkcs8::DecodePublicKey;
1087+ let key = $c::PublicKey::from_public_key_der(&der)?;
1088+ let point = key.to_encoded_point(false);
1089+ serde_json::json!({
1090+ "kty": "EC",
1091+ "crv": crv,
1092+ "x": base64url(point.x().ok_or_else(|| anyhow!("no x"))?),
1093+ "y": base64url(point.y().ok_or_else(|| anyhow!("no y"))?),
1094+ })
1095+ }};
1096+ }
1097+ ec_curve!(crv, export)
1098+ }
1099+ ("ec", true) => {
1100+ let crv = ec_jwk_crv(&parsed)?;
1101+ macro_rules! export {
1102+ ($c:ident) => {{
1103+ use $c::elliptic_curve::sec1::ToEncodedPoint;
1104+ use $c::pkcs8::DecodePrivateKey;
1105+ let key = $c::SecretKey::from_pkcs8_der(&der)?;
1106+ let point = key.public_key().to_encoded_point(false);
1107+ serde_json::json!({
1108+ "kty": "EC",
1109+ "crv": crv,
1110+ "x": base64url(point.x().ok_or_else(|| anyhow!("no x"))?),
1111+ "y": base64url(point.y().ok_or_else(|| anyhow!("no y"))?),
1112+ "d": base64url(&key.to_bytes()),
1113+ })
1114+ }};
1115+ }
1116+ ec_curve!(crv, export)
1117+ }
1118+ ("x25519", _) => {
1119+ let raw = &der[der.len() - 32..];
1120+ let mut jwk = serde_json::json!({ "kty": "OKP", "crv": "X25519" });
1121+ if private {
1122+ let scalar: [u8; 32] = raw.try_into().unwrap();
1123+ let secret = x25519_dalek::StaticSecret::from(scalar);
1124+ jwk["x"] = serde_json::Value::String(base64url(
1125+ x25519_dalek::PublicKey::from(&secret).as_bytes(),
1126+ ));
1127+ jwk["d"] = serde_json::Value::String(base64url(raw));
1128+ } else {
1129+ jwk["x"] = serde_json::Value::String(base64url(raw));
1130+ }
1131+ jwk
1132+ }
1133+ ("ed25519", false) => {
1134+ use ed25519_dalek::pkcs8::DecodePublicKey;
1135+ let key = ed25519_dalek::VerifyingKey::from_public_key_der(&der)
1136+ .map_err(|_| anyhow!("invalid Ed25519 public key"))?;
1137+ serde_json::json!({
1138+ "alg": "EdDSA",
1139+ "kty": "OKP",
1140+ "crv": "Ed25519",
1141+ "x": base64url(key.as_bytes()),
1142+ })
1143+ }
1144+ ("ed25519", true) => {
1145+ use ed25519_dalek::pkcs8::DecodePrivateKey;
1146+ let key = ed25519_dalek::SigningKey::from_pkcs8_der(&der)
1147+ .map_err(|_| anyhow!("invalid Ed25519 private key"))?;
1148+ serde_json::json!({
1149+ "alg": "EdDSA",
1150+ "kty": "OKP",
1151+ "crv": "Ed25519",
1152+ "x": base64url(key.verifying_key().as_bytes()),
1153+ "d": base64url(&key.to_bytes()),
1154+ })
1155+ }
1156+ ("dsa", _) => return Err(anyhow!("Key type is invalid for JWK export")),
1157+ (other, _) => return Err(anyhow!("cannot export {other} as JWK")),
1158+ };
1159+ Ok(serde_json::json!({
1160+ "keyType": parsed.kind,
1161+ "jwk": jwk,
1162+ "details": parsed.details,
1163+ }))
1164+ }
1165+ _ => Err(anyhow!("unsupported crypto operation")),
1166+ }
1167+}
1168+
1169+pub(super) fn op_crypto_operation(
1170+ scope: &mut v8::PinScope,
1171+ args: v8::FunctionCallbackArguments,
1172+ mut rv: v8::ReturnValue<v8::Value>,
1173+) {
1174+ let operation = args.get(0).to_rust_string_lossy(scope);
1175+ let input: serde_json::Value =
1176+ serde_json::from_str(&args.get(1).to_rust_string_lossy(scope)).unwrap_or_default();
1177+ match crypto_operation(&operation, &input) {
1178+ Ok(value) => {
1179+ let json = value.to_string();
1180+ rv.set(v8::String::new(scope, &json).unwrap().into());
1181+ }
1182+ Err(error) => {
1183+ let message = v8::String::new(scope, &format!("crypto: {error}")).unwrap();
1184+ let exception = v8::Exception::error(scope, message);
1185+ scope.throw_exception(exception);
1186+ }
1187+ }
1188+}
1189+
1190+/// Fill an existing integer typed array in-place. JS performs the WebCrypto
1191+/// type and 65,536-byte quota checks before entering this host op.
1192+pub(super) fn op_webcrypto_random(
1193+ scope: &mut v8::PinScope,
1194+ args: v8::FunctionCallbackArguments,
1195+ _rv: v8::ReturnValue<v8::Value>,
1196+) {
1197+ let Ok(view) = v8::Local::<v8::ArrayBufferView>::try_from(args.get(0)) else {
1198+ return;
1199+ };
1200+ let Some(buffer) = view.buffer(scope) else {
1201+ return;
1202+ };
1203+ let store = buffer.get_backing_store();
1204+ let offset = view.byte_offset();
1205+ let len = view.byte_length();
1206+ let bytes = unsafe {
1207+ std::slice::from_raw_parts_mut(store[offset..offset + len].as_ptr() as *mut u8, len)
1208+ };
1209+ if getrandom::fill(bytes).is_err() {
1210+ let message = v8::String::new(scope, "secure random generation failed").unwrap();
1211+ let exception = v8::Exception::error(scope, message);
1212+ scope.throw_exception(exception);
1213+ }
1214+}
1215+
1216+/// WebCrypto digest: (algorithm, ArrayBufferView) -> Uint8Array.
1217+pub(super) fn op_webcrypto_digest(
1218+ scope: &mut v8::PinScope,
1219+ args: v8::FunctionCallbackArguments,
1220+ rv: v8::ReturnValue<v8::Value>,
1221+) {
1222+ use sha2::Digest;
1223+ let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
1224+ let Some(bytes) = view_bytes(args.get(1)) else {
1225+ return;
1226+ };
1227+ let digest = match algorithm.as_str() {
1228+ "MD5" => md5::Md5::digest(&bytes).to_vec(),
1229+ // Not digests, but DigestStream accepts them: the AWS SDKs and S3
1230+ // checksum with these, so a Worker computing an upload checksum
1231+ // needs them. Big-endian, as the checksum headers carry them.
1232+ "CRC32" => crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC)
1233+ .checksum(&bytes)
1234+ .to_be_bytes()
1235+ .to_vec(),
1236+ "CRC32C" => crc::Crc::<u32>::new(&crc::CRC_32_ISCSI)
1237+ .checksum(&bytes)
1238+ .to_be_bytes()
1239+ .to_vec(),
1240+ "CRC64NVME" => crc::Crc::<u64>::new(&crc::CRC_64_NVME)
1241+ .checksum(&bytes)
1242+ .to_be_bytes()
1243+ .to_vec(),
1244+ "SHA-1" => sha1::Sha1::digest(&bytes).to_vec(),
1245+ "SHA-224" => sha2::Sha224::digest(&bytes).to_vec(),
1246+ "SHA-256" => sha2::Sha256::digest(&bytes).to_vec(),
1247+ "SHA-384" => sha2::Sha384::digest(&bytes).to_vec(),
1248+ "SHA-512" => sha2::Sha512::digest(&bytes).to_vec(),
1249+ _ => return,
1250+ };
1251+ webcrypto_return_bytes(scope, rv, &digest);
1252+}
1253+
1254+pub(super) fn op_webcrypto_hmac_sign(
1255+ scope: &mut v8::PinScope,
1256+ args: v8::FunctionCallbackArguments,
1257+ rv: v8::ReturnValue<v8::Value>,
1258+) {
1259+ use hmac::Mac;
1260+ let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
1261+ let Some(key) = view_bytes(args.get(1)) else {
1262+ return;
1263+ };
1264+ let Some(data) = view_bytes(args.get(2)) else {
1265+ return;
1266+ };
1267+ macro_rules! sign {
1268+ ($digest:ty) => {{
1269+ let Ok(mut mac) = <hmac::Hmac<$digest> as hmac::Mac>::new_from_slice(&key) else {
1270+ return;
1271+ };
1272+ mac.update(&data);
1273+ mac.finalize().into_bytes().to_vec()
1274+ }};
1275+ }
1276+ let signature = match algorithm.as_str() {
1277+ "MD5" => sign!(md5::Md5),
1278+ "SHA-1" => sign!(sha1::Sha1),
1279+ "SHA-224" => sign!(sha2::Sha224),
1280+ "SHA-256" => sign!(sha2::Sha256),
1281+ "SHA-384" => sign!(sha2::Sha384),
1282+ "SHA-512" => sign!(sha2::Sha512),
1283+ _ => return,
1284+ };
1285+ webcrypto_return_bytes(scope, rv, &signature);
1286+}
1287+
1288+/// HMAC-based KDF cores for node:crypto. Manual PBKDF2 (RFC 2898) and HKDF
1289+/// (RFC 5869) over the hmac crate — no extra dependencies. The JS layer has
1290+/// already validated the digest name and the 255×hashLen output cap.
1291+fn hmac_once<D>(key: &[u8], parts: &[&[u8]]) -> Vec<u8>
1292+where
1293+ D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
1294+{
1295+ use hmac::Mac;
1296+ let mut mac = <hmac::SimpleHmac<D> as hmac::Mac>::new_from_slice(key)
1297+ .expect("HMAC accepts any key length");
1298+ for part in parts {
1299+ mac.update(part);
1300+ }
1301+ mac.finalize().into_bytes().to_vec()
1302+}
1303+
1304+fn pbkdf2_kdf<D>(password: &[u8], salt: &[u8], iterations: u32, keylen: usize) -> Vec<u8>
1305+where
1306+ D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
1307+{
1308+ let mut out = Vec::with_capacity(keylen);
1309+ let mut block: u32 = 1;
1310+ while out.len() < keylen {
1311+ let mut u = hmac_once::<D>(password, &[salt, &block.to_be_bytes()]);
1312+ let mut t = u.clone();
1313+ for _ in 1..iterations {
1314+ u = hmac_once::<D>(password, &[&u]);
1315+ for (t_, u_) in t.iter_mut().zip(&u) {
1316+ *t_ ^= u_;
1317+ }
1318+ }
1319+ out.extend_from_slice(&t);
1320+ block += 1;
1321+ }
1322+ out.truncate(keylen);
1323+ out
1324+}
1325+
1326+fn hkdf_kdf<D>(ikm: &[u8], salt: &[u8], info: &[u8], length: usize) -> Vec<u8>
1327+where
1328+ D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
1329+{
1330+ let prk = hmac_once::<D>(salt, &[ikm]);
1331+ let mut out = Vec::with_capacity(length);
1332+ let mut t: Vec<u8> = Vec::new();
1333+ let mut counter: u8 = 1;
1334+ while out.len() < length {
1335+ t = hmac_once::<D>(&prk, &[&t, info, &[counter]]);
1336+ out.extend_from_slice(&t);
1337+ counter += 1;
1338+ }
1339+ out.truncate(length);
1340+ out
1341+}
1342+
1343+macro_rules! dispatch_digest {
1344+ ($name:expr, $fn:ident, ($($arg:expr),*)) => {
1345+ match $name {
1346+ "MD5" => Some($fn::<md5::Md5>($($arg),*)),
1347+ "SHA-1" => Some($fn::<sha1::Sha1>($($arg),*)),
1348+ "SHA-224" => Some($fn::<sha2::Sha224>($($arg),*)),
1349+ "SHA-256" => Some($fn::<sha2::Sha256>($($arg),*)),
1350+ "SHA-384" => Some($fn::<sha2::Sha384>($($arg),*)),
1351+ "SHA-512" => Some($fn::<sha2::Sha512>($($arg),*)),
1352+ _ => None,
1353+ }
1354+ };
1355+}
1356+
1357+/// `$$pbkdf2(algorithm, password, salt, iterations, keylen)` -> Uint8Array
1358+pub(super) fn op_node_pbkdf2(
1359+ scope: &mut v8::PinScope,
1360+ args: v8::FunctionCallbackArguments,
1361+ rv: v8::ReturnValue<v8::Value>,
1362+) {
1363+ let algorithm = args.get(0).to_rust_string_lossy(scope);
1364+ let Some(password) = view_bytes(args.get(1)) else {
1365+ return;
1366+ };
1367+ let Some(salt) = view_bytes(args.get(2)) else {
1368+ return;
1369+ };
1370+ let iterations = args.get(3).uint32_value(scope).unwrap_or(0).max(1);
1371+ let keylen = args.get(4).uint32_value(scope).unwrap_or(0) as usize;
1372+ let out = dispatch_digest!(
1373+ algorithm.as_str(),
1374+ pbkdf2_kdf,
1375+ (&password, &salt, iterations, keylen)
1376+ );
1377+ if let Some(out) = out {
1378+ webcrypto_return_bytes(scope, rv, &out);
1379+ }
1380+}
1381+
1382+/// `$$hkdf(algorithm, ikm, salt, info, length)` -> Uint8Array
1383+pub(super) fn op_node_hkdf(
1384+ scope: &mut v8::PinScope,
1385+ args: v8::FunctionCallbackArguments,
1386+ rv: v8::ReturnValue<v8::Value>,
1387+) {
1388+ let algorithm = args.get(0).to_rust_string_lossy(scope);
1389+ let Some(ikm) = view_bytes(args.get(1)) else {
1390+ return;
1391+ };
1392+ let Some(salt) = view_bytes(args.get(2)) else {
1393+ return;
1394+ };
1395+ let Some(info) = view_bytes(args.get(3)) else {
1396+ return;
1397+ };
1398+ let length = args.get(4).uint32_value(scope).unwrap_or(0) as usize;
1399+ let out = dispatch_digest!(algorithm.as_str(), hkdf_kdf, (&ikm, &salt, &info, length));
1400+ if let Some(out) = out {
1401+ webcrypto_return_bytes(scope, rv, &out);
1402+ }
1403+}
1404+
1405+/// Constant-time equality for equal-length byte views. The JS surfaces own
1406+/// their distinct argument and length errors; one native primitive owns the
1407+/// security property both APIs promise.
1408+pub(super) fn op_timing_safe_equal(
1409+ scope: &mut v8::PinScope,
1410+ args: v8::FunctionCallbackArguments,
1411+ mut rv: v8::ReturnValue<v8::Value>,
1412+) {
1413+ use subtle::ConstantTimeEq;
1414+ let (Some(left), Some(right)) = (view_bytes(args.get(0)), view_bytes(args.get(1))) else {
1415+ return;
1416+ };
1417+ rv.set(v8::Boolean::new(scope, bool::from(left.ct_eq(&right))).into());
1418+}
1419+
1420+pub(super) fn op_webcrypto_hmac_verify(
1421+ scope: &mut v8::PinScope,
1422+ args: v8::FunctionCallbackArguments,
1423+ mut rv: v8::ReturnValue<v8::Value>,
1424+) {
1425+ use hmac::Mac;
1426+ let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
1427+ let Some(key) = view_bytes(args.get(1)) else {
1428+ return;
1429+ };
1430+ let Some(signature) = view_bytes(args.get(2)) else {
1431+ return;
1432+ };
1433+ let Some(data) = view_bytes(args.get(3)) else {
1434+ return;
1435+ };
1436+ macro_rules! verify {
1437+ ($digest:ty) => {{
1438+ let Ok(mut mac) = <hmac::Hmac<$digest> as hmac::Mac>::new_from_slice(&key) else {
1439+ return;
1440+ };
1441+ mac.update(&data);
1442+ mac.verify_slice(&signature).is_ok()
1443+ }};
1444+ }
1445+ let valid = match algorithm.as_str() {
1446+ "SHA-1" => verify!(sha1::Sha1),
1447+ "SHA-256" => verify!(sha2::Sha256),
1448+ "SHA-384" => verify!(sha2::Sha384),
1449+ "SHA-512" => verify!(sha2::Sha512),
1450+ _ => return,
1451+ };
1452+ rv.set(v8::Boolean::new(scope, valid).into());
1453+}
1454+
1455+/// AES-GCM for the Web Crypto ops. Two key sizes and three IV lengths, all
1456+/// instantiated explicitly because the crate fixes both in the type.
1457+///
1458+/// Web Crypto permits any IV length; 96 bits is the recommendation, not the
1459+/// rule, so 128-bit IVs are accepted too. For anything but 96 bits the crate
1460+/// derives J0 by GHASHing the IV, per NIST SP 800-38D. An empty IV is
1461+/// rejected in the JS layer, by name, before reaching here.
1462+fn webcrypto_aes_gcm(key: &[u8], iv: &[u8], data: &[u8], encrypting: bool) -> Option<Vec<u8>> {
1463+ use aes_gcm::aead::consts::{U12, U16};
1464+ use aes_gcm::aead::{Aead, KeyInit};
1465+ macro_rules! run {
1466+ ($aes:ty, $size:ty) => {{
1467+ type Gcm = aes_gcm::AesGcm<$aes, $size>;
1468+ let cipher = <Gcm as KeyInit>::new_from_slice(key).ok()?;
1469+ let nonce = aes_gcm::Nonce::<$size>::from_slice(iv);
1470+ if encrypting {
1471+ cipher.encrypt(nonce, data)
1472+ } else {
1473+ cipher.decrypt(nonce, data)
1474+ }
1475+ .ok()?
1476+ }};
1477+ }
1478+ macro_rules! by_iv {
1479+ ($aes:ty) => {
1480+ match iv.len() {
1481+ 12 => run!($aes, U12),
1482+ 16 => run!($aes, U16),
1483+ _ => return None,
1484+ }
1485+ };
1486+ }
1487+ Some(match key.len() {
1488+ 16 => by_iv!(aes::Aes128),
1489+ 32 => by_iv!(aes::Aes256),
1490+ _ => return None,
1491+ })
1492+}
1493+
1494+pub(super) fn op_webcrypto_aes_encrypt(
1495+ scope: &mut v8::PinScope,
1496+ args: v8::FunctionCallbackArguments,
1497+ rv: v8::ReturnValue<v8::Value>,
1498+) {
1499+ let (Some(key), Some(iv), Some(data)) = (
1500+ view_bytes(args.get(0)),
1501+ view_bytes(args.get(1)),
1502+ view_bytes(args.get(2)),
1503+ ) else {
1504+ return;
1505+ };
1506+ let Some(out) = webcrypto_aes_gcm(&key, &iv, &data, true) else {
1507+ return;
1508+ };
1509+ webcrypto_return_bytes(scope, rv, &out);
1510+}
1511+
1512+pub(super) fn op_webcrypto_aes_decrypt(
1513+ scope: &mut v8::PinScope,
1514+ args: v8::FunctionCallbackArguments,
1515+ rv: v8::ReturnValue<v8::Value>,
1516+) {
1517+ let (Some(key), Some(iv), Some(data)) = (
1518+ view_bytes(args.get(0)),
1519+ view_bytes(args.get(1)),
1520+ view_bytes(args.get(2)),
1521+ ) else {
1522+ return;
1523+ };
1524+ let Some(out) = webcrypto_aes_gcm(&key, &iv, &data, false) else {
1525+ return;
1526+ };
1527+ webcrypto_return_bytes(scope, rv, &out);
1528+}
modifiedcrates/celld/js/harness.js+527−193View file
@@ -11,6 +11,74 @@
1111 return new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice();
1212 return new TextEncoder().encode(String(body));
1313 }
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+}
1482 function __chunkBytes(chunk) {
1583 if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
1684 if (ArrayBuffer.isView(chunk))
@@ -163,10 +231,10 @@
163231 // Streaming/iterable detection runs only for object bodies, so
164232 // the common string path skips every instanceof below.
165233 let stream = null;
166- let blob = null;
234+ let typed = null;
167235 if (body !== null && typeof body === "object") {
168236 if (body instanceof ReadableStream) stream = body;
169- else if (globalThis.Blob && body instanceof Blob) blob = body;
237+ else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ }
170238 else {
171239 const iterable = __iterableBody(body);
172240 if (iterable instanceof ReadableStream) stream = iterable;
@@ -175,7 +243,7 @@
175243 }
176244 this._bodyBytes = stream !== null
177245 ? null
178- : blob ? blob._bytes.slice() : __bodyBytes(body);
246+ : typed ? typed.bytes : __bodyBytes(body);
179247 this._body = stream !== null
180248 ? null
181249 : new TextDecoder().decode(this._bodyBytes);
@@ -191,8 +259,8 @@
191259 this.status = init.status === undefined ? 200 : Number(init.status);
192260 this.statusText = init.statusText === undefined ? "" : String(init.statusText);
193261 this.headers = new Headers(init.headers);
194- if (blob && blob.type && !this.headers.has("content-type"))
195- this.headers.set("content-type", blob.type);
262+ if (typed && typed.type && !this.headers.has("content-type"))
263+ this.headers.set("content-type", typed.type);
196264 this.webSocket = init.webSocket;
197265 this._wsTarget = init.__wsTarget || init._wsTarget || null;
198266 this.ok = this.status >= 200 && this.status <= 299;
@@ -274,10 +342,10 @@
274342 Object.prototype.hasOwnProperty.call(init, "body");
275343 let body = hasBody ? init.body : null;
276344 let stream = null;
277- let blob = null;
345+ let typed = null;
278346 if (hasBody && body !== null && typeof body === "object") {
279347 if (body instanceof ReadableStream) stream = body;
280- else if (globalThis.Blob && body instanceof Blob) blob = body;
348+ else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ }
281349 else {
282350 const iterable = __iterableBody(body);
283351 if (iterable instanceof ReadableStream) stream = iterable;
@@ -293,15 +361,37 @@
293361 this._bodyBytes = stream !== null
294362 ? null
295363 : hasBody
296- ? (blob ? blob._bytes.slice() : __bodyBytes(body))
364+ ? (typed ? typed.bytes : __bodyBytes(body))
297365 : (prior ? prior._bodyBytes.slice() : new Uint8Array());
298- this._body = this._bodyBytes === null
299- ? null
300- : new TextDecoder().decode(this._bodyBytes);
301- this.headers = new Headers(init.headers === undefined && prior ? prior.headers : init.headers);
302- if (blob && blob.type && !this.headers.has("content-type"))
303- this.headers.set("content-type", blob.type);
366+ // Body text is decoded on the first text()/json(), not here: a request
367+ // whose body is never read never pays the decode.
368+ this._body = undefined;
369+ // Headers are stored raw and built on the first `.headers` access. The
370+ // hot paths -- a hello world, a Worker that only forwards to a cell --
371+ // read none, so `new Headers` and the JSON.parse behind it never run.
372+ if (init.__headersJson !== undefined) {
373+ this._headersJson = init.__headersJson;
374+ this._headersInit = undefined;
375+ } else if (init.headers === undefined && prior) {
376+ this._headersJson = prior._headersJson;
377+ this._headersInit = prior._headers ?? prior._headersInit;
378+ } else {
379+ this._headersJson = undefined;
380+ this._headersInit = init.headers;
381+ }
382+ this._headers = null;
383+ // A typed body's default content-type must land now; only user-built
384+ // typed bodies reach this, never the incoming request path.
385+ if (typed && typed.type && !this.headers.has("content-type")) {
386+ this.headers.set("content-type", typed.type);
387+ }
304388 this.bodyUsed = false;
389+ // The body stream and the signal stay eager, own properties: the RPC and
390+ // storage serializers fall back to the lift-into-marker path only when a
391+ // value is not directly structured-cloneable, and a Request's un-cloneable
392+ // body stream (or AbortSignal) is what triggers that. Making them lazy
393+ // getters let `__sc_encode` clone the Request into a broken plain object
394+ // and skip the lift -- the serializeHttpTypes conformance failure.
305395 this.body = stream !== null
306396 ? stream
307397 : ["GET", "HEAD"].includes(this.method)
@@ -319,15 +409,30 @@
319409 ? this.signal
320410 : (prior ? prior._signalForSubrequests : null);
321411 }
412+ get headers() {
413+ if (this._headers === null) {
414+ const src = this._headersJson !== undefined
415+ ? JSON.parse(this._headersJson)
416+ : this._headersInit;
417+ this._headers = new Headers(src);
418+ this._headersJson = undefined;
419+ this._headersInit = undefined;
420+ }
421+ return this._headers;
422+ }
423+ set headers(value) {
424+ this._headers = value instanceof Headers ? value : new Headers(value);
425+ this._headersJson = undefined;
426+ this._headersInit = undefined;
427+ }
322428 async _consume() {
323429 if (this._bodyBytes !== null) return this._bodyBytes;
324430 return __drainBody(this);
325431 }
326432 async text() {
327433 this.bodyUsed = true;
328- if (this._body !== null) return this._body;
329- await this._consume();
330- return this._body;
434+ const bytes = await this._consume();
435+ return this._body ??= new TextDecoder().decode(bytes);
331436 }
332437 async json() { return JSON.parse(await this.text()); }
333438 async formData() {
@@ -357,7 +462,10 @@
357462 url, method, body, headersJson = "[]", signal = undefined,
358463 incomingSignal = false,
359464 ) => new Request(url, {
360- method, body, headers: JSON.parse(headersJson), signal,
465+ // The raw header JSON, not a parsed object: an incoming request whose
466+ // handler never reads `.headers` (a hello world, or a Worker that only
467+ // routes to a cell) then never parses it. See `get headers()`.
468+ method, body, __headersJson: headersJson, signal,
361469 __celldIncomingSignal: incomingSignal,
362470 });
363471 const __fmt = (a) => a.map((x) => {
@@ -981,6 +1089,30 @@
9811089 return new DurableObjectRoutingError();
9821090 }
9831091 };
1092+// A cell's input gate as the isolate sees it, for the one delivery
1093+// point that is inside the isolate rather than in front of it: an
1094+// RPC stub op. `shut` counts the blocks that have asked for the gate
1095+// and is raised synchronously, so no window exists in which a block
1096+// has started and the isolate still thinks the cell is open.
1097+// `holder` names the block actually running — a second block that is
1098+// still queued has raised `shut` but holds nothing.
1099+//
1100+// A stub minted while a block runs carries that block's token and
1101+// re-enters it instead of queueing behind it. That is Workerd's
1102+// `IoContext::makeReentryCallback`, and without it a callback the
1103+// block itself sent out could never come back.
1104+const __cellBlocks = new Map();
1105+const __blockEnter = (scope) => {
1106+ const block = __cellBlocks.get(scope);
1107+ if (block !== undefined) return (block.shut++, block);
1108+ const fresh = { shut: 1, holder: null };
1109+ __cellBlocks.set(scope, fresh);
1110+ return fresh;
1111+};
1112+const __blockLeave = (scope, block) => {
1113+ block.holder = null;
1114+ if (--block.shut === 0) __cellBlocks.delete(scope);
1115+};
9841116 class DurableObjectState {
9851117 constructor(scope) {
9861118 this._scope = scope;
@@ -1006,7 +1138,58 @@
10061138 "blockConcurrencyWhile() calls are nested too deeply.",
10071139 );
10081140 if (this._blockDepth > 0) return this._runConcurrencyBlock(f);
1009- const next = this._gate.then(() => this._runConcurrencyBlock(f));
1141+ // The host owns the gate (celld_logic::gate::InputGate). It replaces a
1142+ // promise chain that could only order blocks against each other; the
1143+ // gate sits at the delivery points, so nothing else is delivered to this
1144+ // cell at all while the block runs.
1145+ //
1146+ // The acquire waits. It used to be synchronous, and had to be: a cell's
1147+ // events came off one channel, so yielding even one microtask reopened a
1148+ // window in which this cell delivered an event that then waited on a
1149+ // gate nothing would release. Events are independent tasks now, so two
1150+ // can reach a block together and the second has to queue — and nothing
1151+ // nests, so waiting cannot deadlock on an event suspended beneath it.
1152+ // Asked for synchronously, awaited asynchronously, and the split is the
1153+ // whole point. The op shuts the gate in this very call, so no event can
1154+ // be delivered to this cell from here on — that immediacy is what makes
1155+ // `failCriticalSection()` reject a `ping()` issued right after it.
1156+ // Waiting for the *ticket* is separate: events are independent tasks
1157+ // now, so two of them can reach a block together and the second has to
1158+ // queue behind the first. Calling this inside the async body instead
1159+ // costs one microtask, and an event delivered in that window walks
1160+ // straight into the critical section.
1161+ const block = __blockEnter(this._scope);
1162+ const acquired = __gate_acquire(this._scope);
1163+ const next = (async () => {
1164+ try {
1165+ // The op answers a string; the gate keys events by number.
1166+ const event = Number(await acquired);
1167+ block.holder = event;
1168+ // A critical section that fails resets the actor, so whatever queued
1169+ // behind its gate must be refused rather than handed to the reset
1170+ // one — it was sent to a cell whose state no longer exists. The
1171+ // failure rides with the release for that: waiters are woken with it
1172+ // instead of merely woken.
1173+ let failure = null;
1174+ try {
1175+ return await this._runConcurrencyBlock(f);
1176+ } catch (error) {
1177+ failure = String((error && error.message) || error);
1178+ throw error;
1179+ } finally {
1180+ __gate_release(this._scope, event, failure);
1181+ }
1182+ } finally {
1183+ // Also on a rejected `acquired`: the block ahead failed, this one
1184+ // never ran, and the cell must not stay shut on its behalf.
1185+ __blockLeave(this._scope, block);
1186+ }
1187+ })();
1188+ // `_ready()` awaits this. The host gate stops *other* events, but a
1189+ // block taken in the constructor runs inside the very event that is
1190+ // being delivered, so nothing external can hold that event back — the
1191+ // promise does. Concurrent blocks within one event go through
1192+ // `_blockDepth` above and never reach here.
10101193 this._gate = next;
10111194 return next;
10121195 }
@@ -1101,6 +1284,45 @@
11011284 this.getWebSockets().find((ws) => ws._id === id) ||
11021285 __wsStub(id);
11031286 }
1287+ // Workerd actor-state.c++ setWebSocketAutoResponse: no pair unsets, and
1288+ // each side is capped at 2048 UTF-8 bytes. The pair itself lives in the
1289+ // shell — a matched message is answered without waking this cell.
1290+ setWebSocketAutoResponse(pair) {
1291+ if (pair === undefined || pair === null) {
1292+ __ws_auto_response_set(this._scope, null, null);
1293+ return;
1294+ }
1295+ if (!(pair instanceof WebSocketRequestResponsePair))
1296+ throw new TypeError(
1297+ "Failed to execute 'setWebSocketAutoResponse' on " +
1298+ "'DurableObjectState': parameter 1 is not of type " +
1299+ "'WebSocketRequestResponsePair'.",
1300+ );
1301+ const max = 2048;
1302+ const bytes = (s) => new TextEncoder().encode(s).length;
1303+ const requestSize = bytes(pair.request);
1304+ if (requestSize > max)
1305+ throw new RangeError(
1306+ `Request cannot be larger than ${max} bytes. ` +
1307+ `A request of size ${requestSize} was provided.`,
1308+ );
1309+ const responseSize = bytes(pair.response);
1310+ if (responseSize > max)
1311+ throw new RangeError(
1312+ `Response cannot be larger than ${max} bytes. ` +
1313+ `A response of size ${responseSize} was provided.`,
1314+ );
1315+ __ws_auto_response_set(this._scope, pair.request, pair.response);
1316+ }
1317+ getWebSocketAutoResponse() {
1318+ const pair = JSON.parse(__ws_auto_response_get(this._scope));
1319+ if (pair === null) return null;
1320+ return new WebSocketRequestResponsePair(pair[0], pair[1]);
1321+ }
1322+ getWebSocketAutoResponseTimestamp(ws) {
1323+ const ms = __ws_auto_response_ts(ws._id);
1324+ return ms === null ? null : new Date(ms);
1325+ }
11041326 waitUntil(promise) {
11051327 globalThis.__registerWaitUntil(promise);
11061328 }
@@ -1352,10 +1574,36 @@
13521574 idPromise.then((id) => finalizer.register(stub, id), () => {});
13531575 return stub;
13541576 };
1577+ // JSON.stringify silently drops binary values, so each non-string module —
1578+ // wasm bytes as a BufferSource, or workerd's `{ wasm }` / `{ esModule }`
1579+ // module shapes — is normalized first: ES modules to plain strings, wasm
1580+ // pulled out into a side-band `[name, Uint8Array]` list the op reads
1581+ // directly, so multi-MB blobs never take a base64/JSON round-trip.
1582+ const toBytes = (v) => v instanceof ArrayBuffer ? new Uint8Array(v)
1583+ : ArrayBuffer.isView(v)
1584+ ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : null;
1585+ const encodeModules = (c) => {
1586+ if (c === null || typeof c !== "object" || c.modules === null
1587+ || typeof c.modules !== "object") return { config: c, wasm: [] };
1588+ const modules = {};
1589+ const wasm = [];
1590+ for (const [name, value] of Object.entries(c.modules)) {
1591+ const wrapped = value !== null && typeof value === "object" ? value : {};
1592+ const bytes = toBytes(value) ?? toBytes(wrapped.wasm);
1593+ if (bytes !== null) wasm.push([name, bytes]);
1594+ else if (typeof wrapped.esModule === "string") modules[name] = wrapped.esModule;
1595+ else modules[name] = value;
1596+ }
1597+ return { config: { ...c, modules }, wasm };
1598+ };
13551599 // getCode is deferred into a microtask so a throw (or async getCode)
13561600 // surfaces as a rejection when the worker is first used, not at get()/load().
13571601 const loadFrom = (getCode) =>
1358- Promise.resolve().then(getCode).then((c) => __loader_load(JSON.stringify(c)));
1602+ Promise.resolve().then(getCode)
1603+ .then((c) => {
1604+ const { config, wasm } = encodeModules(c);
1605+ return __loader_load(JSON.stringify(config), wasm);
1606+ });
13591607 return {
13601608 load(code) { return makeStub(loadFrom(() => code), true); },
13611609 get(name, getCode) {
@@ -1647,10 +1895,14 @@
16471895 const __newEntry = (target) => {
16481896 // `scope` records the actor event that minted the entry (top of
16491897 // the event stack at lift time), so an actor breakage can find
1650- // and abort the contexts hosting its exported stubs.
1898+ // and abort the contexts hosting its exported stubs, and an op on
1899+ // the stub can queue on that cell's input gate. `section` is the
1900+ // critical section running at lift time, if any — an op on this
1901+ // stub re-enters it rather than queueing behind it.
1902+ const scope = __actorEventStack[__actorEventStack.length - 1];
16511903 const entry = {
1652- id: __nextStubId++, target, refs: 1, ctx: __ctxNow(),
1653- scope: __actorEventStack[__actorEventStack.length - 1],
1904+ id: __nextStubId++, target, refs: 1, ctx: __ctxNow(), scope,
1905+ section: __cellBlocks.get(scope)?.holder ?? null,
16541906 };
16551907 __stubEntries.set(entry.id, entry);
16561908 return entry;
@@ -2213,6 +2465,19 @@
22132465 // with the reason, not the post-abort message). Bodies queue
22142466 // in call order, so e-order holds.
22152467 await null;
2468+ // The cell that minted this stub gates it like any other event.
2469+ // The op is dispatched inside the isolate and never becomes a
2470+ // drive, so it is the one delivery point that has to ask here
2471+ // rather than in Rust. A stub carrying the running critical
2472+ // section re-enters it; everything else queues, and a section
2473+ // that failed refuses what queued.
2474+ const cell = entry.scope;
2475+ if (cell !== undefined) {
2476+ const block = __cellBlocks.get(cell);
2477+ if (block !== undefined && (entry.section === null ||
2478+ entry.section !== block.holder))
2479+ await __gate_wait(cell);
2480+ }
22162481 const reply = await __ctxRun(entry.ctx,
22172482 () => __rpcRun(async () => {
22182483 const decoded =
@@ -2671,145 +2936,159 @@
26712936 const namespaceKey = __cell.namespaceKeys[className];
26722937 if (typeof namespaceKey !== "string")
26732938 throw new Error("no Durable Object namespace key for " + className);
2674- const namespace = {
2675- idFromName(name) {
2676- name = String(name);
2677- return new DurableObjectId(
2678- className, __do_id(namespaceKey, "name", name), name,
2679- );
2680- },
2681- idFromString(value) {
2682- return new DurableObjectId(
2683- className, __do_id(namespaceKey, "validate", String(value)),
2684- );
2685- },
2686- newUniqueId(options = {}) {
2687- const jurisdiction = options == null ? undefined : options.jurisdiction;
2688- if (jurisdiction != null)
2689- throw new Error("Jurisdiction restrictions are not implemented");
2690- return new DurableObjectId(
2691- className, __do_id(namespaceKey, "unique", ""),
2692- );
2693- },
2694- jurisdiction(value) {
2695- if (value == null) return namespace;
2939+ return new DurableObjectNamespace(className, namespaceKey);
2940+}
2941+// A named class: SDKs sniff bindings by constructor name (workers-rs
2942+// EnvBinding requires `constructor.name === "DurableObjectNamespace"`).
2943+class DurableObjectNamespace {
2944+ constructor(className, namespaceKey) {
2945+ Object.defineProperty(this, "_className", { value: className });
2946+ Object.defineProperty(this, "_namespaceKey", { value: namespaceKey });
2947+ }
2948+ idFromName(name) {
2949+ name = String(name);
2950+ return new DurableObjectId(
2951+ this._className, __do_id(this._namespaceKey, "name", name), name,
2952+ );
2953+ }
2954+ idFromString(value) {
2955+ return new DurableObjectId(
2956+ this._className, __do_id(this._namespaceKey, "validate", String(value)),
2957+ );
2958+ }
2959+ newUniqueId(options = {}) {
2960+ const jurisdiction = options == null ? undefined : options.jurisdiction;
2961+ if (jurisdiction != null)
26962962 throw new Error("Jurisdiction restrictions are not implemented");
2697- },
2698- getByName(name, options) {
2699- return namespace.get(namespace.idFromName(name), options);
2700- },
2701- get(id) {
2702- if (!(id instanceof DurableObjectId) || id._className !== className)
2703- throw new TypeError("Durable Object ID is not valid for this namespace");
2704- const scope = id._scope();
2705- // Emulate production: the actor recovers its name only when it is
2706- // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is
2707- // undefined. The full name still seeds the routing hash, so
2708- // dispatch is unchanged. Short names skip the byte count (< 256
2709- // chars is always <= 1020 bytes) to keep the hot path alloc-free.
2710- const nm = id.name;
2711- const dispatchName = nm === undefined ? undefined
2712- : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024
2713- ? nm : undefined;
2714- if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName;
2715- // Fetch and native RPC use the same host routing/activation seam.
2716- // Never expose `.then`: a DO stub is not itself a promise.
2717- // `__celldDo` brands the stub so the RPC lift can send it as a
2718- // revivable marker rather than failing the clone; non-enumerable
2719- // so Object.keys(stub) stays Workerd's [id, name].
2720- const target = { id, name: dispatchName };
2721- Object.defineProperty(target, "__celldDo", { value: id });
2722- const abortMarker = "__CELLD_ACTOR_ABORT__:";
2723- const processExitMarker = "__CELLD_PROCESS_EXIT__:";
2724- let brokenReason = null;
2725- const invoke = async (operation) => {
2726- if (brokenReason !== null) throw new Error(brokenReason);
2727- try {
2728- return await operation();
2729- } catch (error) {
2730- const routingError = __durableObjectRoutingError(error);
2731- if (routingError !== null) throw routingError;
2732- const message = String(error && error.message || error);
2733- const marker = [abortMarker, processExitMarker]
2734- .find((candidate) => message.includes(candidate));
2735- if (!marker) throw error;
2736- brokenReason = message.slice(message.indexOf(marker) + marker.length);
2737- throw new Error(brokenReason);
2963+ return new DurableObjectId(
2964+ this._className, __do_id(this._namespaceKey, "unique", ""),
2965+ );
2966+ }
2967+ jurisdiction(value) {
2968+ if (value == null) return this;
2969+ throw new Error("Jurisdiction restrictions are not implemented");
2970+ }
2971+ getByName(name, options) {
2972+ return this.get(this.idFromName(name), options);
2973+ }
2974+ get(id) {
2975+ const className = this._className;
2976+ if (!(id instanceof DurableObjectId) || id._className !== className)
2977+ throw new TypeError("Durable Object ID is not valid for this namespace");
2978+ const scope = id._scope();
2979+ // Emulate production: the actor recovers its name only when it is
2980+ // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is
2981+ // undefined. The full name still seeds the routing hash, so
2982+ // dispatch is unchanged. Short names skip the byte count (< 256
2983+ // chars is always <= 1020 bytes) to keep the hot path alloc-free.
2984+ const nm = id.name;
2985+ const dispatchName = nm === undefined ? undefined
2986+ : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024
2987+ ? nm : undefined;
2988+ if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName;
2989+ // Fetch and native RPC use the same host routing/activation seam.
2990+ // Never expose `.then`: a DO stub is not itself a promise.
2991+ // `__celldDo` brands the stub so the RPC lift can send it as a
2992+ // revivable marker rather than failing the clone; non-enumerable
2993+ // so Object.keys(stub) stays Workerd's [id, name].
2994+ const target = { id, name: dispatchName };
2995+ Object.defineProperty(target, "__celldDo", { value: id });
2996+ const abortMarker = "__CELLD_ACTOR_ABORT__:";
2997+ const processExitMarker = "__CELLD_PROCESS_EXIT__:";
2998+ let brokenReason = null;
2999+ const invoke = async (operation) => {
3000+ if (brokenReason !== null) throw new Error(brokenReason);
3001+ try {
3002+ return await operation();
3003+ } catch (error) {
3004+ const routingError = __durableObjectRoutingError(error);
3005+ if (routingError !== null) throw routingError;
3006+ const message = String(error && error.message || error);
3007+ const marker = [abortMarker, processExitMarker]
3008+ .find((candidate) => message.includes(candidate));
3009+ if (!marker) throw error;
3010+ brokenReason = message.slice(message.indexOf(marker) + marker.length);
3011+ throw new Error(brokenReason);
3012+ }
3013+ };
3014+ const doFetch = async (input, init) => {
3015+ const req = new Request(input, init);
3016+ const signal = req._signalForSubrequests;
3017+ if (signal?.aborted) throw signal.reason;
3018+ // The DO seam carries exact bytes; a stream body is drained
3019+ // (and per spec disturbed) first.
3020+ const body_ = req._bodyBytes === null
3021+ ? await req._consume() : req._bodyBytes;
3022+ // Forward the request's headers to the cell as JSON. When they were
3023+ // never materialized -- a Worker that only routes to a cell reads
3024+ // none -- pass the raw header string straight through, so the whole
3025+ // dispatch never builds a Headers object on either side.
3026+ const headersJson = req._headersJson !== undefined
3027+ ? req._headersJson
3028+ : JSON.stringify(Array.from(req.headers));
3029+ // Fast path: this isolate owns the target cell — run the DO
3030+ // in-isolate, avoiding the __do_call host round trip.
3031+ if (__cell.owned[scope]) {
3032+ return await invoke(() => __dispatchTo(
3033+ scope, req.url, req.method, body_,
3034+ headersJson,
3035+ null,
3036+ true,
3037+ signal,
3038+ ));
27383039 }
2739- };
2740- const doFetch = async (input, init) => {
2741- const req = new Request(input, init);
2742- const signal = req._signalForSubrequests;
2743- if (signal?.aborted) throw signal.reason;
2744- // The DO seam carries exact bytes; a stream body is drained
2745- // (and per spec disturbed) first.
2746- const body_ = req._bodyBytes === null
2747- ? await req._consume() : req._bodyBytes;
2748- // Fast path: this isolate owns the target cell — run the DO
2749- // in-isolate, avoiding the __do_call host round trip.
2750- if (__cell.owned[scope]) {
2751- return await invoke(() => __dispatchTo(
2752- scope, req.url, req.method, body_,
2753- JSON.stringify(Array.from(req.headers)),
2754- null,
2755- true,
2756- signal,
2757- ));
2758- }
2759- const r = JSON.parse(await invoke(() => {
2760- if (!signal) return __do_call(
3040+ const r = JSON.parse(await invoke(() => {
3041+ if (!signal) return __do_call(
3042+ scope, dispatchName ?? null, req.url, req.method, body_,
3043+ headersJson,
3044+ );
3045+ return __awaitCancellableDoCall(
3046+ __do_call_cancellable(
27613047 scope, dispatchName ?? null, req.url, req.method, body_,
2762- JSON.stringify(Array.from(req.headers)),
2763- );
2764- return __awaitCancellableDoCall(
2765- __do_call_cancellable(
2766- scope, dispatchName ?? null, req.url, req.method, body_,
2767- JSON.stringify(Array.from(req.headers)),
2768- ),
2769- signal,
2770- );
2771- }));
2772- const body = r.streamId !== undefined
2773- ? new CelldHttpBodyStream(r.streamId)
2774- : r.body !== undefined
2775- ? r.body
2776- : Uint8Array.from(r.bodyBytes || []);
2777- return new Response(body, {
2778- status: r.status, headers: r.headers, __wsTarget: r.wsTarget,
2779- });
2780- };
2781- const stub = new Proxy(target, { get: (_target, prop) => {
2782- if (prop === "then") return undefined;
2783- if (Reflect.has(_target, prop)) return Reflect.get(_target, prop);
2784- if (prop === "fetch") return doFetch;
2785- if (typeof prop !== "string") return undefined;
2786- if (__cell.compat.fetcherGetPutDelete &&
2787- (prop === "get" || prop === "put" || prop === "delete"))
2788- return __fetcherHelper(doFetch, prop);
2789- // Fast path: this isolate owns the target cell — run the DO RPC
2790- // in-isolate, avoiding the __rpc_call host round trip. Still a
2791- // structured clone each way: Workerd extracts a copy even for a
2792- // same-isolate call, and JSON round-tripped here before. The
2793- // reply decodes inside invoke() so abort/exit markers rethrown
2794- // from the envelope still trip the broken-stub sniffing.
2795- if (__cell.owned[scope])
2796- return async (...args) => invoke(
2797- async () => __rpcDes(await __dispatchRpc(
2798- scope, prop, __rpcOut(args, true))),
3048+ headersJson,
3049+ ),
3050+ signal,
27993051 );
2800- // The routed channel also lifts: same-process dispatch
2801- // re-enters this isolate, where the markers revive; bytes
2802- // that land elsewhere revive as loud foreign stubs.
3052+ }));
3053+ const body = r.streamId !== undefined
3054+ ? new CelldHttpBodyStream(r.streamId)
3055+ : r.body !== undefined
3056+ ? r.body
3057+ : Uint8Array.from(r.bodyBytes || []);
3058+ return new Response(body, {
3059+ status: r.status, headers: r.headers, __wsTarget: r.wsTarget,
3060+ });
3061+ };
3062+ const stub = new Proxy(target, { get: (_target, prop) => {
3063+ if (prop === "then") return undefined;
3064+ if (Reflect.has(_target, prop)) return Reflect.get(_target, prop);
3065+ if (prop === "fetch") return doFetch;
3066+ if (typeof prop !== "string") return undefined;
3067+ if (__cell.compat.fetcherGetPutDelete &&
3068+ (prop === "get" || prop === "put" || prop === "delete"))
3069+ return __fetcherHelper(doFetch, prop);
3070+ // Fast path: this isolate owns the target cell — run the DO RPC
3071+ // in-isolate, avoiding the __rpc_call host round trip. Still a
3072+ // structured clone each way: Workerd extracts a copy even for a
3073+ // same-isolate call, and JSON round-tripped here before. The
3074+ // reply decodes inside invoke() so abort/exit markers rethrown
3075+ // from the envelope still trip the broken-stub sniffing.
3076+ if (__cell.owned[scope])
28033077 return async (...args) => invoke(
2804- async () => __rpcDes(await __rpc_call(
2805- scope, dispatchName ?? null, prop, __rpcOut(args, true),
2806- )),
3078+ async () => __rpcDes(await __dispatchRpc(
3079+ scope, prop, __rpcOut(args, true))),
28073080 );
2808- }});
2809- return stub;
2810- }
2811- };
2812- return namespace;
3081+ // The routed channel also lifts: same-process dispatch
3082+ // re-enters this isolate, where the markers revive; bytes
3083+ // that land elsewhere revive as loud foreign stubs.
3084+ return async (...args) => invoke(
3085+ async () => __rpcDes(await __rpc_call(
3086+ scope, dispatchName ?? null, prop, __rpcOut(args, true),
3087+ )),
3088+ );
3089+ }});
3090+ return stub;
3091+ }
28133092 }
28143093 const __attachResponseRequestCancellation = (
28153094 response,
@@ -3030,26 +3309,32 @@
30303309 // to that class's fetch, not the module's default export. A plain
30313310 // object export (Workerd's non-class entrypoint) dispatches its
30323311 // handler functions as fn(arg, env, ctx).
3033-globalThis.__dispatchEntrypointFetch = async (name, request) => {
3312+const __dispatchEntrypointMethod = async (name, method, arg) => {
30343313 const handler = __cell.objectEntrypoints[name];
30353314 if (handler !== undefined) {
3036- if (typeof handler.fetch !== "function")
3315+ if (typeof handler[method] !== "function")
30373316 throw new TypeError(
3038- `Entrypoint ${JSON.stringify(name)} has no fetch handler`);
3317+ `Entrypoint ${JSON.stringify(name)} has no ${method} handler`);
30393318 const ctx = __beginEvent();
30403319 try {
30413320 return await __ctxRun(undefined,
3042- () => handler.fetch(request, __cell.env, ctx));
3321+ () => handler[method](arg, __cell.env, ctx));
30433322 } finally {
30443323 __endEvent();
30453324 }
30463325 }
3326+ // A class entrypoint's methods get env and ctx from its constructor,
3327+ // not as arguments.
30473328 const inst = __entrypointInstance(name);
3048- if (typeof inst.fetch !== "function")
3329+ if (typeof inst[method] !== "function")
30493330 throw new TypeError(
3050- `Entrypoint ${JSON.stringify(name)} has no fetch handler`);
3051- return await __ctxRun(undefined, () => inst.fetch(request));
3331+ `Entrypoint ${JSON.stringify(name)} has no ${method} handler`);
3332+ return await __ctxRun(undefined, () => inst[method](arg));
30523333 };
3334+globalThis.__dispatchEntrypointFetch = (name, request) =>
3335+ __dispatchEntrypointMethod(name, "fetch", request);
3336+globalThis.__dispatchEntrypointScheduled = (name, ctrl) =>
3337+ __dispatchEntrypointMethod(name, "scheduled", ctrl);
30533338 // Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class
30543339 // handler method is called as fn(arg, env, ctx), the client must send
30553340 // exactly one argument, and the handler must not declare more than
@@ -3303,7 +3588,7 @@
33033588 // the current event; outside any event this is Workerd's
33043589 // global-scope error.
33053590 waitUntil(promise) {
3306- if (__eventStack.length === 0)
3591+ if (__event_depth() === 0)
33073592 throw new Error(
33083593 "Disallowed operation called within global scope.");
33093594 globalThis.__registerWaitUntil(promise);
@@ -3569,11 +3854,18 @@
35693854 }
35703855 }
35713856 if (!globalThis.AbortSignal) {
3857+ const __abortBrand = Symbol("abortSignal");
35723858 globalThis.AbortSignal = class AbortSignal extends EventTarget {
35733859 // The Headers/Blob clone-poisoning brand: V8's structured
35743860 // clone throws on functions, so a live signal reaches the
35753861 // RPC lift instead of silently flattening to plain data.
35763862 constructor() {
3863+ // Per spec AbortSignal has no constructor: it is only reachable
3864+ // through AbortController, AbortSignal.abort/timeout/any. The internal
3865+ // paths pass the brand to get past this.
3866+ if (arguments[0] !== __abortBrand) {
3867+ throw new TypeError("Illegal constructor");
3868+ }
35773869 super();
35783870 this.aborted = false;
35793871 this.reason = undefined;
@@ -3600,7 +3892,7 @@
36003892 }
36013893 };
36023894 globalThis.AbortController = class AbortController {
3603- constructor() { this.signal = new AbortSignal(); }
3895+ constructor() { this.signal = new AbortSignal(__abortBrand); }
36043896 abort(reason = new DOMException("This operation was aborted", "AbortError")) {
36053897 __abortSignal(this.signal, reason);
36063898 }
@@ -3737,6 +4029,13 @@
37374029 globalThis.__parseFormData = (text, contentType) => {
37384030 const ct = String(contentType || "");
37394031 if (/^\s*application\/x-www-form-urlencoded/i.test(ct)) {
4032+ // The body has already been decoded as UTF-8, so a declared charset that
4033+ // is not UTF-8 cannot be honoured. Refuse rather than mis-decode.
4034+ const charset = /;\s*charset\s*=\s*"?([^";]+)/i.exec(ct);
4035+ if (charset && !/^utf-?8$/i.test(charset[1].trim()))
4036+ throw new TypeError(
4037+ `Unsupported charset "${charset[1].trim()}". FormData can only ` +
4038+ "parse UTF-8 encoded bodies.");
37404039 const form = new FormData();
37414040 for (const [key, value] of new URLSearchParams(text))
37424041 form.append(key, value);
@@ -3755,20 +4054,41 @@
37554054 const boundary = (found[1] !== undefined ? found[1] : found[2]).trim();
37564055 const form = new FormData();
37574056 const delimiter = "--" + boundary;
3758- // Parts are delimited by the boundary; the preamble before the first
3759- // delimiter and the epilogue after the closing one are ignored.
3760- const chunks = text.split(delimiter);
3761- for (let i = 1; i < chunks.length; i++) {
3762- let chunk = chunks[i];
3763- if (chunk.startsWith("--")) break; // closing delimiter
3764- chunk = chunk.replace(/^\r?\n/, "");
4057+ // Walk the delimiters rather than splitting on them, so that a truncated or
4058+ // corrupt body is refused instead of silently yielding the parts that
4059+ // happened to parse. The preamble before the first delimiter and the
4060+ // epilogue after the closing one are ignored.
4061+ let cursor = text.indexOf(delimiter);
4062+ if (cursor < 0)
4063+ throw new TypeError(
4064+ "No boundary delimiter was found in the multipart/form-data body.");
4065+ cursor += delimiter.length;
4066+ for (;;) {
4067+ // What follows a delimiter decides everything: "--" closes the body, a
4068+ // line break opens another part, and anything else is malformed.
4069+ if (text.startsWith("--", cursor)) break;
4070+ const lineBreak = text.startsWith("\r\n", cursor)
4071+ ? 2
4072+ : text.startsWith("\n", cursor) ? 1 : 0;
4073+ if (lineBreak === 0)
4074+ throw new TypeError(
4075+ "A boundary delimiter must be followed by CRLF, LF, or \"--\".");
4076+ cursor += lineBreak;
4077+ const next = text.indexOf(delimiter, cursor);
4078+ if (next < 0)
4079+ throw new TypeError(
4080+ "The multipart/form-data body ended without a closing boundary " +
4081+ "delimiter.");
4082+ // The line break before a delimiter belongs to the delimiter, not to the
4083+ // part it terminates.
4084+ const chunk = text.slice(cursor, next).replace(/\r?\n$/, "");
4085+ cursor = next + delimiter.length;
37654086 const split = /\r?\n\r?\n/.exec(chunk);
3766- if (!split) continue;
4087+ if (!split)
4088+ throw new TypeError(
4089+ "A FormData part's headers must be terminated by a blank line.");
37674090 const rawHeaders = chunk.slice(0, split.index);
3768- // Trim the CRLF that belongs to the following delimiter.
3769- const body = chunk
3770- .slice(split.index + split[0].length)
3771- .replace(/\r?\n$/, "");
4091+ const body = chunk.slice(split.index + split[0].length);
37724092 let disposition = null;
37734093 let type = "";
37744094 for (const line of rawHeaders.split(/\r?\n/)) {
@@ -4188,8 +4508,10 @@
41884508 }
41894509 }
41904510 serializeAttachment(value) {
4511+ // Structured clone, not JSON: Cloudflare accepts anything cloneable
4512+ // here, so a Date must come back a Date and a Map a Map.
41914513 this._attachment = value;
4192- __ws_attachment_set(this._id, JSON.stringify(value));
4514+ __ws_attachment_set(this._id, __sc_encode(value));
41934515 }
41944516 deserializeAttachment() { return this._attachment; }
41954517 _dispatchMessage(data) {
@@ -4235,10 +4557,27 @@
42354557 ws._tags = row.tags || [];
42364558 ws._hibernatable = true;
42374559 if (row.attachment != null) {
4238- try { ws._attachment = JSON.parse(row.attachment); } catch { ws._attachment = undefined; }
4560+ try {
4561+ ws._attachment = __sc_decode(new Uint8Array(row.attachment));
4562+ } catch {
4563+ ws._attachment = undefined;
4564+ }
42394565 }
42404566 return ws;
42414567 };
4568+// Workerd's api::WebSocketRequestResponsePair (websocket.h): an immutable
4569+// request/response pair for state.setWebSocketAutoResponse.
4570+globalThis.WebSocketRequestResponsePair =
4571+ class WebSocketRequestResponsePair {
4572+ #request;
4573+ #response;
4574+ constructor(request, response) {
4575+ this.#request = String(request);
4576+ this.#response = String(response);
4577+ }
4578+ get request() { return this.#request; }
4579+ get response() { return this.#response; }
4580+ };
42424581 globalThis.WebSocketPair = function WebSocketPair() {
42434582 const id = __ws_alloc();
42444583 const client = __makeSocket(id);
@@ -4308,10 +4647,8 @@
43084647 // Web Crypto is installed after the rest of the harness so it can use
43094648 // DOMException, structuredClone, and Buffer.
43104649 // `Buffer` is read at call time, which materializes the lazy global.
4311-const __zlibSync = (mode, data) => Buffer.from(JSON.parse(__zlib(
4312- mode,
4313- JSON.stringify(Array.from(Buffer.from(data))),
4314-)));
4650+const __zlibSync = (mode, data) =>
4651+ Buffer.from(__zlib(mode, Buffer.from(data)));
43154652 globalThis.__zlibModule = {
43164653 constants: {
43174654 Z_NO_FLUSH: 0,
@@ -4349,20 +4686,21 @@
43494686 globalThis.process.getBuiltinModule =
43504687 (id) => __builtin_module(String(id));
43514688 if (!globalThis.global) globalThis.global = globalThis;
4352-const __eventStack = [];
4689+// Events belong to the request, and the host owns the request. `__event_*`
4690+// and `__wait_until` operate on whichever context the host has made current
4691+// for this turn, so nothing here has to know which request is running — and
4692+// two requests sharing an isolate cannot pop each other's events.
43534693 globalThis.__registerWaitUntil = (promise) => {
4354- const event = __eventStack[__eventStack.length - 1];
43554694 const tracked = Promise.resolve(promise).catch((error) => {
43564695 console.error("waitUntil rejected", error);
43574696 });
4358- if (event) event.waitUntil.push(tracked);
4697+ __wait_until(tracked);
43594698 };
43604699 // `props` are the per-stub props a loopback service stub carries
43614700 // (ctx.props); `exports` is built once, on first access.
43624701 const __defaultProps = {};
43634702 globalThis.__beginEvent = (props = __defaultProps) => {
4364- const event = { waitUntil: [] };
4365- __eventStack.push(event);
4703+ __event_begin();
43664704 return {
43674705 waitUntil: globalThis.__registerWaitUntil,
43684706 passThroughOnException() {},
@@ -4371,11 +4709,7 @@
43714709 get exports() { return __ctxExports(); },
43724710 };
43734711 };
4374-globalThis.__endEvent = () => {
4375- const event = __eventStack.pop();
4376- if (!event || event.waitUntil.length === 0) return null;
4377- return Promise.allSettled(event.waitUntil);
4378-};
4712+globalThis.__endEvent = () => __event_end();
43794713 // fs stub that behaves like a no-filesystem env: reads throw ENOENT and
43804714 // existsSync is false, so the common `try { readFileSync } catch (ENOENT)`
43814715 // fallbacks in real deps (e.g. pi-agent config) take their default path.
addedcrates/celld/js/modules.rs+805−0View file
@@ -1,0 +1,805 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! ES module resolution and compilation.
4+//!
5+//! A specifier is either a builtin, whose source this module holds, or an
6+//! import of another worker, which resolves through the loader. Most builtins
7+//! are lazy: a module compiles the first time something reads its global, so
8+//! a worker that never touches `node:zlib` never compiles it.
9+use super::*;
10+
11+pub(super) fn compile_module<'s>(
12+ scope: &mut v8::PinScope<'s, '_>,
13+ name: &str,
14+ src: &str,
15+) -> Option<v8::Local<'s, v8::Module>> {
16+ let name = v8::String::new(scope, name)?;
17+ let source = v8::String::new(scope, src)?;
18+ let origin = v8::ScriptOrigin::new(
19+ scope,
20+ name.into(),
21+ 0,
22+ 0,
23+ false,
24+ 0,
25+ None,
26+ false,
27+ false,
28+ true,
29+ None,
30+ );
31+ let mut src = v8::script_compiler::Source::new(source, Some(&origin));
32+ v8::script_compiler::compile_module(scope, &mut src)
33+}
34+
35+/// specifier -> pre-compiled stub module, consulted by `resolve_external`
36+/// while V8 statically links a real worker bundle's imports, and by
37+/// `dynamic_namespace` as its once-per-isolate cache.
38+///
39+/// **An isolate slot, not a thread-local.** These are `Global<Module>`
40+/// handles into *one* isolate's heap. Under D1 several isolates are built and
41+/// entered from the same tokio worker, so a thread-local made them share one
42+/// table: `register_stubs` clearing it for a new isolate wiped a live one's
43+/// stubs, and `dynamic_namespace` could localise a handle belonging to a
44+/// different isolate — not a wrong answer but an invalid one. The registry
45+/// belongs to the isolate because its contents do.
46+#[derive(Default)]
47+pub(super) struct ModuleRegistry(Mutex<HashMap<String, v8::Global<v8::Module>>>);
48+
49+fn modreg(scope: &mut v8::PinScope) -> Arc<ModuleRegistry> {
50+ scope
51+ .get_slot::<Arc<ModuleRegistry>>()
52+ .cloned()
53+ .expect("isolate has no module registry")
54+}
55+
56+/// Scan a bundle for its external (`cloudflare:*` / `node:*`) imports and the
57+/// named/default bindings pulled from each. V8 static-links these, so a stub
58+/// must provide exactly these names; namespace imports (`* as x`) need none.
59+/// Is `spec` an external builtin (`node:*`, `cloudflare:*`, or a bare node
60+/// builtin)? esbuild bundles every npm dep inline and leaves only builtins
61+/// external, so a remaining bare specifier is a node builtin.
62+fn is_external(spec: &str) -> bool {
63+ const BARE: &[&str] = &[
64+ "path",
65+ "os",
66+ "fs",
67+ "fs/promises",
68+ "crypto",
69+ "stream",
70+ "util",
71+ "util/types",
72+ "assert",
73+ "module",
74+ "process",
75+ "tty",
76+ "url",
77+ "v8",
78+ "constants",
79+ "buffer",
80+ "events",
81+ "zlib",
82+ "child_process",
83+ "http",
84+ "https",
85+ "http2",
86+ "net",
87+ "tls",
88+ "dns",
89+ "readline",
90+ "string_decoder",
91+ "querystring",
92+ "async_hooks",
93+ "perf_hooks",
94+ "worker_threads",
95+ "vm",
96+ "diagnostics_channel",
97+ "timers",
98+ "inspector",
99+ "dgram",
100+ "cluster",
101+ "punycode",
102+ "sqlite",
103+ ];
104+ if spec.starts_with("node:") || spec.starts_with("cloudflare:") {
105+ return true;
106+ }
107+ // bare builtin, or a builtin submodule like `stream/promises`
108+ BARE.contains(&spec) || BARE.contains(&spec.split('/').next().unwrap_or(""))
109+}
110+
111+fn scan_external_imports(
112+ src: &str,
113+) -> std::collections::BTreeMap<String, std::collections::BTreeSet<String>> {
114+ let re = regex::Regex::new(r#"import\s+([^;]*?)\s*from\s*["']([^"']+)["']"#).unwrap();
115+ let braces = regex::Regex::new(r"\{([^}]*)\}").unwrap();
116+ let mut map: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
117+ Default::default();
118+ for cap in re.captures_iter(src) {
119+ if !is_external(&cap[2]) {
120+ continue;
121+ }
122+ let clause = cap[1].trim();
123+ let set = map.entry(cap[2].to_string()).or_default();
124+ if let Some(b) = braces.captures(clause) {
125+ for part in b[1].split(',') {
126+ let name = part.split_whitespace().next().unwrap_or("");
127+ // A commented-out binding inside the braces is not a name.
128+ if !name.is_empty() && !name.starts_with("//") {
129+ set.insert(name.to_string());
130+ }
131+ }
132+ }
133+ let head = clause
134+ .split(['{', '*'])
135+ .next()
136+ .unwrap_or("")
137+ .trim()
138+ .trim_end_matches(',')
139+ .trim();
140+ if !head.is_empty() {
141+ set.insert("default".into());
142+ } // default import
143+ // `import * as x` consumes the whole namespace; the stub must then
144+ // export the module's full surface, not just the scanned names.
145+ if clause.contains('*') {
146+ set.insert("*".into());
147+ }
148+ }
149+ map
150+}
151+
152+/// A stub ES module for `spec`. `cloudflare:workers` binds the real DO base
153+/// class from the harness; every other builtin routes to a pass-through proxy
154+/// so evaluation never crashes on an unsupported node/cf API.
155+/// A module Cells really implements in JS. Its source is injected into the
156+/// generated stub module, and `register_stubs` only builds stubs for
157+/// specifiers a bundle actually imports — so an isolate that never imports it
158+/// pays nothing at load. `global` is what the source defines and doubles as
159+/// the redefinition guard when a bundle imports several aliases.
160+struct LazyModule {
161+ specs: &'static [&'static str],
162+ global: &'static str,
163+ source: &'static str,
164+}
165+
166+const LAZY_MODULES: &[LazyModule] = &[
167+ LazyModule {
168+ specs: &["assert", "node:assert"],
169+ global: "__assertModule",
170+ source: include_str!("node_assert.js"),
171+ },
172+ LazyModule {
173+ specs: &["assert/strict", "node:assert/strict"],
174+ global: "__assertStrictModule",
175+ source: include_str!("node_assert.js"),
176+ },
177+ LazyModule {
178+ specs: &["timers/promises", "node:timers/promises"],
179+ global: "__timersPromises",
180+ source: include_str!("node_timers.js"),
181+ },
182+ LazyModule {
183+ specs: &["test", "node:test", "node:test/reporters"],
184+ global: "__nodeTest",
185+ source: include_str!("node_test.js"),
186+ },
187+ LazyModule {
188+ specs: &["util", "node:util"],
189+ global: "__utilModule",
190+ source: include_str!("node_util.js"),
191+ },
192+ // Same source, different namespace: node:util/types has the type
193+ // predicates as its named exports. The shared source defines both
194+ // globals, so either entry's guard covers the other.
195+ LazyModule {
196+ specs: &["util/types", "node:util/types"],
197+ global: "__utilTypesModule",
198+ source: include_str!("node_util.js"),
199+ },
200+ LazyModule {
201+ specs: &["events", "node:events"],
202+ global: "__eventsModule",
203+ source: include_str!("node_events.js"),
204+ },
205+ LazyModule {
206+ specs: &["path", "node:path", "path/posix", "node:path/posix"],
207+ global: "__pathModule",
208+ source: include_str!("node_path.js"),
209+ },
210+ // Same source; either entry's guard covers the other.
211+ LazyModule {
212+ specs: &["path/win32", "node:path/win32"],
213+ global: "__pathWin32Module",
214+ source: include_str!("node_path.js"),
215+ },
216+ // Shares its source with the `Buffer` LAZY_GLOBALS entry; the script
217+ // is self-guarded, so whichever seam runs first wins and the other
218+ // reuses the same classes.
219+ LazyModule {
220+ specs: &["buffer", "node:buffer"],
221+ global: "__buffer",
222+ source: include_str!("node_buffer.js"),
223+ },
224+ LazyModule {
225+ specs: &["crypto", "node:crypto"],
226+ global: "__cryptoModule",
227+ source: include_str!("node_crypto.js"),
228+ },
229+ LazyModule {
230+ specs: &["async_hooks", "node:async_hooks"],
231+ global: "__asyncHooksModule",
232+ source: include_str!("node_async_hooks.js"),
233+ },
234+ // One source defines the whole stream family; whichever entry runs
235+ // first, its guard covers the others.
236+ LazyModule {
237+ specs: &["stream", "node:stream"],
238+ global: "__streamModule",
239+ source: include_str!("node_stream.js"),
240+ },
241+ LazyModule {
242+ specs: &["stream/promises", "node:stream/promises"],
243+ global: "__streamPromises",
244+ source: include_str!("node_stream.js"),
245+ },
246+ LazyModule {
247+ specs: &["stream/web", "node:stream/web"],
248+ global: "__streamWeb",
249+ source: include_str!("node_stream.js"),
250+ },
251+ LazyModule {
252+ specs: &["stream/consumers", "node:stream/consumers"],
253+ global: "__streamConsumers",
254+ source: include_str!("node_stream.js"),
255+ },
256+];
257+
258+/// A global whose definition only compiles when something reads the name.
259+/// One script may define several names; touching any of them installs them
260+/// all. A bundle that names none pays only the `SetLazyDataProperty` calls
261+/// at boot, so this is where a new global belongs unless the prelude has to
262+/// see it.
263+struct LazyGlobal {
264+ names: &'static [&'static str],
265+ source: &'static str,
266+}
267+
268+const LAZY_GLOBALS: &[LazyGlobal] = &[
269+ LazyGlobal {
270+ names: &["IdentityTransformStream", "FixedLengthStream"],
271+ source: include_str!("identity_transform_stream.js"),
272+ },
273+ LazyGlobal {
274+ names: &["CompressionStream", "DecompressionStream"],
275+ source: include_str!("compression_streams.js"),
276+ },
277+ LazyGlobal {
278+ names: &[
279+ "ReadableByteStreamController",
280+ "ReadableStreamBYOBReader",
281+ "ReadableStreamBYOBRequest",
282+ ],
283+ source: include_str!("byte_streams.js"),
284+ },
285+ LazyGlobal {
286+ names: &["Buffer"],
287+ source: include_str!("node_buffer.js"),
288+ },
289+ LazyGlobal {
290+ names: &["setImmediate", "clearImmediate"],
291+ source: include_str!("set_immediate.js"),
292+ },
293+ LazyGlobal {
294+ names: &["URLPattern"],
295+ source: include_str!("url_pattern.js"),
296+ },
297+];
298+
299+/// Runs once per group, the first time one of its names is read. V8 then
300+/// replaces the accessor with the returned value, so the script never
301+/// compiles twice.
302+fn lazy_global_getter(
303+ scope: &mut v8::PinScope,
304+ name: v8::Local<v8::Name>,
305+ args: v8::PropertyCallbackArguments,
306+ mut rv: v8::ReturnValue<v8::Value>,
307+) {
308+ let index = args.data().integer_value(scope).unwrap();
309+ let group = &LAZY_GLOBALS[index as usize];
310+ let code = v8::String::new(scope, group.source).unwrap();
311+ let script = v8::Script::compile(scope, code, None).unwrap();
312+ let exports = script.run(scope).unwrap();
313+ let exports: v8::Local<v8::Object> = exports.try_into().unwrap();
314+ // The group's other names are still lazy; define them now or reading one
315+ // would compile the same script again. Not this one — V8 asserts the
316+ // property is still an accessor when the getter returns.
317+ let global = scope.get_current_context().global(scope);
318+ for other in group.names {
319+ let key = v8::String::new(scope, other).unwrap();
320+ if name.strict_equals(key.into()) {
321+ continue;
322+ }
323+ let value = exports.get(scope, key.into()).unwrap();
324+ global.create_data_property(scope, key.into(), value);
325+ }
326+ rv.set(exports.get(scope, name.into()).unwrap());
327+}
328+
329+pub(super) fn install_lazy_globals(scope: &mut v8::PinScope) -> Result<()> {
330+ let global = scope.get_current_context().global(scope);
331+ for (i, group) in LAZY_GLOBALS.iter().enumerate() {
332+ let data = v8::Integer::new(scope, i as i32);
333+ for name in group.names {
334+ let key = v8::String::new(scope, name).unwrap();
335+ global.set_lazy_data_property_with_data(
336+ scope,
337+ key.into(),
338+ lazy_global_getter,
339+ data.into(),
340+ v8::PropertyAttribute::NONE,
341+ v8::SideEffectType::HasSideEffect,
342+ v8::SideEffectType::HasSideEffect,
343+ );
344+ }
345+ }
346+ Ok(())
347+}
348+
349+/// Globals already installed by the src/js/harness for partially supported
350+/// builtins. These cost every isolate, so new modules belong in
351+/// `LAZY_MODULES` instead.
352+fn eager_module_global(spec: &str) -> Option<&'static str> {
353+ Some(match spec {
354+ "fs" | "node:fs" | "fs/promises" | "node:fs/promises" => "globalThis.__fs",
355+ "zlib" | "node:zlib" => "globalThis.__zlibModule",
356+ _ => return None,
357+ })
358+}
359+
360+fn stub_source(spec: &str, names: &std::collections::BTreeSet<String>) -> String {
361+ let cf = spec == "cloudflare:workers";
362+ let lazy = LAZY_MODULES.iter().find(|m| m.specs.contains(&spec));
363+ let eager = eager_module_global(spec);
364+ let base = if cf {
365+ "globalThis.__cf".to_string()
366+ } else if let Some(m) = lazy {
367+ format!("globalThis.{}", m.global)
368+ } else if let Some(global) = eager {
369+ global.to_string()
370+ } else {
371+ "globalThis.__nodeStub".to_string()
372+ };
373+ let real = cf || lazy.is_some() || eager.is_some();
374+ let mut out = String::new();
375+ if let Some(m) = lazy {
376+ out.push_str(&format!("if (!globalThis.{}) {{\n", m.global));
377+ out.push_str(m.source);
378+ out.push_str("}\n");
379+ }
380+ for n in names {
381+ if n == "*" {
382+ continue; // namespace imports take the full-surface path
383+ } else if n == "default" {
384+ out.push_str(&format!("export default {base};\n"));
385+ } else if cf
386+ && matches!(
387+ n.as_str(),
388+ "DurableObject" | "RpcTarget" | "WorkerEntrypoint" | "env" | "exports"
389+ )
390+ {
391+ out.push_str(&format!("export const {n} = globalThis.__cf.{n};\n"));
392+ } else if real {
393+ out.push_str(&format!("export const {n} = {base}.{n};\n"));
394+ } else {
395+ out.push_str(&format!("export const {n} = globalThis.__nodeStub;\n"));
396+ }
397+ }
398+ out
399+}
400+
401+/// Compile one stub module per external specifier into the isolate's module
402+/// registry. Run before
403+/// instantiating a real bundle; `resolve_external` then serves them.
404+pub(super) fn register_stubs(
405+ scope: &mut v8::PinScope,
406+ src: &str,
407+ modules: &[(String, ModuleSource)],
408+) {
409+ modreg(scope).0.lock().unwrap().clear();
410+ let reg = |spec: String, source: String, scope: &mut v8::PinScope| {
411+ if let Some(m) = compile_module(scope, &spec, &source) {
412+ let g = v8::Global::new(scope, m);
413+ modreg(scope).0.lock().unwrap().insert(spec, g);
414+ } else {
415+ tracing::warn!(%spec, "module stub failed to compile");
416+ }
417+ };
418+ for (spec, names) in scan_external_imports(src) {
419+ // `import * as x` binds the whole namespace, so the stub's exports
420+ // must be the module's full surface — probed from the backing
421+ // object, like dynamic import() — not just the scanned names.
422+ let s = if names.contains("*") {
423+ full_surface_source(scope, &spec, &names).unwrap_or_else(|| stub_source(&spec, &names))
424+ } else {
425+ stub_source(&spec, &names)
426+ };
427+ reg(spec, s, scope);
428+ }
429+ // sibling text modules (wrangler Text rule: `import md from './x.md'`)
430+ for (spec, source) in modules {
431+ let ModuleSource::Text(content) = source else {
432+ continue;
433+ };
434+ let s = format!(
435+ "export default {};",
436+ serde_json::to_string(content).unwrap()
437+ );
438+ reg(spec.clone(), s, scope);
439+ }
440+ tracing::debug!(
441+ mods = modreg(scope).0.lock().unwrap().len(),
442+ "registered import stubs + text modules"
443+ );
444+}
445+
446+/// Compile `source` and insert it into the isolate's module registry under
447+/// both `name` and `./name`, so bare and relative sibling imports resolve to
448+/// one module.
449+fn register_sibling_module(scope: &mut v8::PinScope, name: &str, source: &str) {
450+ let Some(m) = compile_module(scope, name, source) else {
451+ tracing::warn!(%name, "sibling module failed to compile");
452+ return;
453+ };
454+ let g = v8::Global::new(scope, m);
455+ let registry = modreg(scope);
456+ let mut reg = registry.0.lock().unwrap();
457+ reg.insert(name.to_string(), g.clone());
458+ reg.insert(format!("./{name}"), g);
459+}
460+
461+/// Compiled-wasm modules shared process-wide: the first isolate to see a blob
462+/// compiles it and caches the `CompiledWasmModule`; every later isolate (each
463+/// pool thread, each DO cell activation) rehydrates that without recompiling,
464+/// as workerd does via `FromCompiledModule`. Bounded LRU: deployed modules
465+/// are fixed at startup (a redeploy restarts the process), but the Worker
466+/// Loader can stream in distinct wasm blobs at runtime, so modules that
467+/// evicted dynamic workers leave behind age out instead of accumulating
468+/// for the life of the daemon.
469+#[derive(Default)]
470+struct CompiledWasmCache {
471+ entries: HashMap<[u8; 32], (v8::CompiledWasmModule, u64)>,
472+ tick: u64,
473+}
474+
475+const MAX_COMPILED_WASM_MODULES: usize = 32;
476+
477+impl CompiledWasmCache {
478+ fn get(&mut self, hash: &[u8; 32]) -> Option<&v8::CompiledWasmModule> {
479+ self.tick += 1;
480+ let tick = self.tick;
481+ self.entries.get_mut(hash).map(|(module, used)| {
482+ *used = tick;
483+ &*module
484+ })
485+ }
486+
487+ fn insert(&mut self, hash: [u8; 32], module: v8::CompiledWasmModule) {
488+ if self.entries.len() >= MAX_COMPILED_WASM_MODULES {
489+ let lru = self
490+ .entries
491+ .iter()
492+ .min_by_key(|(_, (_, used))| *used)
493+ .map(|(hash, _)| *hash);
494+ if let Some(lru) = lru {
495+ self.entries.remove(&lru);
496+ }
497+ }
498+ self.tick += 1;
499+ self.entries.insert(hash, (module, self.tick));
500+ }
501+}
502+
503+/// Compile wasm bytes behind a TryCatch (so invalid bytes cannot leave a
504+/// pending exception dangling over the rest of the load) and record the
505+/// compiled module in the shared cache for later isolates. The compile runs
506+/// outside the cache lock; only the insert takes it.
507+fn compile_wasm<'s>(
508+ scope: &mut v8::PinScope<'s, '_>,
509+ bytes: &[u8],
510+ hash: [u8; 32],
511+ cache: &Mutex<CompiledWasmCache>,
512+) -> Result<v8::Local<'s, v8::WasmModuleObject>, String> {
513+ let compiled = {
514+ let tc = std::pin::pin!(v8::TryCatch::new(scope));
515+ let tcs = &mut tc.init();
516+ match v8::WasmModuleObject::compile(tcs, bytes) {
517+ Some(module) => {
518+ cache
519+ .lock()
520+ .unwrap()
521+ .insert(hash, module.get_compiled_module());
522+ Ok(v8::Global::new(tcs, module))
523+ }
524+ None => Err(exc!(tcs)),
525+ }
526+ };
527+ compiled.map(|module| v8::Local::new(scope, &module))
528+}
529+
530+/// Register each sibling wasm module under its name and `./name` as a stub
531+/// whose default export is the compiled `WebAssembly.Module` — the shape
532+/// workerd gives a `CompiledWasm` module import, which is what
533+/// wasm-bindgen/workers-rs bundles expect from `import x from "./x.wasm"`.
534+/// Each stub reads its compiled module from `globalThis.__wasmModules`, and
535+/// its one-time evaluation consumes that entry.
536+pub(super) fn register_wasm_modules(scope: &mut v8::PinScope, modules: &[(String, ModuleSource)]) {
537+ static COMPILED: OnceLock<Mutex<CompiledWasmCache>> = OnceLock::new();
538+ let wasm = modules.iter().filter_map(|(name, source)| match source {
539+ ModuleSource::Wasm(bytes) => Some((name, bytes)),
540+ _ => None,
541+ });
542+ let mut table = None;
543+ let cache = COMPILED.get_or_init(Default::default);
544+ for (name, bytes) in wasm {
545+ let table = *table.get_or_insert_with(|| {
546+ // Non-enumerable, like every host-injected global (see the
547+ // `ops!` macro): a bundle walking `globalThis` must not find
548+ // runtime internals.
549+ let global = scope.get_current_context().global(scope);
550+ let table = v8::Object::new(scope);
551+ let table_key = v8::String::new(scope, "__wasmModules").unwrap();
552+ global.define_own_property(
553+ scope,
554+ table_key.into(),
555+ table.into(),
556+ v8::PropertyAttribute::DONT_ENUM,
557+ );
558+ table
559+ });
560+ use sha2::Digest;
561+ let hash: [u8; 32] = sha2::Sha256::digest(bytes).into();
562+ // `CompiledWasmModule` is not Clone, so the rehydrate reads the cache
563+ // entry in place; `from_compiled_module` shares the compiled code
564+ // rather than recompiling, so the lock is held only briefly.
565+ let cached = {
566+ let mut cache = cache.lock().unwrap();
567+ cache
568+ .get(&hash)
569+ .and_then(|compiled| v8::WasmModuleObject::from_compiled_module(scope, compiled))
570+ };
571+ let module = match cached {
572+ Some(module) => Ok(module),
573+ None => compile_wasm(scope, bytes, hash, cache),
574+ };
575+ let quoted = serde_json::to_string(name).unwrap();
576+ let source = match module {
577+ Ok(module) => {
578+ let key = v8::String::new(scope, name).unwrap();
579+ table.set(scope, key.into(), module.into());
580+ format!(
581+ "const m = globalThis.__wasmModules[{quoted}];\n\
582+ delete globalThis.__wasmModules[{quoted}];\n\
583+ export default m;"
584+ )
585+ }
586+ // The importing module reports the failure, matching the eager
587+ // `new WebAssembly.Module(bytes)` stub this replaces.
588+ Err(error) => {
589+ tracing::warn!(%name, %error, "wasm module failed to compile");
590+ let message =
591+ serde_json::to_string(&format!("{name} failed to compile: {error}")).unwrap();
592+ format!("throw new WebAssembly.CompileError({message});")
593+ }
594+ };
595+ register_sibling_module(scope, name, &source);
596+ }
597+}
598+
599+/// Register a loaded worker's sibling JS modules (Worker Loader multi-module
600+/// bundles), in addition to the builtins `register_stubs` already added for the
601+/// main module. Each module is registered under its own name and `./name` so
602+/// both bare and relative sibling imports resolve; the whole graph links when
603+/// the main module instantiates. Any builtin a sibling imports (and the main
604+/// module did not) is stubbed too.
605+pub(super) fn register_loader_modules(
606+ scope: &mut v8::PinScope,
607+ modules: &[(String, ModuleSource)],
608+) {
609+ let es_modules = || {
610+ modules.iter().filter_map(|(name, source)| match source {
611+ ModuleSource::EsModule(source) => Some((name, source)),
612+ _ => None,
613+ })
614+ };
615+ for (_name, source) in es_modules() {
616+ for (spec, names) in scan_external_imports(source) {
617+ if modreg(scope).0.lock().unwrap().contains_key(&spec) {
618+ continue;
619+ }
620+ let s = if names.contains("*") {
621+ full_surface_source(scope, &spec, &names)
622+ .unwrap_or_else(|| stub_source(&spec, &names))
623+ } else {
624+ stub_source(&spec, &names)
625+ };
626+ if let Some(m) = compile_module(scope, &spec, &s) {
627+ let g = v8::Global::new(scope, m);
628+ modreg(scope).0.lock().unwrap().insert(spec, g);
629+ }
630+ }
631+ }
632+ for (name, source) in es_modules() {
633+ register_sibling_module(scope, name, source);
634+ }
635+}
636+
637+/// Module resolve callback: serve a registered stub for `cloudflare:*`/`node:*`.
638+/// celld bundles are single-file, so anything else is genuinely unresolvable.
639+pub(super) fn resolve_external<'s>(
640+ context: v8::Local<'s, v8::Context>,
641+ specifier: v8::Local<'s, v8::String>,
642+ _a: v8::Local<'s, v8::FixedArray>,
643+ _r: v8::Local<'s, v8::Module>,
644+) -> Option<v8::Local<'s, v8::Module>> {
645+ v8::callback_scope!(unsafe scope, context);
646+ let spec = specifier.to_rust_string_lossy(scope);
647+ let registry = modreg(scope);
648+ let m = registry
649+ .0
650+ .lock()
651+ .unwrap()
652+ .get(&spec)
653+ .map(|g| v8::Local::new(scope, g));
654+ if m.is_none() {
655+ tracing::warn!(%spec, "resolve: no stub for specifier");
656+ }
657+ m
658+}
659+
660+/// The (guarded setup script, backing-object expression) pair for a builtin
661+/// specifier, or None if `spec` is not one. The setup materializes a lazy
662+/// module's source at most once; the expression then names its global.
663+fn builtin_source(spec: &str) -> Option<(String, String)> {
664+ if spec == "cloudflare:workers" {
665+ return Some((String::new(), "globalThis.__cf".into()));
666+ }
667+ if let Some(m) = LAZY_MODULES.iter().find(|m| m.specs.contains(&spec)) {
668+ return Some((
669+ format!("if (!globalThis.{}) {{\n{}}}\n", m.global, m.source),
670+ format!("globalThis.{}", m.global),
671+ ));
672+ }
673+ if let Some(global) = eager_module_global(spec) {
674+ return Some((String::new(), global.to_string()));
675+ }
676+ is_external(spec).then(|| (String::new(), "globalThis.__nodeStub".to_string()))
677+}
678+
679+/// Full-surface module source for a builtin: run the (guarded) setup, probe
680+/// the backing object's enumerable keys, and re-export each one. Serves both
681+/// `import * as x` stubs and dynamic import(). `extra` adds statically
682+/// scanned names the probe may have missed, so mixed named + namespace
683+/// imports still link. String export names sidestep identifier restrictions.
684+fn full_surface_source(
685+ scope: &mut v8::PinScope,
686+ spec: &str,
687+ extra: &std::collections::BTreeSet<String>,
688+) -> Option<String> {
689+ let (setup, expr) = builtin_source(spec)?;
690+ let probe = format!("{setup}JSON.stringify(Object.keys(Object({expr})))");
691+ let code = v8::String::new(scope, &probe)?;
692+ let script = v8::Script::compile(scope, code, None)?;
693+ let keys = script.run(scope)?.to_rust_string_lossy(scope);
694+ let mut names: Vec<String> = serde_json::from_str(&keys).unwrap_or_default();
695+ for name in extra {
696+ if name != "*" && !names.contains(name) {
697+ names.push(name.clone());
698+ }
699+ }
700+ let mut src = format!("const __b = {expr};\nexport default __b;\n");
701+ for (i, name) in names.iter().enumerate() {
702+ if name == "default" {
703+ continue;
704+ }
705+ let name = serde_json::to_string(name).unwrap();
706+ src.push_str(&format!(
707+ "const __e{i} = __b[{name}]; export {{ __e{i} as {name} }};\n"
708+ ));
709+ }
710+ Some(src)
711+}
712+
713+/// `process.getBuiltinModule(id)`: the builtin's backing object, or
714+/// undefined for anything that is not a node builtin.
715+pub(super) fn op_builtin_module(
716+ scope: &mut v8::PinScope,
717+ args: v8::FunctionCallbackArguments,
718+ mut rv: v8::ReturnValue<v8::Value>,
719+) {
720+ let spec = args.get(0).to_rust_string_lossy(scope);
721+ if spec.starts_with("cloudflare:") {
722+ return; // not a node builtin
723+ }
724+ let Some((setup, expr)) = builtin_source(&spec) else {
725+ return;
726+ };
727+ let code = v8::String::new(scope, &format!("{setup}{expr}")).unwrap();
728+ if let Some(script) = v8::Script::compile(scope, code, None) {
729+ if let Some(value) = script.run(scope) {
730+ rv.set(value);
731+ }
732+ }
733+}
734+
735+/// Evaluate (once per isolate) a full-namespace module for a builtin
736+/// specifier. Unlike the static stubs, whose exports are the statically
737+/// scanned import names, this re-exports every enumerable key of the
738+/// backing object — a dynamic import's consumer can reach for any of them.
739+/// Cached in the isolate's module registry under a `dyn:` key so later
740+/// import() calls are a
741+/// table lookup.
742+fn dynamic_namespace<'s>(
743+ scope: &mut v8::PinScope<'s, '_>,
744+ spec: &str,
745+) -> Result<v8::Local<'s, v8::Value>> {
746+ let key = format!("dyn:{spec}");
747+ let registry = modreg(scope);
748+ let cached = registry
749+ .0
750+ .lock()
751+ .unwrap()
752+ .get(&key)
753+ .map(|g| v8::Local::new(scope, g));
754+ if let Some(module) = cached {
755+ return Ok(module.get_module_namespace());
756+ }
757+ let src = full_surface_source(scope, spec, &Default::default())
758+ .ok_or_else(|| anyhow!("dynamic import of \"{spec}\" is not supported"))?;
759+ let module = compile_module(scope, spec, &src)
760+ .ok_or_else(|| anyhow!("dynamic module for {spec} did not compile"))?;
761+ module
762+ .instantiate_module(scope, resolve_external)
763+ .ok_or_else(|| anyhow!("dynamic module for {spec} did not link"))?;
764+ module
765+ .evaluate(scope)
766+ .ok_or_else(|| anyhow!("dynamic module for {spec} threw"))?;
767+ if module.get_status() != v8::ModuleStatus::Evaluated {
768+ return Err(anyhow!("dynamic module for {spec} failed to evaluate"));
769+ }
770+ let g = v8::Global::new(scope, module);
771+ modreg(scope).0.lock().unwrap().insert(key, g);
772+ Ok(module.get_module_namespace())
773+}
774+
775+/// Dynamic `import()` host hook. Builtin specifiers resolve through the same
776+/// table static imports use; anything else rejects — celld bundles are
777+/// single-file, so there is nothing else to load.
778+pub(super) fn host_import_module_dynamically<'s>(
779+ scope: &mut v8::PinScope<'s, '_>,
780+ _host_defined_options: v8::Local<'s, v8::Data>,
781+ _resource_name: v8::Local<'s, v8::Value>,
782+ specifier: v8::Local<'s, v8::String>,
783+ _import_attributes: v8::Local<'s, v8::FixedArray>,
784+) -> Option<v8::Local<'s, v8::Promise>> {
785+ let resolver = v8::PromiseResolver::new(scope)?;
786+ let promise = resolver.get_promise(scope);
787+ let spec = specifier.to_rust_string_lossy(scope);
788+ let tc = std::pin::pin!(v8::TryCatch::new(scope));
789+ let tc = &mut tc.init();
790+ match dynamic_namespace(tc, &spec) {
791+ Ok(namespace) => {
792+ resolver.resolve(tc, namespace);
793+ }
794+ Err(error) => {
795+ let caught = tc.exception();
796+ tc.reset();
797+ let exception = caught.unwrap_or_else(|| {
798+ let message = v8::String::new(tc, &error.to_string()).unwrap();
799+ v8::Exception::error(tc, message)
800+ });
801+ resolver.reject(tc, exception);
802+ }
803+ }
804+ Some(promise)
805+}
modifiedcrates/celld/js/node_crypto.js+1523−1294View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/storage_ops.rs+709−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/text_encoding.js+6−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/url.js+8−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/websocket.rs+847−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/zlib.rs+256−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/lib.rs+80−87View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ltx_repl.rs+1092−521View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main.rs+4961−5362View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/main/cli.rs+291−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/main/machine.rs+245−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/main/websocket.rs+831−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/otlp.rs+350−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ownership_store.rs+406−404View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/peer_probe.rs+59−59View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/pool.rs+472−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/protocol.rs+40−6View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/replication.rs+35−27View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/runtime.rs+1929−1341View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/startup.rs+245−216View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/storage.rs+2708−2377View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/telemetry.rs+1254−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/wake.rs+244−234View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/alarm.rs+26−38View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/cache.rs+3−3View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/gate.rs+145−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/isolate.rs+303−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/lib.rs+4229−4091View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/pressure.rs+53−110View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/restore.rs+26−27View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/routing.rs+25−57View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/schedule.rs+0−22View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/sqlite.rs+26−51View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/types.rs+754−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/wake.rs+221−221View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/Cargo.toml+16−20View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/LICENSE.pierrec-lz4+27−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/README.md+47−17View file
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/reference/litestream-go/testdata/db/enforce-retention/database+0−0
Binary file not shown.
deletedcrates/ltx/reference/litestream-go/testdata/db/write-snapshot-to/database+0−0
Binary file not shown.
modifiedcrates/ltx/reference/ltx-format.md+87−78View file
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/scripts/guards.sh+0−42
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/file.rs+145−191View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/mod.rs+161−185View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/object_store.rs+985−1275View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/codec.rs+362−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/compaction_level.rs+199−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/compactor.rs+435−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/db.rs+864−864View file
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/src/leaser.rs+0−1665
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/lib.rs+59−68View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/ltx.rs+788−897View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/lz4_block.rs+271−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica.rs+1194−1162View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/replica_compactor.rs+352−0View file
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/src/store.rs+0−263
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/wal.rs+828−856View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/differential_xtool.rs+422−422View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/faults_inject.rs+18−28View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/integration_file.rs+85−85View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/integration_minio.rs+103−167View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/integration_resilience.rs+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/litestream_helpers.rs+0−34View file
Diff not rendered to keep this page fast. View the file
modifieddocs/README.md+318−183View file
Diff not rendered to keep this page fast. View the file
modifieddocs/cloudflare-compat.md+110−81View file
Diff not rendered to keep this page fast. View the file
addeddocs/fencing.md+107−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/limitations.md+36−30View file
Diff not rendered to keep this page fast. View the file
modifieddocs/security.md+99−40View file
Diff not rendered to keep this page fast. View the file
addeddocs/telemetry.md+134−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/testing.md+4−3View file
Diff not rendered to keep this page fast. View the file
addeddocs/wasm.md+78−0View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/README.md+11−6View file
Diff not rendered to keep this page fast. View the file
addedexamples/rpc/index.js+136−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/rpc/wrangler.jsonc+7−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/wasm/.gitignore+3−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/wasm/Cargo.toml+14−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/wasm/README.md+28−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/wasm/src/lib.rs+38−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/wasm/wrangler.jsonc+8−0View file
Diff not rendered to keep this page fast. View the file