Diffinery

homeflare/celldpublic

v0.0.2

The RPO=0 output gate is now on by default: HTTP responses, outgoing WebSocket
frames, and broadcasts are held until the cell's writes are durably replicated,
including writes from co-hosted Durable Objects. Set CELLD_OUTPUT_GATE=0 to
acknowledge writes without proving durability.

Replication now runs in-process by default via the new celld-ltx backend;
CELLD_REPLICATOR=litestream keeps the external process.

Evicting a cell now releases its ownership, nodes publish real load for
placement, and concurrent evictions are bounded. Outbound WebSockets per cell
are now bounded. Peer requests get a connect timeout, and stale WebSocket
routes are refreshed. V8 is upgraded to 152, and bootstrap bytecode is cached
across isolates. RFC 6598 overlay addresses (Tailscale) are accepted.
Ryan Dahl authored signed1 parent 44cec22commit 1d3f5bd31c91ab60159fd265984e9c8b7ed90315Browse files
167 files changed+70869−52807
Files (167)
modifiedCargo.lock+465−87View file
@@ -71,6 +71,15 @@
7171 checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
7272
7373 [[package]]
74+name = "android_system_properties"
75+version = "0.1.5"
76+source = "registry+https://github.com/rust-lang/crates.io-index"
77+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
78+dependencies = [
79+ "libc",
80+]
81+
82+[[package]]
7483 name = "anyhow"
7584 version = "1.0.104"
7685 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -110,9 +119,9 @@
110119
111120 [[package]]
112121 name = "aws-config"
113-version = "1.10.0"
122+version = "1.10.1"
114123 source = "registry+https://github.com/rust-lang/crates.io-index"
115-checksum = "701418aa459dac33e50a0f8e818e5662a16bc018a6ac7423659b70f3799d67a8"
124+checksum = "1b180a3c8b55960db3426d8964b8745e652466a1a49fe1a2eda828046d30b5e4"
116125 dependencies = [
117126 "aws-credential-types",
118127 "aws-runtime",
@@ -130,7 +139,7 @@
130139 "bytes",
131140 "fastrand",
132141 "hex",
133- "http 1.4.2",
142+ "http 1.5.0",
134143 "sha1 0.10.7",
135144 "time",
136145 "tokio",
@@ -176,9 +185,9 @@
176185
177186 [[package]]
178187 name = "aws-runtime"
179-version = "1.9.0"
188+version = "1.9.1"
180189 source = "registry+https://github.com/rust-lang/crates.io-index"
181-checksum = "a6b50a43f3ccdf331521c6d6c68b7cc9668b6e09d439ebda9569df5722324d76"
190+checksum = "c9007227e10b5fed2f3e0a2beff489211e2b5604c400b7a9d5d81ca9d64c24bb"
182191 dependencies = [
183192 "aws-credential-types",
184193 "aws-sigv4",
@@ -193,7 +202,7 @@
193202 "bytes-utils",
194203 "fastrand",
195204 "http 0.2.12",
196- "http 1.4.2",
205+ "http 1.5.0",
197206 "http-body 0.4.6",
198207 "http-body 1.1.0",
199208 "percent-encoding",
@@ -204,9 +213,9 @@
204213
205214 [[package]]
206215 name = "aws-sdk-s3"
207-version = "1.139.0"
216+version = "1.140.0"
208217 source = "registry+https://github.com/rust-lang/crates.io-index"
209-checksum = "a159b9721a6a41468f967d1029bece78f410b0beb0594498435deb6ff72bfe48"
218+checksum = "e9660cf991e512fbe6094f1041ff3d3282bc5aeeeb6184e8de437ec2de024a10"
210219 dependencies = [
211220 "arc-swap",
212221 "aws-credential-types",
@@ -229,7 +238,7 @@
229238 "hex",
230239 "hmac 0.13.0",
231240 "http 0.2.12",
232- "http 1.4.2",
241+ "http 1.5.0",
233242 "http-body 1.1.0",
234243 "lru",
235244 "percent-encoding",
@@ -241,9 +250,9 @@
241250
242251 [[package]]
243252 name = "aws-sdk-sso"
244-version = "1.104.0"
253+version = "1.105.0"
245254 source = "registry+https://github.com/rust-lang/crates.io-index"
246-checksum = "b53416d16c278234845392e38d93bd4481d2f09daa0f005a2277f0aa91f59c22"
255+checksum = "6ffd0fbe7873cb548a7aa60f9573c268fff94155397fd4f14dc9f1ecaaab8516"
247256 dependencies = [
248257 "arc-swap",
249258 "aws-credential-types",
@@ -260,16 +269,16 @@
260269 "bytes",
261270 "fastrand",
262271 "http 0.2.12",
263- "http 1.4.2",
272+ "http 1.5.0",
264273 "regex-lite",
265274 "tracing",
266275 ]
267276
268277 [[package]]
269278 name = "aws-sdk-ssooidc"
270-version = "1.106.0"
279+version = "1.107.0"
271280 source = "registry+https://github.com/rust-lang/crates.io-index"
272-checksum = "cc9b706c3305ed0285d5b1b696c747aa34950f830fb03e3e6c76890f99b9f188"
281+checksum = "175763eb222a46377df7aa257a3bca980ab3e96703fefc8f4d0b8da6ad2e254c"
273282 dependencies = [
274283 "arc-swap",
275284 "aws-credential-types",
@@ -286,16 +295,16 @@
286295 "bytes",
287296 "fastrand",
288297 "http 0.2.12",
289- "http 1.4.2",
298+ "http 1.5.0",
290299 "regex-lite",
291300 "tracing",
292301 ]
293302
294303 [[package]]
295304 name = "aws-sdk-sts"
296-version = "1.109.0"
305+version = "1.110.0"
297306 source = "registry+https://github.com/rust-lang/crates.io-index"
298-checksum = "32d214cdfa5bbe17f117e76a7643fadf32a5234fb597322ef8b1fb4b2f17dbbd"
307+checksum = "dd8b14781dfbff48984017d57167b6ea0b6471c6920ec52b44a2677c7feb3c13"
299308 dependencies = [
300309 "arc-swap",
301310 "aws-credential-types",
@@ -313,7 +322,7 @@
313322 "aws-types",
314323 "fastrand",
315324 "http 0.2.12",
316- "http 1.4.2",
325+ "http 1.5.0",
317326 "regex-lite",
318327 "tracing",
319328 ]
@@ -335,7 +344,7 @@
335344 "hex",
336345 "hmac 0.13.0",
337346 "http 0.2.12",
338- "http 1.4.2",
347+ "http 1.5.0",
339348 "p256",
340349 "percent-encoding",
341350 "sha2 0.11.0",
@@ -367,7 +376,7 @@
367376 "bytes",
368377 "crc-fast",
369378 "hex",
370- "http 1.4.2",
379+ "http 1.5.0",
371380 "http-body 1.1.0",
372381 "http-body-util",
373382 "md-5 0.11.0",
@@ -401,7 +410,7 @@
401410 "bytes-utils",
402411 "futures-core",
403412 "futures-util",
404- "http 1.4.2",
413+ "http 1.5.0",
405414 "http-body 1.1.0",
406415 "http-body-util",
407416 "percent-encoding",
@@ -422,7 +431,7 @@
422431 "h2 0.3.27",
423432 "h2 0.4.15",
424433 "http 0.2.12",
425- "http 1.4.2",
434+ "http 1.5.0",
426435 "http-body 0.4.6",
427436 "hyper 0.14.32",
428437 "hyper 1.11.0",
@@ -431,7 +440,7 @@
431440 "hyper-util",
432441 "pin-project-lite",
433442 "rustls 0.21.12",
434- "rustls 0.23.42",
443+ "rustls 0.23.43",
435444 "rustls-native-certs",
436445 "rustls-pki-types",
437446 "tokio",
@@ -475,9 +484,9 @@
475484
476485 [[package]]
477486 name = "aws-smithy-runtime"
478-version = "1.12.0"
487+version = "1.12.1"
479488 source = "registry+https://github.com/rust-lang/crates.io-index"
480-checksum = "bea94a9ff8464016338c851e24b472d7131c388c88898a502e781815b2ee6045"
489+checksum = "07505b34e8f4b3591a4fa69e9792b52289b95488dbbc68c3c0075b7bedb245e1"
481490 dependencies = [
482491 "aws-smithy-async",
483492 "aws-smithy-http",
@@ -489,7 +498,7 @@
489498 "bytes",
490499 "fastrand",
491500 "http 0.2.12",
492- "http 1.4.2",
501+ "http 1.5.0",
493502 "http-body 0.4.6",
494503 "http-body 1.1.0",
495504 "http-body-util",
@@ -501,16 +510,16 @@
501510
502511 [[package]]
503512 name = "aws-smithy-runtime-api"
504-version = "1.13.0"
513+version = "1.14.0"
505514 source = "registry+https://github.com/rust-lang/crates.io-index"
506-checksum = "22ed1ebe6e0a95ea84570225f5a8208dec4b8f77e61a9b0d6f51773fcb4612f0"
515+checksum = "3b98f2e1fd67ec06618f9c291e5e495a468e60519e44c9c1979cd0521f3affdb"
507516 dependencies = [
508517 "aws-smithy-async",
509518 "aws-smithy-runtime-api-macros",
510519 "aws-smithy-types",
511520 "bytes",
512521 "http 0.2.12",
513- "http 1.4.2",
522+ "http 1.5.0",
514523 "pin-project-lite",
515524 "tokio",
516525 "tracing",
@@ -536,7 +545,7 @@
536545 dependencies = [
537546 "aws-smithy-runtime-api",
538547 "aws-smithy-types",
539- "http 1.4.2",
548+ "http 1.5.0",
540549 ]
541550
542551 [[package]]
@@ -550,7 +559,7 @@
550559 "bytes-utils",
551560 "futures-core",
552561 "http 0.2.12",
553- "http 1.4.2",
562+ "http 1.5.0",
554563 "http-body 0.4.6",
555564 "http-body 1.1.0",
556565 "http-body-util",
@@ -602,7 +611,7 @@
602611 "axum-core",
603612 "bytes",
604613 "futures-util",
605- "http 1.4.2",
614+ "http 1.5.0",
606615 "http-body 1.1.0",
607616 "http-body-util",
608617 "hyper 1.11.0",
@@ -636,7 +645,7 @@
636645 "async-trait",
637646 "bytes",
638647 "futures-util",
639- "http 1.4.2",
648+ "http 1.5.0",
640649 "http-body 1.1.0",
641650 "http-body-util",
642651 "mime",
@@ -703,6 +712,21 @@
703712 ]
704713
705714 [[package]]
715+name = "bit-set"
716+version = "0.8.0"
717+source = "registry+https://github.com/rust-lang/crates.io-index"
718+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
719+dependencies = [
720+ "bit-vec",
721+]
722+
723+[[package]]
724+name = "bit-vec"
725+version = "0.8.0"
726+source = "registry+https://github.com/rust-lang/crates.io-index"
727+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
728+
729+[[package]]
706730 name = "bitflags"
707731 version = "2.13.1"
708732 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -760,9 +784,9 @@
760784
761785 [[package]]
762786 name = "cc"
763-version = "1.3.0"
787+version = "1.4.0"
764788 source = "registry+https://github.com/rust-lang/crates.io-index"
765-checksum = "c89588d05638b5b4594a3348a2d6c20277e43a7f5c5202b05cc56888475a47b8"
789+checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
766790 dependencies = [
767791 "find-msvc-tools",
768792 "jobserver",
@@ -772,7 +796,7 @@
772796
773797 [[package]]
774798 name = "celld"
775-version = "0.0.1"
799+version = "0.0.2"
776800 dependencies = [
777801 "aes-gcm",
778802 "anyhow",
@@ -783,6 +807,7 @@
783807 "axum",
784808 "base64 0.22.1",
785809 "celld-logic",
810+ "celld-ltx",
786811 "deno_core_icudata",
787812 "ed25519-dalek",
788813 "encoding_rs",
@@ -805,7 +830,7 @@
805830 "reqwest",
806831 "rsa",
807832 "rusqlite",
808- "rustls 0.23.42",
833+ "rustls 0.23.43",
809834 "serde",
810835 "serde_json",
811836 "sha1 0.10.7",
@@ -823,9 +848,31 @@
823848
824849 [[package]]
825850 name = "celld-logic"
826-version = "0.0.1"
851+version = "0.0.2"
827852
828853 [[package]]
854+name = "celld-ltx"
855+version = "0.0.0"
856+dependencies = [
857+ "async-trait",
858+ "bytes",
859+ "futures",
860+ "hex",
861+ "lz4_flex",
862+ "object_store",
863+ "proptest",
864+ "reqwest",
865+ "rusqlite",
866+ "serde",
867+ "serde_json",
868+ "sha2 0.10.9",
869+ "tempfile",
870+ "thiserror 2.0.19",
871+ "tokio",
872+ "tracing",
873+]
874+
875+[[package]]
829876 name = "cexpr"
830877 version = "0.6.0"
831878 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -858,6 +905,18 @@
858905 ]
859906
860907 [[package]]
908+name = "chrono"
909+version = "0.4.45"
910+source = "registry+https://github.com/rust-lang/crates.io-index"
911+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
912+dependencies = [
913+ "iana-time-zone",
914+ "num-traits",
915+ "serde",
916+ "windows-link",
917+]
918+
919+[[package]]
861920 name = "cipher"
862921 version = "0.4.4"
863922 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -869,9 +928,9 @@
869928
870929 [[package]]
871930 name = "clang-sys"
872-version = "1.8.1"
931+version = "1.9.1"
873932 source = "registry+https://github.com/rust-lang/crates.io-index"
874-checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
933+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
875934 dependencies = [
876935 "glob",
877936 "libc",
@@ -1131,13 +1190,13 @@
11311190
11321191 [[package]]
11331192 name = "displaydoc"
1134-version = "0.2.6"
1193+version = "0.2.7"
11351194 source = "registry+https://github.com/rust-lang/crates.io-index"
1136-checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
1195+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
11371196 dependencies = [
11381197 "proc-macro2",
11391198 "quote",
1140- "syn 2.0.119",
1199+ "syn 3.0.3",
11411200 ]
11421201
11431202 [[package]]
@@ -1186,9 +1245,9 @@
11861245
11871246 [[package]]
11881247 name = "either"
1189-version = "1.16.0"
1248+version = "1.17.0"
11901249 source = "registry+https://github.com/rust-lang/crates.io-index"
1191-checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
1250+checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
11921251
11931252 [[package]]
11941253 name = "elliptic-curve"
@@ -1263,7 +1322,7 @@
12631322 "axum-core",
12641323 "base64 0.21.7",
12651324 "bytes",
1266- "http 1.4.2",
1325+ "http 1.5.0",
12671326 "http-body-util",
12681327 "hyper 1.11.0",
12691328 "hyper-util",
@@ -1365,12 +1424,28 @@
13651424 ]
13661425
13671426 [[package]]
1427+name = "futures"
1428+version = "0.3.33"
1429+source = "registry+https://github.com/rust-lang/crates.io-index"
1430+checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218"
1431+dependencies = [
1432+ "futures-channel",
1433+ "futures-core",
1434+ "futures-executor",
1435+ "futures-io",
1436+ "futures-sink",
1437+ "futures-task",
1438+ "futures-util",
1439+]
1440+
1441+[[package]]
13681442 name = "futures-channel"
13691443 version = "0.3.33"
13701444 source = "registry+https://github.com/rust-lang/crates.io-index"
13711445 checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae"
13721446 dependencies = [
13731447 "futures-core",
1448+ "futures-sink",
13741449 ]
13751450
13761451 [[package]]
@@ -1380,6 +1455,17 @@
13801455 checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
13811456
13821457 [[package]]
1458+name = "futures-executor"
1459+version = "0.3.33"
1460+source = "registry+https://github.com/rust-lang/crates.io-index"
1461+checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458"
1462+dependencies = [
1463+ "futures-core",
1464+ "futures-task",
1465+ "futures-util",
1466+]
1467+
1468+[[package]]
13831469 name = "futures-io"
13841470 version = "0.3.33"
13851471 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1414,6 +1500,7 @@
14141500 source = "registry+https://github.com/rust-lang/crates.io-index"
14151501 checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"
14161502 dependencies = [
1503+ "futures-channel",
14171504 "futures-core",
14181505 "futures-io",
14191506 "futures-macro",
@@ -1540,7 +1627,7 @@
15401627 "fnv",
15411628 "futures-core",
15421629 "futures-sink",
1543- "http 1.4.2",
1630+ "http 1.5.0",
15441631 "indexmap",
15451632 "slab",
15461633 "tokio",
@@ -1584,6 +1671,12 @@
15841671 ]
15851672
15861673 [[package]]
1674+name = "heck"
1675+version = "0.5.0"
1676+source = "registry+https://github.com/rust-lang/crates.io-index"
1677+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
1678+
1679+[[package]]
15871680 name = "hex"
15881681 version = "0.4.3"
15891682 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1629,9 +1722,9 @@
16291722
16301723 [[package]]
16311724 name = "http"
1632-version = "1.4.2"
1725+version = "1.5.0"
16331726 source = "registry+https://github.com/rust-lang/crates.io-index"
1634-checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"
1727+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
16351728 dependencies = [
16361729 "bytes",
16371730 "itoa",
@@ -1655,7 +1748,7 @@
16551748 checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
16561749 dependencies = [
16571750 "bytes",
1658- "http 1.4.2",
1751+ "http 1.5.0",
16591752 ]
16601753
16611754 [[package]]
@@ -1666,7 +1759,7 @@
16661759 dependencies = [
16671760 "bytes",
16681761 "futures-core",
1669- "http 1.4.2",
1762+ "http 1.5.0",
16701763 "http-body 1.1.0",
16711764 "pin-project-lite",
16721765 ]
@@ -1684,10 +1777,16 @@
16841777 checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
16851778
16861779 [[package]]
1780+name = "humantime"
1781+version = "2.4.0"
1782+source = "registry+https://github.com/rust-lang/crates.io-index"
1783+checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"
1784+
1785+[[package]]
16871786 name = "hybrid-array"
1688-version = "0.4.13"
1787+version = "0.4.14"
16891788 source = "registry+https://github.com/rust-lang/crates.io-index"
1690-checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c"
1789+checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
16911790 dependencies = [
16921791 "typenum",
16931792 ]
@@ -1727,7 +1826,7 @@
17271826 "futures-channel",
17281827 "futures-core",
17291828 "h2 0.4.15",
1730- "http 1.4.2",
1829+ "http 1.5.0",
17311830 "http-body 1.1.0",
17321831 "httparse",
17331832 "httpdate",
@@ -1759,10 +1858,10 @@
17591858 source = "registry+https://github.com/rust-lang/crates.io-index"
17601859 checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
17611860 dependencies = [
1762- "http 1.4.2",
1861+ "http 1.5.0",
17631862 "hyper 1.11.0",
17641863 "hyper-util",
1765- "rustls 0.23.42",
1864+ "rustls 0.23.43",
17661865 "rustls-native-certs",
17671866 "tokio",
17681867 "tokio-rustls 0.26.4",
@@ -1780,7 +1879,7 @@
17801879 "bytes",
17811880 "futures-channel",
17821881 "futures-util",
1783- "http 1.4.2",
1882+ "http 1.5.0",
17841883 "http-body 1.1.0",
17851884 "hyper 1.11.0",
17861885 "ipnet",
@@ -1794,6 +1893,30 @@
17941893 ]
17951894
17961895 [[package]]
1896+name = "iana-time-zone"
1897+version = "0.1.65"
1898+source = "registry+https://github.com/rust-lang/crates.io-index"
1899+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
1900+dependencies = [
1901+ "android_system_properties",
1902+ "core-foundation-sys",
1903+ "iana-time-zone-haiku",
1904+ "js-sys",
1905+ "log",
1906+ "wasm-bindgen",
1907+ "windows-core",
1908+]
1909+
1910+[[package]]
1911+name = "iana-time-zone-haiku"
1912+version = "0.1.2"
1913+source = "registry+https://github.com/rust-lang/crates.io-index"
1914+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
1915+dependencies = [
1916+ "cc",
1917+]
1918+
1919+[[package]]
17971920 name = "icu_calendar"
17981921 version = "2.2.1"
17991922 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1963,9 +2086,9 @@
19632086
19642087 [[package]]
19652088 name = "ipnet"
1966-version = "2.12.0"
2089+version = "2.12.1"
19672090 source = "registry+https://github.com/rust-lang/crates.io-index"
1968-checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
2091+checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78"
19692092
19702093 [[package]]
19712094 name = "itertools"
@@ -2058,6 +2181,12 @@
20582181 checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
20592182
20602183 [[package]]
2184+name = "linux-raw-sys"
2185+version = "0.12.1"
2186+source = "registry+https://github.com/rust-lang/crates.io-index"
2187+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
2188+
2189+[[package]]
20612190 name = "litemap"
20622191 version = "0.8.2"
20632192 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2094,6 +2223,15 @@
20942223 checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
20952224
20962225 [[package]]
2226+name = "lz4_flex"
2227+version = "0.11.6"
2228+source = "registry+https://github.com/rust-lang/crates.io-index"
2229+checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a"
2230+dependencies = [
2231+ "twox-hash",
2232+]
2233+
2234+[[package]]
20972235 name = "matchers"
20982236 version = "0.2.0"
20992237 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2176,7 +2314,7 @@
21762314 "bytes",
21772315 "encoding_rs",
21782316 "futures-util",
2179- "http 1.4.2",
2317+ "http 1.5.0",
21802318 "httparse",
21812319 "memchr",
21822320 "mime",
@@ -2255,6 +2393,38 @@
22552393 ]
22562394
22572395 [[package]]
2396+name = "object_store"
2397+version = "0.11.2"
2398+source = "registry+https://github.com/rust-lang/crates.io-index"
2399+checksum = "3cfccb68961a56facde1163f9319e0d15743352344e7808a11795fb99698dcaf"
2400+dependencies = [
2401+ "async-trait",
2402+ "base64 0.22.1",
2403+ "bytes",
2404+ "chrono",
2405+ "futures",
2406+ "httparse",
2407+ "humantime",
2408+ "hyper 1.11.0",
2409+ "itertools",
2410+ "md-5 0.10.6",
2411+ "parking_lot",
2412+ "percent-encoding",
2413+ "quick-xml",
2414+ "rand 0.8.7",
2415+ "reqwest",
2416+ "ring",
2417+ "rustls-pemfile",
2418+ "serde",
2419+ "serde_json",
2420+ "snafu",
2421+ "tokio",
2422+ "tracing",
2423+ "url",
2424+ "walkdir",
2425+]
2426+
2427+[[package]]
22582428 name = "once_cell"
22592429 version = "1.21.4"
22602430 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2460,6 +2630,41 @@
24602630 ]
24612631
24622632 [[package]]
2633+name = "proptest"
2634+version = "1.11.0"
2635+source = "registry+https://github.com/rust-lang/crates.io-index"
2636+checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
2637+dependencies = [
2638+ "bit-set",
2639+ "bit-vec",
2640+ "bitflags",
2641+ "num-traits",
2642+ "rand 0.9.5",
2643+ "rand_chacha 0.9.0",
2644+ "rand_xorshift",
2645+ "regex-syntax",
2646+ "rusty-fork",
2647+ "tempfile",
2648+ "unarray",
2649+]
2650+
2651+[[package]]
2652+name = "quick-error"
2653+version = "1.2.3"
2654+source = "registry+https://github.com/rust-lang/crates.io-index"
2655+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
2656+
2657+[[package]]
2658+name = "quick-xml"
2659+version = "0.37.5"
2660+source = "registry+https://github.com/rust-lang/crates.io-index"
2661+checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
2662+dependencies = [
2663+ "memchr",
2664+ "serde",
2665+]
2666+
2667+[[package]]
24632668 name = "quinn"
24642669 version = "0.11.11"
24652670 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2471,7 +2676,7 @@
24712676 "quinn-proto",
24722677 "quinn-udp",
24732678 "rustc-hash",
2474- "rustls 0.23.42",
2679+ "rustls 0.23.43",
24752680 "socket2 0.6.5",
24762681 "thiserror 2.0.19",
24772682 "tokio",
@@ -2492,7 +2697,7 @@
24922697 "rand_pcg",
24932698 "ring",
24942699 "rustc-hash",
2495- "rustls 0.23.42",
2700+ "rustls 0.23.43",
24962701 "rustls-pki-types",
24972702 "slab",
24982703 "thiserror 2.0.19",
@@ -2622,6 +2827,15 @@
26222827 ]
26232828
26242829 [[package]]
2830+name = "rand_xorshift"
2831+version = "0.4.0"
2832+source = "registry+https://github.com/rust-lang/crates.io-index"
2833+checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
2834+dependencies = [
2835+ "rand_core 0.9.5",
2836+]
2837+
2838+[[package]]
26252839 name = "redox_syscall"
26262840 version = "0.5.18"
26272841 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2675,7 +2889,8 @@
26752889 "bytes",
26762890 "futures-core",
26772891 "futures-util",
2678- "http 1.4.2",
2892+ "h2 0.4.15",
2893+ "http 1.5.0",
26792894 "http-body 1.1.0",
26802895 "http-body-util",
26812896 "hyper 1.11.0",
@@ -2686,7 +2901,8 @@
26862901 "percent-encoding",
26872902 "pin-project-lite",
26882903 "quinn",
2689- "rustls 0.23.42",
2904+ "rustls 0.23.43",
2905+ "rustls-native-certs",
26902906 "rustls-pki-types",
26912907 "serde",
26922908 "serde_json",
@@ -2799,11 +3015,24 @@
27993015 "bitflags",
28003016 "errno",
28013017 "libc",
2802- "linux-raw-sys",
2803- "windows-sys 0.59.0",
3018+ "linux-raw-sys 0.4.15",
3019+ "windows-sys 0.52.0",
28043020 ]
28053021
28063022 [[package]]
3023+name = "rustix"
3024+version = "1.1.4"
3025+source = "registry+https://github.com/rust-lang/crates.io-index"
3026+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
3027+dependencies = [
3028+ "bitflags",
3029+ "errno",
3030+ "libc",
3031+ "linux-raw-sys 0.12.1",
3032+ "windows-sys 0.61.2",
3033+]
3034+
3035+[[package]]
28073036 name = "rustls"
28083037 version = "0.21.12"
28093038 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2817,9 +3046,9 @@
28173046
28183047 [[package]]
28193048 name = "rustls"
2820-version = "0.23.42"
3049+version = "0.23.43"
28213050 source = "registry+https://github.com/rust-lang/crates.io-index"
2822-checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138"
3051+checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06"
28233052 dependencies = [
28243053 "aws-lc-rs",
28253054 "once_cell",
@@ -2843,6 +3072,15 @@
28433072 ]
28443073
28453074 [[package]]
3075+name = "rustls-pemfile"
3076+version = "2.2.0"
3077+source = "registry+https://github.com/rust-lang/crates.io-index"
3078+checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
3079+dependencies = [
3080+ "rustls-pki-types",
3081+]
3082+
3083+[[package]]
28463084 name = "rustls-pki-types"
28473085 version = "1.15.1"
28483086 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2881,12 +3119,33 @@
28813119 checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
28823120
28833121 [[package]]
3122+name = "rusty-fork"
3123+version = "0.3.1"
3124+source = "registry+https://github.com/rust-lang/crates.io-index"
3125+checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
3126+dependencies = [
3127+ "fnv",
3128+ "quick-error",
3129+ "tempfile",
3130+ "wait-timeout",
3131+]
3132+
3133+[[package]]
28843134 name = "ryu"
28853135 version = "1.0.23"
28863136 source = "registry+https://github.com/rust-lang/crates.io-index"
28873137 checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
28883138
28893139 [[package]]
3140+name = "same-file"
3141+version = "1.0.6"
3142+source = "registry+https://github.com/rust-lang/crates.io-index"
3143+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
3144+dependencies = [
3145+ "winapi-util",
3146+]
3147+
3148+[[package]]
28903149 name = "schannel"
28913150 version = "0.1.29"
28923151 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3124,6 +3383,27 @@
31243383 checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
31253384
31263385 [[package]]
3386+name = "snafu"
3387+version = "0.8.9"
3388+source = "registry+https://github.com/rust-lang/crates.io-index"
3389+checksum = "6e84b3f4eacbf3a1ce05eac6763b4d629d60cbc94d632e4092c54ade71f1e1a2"
3390+dependencies = [
3391+ "snafu-derive",
3392+]
3393+
3394+[[package]]
3395+name = "snafu-derive"
3396+version = "0.8.9"
3397+source = "registry+https://github.com/rust-lang/crates.io-index"
3398+checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451"
3399+dependencies = [
3400+ "heck",
3401+ "proc-macro2",
3402+ "quote",
3403+ "syn 2.0.119",
3404+]
3405+
3406+[[package]]
31273407 name = "socket2"
31283408 version = "0.5.10"
31293409 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3229,6 +3509,19 @@
32293509 ]
32303510
32313511 [[package]]
3512+name = "tempfile"
3513+version = "3.27.0"
3514+source = "registry+https://github.com/rust-lang/crates.io-index"
3515+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
3516+dependencies = [
3517+ "fastrand",
3518+ "getrandom 0.4.3",
3519+ "once_cell",
3520+ "rustix 1.1.4",
3521+ "windows-sys 0.61.2",
3522+]
3523+
3524+[[package]]
32323525 name = "temporal_capi"
32333526 version = "0.2.4"
32343527 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3313,9 +3606,9 @@
33133606
33143607 [[package]]
33153608 name = "time"
3316-version = "0.3.54"
3609+version = "0.3.55"
33173610 source = "registry+https://github.com/rust-lang/crates.io-index"
3318-checksum = "3e1d5e639ff6bab73cb6885cc7e7b1de96c3f32c68ec55f3952614bec1092244"
3611+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
33193612 dependencies = [
33203613 "deranged",
33213614 "num-conv",
@@ -3398,13 +3691,13 @@
33983691
33993692 [[package]]
34003693 name = "tokio-macros"
3401-version = "2.7.1"
3694+version = "2.7.2"
34023695 source = "registry+https://github.com/rust-lang/crates.io-index"
3403-checksum = "6328af13490e73a9b4694030fafd93f8c8c6a9dede33e821c3fc63eddf8042ba"
3696+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
34043697 dependencies = [
34053698 "proc-macro2",
34063699 "quote",
3407- "syn 2.0.119",
3700+ "syn 3.0.3",
34083701 ]
34093702
34103703 [[package]]
@@ -3423,7 +3716,7 @@
34233716 source = "registry+https://github.com/rust-lang/crates.io-index"
34243717 checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
34253718 dependencies = [
3426- "rustls 0.23.42",
3719+ "rustls 0.23.43",
34273720 "tokio",
34283721 ]
34293722
@@ -3446,7 +3739,7 @@
34463739 dependencies = [
34473740 "futures-util",
34483741 "log",
3449- "rustls 0.23.42",
3742+ "rustls 0.23.43",
34503743 "rustls-pki-types",
34513744 "tokio",
34523745 "tokio-rustls 0.26.4",
@@ -3465,6 +3758,7 @@
34653758 "futures-sink",
34663759 "libc",
34673760 "pin-project-lite",
3761+ "slab",
34683762 "tokio",
34693763 ]
34703764
@@ -3493,7 +3787,7 @@
34933787 "bitflags",
34943788 "bytes",
34953789 "futures-util",
3496- "http 1.4.2",
3790+ "http 1.5.0",
34973791 "http-body 1.1.0",
34983792 "pin-project-lite",
34993793 "tower",
@@ -3590,11 +3884,11 @@
35903884 dependencies = [
35913885 "bytes",
35923886 "data-encoding",
3593- "http 1.4.2",
3887+ "http 1.5.0",
35943888 "httparse",
35953889 "log",
35963890 "rand 0.9.5",
3597- "rustls 0.23.42",
3891+ "rustls 0.23.43",
35983892 "rustls-pki-types",
35993893 "sha1 0.10.7",
36003894 "thiserror 2.0.19",
@@ -3602,12 +3896,24 @@
36023896 ]
36033897
36043898 [[package]]
3899+name = "twox-hash"
3900+version = "2.1.3"
3901+source = "registry+https://github.com/rust-lang/crates.io-index"
3902+checksum = "8464ec13c3691491391d9fce00f6416c9a48e46972f72d7865688be2080192c9"
3903+
3904+[[package]]
36053905 name = "typenum"
36063906 version = "1.20.1"
36073907 source = "registry+https://github.com/rust-lang/crates.io-index"
36083908 checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
36093909
36103910 [[package]]
3911+name = "unarray"
3912+version = "0.1.4"
3913+source = "registry+https://github.com/rust-lang/crates.io-index"
3914+checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
3915+
3916+[[package]]
36113917 name = "unicode-ident"
36123918 version = "1.0.24"
36133919 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3683,9 +3989,9 @@
36833989
36843990 [[package]]
36853991 name = "v8"
3686-version = "150.3.0"
3992+version = "152.0.0"
36873993 source = "registry+https://github.com/rust-lang/crates.io-index"
3688-checksum = "a60e502a2130c372cdee0df8c1e614dab69a04ba439067dc4c0763cfd1ab92f7"
3994+checksum = "91c89be3a18777511705994775d413eb7595c1efcf51ded4b19bbbf6aec7a66c"
36893995 dependencies = [
36903996 "bindgen",
36913997 "bitflags",
@@ -3723,6 +4029,25 @@
37234029 checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
37244030
37254031 [[package]]
4032+name = "wait-timeout"
4033+version = "0.2.1"
4034+source = "registry+https://github.com/rust-lang/crates.io-index"
4035+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
4036+dependencies = [
4037+ "libc",
4038+]
4039+
4040+[[package]]
4041+name = "walkdir"
4042+version = "2.5.0"
4043+source = "registry+https://github.com/rust-lang/crates.io-index"
4044+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
4045+dependencies = [
4046+ "same-file",
4047+ "winapi-util",
4048+]
4049+
4050+[[package]]
37264051 name = "want"
37274052 version = "0.3.1"
37284053 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3860,7 +4185,7 @@
38604185 dependencies = [
38614186 "either",
38624187 "home",
3863- "rustix",
4188+ "rustix 0.38.44",
38644189 "winsafe",
38654190 ]
38664191
@@ -3881,31 +4206,84 @@
38814206 checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
38824207
38834208 [[package]]
4209+name = "winapi-util"
4210+version = "0.1.11"
4211+source = "registry+https://github.com/rust-lang/crates.io-index"
4212+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
4213+dependencies = [
4214+ "windows-sys 0.61.2",
4215+]
4216+
4217+[[package]]
38844218 name = "winapi-x86_64-pc-windows-gnu"
38854219 version = "0.4.0"
38864220 source = "registry+https://github.com/rust-lang/crates.io-index"
38874221 checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
38884222
38894223 [[package]]
4224+name = "windows-core"
4225+version = "0.62.2"
4226+source = "registry+https://github.com/rust-lang/crates.io-index"
4227+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
4228+dependencies = [
4229+ "windows-implement",
4230+ "windows-interface",
4231+ "windows-link",
4232+ "windows-result",
4233+ "windows-strings",
4234+]
4235+
4236+[[package]]
4237+name = "windows-implement"
4238+version = "0.60.2"
4239+source = "registry+https://github.com/rust-lang/crates.io-index"
4240+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
4241+dependencies = [
4242+ "proc-macro2",
4243+ "quote",
4244+ "syn 2.0.119",
4245+]
4246+
4247+[[package]]
4248+name = "windows-interface"
4249+version = "0.59.3"
4250+source = "registry+https://github.com/rust-lang/crates.io-index"
4251+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
4252+dependencies = [
4253+ "proc-macro2",
4254+ "quote",
4255+ "syn 2.0.119",
4256+]
4257+
4258+[[package]]
38904259 name = "windows-link"
38914260 version = "0.2.1"
38924261 source = "registry+https://github.com/rust-lang/crates.io-index"
38934262 checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
38944263
38954264 [[package]]
3896-name = "windows-sys"
3897-version = "0.52.0"
4265+name = "windows-result"
4266+version = "0.4.1"
38984267 source = "registry+https://github.com/rust-lang/crates.io-index"
3899-checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
4268+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
39004269 dependencies = [
3901- "windows-targets",
4270+ "windows-link",
39024271 ]
39034272
39044273 [[package]]
4274+name = "windows-strings"
4275+version = "0.5.1"
4276+source = "registry+https://github.com/rust-lang/crates.io-index"
4277+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
4278+dependencies = [
4279+ "windows-link",
4280+]
4281+
4282+[[package]]
39054283 name = "windows-sys"
3906-version = "0.59.0"
4284+version = "0.52.0"
39074285 source = "registry+https://github.com/rust-lang/crates.io-index"
3908-checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
4286+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
39094287 dependencies = [
39104288 "windows-targets",
39114289 ]
modifiedCargo.toml+2−5View file
@@ -1,8 +1,5 @@
1-# The celld engine is a cargo workspace: `crates/celld` is the engine (a lib +
2-# a thin bin), `crates/logic` is the pure, zero-dependency decision core.
3-# Keeping `logic` a separate zero-dependency crate is deliberate: it can be
4-# depended on without pulling in the engine (v8/tokio), and a stray I/O
5-# dependency fails to compile — enforcing the sans-IO contract at the boundary.
1+# Clean-sheet celld workspace. `crates/logic` owns all behavioral state and
2+# decisions; `crates/celld` is only an effect executor and adapter host.
63 [workspace]
74 resolver = "2"
85 members = ["crates/*"]
modifiedDockerfile+14−35View file
@@ -2,11 +2,9 @@
22
33 ARG RUST_VERSION=1.97.1
44 ARG GO_VERSION=1.25.12
5-ARG ESBUILD_VERSION=0.28.1
65 ARG CELLD_COMMIT=unknown
7-ARG CELLD_VERSION=unknown
86
9-FROM rust:${RUST_VERSION}-bookworm AS celld-build
7+FROM rust:${RUST_VERSION}-bookworm AS build
108 ARG TARGETARCH
119 WORKDIR /src
1210 COPY Cargo.toml Cargo.lock ./
@@ -15,12 +13,13 @@
1513 --mount=type=cache,id=celld-cargo-git,target=/usr/local/cargo/git,sharing=locked \
1614 --mount=type=cache,id=celld-target-${TARGETARCH},target=/src/target,sharing=locked \
1715 mkdir -p /out && \
18- cargo build --release --locked && \
19- install -m 755 target/release/celld /out/celld && \
20- PACKAGE_VERSION=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/celld/Cargo.toml | head -1) && \
21- test "$(/out/celld --version)" = "celld ${PACKAGE_VERSION}"
16+ cargo build --release --locked -p celld && \
17+ install -m 755 target/release/celld /out/celld
2218
23-FROM celld-build AS test
19+# The release workflow builds this stage on every candidate push, so a
20+# break in the engine's own tests or lints stops a release before any
21+# artifact is drafted.
22+FROM build AS test
2423 ARG TARGETARCH
2524 RUN rustup component add clippy
2625 RUN --mount=type=cache,id=celld-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
@@ -35,7 +34,7 @@
3534 rm -rf /var/lib/apt/lists/*
3635 WORKDIR /src
3736 COPY crates/celld/Cargo.toml /tmp/celld-Cargo.toml
38-RUN --mount=type=cache,id=litestream-source,target=/var/cache/litestream,sharing=locked \
37+RUN --mount=type=cache,id=celld-litestream-source,target=/var/cache/litestream,sharing=locked \
3938 LITESTREAM_SHA=$(sed -n \
4039 's/^litestream-commit = "\(.*\)"$/\1/p' /tmp/celld-Cargo.toml) && \
4140 test -n "${LITESTREAM_SHA}" && \
@@ -48,8 +47,8 @@
4847 git -C /var/cache/litestream fetch --depth=1 origin "${LITESTREAM_SHA}"; \
4948 fi && \
5049 git -C /var/cache/litestream archive "${LITESTREAM_SHA}" | tar -xf - -C /src
51-RUN --mount=type=cache,id=litestream-go-build,target=/root/.cache/go-build,sharing=locked \
52- --mount=type=cache,id=litestream-go-mod,target=/go/pkg/mod,sharing=locked \
50+RUN --mount=type=cache,id=celld-litestream-go-build,target=/root/.cache/go-build,sharing=locked \
51+ --mount=type=cache,id=celld-litestream-go-mod,target=/go/pkg/mod,sharing=locked \
5352 LITESTREAM_VERSION=$(sed -n \
5453 's/^litestream-version = "\(.*\)"$/\1/p' /tmp/celld-Cargo.toml) && \
5554 test -n "${LITESTREAM_VERSION}" && \
@@ -60,36 +59,16 @@
6059 ./cmd/litestream && \
6160 test "$(/out/litestream version)" = "${LITESTREAM_VERSION}"
6261
63-FROM node:22-bookworm-slim AS esbuild
64-ARG ESBUILD_VERSION
65-ARG TARGETARCH
66-RUN npm install --global "esbuild@${ESBUILD_VERSION}" && \
67- case "${TARGETARCH}" in \
68- amd64) ESBUILD_ARCH=x64 ;; \
69- arm64) ESBUILD_ARCH=arm64 ;; \
70- *) echo "unsupported esbuild architecture: ${TARGETARCH}" >&2; exit 1 ;; \
71- esac && \
72- mkdir -p /out && \
73- install -m 755 \
74- "/usr/local/lib/node_modules/esbuild/node_modules/@esbuild/linux-${ESBUILD_ARCH}/bin/esbuild" \
75- /out/esbuild && \
76- test "$(/out/esbuild --version)" = "${ESBUILD_VERSION}"
77-
7862 FROM debian:bookworm-slim
7963 RUN apt-get update && \
8064 apt-get install -y --no-install-recommends ca-certificates && \
8165 rm -rf /var/lib/apt/lists/*
8266 ARG CELLD_COMMIT
83-ARG CELLD_VERSION
84-ARG ESBUILD_VERSION
67+ARG CELLD_VERSION=unknown
8568 LABEL org.opencontainers.image.title="celld" \
86- org.opencontainers.image.source="https://github.com/denoland/celld" \
8769 org.opencontainers.image.revision="${CELLD_COMMIT}" \
88- org.opencontainers.image.version="${CELLD_VERSION}" \
89- dev.celld.esbuild.version="${ESBUILD_VERSION}"
90-COPY --from=celld-build /out/celld /usr/local/bin/celld
70+ org.opencontainers.image.version="${CELLD_VERSION}"
71+COPY --from=build /out/celld /usr/local/bin/celld
9172 COPY --from=litestream-build /out/litestream /usr/local/bin/litestream
92-COPY --from=esbuild /out/esbuild /usr/local/bin/esbuild
93-ENV LITESTREAM_BIN=/usr/local/bin/litestream \
94- CELLD_ESBUILD=/usr/local/bin/esbuild
73+ENV LITESTREAM_BIN=/usr/local/bin/litestream
9574 ENTRYPOINT ["/usr/local/bin/celld"]
modifiedREADME.md+14−13View file
@@ -2,9 +2,9 @@
22
33 Self-hosted, distributed **Durable Objects**.
44
5-celld is an open-source daemon that runs Cloudflare Workers and Durable Objects
6-on your own machines — a distributed system you program like a database. Each
7-object is its own SQLite database, addressed by name and replicated to an
5+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
88 S3-compatible bucket you own; nodes coordinate through that bucket alone, with
99 no control plane or consensus. Because every object is its own small database,
1010 applications shard by construction — the contention and blast-radius failures
@@ -55,8 +55,8 @@
5555 for `celld deploy`. It is published for Linux x86-64 and ARM64:
5656
5757 ```sh
58-docker pull ghcr.io/denoland/celld:0.0.1
59-docker run --rm ghcr.io/denoland/celld:0.0.1 --version
58+docker pull ghcr.io/denoland/celld:latest
59+docker run --rm ghcr.io/denoland/celld:latest --version
6060 ```
6161
6262 `latest` and the Cargo version are convenient mutable tags. Use
@@ -72,7 +72,7 @@
7272 -e AWS_SESSION_TOKEN \
7373 -e CELLD_WATCH=/var/lib/celld/state \
7474 -v celld-state:/var/lib/celld \
75- ghcr.io/denoland/celld:0.0.1 \
75+ ghcr.io/denoland/celld:latest \
7676 --bucket s3://my-cells-bucket \
7777 --endpoint https://ACCOUNT.r2.cloudflarestorage.com \
7878 --region auto \
@@ -102,7 +102,7 @@
102102 cannot be inferred. A fleet runs one application, and every node loads its
103103 latest successfully committed deployment from `deploy/current.json`. Run
104104 `celld --help` for the complete command line.
105-Deployment objects use the documented types in `src/protocol.rs`. `celld
105+Deployment objects use the documented types in `crates/celld/protocol.rs`. `celld
106106 deploy` invokes `esbuild` from `PATH` for Worker code, accepts the supported
107107 Wrangler config subset—including co-deployed or asset-only static
108108 assets—and writes those objects directly. Every node discovers owners and
@@ -158,8 +158,8 @@
158158 cargo clippy --all-targets --locked -- -D warnings
159159 ```
160160
161-The root package builds the `celld` runtime. Its versioned object-storage
162-protocol lives in `src/protocol.rs`. Small Wrangler projects under `examples/`
161+The workspace builds the `celld` runtime. Its versioned object-storage
162+protocol lives in `crates/celld/protocol.rs`. Small Wrangler projects under `examples/`
163163 exercise the supported Worker and Durable Object surface.
164164
165165 The runtime and compatibility surface are still evolving. Public tests cover
@@ -176,9 +176,10 @@
176176
177177 Send a `git format-patch` attachment to [[email protected]](mailto:[email protected]).
178178
179-By emailing a patch, you certify that you have the right to submit it and assign
180-to Deno Land Inc. all rights in the patch that you can assign. Where a right
181-cannot be assigned, you grant Deno Land Inc. a perpetual, irrevocable,
179+Contributor License Agreement: By emailing a patch, you certify that you have
180+the right to submit it and assign to Deno Land Inc. all rights in the patch
181+that you can assign. Where a right cannot be assigned, you grant Deno Land
182+Inc. a perpetual, irrevocable,
182183 worldwide, royalty-free, transferable, sublicensable license to use, modify,
183184 combine, relicense, redistribute, or publish the patch, in whole or in part,
184185 with or without attribution.
@@ -187,5 +188,5 @@
187188
188189 [MIT](LICENSE)
189190
190-See the [support matrix](docs/support.md), [v0.0.1 limitations](docs/limitations.md),
191+See the [support matrix](docs/support.md), [limitations](docs/limitations.md),
191192 and [security](docs/security.md) before operating a public fleet.
modifiedcrates/celld/Cargo.toml+41−40View file
@@ -1,6 +1,6 @@
11 [package]
22 name = "celld"
3-version = "0.0.1"
3+version = "0.0.2"
44 edition = "2021"
55 rust-version = "1.94.1"
66 license = "MIT"
@@ -8,63 +8,64 @@
88 [package.metadata.release]
99 litestream-version = "v0.5.15"
1010 litestream-commit = "5a2624418478f358cf85ed7d4606eb55029194ec"
11-litestream-upstream-pr = 1328
1211
12+[lib]
13+path = "lib.rs"
14+
15+[[bin]]
16+name = "celld"
17+path = "main.rs"
18+
1319 [lints.rust.unexpected_cfgs]
1420 level = "warn"
15-check-cfg = ["cfg(celld_internal_tests)"]
21+check-cfg = ["cfg(celld_internal_tests)", "cfg(celld_proxy_internals)"]
1622
1723 [dependencies]
18-celld-logic = { path = "../logic" }
19-tokio = { version = "1", features = ["full"] }
20-tokio-stream = "0.1"
21-serde = { version = "1", features = ["derive"] }
22-serde_json = "1"
24+aes-gcm = "0.10"
2325 anyhow = "1"
24-tracing = "0.1"
25-tracing-subscriber = { version = "0.3", features = ["env-filter"] }
2626 aws-config = { version = "1", features = ["behavior-version-latest"] }
27-aws-sdk-s3 = "1"
2827 aws-credential-types = "1"
28+aws-sdk-s3 = "1"
2929 aws-smithy-http-client = "1"
3030 axum = { version = "0.7", features = ["multipart"] }
31-hyper = { version = "1", features = ["server", "http1"] }
32-hyper-util = { version = "0.1", features = ["tokio"] }
33-http-body-util = "0.1"
34-reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream", "json"] }
35-v8 = "150"
36-rusqlite = { version = "0.31", features = ["backup", "bundled", "hooks"] }
37-url = "2"
38-percent-encoding = "2"
39-tokio-util = { version = "0.7", features = ["io"] }
40-filetime = "0.2"
41-# URLPattern parsing (same crate Deno uses); its icu_properties/regex/url
42-# deps are already in the graph via idna and the crypto stack.
43-urlpattern = "=0.4.2"
4431 base64 = "0.22"
45-fastwebsockets = { version = "0.8", default-features = false, features = ["upgrade", "with_axum"] }
32+celld-logic = { path = "../logic" }
33+celld-ltx = { path = "../ltx", features = ["s3"] }
4634 deno_core_icudata = "0.77"
47-# WHATWG Encoding Standard legacy decoders (windows-1252, Big5, GBK, …);
48-# already in the graph transitively via reqwest/multer.
4935 encoding_rs = "0.8"
50-regex = "1"
51-getrandom = "0.3"
52-md-5 = "0.10"
53-sha1 = "0.10"
54-sha2 = "0.10"
36+ed25519-dalek = { version = "2", features = ["pkcs8"] }
37+fastwebsockets = { version = "0.8", default-features = false, features = ["upgrade", "with_axum"] }
38+filetime = "0.2"
5539 flate2 = "1"
40+fs2 = "0.4"
41+futures-util = "0.3"
42+getrandom = "0.3"
5643 hmac = "0.12"
57-aes-gcm = "0.10"
58-ed25519-dalek = { version = "2", features = ["pkcs8"] }
44+http-body-util = "0.1"
45+hyper = { version = "1", features = ["server", "http1"] }
46+hyper-util = { version = "0.1", features = ["tokio"] }
47+md-5 = "0.10"
48+percent-encoding = "2"
5949 p256 = { version = "0.13", features = ["ecdsa", "pkcs8"] }
60-rsa = { version = "0.9", features = ["sha2"] }
6150 rand = "0.8"
62-fs2 = "0.4"
63-futures-util = "0.3"
64-tokio-tungstenite = { version = "0.28", features = ["rustls-tls-webpki-roots"] }
65-# process-level TLS provider selection: two providers exist in the graph
66-# (aws-lc-rs via the AWS SDK, ring via reqwest), so main() must install one
51+regex = "1"
52+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream", "json"] }
53+rusqlite = { version = "0.31", features = ["backup", "bundled", "hooks"] }
6754 rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs"] }
55+rsa = { version = "0.9", features = ["sha2"] }
56+serde = { version = "1", features = ["derive"] }
57+serde_json = "1"
58+sha1 = "0.10"
59+sha2 = "0.10"
60+tokio = { version = "1", features = ["full"] }
61+tokio-stream = "0.1"
62+tokio-tungstenite = { version = "0.28", features = ["rustls-tls-webpki-roots"] }
63+tokio-util = { version = "0.7", features = ["io", "time"] }
64+tracing = "0.1"
65+tracing-subscriber = { version = "0.3", features = ["env-filter"] }
66+url = "2"
67+urlpattern = "=0.4.2"
68+v8 = "152"
6869
6970 [target.'cfg(unix)'.dependencies]
7071 libc = "0.2"
addedcrates/celld/assets.rs+1243−0View file
@@ -1,0 +1,1243 @@
1+use crate::js;
2+use crate::protocol::{asset_blob_key, AssetEntry, AssetIndex, AssetManifestRef, RunWorkerFirst};
3+use anyhow::{anyhow, Context};
4+use aws_sdk_s3::Client;
5+use axum::body::Body;
6+use axum::http::{HeaderMap, HeaderValue, StatusCode};
7+use axum::response::Response;
8+use futures_util::StreamExt;
9+use percent_encoding::percent_decode_str;
10+use rand::RngCore;
11+use sha2::{Digest, Sha256};
12+use std::collections::HashMap;
13+use std::path::{Path, PathBuf};
14+use std::sync::Arc;
15+use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
16+use tokio::sync::Mutex;
17+use tokio_util::io::ReaderStream;
18+
19+const DEFAULT_ASSET_CACHE_BYTES: u64 = 512 * 1024 * 1024;
20+
21+#[derive(Clone)]
22+pub struct AssetResolver {
23+ inner: Arc<AssetResolverInner>,
24+}
25+
26+struct AssetResolverInner {
27+ client: Client,
28+ bucket: String,
29+ index: AssetIndex,
30+ asset_only: bool,
31+ cache_root: PathBuf,
32+ cache_max_bytes: u64,
33+ download_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
34+ cleanup_lock: Mutex<()>,
35+ header_rules: Vec<HeaderRule>,
36+ redirect_rules: Vec<RedirectRule>,
37+}
38+
39+enum Route {
40+ Asset {
41+ path: String,
42+ entry: AssetEntry,
43+ status: StatusCode,
44+ },
45+ Redirect {
46+ location: String,
47+ status: StatusCode,
48+ },
49+ Missing,
50+}
51+
52+#[derive(Clone, Copy)]
53+enum RequestedRange {
54+ Full,
55+ Partial { start: u64, end: u64 },
56+ Unsatisfiable,
57+}
58+
59+struct RulePattern {
60+ host: Option<regex::Regex>,
61+ path: regex::Regex,
62+}
63+
64+struct HeaderRule {
65+ pattern: RulePattern,
66+ operations: Vec<HeaderOperation>,
67+}
68+
69+enum HeaderOperation {
70+ Set(String, String),
71+ Remove(String),
72+}
73+
74+struct RedirectRule {
75+ pattern: RulePattern,
76+ destination: String,
77+ status: u16,
78+}
79+
80+impl AssetResolver {
81+ pub async fn load(
82+ client: &Client,
83+ bucket: &str,
84+ prefix: &str,
85+ reference: &AssetManifestRef,
86+ asset_only: bool,
87+ ) -> anyhow::Result<Self> {
88+ if reference.index != "assets.json" {
89+ return Err(anyhow!("unsupported asset index name: {}", reference.index));
90+ }
91+ let key = format!("{prefix}/{}", reference.index);
92+ let object = client
93+ .get_object()
94+ .bucket(bucket)
95+ .key(&key)
96+ .send()
97+ .await
98+ .with_context(|| format!("read s3://{bucket}/{key}"))?;
99+ let bytes = object
100+ .body
101+ .collect()
102+ .await
103+ .context("read asset index body")?
104+ .into_bytes();
105+ let sha256 = format!("{:x}", Sha256::digest(&bytes));
106+ if sha256 != reference.sha256 {
107+ return Err(anyhow!("asset index checksum mismatch"));
108+ }
109+ let index: AssetIndex = serde_json::from_slice(&bytes).context("decode asset index")?;
110+ validate_index(&index, reference)?;
111+ let header_rules = parse_header_rules(index.config.headers.as_deref().unwrap_or(""))?;
112+ let redirect_rules = parse_redirect_rules(index.config.redirects.as_deref().unwrap_or(""))?;
113+ let cache_root = std::env::var_os("CELLD_ASSET_CACHE_DIR")
114+ .map(PathBuf::from)
115+ .unwrap_or_else(|| std::env::temp_dir().join("celld").join("asset-cache"));
116+ std::fs::create_dir_all(&cache_root)
117+ .with_context(|| format!("create asset cache directory {}", cache_root.display()))?;
118+ let cache_max_bytes = std::env::var("CELLD_ASSET_CACHE_BYTES")
119+ .ok()
120+ .and_then(|value| value.parse::<u64>().ok())
121+ .unwrap_or(DEFAULT_ASSET_CACHE_BYTES);
122+ Ok(Self {
123+ inner: Arc::new(AssetResolverInner {
124+ client: client.clone(),
125+ bucket: bucket.to_string(),
126+ index,
127+ asset_only,
128+ cache_root,
129+ cache_max_bytes,
130+ download_locks: Mutex::new(HashMap::new()),
131+ cleanup_lock: Mutex::new(()),
132+ header_rules,
133+ redirect_rules,
134+ }),
135+ })
136+ }
137+
138+ pub fn binding_name(&self) -> Option<&str> {
139+ self.inner.index.config.binding.as_deref()
140+ }
141+
142+ pub fn asset_only(&self) -> bool {
143+ self.inner.asset_only
144+ }
145+
146+ pub fn should_run_worker_first(&self, encoded_path: &str) -> bool {
147+ let Some(path) = decode_path(encoded_path) else {
148+ return false;
149+ };
150+ match &self.inner.index.config.run_worker_first {
151+ RunWorkerFirst::Bool(value) => *value,
152+ RunWorkerFirst::Routes(rules) => {
153+ let excluded = rules
154+ .iter()
155+ .filter_map(|rule| rule.strip_prefix('!'))
156+ .any(|rule| route_pattern_matches(rule, &path));
157+ !excluded
158+ && rules
159+ .iter()
160+ .filter(|rule| !rule.starts_with('!'))
161+ .any(|rule| route_pattern_matches(rule, &path))
162+ }
163+ }
164+ }
165+
166+ pub async fn ingress_response(
167+ &self,
168+ encoded_path: &str,
169+ query: Option<&str>,
170+ head: bool,
171+ request_headers: &HeaderMap,
172+ ) -> anyhow::Result<Option<Response>> {
173+ let include_not_found =
174+ self.inner.asset_only || self.navigation_prefers_asset_serving(request_headers);
175+ let host = request_headers
176+ .get("host")
177+ .and_then(|value| value.to_str().ok())
178+ .map(strip_port);
179+ self.response(
180+ encoded_path,
181+ query,
182+ host,
183+ head,
184+ request_headers,
185+ include_not_found,
186+ )
187+ .await
188+ }
189+
190+ async fn response(
191+ &self,
192+ encoded_path: &str,
193+ query: Option<&str>,
194+ host: Option<&str>,
195+ head: bool,
196+ request_headers: &HeaderMap,
197+ include_not_found: bool,
198+ ) -> anyhow::Result<Option<Response>> {
199+ let Some(path) = decode_path(encoded_path) else {
200+ return Ok(None);
201+ };
202+ let mut selected = None;
203+ for rule in &self.inner.redirect_rules {
204+ let Some(captures) = rule.pattern.matches(host, &path) else {
205+ continue;
206+ };
207+ let destination = substitute(&rule.destination, &captures);
208+ if rule.status == 200 {
209+ let boundary = destination.find(['?', '#']).unwrap_or(destination.len());
210+ let destination_path = &destination[..boundary];
211+ if !destination_path.starts_with('/') {
212+ return Err(anyhow!("asset proxy destination must be a local path"));
213+ }
214+ selected = Some(route(&self.inner.index, destination_path, true));
215+ } else {
216+ let status = StatusCode::from_u16(rule.status)
217+ .context("invalid static asset redirect status")?;
218+ return Ok(Some(
219+ Response::builder()
220+ .status(status)
221+ .header("location", destination)
222+ .body(Body::empty())?,
223+ ));
224+ }
225+ break;
226+ }
227+ match selected.unwrap_or_else(|| route(&self.inner.index, &path, include_not_found)) {
228+ Route::Missing => Ok(None),
229+ Route::Redirect {
230+ mut location,
231+ status,
232+ } => {
233+ if let Some(query) = query.filter(|value| !value.is_empty()) {
234+ location.push('?');
235+ location.push_str(query);
236+ }
237+ Ok(Some(
238+ Response::builder()
239+ .status(status)
240+ .header("location", location)
241+ .body(Body::empty())?,
242+ ))
243+ }
244+ Route::Asset {
245+ path: resolved_path,
246+ entry,
247+ status,
248+ } => {
249+ let etag = format!("\"{}\"", entry.sha256);
250+ if request_headers
251+ .get("if-none-match")
252+ .and_then(|value| value.to_str().ok())
253+ .is_some_and(|value| etag_matches(value, &etag))
254+ {
255+ let mut response = Response::builder()
256+ .status(StatusCode::NOT_MODIFIED)
257+ .header("etag", etag)
258+ .body(Body::empty())?;
259+ self.apply_headers(response.headers_mut(), host, &path)?;
260+ return Ok(Some(response));
261+ }
262+ let requested_range = if status == StatusCode::OK {
263+ requested_range(request_headers, entry.bytes, &etag)
264+ } else {
265+ RequestedRange::Full
266+ };
267+ if matches!(requested_range, RequestedRange::Unsatisfiable) {
268+ let mut response = Response::builder()
269+ .status(StatusCode::RANGE_NOT_SATISFIABLE)
270+ .header("content-range", format!("bytes */{}", entry.bytes))
271+ .header("accept-ranges", "bytes")
272+ .header("etag", etag)
273+ .body(Body::empty())?;
274+ self.apply_headers(response.headers_mut(), host, &path)?;
275+ return Ok(Some(response));
276+ }
277+ let (response_status, start, content_length) = match requested_range {
278+ RequestedRange::Partial { start, end } => {
279+ (StatusCode::PARTIAL_CONTENT, start, end - start + 1)
280+ }
281+ RequestedRange::Full | RequestedRange::Unsatisfiable => {
282+ (status, 0, entry.bytes)
283+ }
284+ };
285+ let mut builder = Response::builder()
286+ .status(response_status)
287+ .header("content-length", content_length)
288+ .header("accept-ranges", "bytes")
289+ .header("etag", &etag);
290+ if let RequestedRange::Partial { start, end } = requested_range {
291+ builder = builder.header(
292+ "content-range",
293+ format!("bytes {start}-{end}/{}", entry.bytes),
294+ );
295+ }
296+ if !request_headers.contains_key("authorization")
297+ && !request_headers.contains_key("range")
298+ {
299+ builder = builder.header("cache-control", "public, max-age=0, must-revalidate");
300+ }
301+ if let Some(content_type) = &entry.content_type {
302+ builder = builder.header(
303+ "content-type",
304+ HeaderValue::from_str(content_type)
305+ .context("invalid asset content type")?,
306+ );
307+ }
308+ let body = if head {
309+ Body::empty()
310+ } else {
311+ let mut file = self.open_asset(&resolved_path, &entry).await?;
312+ if start > 0 {
313+ file.seek(std::io::SeekFrom::Start(start))
314+ .await
315+ .context("seek asset cache file")?;
316+ }
317+ let stream = ReaderStream::new(file.take(content_length))
318+ .map(|result| result.map_err(std::io::Error::other));
319+ Body::from_stream(stream)
320+ };
321+ let mut response = builder.body(body)?;
322+ self.apply_headers(response.headers_mut(), host, &path)?;
323+ Ok(Some(response))
324+ }
325+ }
326+ }
327+
328+ pub async fn binding_response(
329+ &self,
330+ url: &str,
331+ method: &str,
332+ headers: &[(String, String)],
333+ ) -> anyhow::Result<js::HttpResponse> {
334+ if !matches!(method, "GET" | "HEAD") {
335+ return Ok(js::HttpResponse {
336+ status: StatusCode::METHOD_NOT_ALLOWED.as_u16(),
337+ body: b"Method not allowed".to_vec(),
338+ stream: None,
339+ headers: vec![("content-type".into(), "text/plain; charset=utf-8".into())],
340+ ws: None,
341+ write_position: None,
342+ });
343+ }
344+ let path = url::Url::parse(url).context("invalid assets binding URL")?;
345+ let encoded_path = path.path().to_string();
346+ let query = path.query().map(str::to_string);
347+ let host = path.host_str().map(str::to_string);
348+ let mut request_headers = HeaderMap::new();
349+ for (name, value) in headers {
350+ let Ok(name) = name.parse::<axum::http::HeaderName>() else {
351+ continue;
352+ };
353+ let Ok(value) = HeaderValue::from_str(value) else {
354+ continue;
355+ };
356+ request_headers.append(name, value);
357+ }
358+ let response = match self
359+ .response(
360+ &encoded_path,
361+ query.as_deref(),
362+ host.as_deref(),
363+ method == "HEAD",
364+ &request_headers,
365+ true,
366+ )
367+ .await?
368+ {
369+ Some(response) => response,
370+ None => Response::builder()
371+ .status(StatusCode::NOT_FOUND)
372+ .header("content-type", "text/plain; charset=utf-8")
373+ .body(Body::from("Not found"))?,
374+ };
375+ let (parts, body) = response.into_parts();
376+ let body = axum::body::to_bytes(body, 25 * 1024 * 1024 + 1)
377+ .await
378+ .context("buffer assets binding response")?
379+ .to_vec();
380+ Ok(js::HttpResponse {
381+ status: parts.status.as_u16(),
382+ body,
383+ stream: None,
384+ headers: parts
385+ .headers
386+ .iter()
387+ .map(|(name, value)| {
388+ (
389+ name.as_str().to_string(),
390+ value.to_str().unwrap_or_default().to_string(),
391+ )
392+ })
393+ .collect(),
394+ ws: None,
395+ write_position: None,
396+ })
397+ }
398+
399+ fn apply_headers(
400+ &self,
401+ headers: &mut HeaderMap,
402+ host: Option<&str>,
403+ path: &str,
404+ ) -> anyhow::Result<()> {
405+ let mut custom = std::collections::HashSet::new();
406+ for rule in &self.inner.header_rules {
407+ let Some(captures) = rule.pattern.matches(host, path) else {
408+ continue;
409+ };
410+ for operation in &rule.operations {
411+ match operation {
412+ HeaderOperation::Remove(name) => {
413+ headers.remove(name);
414+ custom.insert(name.clone());
415+ }
416+ HeaderOperation::Set(name, value) => {
417+ let value = substitute(value, &captures);
418+ if custom.insert(name.clone()) {
419+ headers.remove(name);
420+ }
421+ let combined = match headers.get(name).and_then(|value| value.to_str().ok())
422+ {
423+ Some(previous) => format!("{previous}, {value}"),
424+ None => value,
425+ };
426+ headers.insert(
427+ name.parse::<axum::http::HeaderName>()
428+ .context("invalid custom asset header name")?,
429+ HeaderValue::from_str(&combined)
430+ .context("invalid custom asset header value")?,
431+ );
432+ }
433+ }
434+ }
435+ }
436+ Ok(())
437+ }
438+
439+ fn navigation_prefers_asset_serving(&self, headers: &HeaderMap) -> bool {
440+ if headers
441+ .get("sec-fetch-mode")
442+ .and_then(|value| value.to_str().ok())
443+ != Some("navigate")
444+ {
445+ return false;
446+ }
447+ let config = &self.inner.index.config;
448+ if config
449+ .compatibility_flags
450+ .iter()
451+ .any(|flag| flag == "assets_navigation_has_no_effect")
452+ {
453+ return false;
454+ }
455+ config
456+ .compatibility_flags
457+ .iter()
458+ .any(|flag| flag == "assets_navigation_prefers_asset_serving")
459+ || config
460+ .compatibility_date
461+ .as_deref()
462+ .is_some_and(|date| date >= "2025-04-01")
463+ }
464+
465+ async fn open_asset(
466+ &self,
467+ resolved_path: &str,
468+ entry: &AssetEntry,
469+ ) -> anyhow::Result<tokio::fs::File> {
470+ let cache_path = cache_path(&self.inner.cache_root, &entry.sha256)?;
471+ if let Some(file) = valid_cached_file(&cache_path, entry.bytes).await? {
472+ touch_cache_file(cache_path.clone());
473+ return Ok(file);
474+ }
475+
476+ let lock = {
477+ let mut locks = self.inner.download_locks.lock().await;
478+ locks
479+ .entry(entry.sha256.clone())
480+ .or_insert_with(|| Arc::new(Mutex::new(())))
481+ .clone()
482+ };
483+ let _guard = lock.lock().await;
484+ if let Some(file) = valid_cached_file(&cache_path, entry.bytes).await? {
485+ touch_cache_file(cache_path.clone());
486+ return Ok(file);
487+ }
488+
489+ let parent = cache_path
490+ .parent()
491+ .context("asset cache path has no parent")?;
492+ tokio::fs::create_dir_all(parent)
493+ .await
494+ .with_context(|| format!("create asset cache shard {}", parent.display()))?;
495+ let mut random = rand::rngs::OsRng;
496+ let temporary = parent.join(format!(".{}.{}.tmp", std::process::id(), random.next_u64()));
497+ let key = asset_blob_key(&entry.sha256)
498+ .ok_or_else(|| anyhow!("invalid asset digest for {resolved_path}"))?;
499+ let object = self
500+ .inner
501+ .client
502+ .get_object()
503+ .bucket(&self.inner.bucket)
504+ .key(&key)
505+ .send()
506+ .await
507+ .with_context(|| {
508+ format!(
509+ "read asset {resolved_path} from s3://{}/{key}",
510+ self.inner.bucket
511+ )
512+ })?;
513+ if object.content_length().unwrap_or(-1) != entry.bytes as i64 {
514+ return Err(anyhow!("asset {resolved_path} has the wrong bucket size"));
515+ }
516+ let mut file = tokio::fs::OpenOptions::new()
517+ .create_new(true)
518+ .write(true)
519+ .open(&temporary)
520+ .await
521+ .with_context(|| format!("create asset cache file {}", temporary.display()))?;
522+ let mut body = object.body;
523+ let mut hasher = Sha256::new();
524+ let mut bytes = 0_u64;
525+ let download = async {
526+ while let Some(chunk) = body.next().await {
527+ let chunk = chunk.with_context(|| format!("read asset body {resolved_path}"))?;
528+ bytes = bytes
529+ .checked_add(chunk.len() as u64)
530+ .context("asset body size overflow")?;
531+ if bytes > entry.bytes {
532+ return Err(anyhow!("asset {resolved_path} exceeds its declared size"));
533+ }
534+ hasher.update(&chunk);
535+ file.write_all(&chunk).await?;
536+ }
537+ file.sync_all().await?;
538+ anyhow::Ok(())
539+ }
540+ .await;
541+ if let Err(error) = download {
542+ drop(file);
543+ let _ = tokio::fs::remove_file(&temporary).await;
544+ return Err(error);
545+ }
546+ drop(file);
547+ let actual = format!("{:x}", hasher.finalize());
548+ if bytes != entry.bytes || actual != entry.sha256 {
549+ let _ = tokio::fs::remove_file(&temporary).await;
550+ return Err(anyhow!(
551+ "asset {resolved_path} checksum mismatch: expected {}, got {actual}",
552+ entry.sha256
553+ ));
554+ }
555+ if valid_cached_file(&cache_path, entry.bytes).await?.is_some() {
556+ let _ = tokio::fs::remove_file(&temporary).await;
557+ } else {
558+ tokio::fs::rename(&temporary, &cache_path)
559+ .await
560+ .with_context(|| {
561+ format!(
562+ "publish asset cache file {} -> {}",
563+ temporary.display(),
564+ cache_path.display()
565+ )
566+ })?;
567+ }
568+ let file = tokio::fs::File::open(&cache_path)
569+ .await
570+ .with_context(|| format!("open asset cache file {}", cache_path.display()))?;
571+ touch_cache_file(cache_path);
572+ let resolver = self.clone();
573+ tokio::spawn(async move {
574+ if let Err(error) = resolver.cleanup_cache().await {
575+ tracing::warn!(
576+ event = "asset_cache_cleanup_failed",
577+ %error,
578+ "could not enforce the local asset cache bound"
579+ );
580+ }
581+ });
582+ Ok(file)
583+ }
584+
585+ async fn cleanup_cache(&self) -> anyhow::Result<()> {
586+ let _guard = self.inner.cleanup_lock.lock().await;
587+ let root = self.inner.cache_root.clone();
588+ let limit = self.inner.cache_max_bytes;
589+ tokio::task::spawn_blocking(move || cleanup_cache_files(&root, limit))
590+ .await
591+ .context("join asset cache cleanup")?
592+ }
593+}
594+
595+impl RulePattern {
596+ fn parse(value: &str, allow_absolute: bool) -> anyhow::Result<Self> {
597+ let (host, path) = if value.starts_with("https://") {
598+ if !allow_absolute {
599+ return Err(anyhow!(
600+ "absolute URLs are not supported in _redirects sources"
601+ ));
602+ }
603+ let url = url::Url::parse(value).context("invalid absolute asset rule URL")?;
604+ if url.scheme() != "https" || url.port().is_some() || url.query().is_some() {
605+ return Err(anyhow!(
606+ "absolute asset rules require an HTTPS host without a port"
607+ ));
608+ }
609+ (
610+ Some(compile_rule_component(
611+ url.host_str().context("asset rule URL has no host")?,
612+ '.',
613+ )?),
614+ url.path().to_string(),
615+ )
616+ } else {
617+ if !value.starts_with('/') {
618+ return Err(anyhow!("asset rule paths must begin with '/'"));
619+ }
620+ (None, value.to_string())
621+ };
622+ Ok(Self {
623+ host,
624+ path: compile_rule_component(&path, '/')?,
625+ })
626+ }
627+
628+ fn matches(&self, host: Option<&str>, path: &str) -> Option<HashMap<String, String>> {
629+ let mut values = HashMap::new();
630+ if let Some(pattern) = &self.host {
631+ let captures = pattern.captures(host?)?;
632+ collect_captures(pattern, &captures, &mut values);
633+ }
634+ let captures = self.path.captures(path)?;
635+ collect_captures(&self.path, &captures, &mut values);
636+ Some(values)
637+ }
638+}
639+
640+fn compile_rule_component(value: &str, delimiter: char) -> anyhow::Result<regex::Regex> {
641+ let mut expression = String::from("^");
642+ let mut characters = value.chars().peekable();
643+ let mut captures = std::collections::HashSet::new();
644+ while let Some(character) = characters.next() {
645+ if character == '*' {
646+ if !captures.insert("splat".to_string()) {
647+ return Err(anyhow!("asset rules may contain only one splat"));
648+ }
649+ expression.push_str("(?P<splat>.*)");
650+ continue;
651+ }
652+ if character == ':'
653+ && characters
654+ .peek()
655+ .is_some_and(|next| next.is_ascii_alphabetic())
656+ {
657+ let mut name = String::new();
658+ while characters
659+ .peek()
660+ .is_some_and(|next| next.is_ascii_alphanumeric() || *next == '_')
661+ {
662+ name.push(characters.next().unwrap());
663+ }
664+ if !captures.insert(name.clone()) {
665+ return Err(anyhow!("asset rule placeholder {name:?} is duplicated"));
666+ }
667+ expression.push_str(&format!(
668+ "(?P<{name}>[^{delimiter}]+)",
669+ delimiter = regex::escape(&delimiter.to_string())
670+ ));
671+ continue;
672+ }
673+ expression.push_str(&regex::escape(&character.to_string()));
674+ }
675+ expression.push('$');
676+ regex::Regex::new(&expression).context("compile asset routing rule")
677+}
678+
679+fn collect_captures(
680+ pattern: &regex::Regex,
681+ captures: &regex::Captures<'_>,
682+ values: &mut HashMap<String, String>,
683+) {
684+ for name in pattern.capture_names().flatten() {
685+ if let Some(value) = captures.name(name) {
686+ values.insert(name.to_string(), value.as_str().to_string());
687+ }
688+ }
689+}
690+
691+fn substitute(template: &str, captures: &HashMap<String, String>) -> String {
692+ let mut result = String::with_capacity(template.len());
693+ let mut characters = template.chars().peekable();
694+ while let Some(character) = characters.next() {
695+ if character != ':'
696+ || !characters
697+ .peek()
698+ .is_some_and(|next| next.is_ascii_alphabetic())
699+ {
700+ result.push(character);
701+ continue;
702+ }
703+ let mut name = String::new();
704+ while characters
705+ .peek()
706+ .is_some_and(|next| next.is_ascii_alphanumeric() || *next == '_')
707+ {
708+ name.push(characters.next().unwrap());
709+ }
710+ if let Some(value) = captures.get(&name) {
711+ result.push_str(value);
712+ } else {
713+ result.push(':');
714+ result.push_str(&name);
715+ }
716+ }
717+ result
718+}
719+
720+fn parse_header_rules(value: &str) -> anyhow::Result<Vec<HeaderRule>> {
721+ let mut rules: Vec<HeaderRule> = Vec::new();
722+ let mut current: Option<usize> = None;
723+ for (line_number, line) in value.lines().enumerate() {
724+ if line.len() > 2_000 {
725+ return Err(anyhow!(
726+ "_headers line {} exceeds 2,000 characters",
727+ line_number + 1
728+ ));
729+ }
730+ let trimmed = line.trim();
731+ if trimmed.is_empty() || trimmed.starts_with('#') {
732+ continue;
733+ }
734+ if line.starts_with(char::is_whitespace) {
735+ let index = current.context("_headers contains an operation before its URL pattern")?;
736+ if let Some(name) = trimmed.strip_prefix("! ") {
737+ let name = parse_custom_header_name(name)?;
738+ rules[index].operations.push(HeaderOperation::Remove(name));
739+ } else {
740+ let (name, value) = trimmed
741+ .split_once(':')
742+ .context("_headers operation is missing ':'")?;
743+ let name = parse_custom_header_name(name)?;
744+ HeaderValue::from_str(value.trim()).context("invalid _headers value")?;
745+ rules[index]
746+ .operations
747+ .push(HeaderOperation::Set(name, value.trim().to_string()));
748+ }
749+ continue;
750+ }
751+ if rules.len() >= 100 {
752+ return Err(anyhow!("_headers exceeds 100 rules"));
753+ }
754+ rules.push(HeaderRule {
755+ pattern: RulePattern::parse(trimmed, true)
756+ .with_context(|| format!("invalid _headers rule on line {}", line_number + 1))?,
757+ operations: Vec::new(),
758+ });
759+ current = Some(rules.len() - 1);
760+ }
761+ Ok(rules)
762+}
763+
764+fn parse_custom_header_name(value: &str) -> anyhow::Result<String> {
765+ let name = value
766+ .trim()
767+ .parse::<axum::http::HeaderName>()
768+ .context("invalid _headers name")?
769+ .as_str()
770+ .to_string();
771+ if matches!(
772+ name.as_str(),
773+ "connection" | "content-length" | "transfer-encoding"
774+ ) {
775+ return Err(anyhow!("_headers cannot override {name}"));
776+ }
777+ Ok(name)
778+}
779+
780+fn parse_redirect_rules(value: &str) -> anyhow::Result<Vec<RedirectRule>> {
781+ let mut rules = Vec::new();
782+ let mut static_rules = 0_usize;
783+ let mut dynamic_rules = 0_usize;
784+ for (line_number, line) in value.lines().enumerate() {
785+ let line = line.trim();
786+ if line.is_empty() || line.starts_with('#') {
787+ continue;
788+ }
789+ if line.len() > 1_000 {
790+ return Err(anyhow!(
791+ "_redirects line {} exceeds 1,000 characters",
792+ line_number + 1
793+ ));
794+ }
795+ let parts = line.split_whitespace().collect::<Vec<_>>();
796+ if !(2..=3).contains(&parts.len()) {
797+ return Err(anyhow!(
798+ "invalid _redirects rule on line {}",
799+ line_number + 1
800+ ));
801+ }
802+ let status = match parts.get(2) {
803+ Some(value) => value.parse::<u16>().context("invalid _redirects status")?,
804+ None => 302,
805+ };
806+ if !matches!(status, 200 | 301 | 302 | 303 | 307 | 308) {
807+ return Err(anyhow!("unsupported _redirects status {status}"));
808+ }
809+ if status == 200 && !parts[1].starts_with('/') {
810+ return Err(anyhow!("_redirects proxy destinations must be local paths"));
811+ }
812+ if status != 200
813+ && !parts[1].starts_with('/')
814+ && url::Url::parse(parts[1])
815+ .ok()
816+ .is_none_or(|url| !matches!(url.scheme(), "http" | "https"))
817+ {
818+ return Err(anyhow!("invalid _redirects destination"));
819+ }
820+ let dynamic = parts[0].contains('*') || parts[0].contains(':');
821+ if dynamic {
822+ dynamic_rules += 1;
823+ } else {
824+ static_rules += 1;
825+ }
826+ if static_rules > 2_000 || dynamic_rules > 100 || rules.len() >= 2_100 {
827+ return Err(anyhow!("_redirects exceeds Cloudflare's rule limits"));
828+ }
829+ rules.push(RedirectRule {
830+ pattern: RulePattern::parse(parts[0], false).with_context(|| {
831+ format!("invalid _redirects source on line {}", line_number + 1)
832+ })?,
833+ destination: parts[1].to_string(),
834+ status,
835+ });
836+ }
837+ Ok(rules)
838+}
839+
840+fn strip_port(host: &str) -> &str {
841+ if host.starts_with('[') {
842+ return host.find(']').map_or(host, |end| &host[1..end]);
843+ }
844+ host.rsplit_once(':')
845+ .filter(|(_, port)| port.bytes().all(|byte| byte.is_ascii_digit()))
846+ .map_or(host, |(host, _)| host)
847+}
848+
849+fn route(index: &AssetIndex, path: &str, include_not_found: bool) -> Route {
850+ let entries = &index.entries;
851+ let html = index
852+ .config
853+ .html_handling
854+ .as_deref()
855+ .unwrap_or("auto-trailing-slash");
856+
857+ // Non-HTML assets are never affected by trailing-slash canonicalization.
858+ if !path.ends_with(".html") {
859+ if let Some(entry) = entries.get(path) {
860+ return asset_route(path, entry, StatusCode::OK);
861+ }
862+ }
863+
864+ if html != "none" {
865+ if let Some((asset_path, entry)) = html_asset(entries, path) {
866+ let canonical = canonical_html_path(&asset_path, html);
867+ if path != canonical {
868+ return Route::Redirect {
869+ location: canonical,
870+ status: StatusCode::TEMPORARY_REDIRECT,
871+ };
872+ }
873+ return asset_route(&asset_path, entry, StatusCode::OK);
874+ }
875+ } else if let Some(entry) = entries.get(path) {
876+ return asset_route(path, entry, StatusCode::OK);
877+ }
878+
879+ if !include_not_found {
880+ return Route::Missing;
881+ }
882+ match index.config.not_found_handling.as_deref() {
883+ Some("single-page-application") => entries
884+ .get("/index.html")
885+ .map(|entry| asset_route("/index.html", entry, StatusCode::OK))
886+ .unwrap_or(Route::Missing),
887+ Some("404-page") => nearest_404(entries, path)
888+ .map(|(path, entry)| asset_route(&path, entry, StatusCode::NOT_FOUND))
889+ .unwrap_or(Route::Missing),
890+ _ => Route::Missing,
891+ }
892+}
893+
894+fn asset_route(path: &str, entry: &AssetEntry, status: StatusCode) -> Route {
895+ Route::Asset {
896+ path: path.to_string(),
897+ entry: entry.clone(),
898+ status,
899+ }
900+}
901+
902+fn html_asset<'a>(
903+ entries: &'a std::collections::BTreeMap<String, AssetEntry>,
904+ path: &str,
905+) -> Option<(String, &'a AssetEntry)> {
906+ let mut candidates = Vec::with_capacity(3);
907+ if path.ends_with(".html") {
908+ candidates.push(path.to_string());
909+ } else if path.ends_with("/index") {
910+ candidates.push(format!("{path}.html"));
911+ } else if path.ends_with('/') {
912+ candidates.push(format!("{path}index.html"));
913+ if path != "/" {
914+ candidates.push(format!("{}.html", path.trim_end_matches('/')));
915+ }
916+ } else {
917+ candidates.push(format!("{path}.html"));
918+ candidates.push(format!("{path}/index.html"));
919+ }
920+ candidates
921+ .into_iter()
922+ .find_map(|candidate| entries.get(&candidate).map(|entry| (candidate, entry)))
923+}
924+
925+fn canonical_html_path(asset_path: &str, html_handling: &str) -> String {
926+ if asset_path == "/index.html" {
927+ return "/".to_string();
928+ }
929+ let base = if let Some(parent) = asset_path.strip_suffix("/index.html") {
930+ parent
931+ } else {
932+ asset_path.strip_suffix(".html").unwrap_or(asset_path)
933+ };
934+ match html_handling {
935+ "force-trailing-slash" => format!("{}/", base.trim_end_matches('/')),
936+ "drop-trailing-slash" => {
937+ let value = base.trim_end_matches('/');
938+ if value.is_empty() {
939+ "/".to_string()
940+ } else {
941+ value.to_string()
942+ }
943+ }
944+ _ if asset_path.ends_with("/index.html") => format!("{}/", base.trim_end_matches('/')),
945+ _ => base.trim_end_matches('/').to_string(),
946+ }
947+}
948+
949+fn nearest_404<'a>(
950+ entries: &'a std::collections::BTreeMap<String, AssetEntry>,
951+ path: &str,
952+) -> Option<(String, &'a AssetEntry)> {
953+ let mut directory = if path.ends_with('/') {
954+ path.trim_end_matches('/').to_string()
955+ } else {
956+ path.rsplit_once('/')
957+ .map(|(parent, _)| parent.to_string())
958+ .unwrap_or_default()
959+ };
960+ loop {
961+ let candidate = if directory.is_empty() {
962+ "/404.html".to_string()
963+ } else {
964+ format!("{directory}/404.html")
965+ };
966+ if let Some(entry) = entries.get(&candidate) {
967+ return Some((candidate, entry));
968+ }
969+ if directory.is_empty() {
970+ return None;
971+ }
972+ directory = directory
973+ .rsplit_once('/')
974+ .map(|(parent, _)| parent.to_string())
975+ .unwrap_or_default();
976+ }
977+}
978+
979+fn etag_matches(value: &str, etag: &str) -> bool {
980+ value.split(',').any(|candidate| {
981+ let candidate = candidate.trim();
982+ candidate == "*" || candidate == etag || candidate.strip_prefix("W/") == Some(etag)
983+ })
984+}
985+
986+fn requested_range(headers: &HeaderMap, bytes: u64, etag: &str) -> RequestedRange {
987+ let Some(value) = headers.get("range").and_then(|value| value.to_str().ok()) else {
988+ return RequestedRange::Full;
989+ };
990+ if headers
991+ .get("if-range")
992+ .and_then(|value| value.to_str().ok())
993+ .is_some_and(|value| value.trim() != etag)
994+ {
995+ return RequestedRange::Full;
996+ }
997+ let Some(value) = value.strip_prefix("bytes=") else {
998+ return RequestedRange::Unsatisfiable;
999+ };
1000+ if value.contains(',') || bytes == 0 {
1001+ return RequestedRange::Unsatisfiable;
1002+ }
1003+ let Some((start, end)) = value.split_once('-') else {
1004+ return RequestedRange::Unsatisfiable;
1005+ };
1006+ if start.is_empty() {
1007+ let Ok(suffix) = end.parse::<u64>() else {
1008+ return RequestedRange::Unsatisfiable;
1009+ };
1010+ if suffix == 0 {
1011+ return RequestedRange::Unsatisfiable;
1012+ }
1013+ let length = suffix.min(bytes);
1014+ return RequestedRange::Partial {
1015+ start: bytes - length,
1016+ end: bytes - 1,
1017+ };
1018+ }
1019+ let Ok(start) = start.parse::<u64>() else {
1020+ return RequestedRange::Unsatisfiable;
1021+ };
1022+ if start >= bytes {
1023+ return RequestedRange::Unsatisfiable;
1024+ }
1025+ let end = if end.is_empty() {
1026+ bytes - 1
1027+ } else {
1028+ let Ok(end) = end.parse::<u64>() else {
1029+ return RequestedRange::Unsatisfiable;
1030+ };
1031+ end.min(bytes - 1)
1032+ };
1033+ if end < start {
1034+ return RequestedRange::Unsatisfiable;
1035+ }
1036+ RequestedRange::Partial { start, end }
1037+}
1038+
1039+fn cache_path(root: &Path, sha256: &str) -> anyhow::Result<PathBuf> {
1040+ asset_blob_key(sha256)
1041+ .context("invalid asset cache digest")
1042+ .map(|_| root.join(&sha256[..2]).join(sha256))
1043+}
1044+
1045+async fn valid_cached_file(
1046+ path: &Path,
1047+ expected_bytes: u64,
1048+) -> anyhow::Result<Option<tokio::fs::File>> {
1049+ match tokio::fs::File::open(path).await {
1050+ Ok(file) => {
1051+ let metadata = file
1052+ .metadata()
1053+ .await
1054+ .with_context(|| format!("stat asset cache file {}", path.display()))?;
1055+ if metadata.len() == expected_bytes {
1056+ Ok(Some(file))
1057+ } else {
1058+ drop(file);
1059+ let _ = tokio::fs::remove_file(path).await;
1060+ Ok(None)
1061+ }
1062+ }
1063+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1064+ Err(error) => {
1065+ Err(error).with_context(|| format!("open asset cache file {}", path.display()))
1066+ }
1067+ }
1068+}
1069+
1070+fn touch_cache_file(path: PathBuf) {
1071+ tokio::task::spawn_blocking(move || {
1072+ let _ = filetime::set_file_mtime(path, filetime::FileTime::now());
1073+ });
1074+}
1075+
1076+fn cleanup_cache_files(root: &Path, limit: u64) -> anyhow::Result<()> {
1077+ let mut files = Vec::new();
1078+ let mut total = 0_u64;
1079+ for shard in
1080+ std::fs::read_dir(root).with_context(|| format!("scan asset cache {}", root.display()))?
1081+ {
1082+ let shard = shard?;
1083+ if !shard.file_type()?.is_dir() {
1084+ continue;
1085+ }
1086+ for entry in std::fs::read_dir(shard.path())? {
1087+ let entry = entry?;
1088+ let name = entry.file_name();
1089+ let name = name.to_string_lossy();
1090+ if name.len() != 64
1091+ || !name
1092+ .bytes()
1093+ .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1094+ {
1095+ continue;
1096+ }
1097+ let metadata = entry.metadata()?;
1098+ if !metadata.is_file() {
1099+ continue;
1100+ }
1101+ total = total.saturating_add(metadata.len());
1102+ files.push((
1103+ metadata.modified().unwrap_or(std::time::UNIX_EPOCH),
1104+ metadata.len(),
1105+ entry.path(),
1106+ ));
1107+ }
1108+ }
1109+ if total <= limit {
1110+ return Ok(());
1111+ }
1112+ files.sort_by_key(|(modified, _, _)| *modified);
1113+ for (_, bytes, path) in files {
1114+ if total <= limit {
1115+ break;
1116+ }
1117+ if std::fs::remove_file(&path).is_ok() {
1118+ total = total.saturating_sub(bytes);
1119+ }
1120+ }
1121+ Ok(())
1122+}
1123+
1124+fn validate_index(index: &AssetIndex, reference: &AssetManifestRef) -> anyhow::Result<()> {
1125+ if index.schema_version != 1 {
1126+ return Err(anyhow!(
1127+ "unsupported asset index schema: {}",
1128+ index.schema_version
1129+ ));
1130+ }
1131+ if index.entries.len() != reference.file_count as usize {
1132+ return Err(anyhow!("asset index file count mismatch"));
1133+ }
1134+ if index.entries.len() > 20_000 {
1135+ return Err(anyhow!("asset index exceeds the file limit"));
1136+ }
1137+ let config = &index.config;
1138+ if !matches!(
1139+ config
1140+ .html_handling
1141+ .as_deref()
1142+ .unwrap_or("auto-trailing-slash"),
1143+ "auto-trailing-slash" | "force-trailing-slash" | "drop-trailing-slash" | "none"
1144+ ) {
1145+ return Err(anyhow!("unsupported asset HTML handling"));
1146+ }
1147+ if !matches!(
1148+ config.not_found_handling.as_deref().unwrap_or("none"),
1149+ "none" | "single-page-application" | "404-page"
1150+ ) {
1151+ return Err(anyhow!("unsupported asset not-found handling"));
1152+ }
1153+ if let Some(binding) = &config.binding {
1154+ let valid = binding.len() <= 128
1155+ && binding
1156+ .chars()
1157+ .next()
1158+ .is_some_and(|value| value == '_' || value == '$' || value.is_ascii_alphabetic())
1159+ && binding
1160+ .chars()
1161+ .skip(1)
1162+ .all(|value| value == '_' || value == '$' || value.is_ascii_alphanumeric());
1163+ if !valid {
1164+ return Err(anyhow!("invalid asset binding name"));
1165+ }
1166+ }
1167+ if let RunWorkerFirst::Routes(routes) = &config.run_worker_first {
1168+ if routes.is_empty() || routes.len() > 100 {
1169+ return Err(anyhow!("invalid asset worker-first route count"));
1170+ }
1171+ let mut positive = false;
1172+ let mut seen = std::collections::HashSet::new();
1173+ for route in routes {
1174+ if route.starts_with('/') {
1175+ positive = true;
1176+ } else if !route.starts_with("!/") {
1177+ return Err(anyhow!("invalid asset worker-first route: {route:?}"));
1178+ }
1179+ if route.len() > 100 || !seen.insert(route) {
1180+ return Err(anyhow!("invalid asset worker-first route: {route:?}"));
1181+ }
1182+ }
1183+ if !positive {
1184+ return Err(anyhow!("asset worker-first routes require a positive rule"));
1185+ }
1186+ }
1187+ let mut total = 0_u64;
1188+ for (path, entry) in &index.entries {
1189+ if decode_path(path).as_deref() != Some(path.as_str())
1190+ || path == "/"
1191+ || asset_blob_key(&entry.sha256).is_none()
1192+ || entry.bytes > 25 * 1024 * 1024
1193+ {
1194+ return Err(anyhow!("invalid asset index entry: {path:?}"));
1195+ }
1196+ if entry
1197+ .content_type
1198+ .as_deref()
1199+ .is_some_and(|value| value.len() > 200 || value.contains(['\r', '\n']))
1200+ {
1201+ return Err(anyhow!("invalid asset content type: {path:?}"));
1202+ }
1203+ total = total
1204+ .checked_add(entry.bytes)
1205+ .context("asset index byte count overflow")?;
1206+ }
1207+ if total != reference.total_bytes {
1208+ return Err(anyhow!("asset index total byte count mismatch"));
1209+ }
1210+ if total > 1024 * 1024 * 1024 {
1211+ return Err(anyhow!("asset index exceeds the deployment byte limit"));
1212+ }
1213+ Ok(())
1214+}
1215+
1216+fn decode_path(path: &str) -> Option<String> {
1217+ if !path.starts_with('/') || path.contains('\\') || path.contains('\0') {
1218+ return None;
1219+ }
1220+ let decoded = percent_decode_str(path).decode_utf8().ok()?.into_owned();
1221+ if decoded.contains('\\')
1222+ || decoded.contains('\0')
1223+ || decoded.split('/').skip(1).any(|segment| {
1224+ segment.is_empty() && decoded != "/" || segment == "." || segment == ".."
1225+ })
1226+ {
1227+ return None;
1228+ }
1229+ Some(decoded)
1230+}
1231+
1232+fn route_pattern_matches(pattern: &str, path: &str) -> bool {
1233+ let mut expression = String::from("^");
1234+ for part in pattern.split('*') {
1235+ expression.push_str(&regex::escape(part));
1236+ expression.push_str(".*");
1237+ }
1238+ if !pattern.ends_with('*') {
1239+ expression.truncate(expression.len().saturating_sub(2));
1240+ expression.push('$');
1241+ }
1242+ regex::Regex::new(&expression).is_ok_and(|pattern| pattern.is_match(path))
1243+}
addedcrates/celld/asyncrt.rs+100−0View file
@@ -1,0 +1,100 @@
1+//! Host async runtime for the JS thread, using structured concurrency. Ops
2+//! never spawn detached: they ENQUEUE a future, and `js::run_loop` owns a
3+//! per-request tokio `JoinSet` (the "region") that spawns, drives, and — on
4+//! every exit path — aborts whatever is still pending.
5+//! Orphan tasks, leaked bookkeeping, and panic-hangs are impossible by
6+//! construction, not patched. The region is the one asupersync idea we take:
7+//! a task cannot outlive the scope that owns it.
8+use std::cell::RefCell;
9+use std::future::Future;
10+use std::pin::Pin;
11+use std::sync::atomic::{AtomicU64, Ordering};
12+use std::sync::OnceLock;
13+
14+static NEXT_ID: AtomicU64 = AtomicU64::new(1);
15+static HOST_RT: OnceLock<tokio::runtime::Handle> = OnceLock::new();
16+
17+/// What an async op resolves its JS promise with: a string, or raw bytes
18+/// (delivered as a `Uint8Array` — the structured-clone RPC payloads).
19+pub enum OpOut {
20+ Str(String),
21+ Bytes(Vec<u8>),
22+}
23+impl From<String> for OpOut {
24+ fn from(value: String) -> Self {
25+ Self::Str(value)
26+ }
27+}
28+impl From<Vec<u8>> for OpOut {
29+ fn from(value: Vec<u8>) -> Self {
30+ Self::Bytes(value)
31+ }
32+}
33+
34+pub type OpFuture = Pin<Box<dyn Future<Output = Result<OpOut, String>> + Send>>;
35+
36+thread_local! {
37+ // Per-JS-thread current-thread runtime: the Worker and each cell run on
38+ // their own thread, so each needs its own runtime — a shared current-thread
39+ // runtime cannot be driven by two threads at once. Held as `Rc` so a serve
40+ // loop can `block_on` on a clone without keeping the RefCell borrowed (which
41+ // would deadlock op spawns that clone the handle mid-drive).
42+ static RT: RefCell<Option<std::rc::Rc<tokio::runtime::Runtime>>> =
43+ const { RefCell::new(None) };
44+ // Ops push (id, future); run_loop drains and spawns them into its region.
45+ static SPAWNS: RefCell<Vec<(u64, OpFuture)>> = const { RefCell::new(Vec::new()) };
46+}
47+
48+pub fn init() {
49+ RT.with(|r| {
50+ if r.borrow().is_none() {
51+ *r.borrow_mut() = Some(std::rc::Rc::new(
52+ tokio::runtime::Builder::new_current_thread()
53+ .enable_all()
54+ .build()
55+ .unwrap(),
56+ ));
57+ }
58+ });
59+}
60+
61+/// The thread's runtime (an `Rc` clone), for a serve loop that drives both hyper
62+/// and this thread's JS ops on one runtime. `block_on` on the returned clone
63+/// leaves the thread-local RefCell free for `handle()`/op spawns.
64+pub fn runtime() -> std::rc::Rc<tokio::runtime::Runtime> {
65+ RT.with(|r| r.borrow().as_ref().unwrap().clone())
66+}
67+
68+/// Install celld's shared Tokio runtime for host I/O. Futures remain owned by
69+/// each request's JoinSet, but polling network work on the shared runtime lets
70+/// a reqwest response body move into Axum and continue streaming after the JS
71+/// handler has returned.
72+pub fn set_host_handle(handle: tokio::runtime::Handle) {
73+ let _ = HOST_RT.set(handle);
74+}
75+
76+pub fn handle() -> tokio::runtime::Handle {
77+ RT.with(|r| r.borrow().as_ref().unwrap().handle().clone())
78+}
79+pub fn op_handle() -> tokio::runtime::Handle {
80+ HOST_RT.get().cloned().unwrap_or_else(handle)
81+}
82+pub fn block_on<F: Future>(f: F) -> F::Output {
83+ let rt = runtime();
84+ rt.block_on(f)
85+}
86+
87+/// Register an async op's future; returns its promise id. NOT spawned here — the
88+/// region in `run_loop` owns spawning, so a task is never detached.
89+pub fn enqueue<T: Into<OpOut>>(
90+ fut: impl Future<Output = Result<T, String>> + Send + 'static,
91+) -> u64 {
92+ let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
93+ let fut: OpFuture = Box::pin(async move { fut.await.map(Into::into) });
94+ SPAWNS.with(|s| s.borrow_mut().push((id, fut)));
95+ id
96+}
97+
98+pub fn drain_spawns() -> Vec<(u64, OpFuture)> {
99+ SPAWNS.with(|s| s.borrow_mut().drain(..).collect())
100+}
addedcrates/celld/control_plane.rs+2849−0View file
@@ -1,0 +1,2849 @@
1+use crate::protocol::{asset_blob_key, AssetIndex, DeployPointer, Manifest};
2+use anyhow::{anyhow, Context};
3+use aws_sdk_s3::primitives::ByteStream;
4+use aws_sdk_s3::Client as S3Client;
5+use celld_logic::PresenceSnapshot;
6+use futures_util::{SinkExt, StreamExt};
7+use rand::RngCore;
8+use rusqlite::{types::ValueRef, Connection, OpenFlags, OptionalExtension};
9+use serde::{Deserialize, Serialize};
10+use sha2::{Digest, Sha256};
11+use std::fs::File;
12+use std::future::Future;
13+use std::path::{Path, PathBuf};
14+use std::pin::Pin;
15+use std::sync::atomic::{AtomicBool, Ordering};
16+use std::sync::{Arc, Mutex, OnceLock};
17+use std::time::{Duration, Instant};
18+use tracing::{info, warn};
19+
20+const DEFAULT_CONTROL_URL: &str = "https://celld.dev";
21+const DEFAULT_ENVIRONMENT: &str = "prod";
22+const MAX_PRESENCE_CELLS: usize = 50;
23+const MAX_PRESENCE_CELL_ID_BYTES: usize = 200;
24+const MAX_EXPLORER_CELL_PAGE: i32 = 100;
25+const MAX_EXPLORER_TABLES: usize = 100;
26+const MAX_EXPLORER_COLUMNS: usize = 32;
27+const MAX_EXPLORER_ROWS: usize = 25;
28+const MAX_EXPLORER_VALUE_BYTES: usize = 2 * 1024;
29+const MAX_EXPLORER_RESPONSE_BYTES: usize = 96 * 1024;
30+const MAX_MANAGED_MODULES: usize = 64;
31+const MAX_MANAGED_MODULE_BYTES: usize = 25 * 1024 * 1024;
32+
33+fn restart_on_deployment_enabled() -> bool {
34+ !std::env::var("CELLD_CLOUD_RESTART_ON_DEPLOY")
35+ .is_ok_and(|value| value.eq_ignore_ascii_case("off"))
36+}
37+
38+#[cfg(unix)]
39+fn restart_process(trigger: &'static str) -> ! {
40+ use std::os::unix::process::CommandExt;
41+ use std::process::Command;
42+
43+ let executable = match std::env::current_exe() {
44+ Ok(executable) => executable,
45+ Err(error) => {
46+ warn!(
47+ event = "control_plane_restart_exec_failed",
48+ trigger,
49+ %error,
50+ "could not locate celld for process reload; exiting for an external supervisor"
51+ );
52+ std::process::exit(75);
53+ }
54+ };
55+ let signer = match crate::peer_probe::reexec_signer_secret() {
56+ Ok(signer) => signer,
57+ Err(error) => {
58+ warn!(
59+ event = "control_plane_restart_exec_failed",
60+ trigger,
61+ %error,
62+ "could not preserve process probe identity; exiting for an external supervisor"
63+ );
64+ std::process::exit(75);
65+ }
66+ };
67+ let mut command = Command::new(executable);
68+ command
69+ .args(std::env::args_os().skip(1))
70+ .env(crate::peer_probe::REEXEC_SIGNER_ENV, signer);
71+ if let Some(node) = REEXEC_NODE_SESSION_ID.get() {
72+ command.env("CELLD_NODE", node);
73+ }
74+ let error = command.exec();
75+ warn!(
76+ event = "control_plane_restart_exec_failed",
77+ trigger,
78+ %error,
79+ "could not re-exec celld for process reload; exiting for an external supervisor"
80+ );
81+ std::process::exit(75);
82+}
83+
84+#[cfg(not(unix))]
85+fn restart_process(_trigger: &'static str) -> ! {
86+ std::process::exit(75);
87+}
88+
89+fn restart_for_deployment() -> ! {
90+ restart_process("deployment")
91+}
92+
93+static REEXEC_NODE_SESSION_ID: OnceLock<String> = OnceLock::new();
94+
95+pub fn install_reexec_node_session_id(node: &str) -> anyhow::Result<()> {
96+ REEXEC_NODE_SESSION_ID
97+ .set(node.to_string())
98+ .map_err(|_| anyhow!("re-exec node-session identity is already installed"))
99+}
100+
101+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102+pub enum ManagedRuntimeState {
103+ Connected,
104+ ControlPlaneUnavailable,
105+ BucketUnavailable,
106+ CredentialRevoked,
107+}
108+
109+impl ManagedRuntimeState {
110+ fn as_str(self) -> &'static str {
111+ match self {
112+ Self::Connected => "connected",
113+ Self::ControlPlaneUnavailable => "control_plane_unavailable",
114+ Self::BucketUnavailable => "bucket_unavailable",
115+ Self::CredentialRevoked => "credential_revoked",
116+ }
117+ }
118+}
119+
120+static MANAGED_RUNTIME_STATE: OnceLock<Mutex<Option<ManagedRuntimeState>>> = OnceLock::new();
121+
122+pub fn report_managed_runtime_state(state: ManagedRuntimeState) {
123+ let mut current = MANAGED_RUNTIME_STATE
124+ .get_or_init(|| Mutex::new(None))
125+ .lock()
126+ .unwrap();
127+ if *current == Some(state) {
128+ return;
129+ }
130+ *current = Some(state);
131+ drop(current);
132+ let managed_state = state.as_str();
133+ match state {
134+ ManagedRuntimeState::Connected => info!(
135+ event = "managed_runtime_state",
136+ managed_state, "Managed Control Plane connected"
137+ ),
138+ ManagedRuntimeState::ControlPlaneUnavailable => info!(
139+ event = "managed_runtime_state",
140+ managed_state, "Managed Control Plane unavailable; bucket-backed serving continues"
141+ ),
142+ ManagedRuntimeState::BucketUnavailable => warn!(
143+ event = "managed_runtime_state",
144+ managed_state, "fleet bucket unavailable; serving cannot start"
145+ ),
146+ // Name the remedy: this condition can be cleared by a restart or an
147+ // explicit credential refresh.
148+ ManagedRuntimeState::CredentialRevoked => warn!(
149+ event = "managed_runtime_state",
150+ managed_state,
151+ "managed storage credential was rejected; restart celld to fetch a \
152+ fresh one, or run `celld credentials refresh` if a rotation is pending"
153+ ),
154+ }
155+}
156+
157+#[derive(Debug)]
158+struct ManagedControlCredentialRevoked;
159+
160+impl std::fmt::Display for ManagedControlCredentialRevoked {
161+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162+ formatter.write_str(
163+ "Managed Control Plane credential was rejected or revoked.\n\
164+ Restart celld to fetch a fresh credential. If that does not help, \
165+ run `celld credentials refresh`, and `celld diagnose` to check \
166+ bucket access.",
167+ )
168+ }
169+}
170+
171+impl std::error::Error for ManagedControlCredentialRevoked {}
172+
173+#[derive(Clone, Debug, PartialEq, Eq)]
174+struct ConnectOptions {
175+ control_url: String,
176+ environment: String,
177+ force: bool,
178+ byo_storage: Option<ByoStorageConfig>,
179+}
180+
181+#[derive(Clone, Deserialize, Serialize)]
182+struct CloudConfig {
183+ #[serde(default = "installation_schema_version")]
184+ version: u32,
185+ #[serde(alias = "instance_id")]
186+ installation_id: String,
187+ #[serde(alias = "instance_token")]
188+ installation_token: Option<String>,
189+ #[serde(default = "initial_credential_version")]
190+ credential_version: u64,
191+ fleet_id: Option<String>,
192+ environment_id: Option<String>,
193+ control_url: String,
194+ environment: String,
195+ #[serde(default)]
196+ storage: Option<ManagedStorageConfig>,
197+ #[serde(default)]
198+ byo_storage: Option<ByoStorageConfig>,
199+ #[serde(default)]
200+ credential_handoff_id: Option<String>,
201+ #[serde(default)]
202+ previous_credential: Option<PreviousCredential>,
203+ #[serde(default)]
204+ pending_claim: Option<PendingClaim>,
205+}
206+
207+#[derive(Clone, Deserialize, Serialize)]
208+struct PreviousCredential {
209+ installation_token: String,
210+ credential_version: u64,
211+ storage: ManagedStorageConfig,
212+}
213+
214+#[derive(Clone, Deserialize, Serialize)]
215+struct PendingClaim {
216+ verification_uri_complete: String,
217+ expires_at_ms: u64,
218+}
219+
220+#[derive(Clone, Deserialize, Serialize)]
221+pub struct ManagedStorageConfig {
222+ pub bucket: String,
223+ pub endpoint: String,
224+ pub region: String,
225+ pub access_key_id: String,
226+ pub secret_access_key: String,
227+ #[serde(default)]
228+ pub session_token: Option<String>,
229+}
230+
231+#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
232+pub struct ByoStorageConfig {
233+ pub bucket: String,
234+ #[serde(default)]
235+ pub endpoint: Option<String>,
236+ pub region: String,
237+}
238+
239+#[derive(Clone)]
240+pub enum InstallationStorageConfig {
241+ Managed(ManagedStorageConfig),
242+ Byo(ByoStorageConfig),
243+}
244+
245+#[derive(Serialize)]
246+struct CreateClaimRequest<'a> {
247+ instance_id: &'a str,
248+ instance_name: &'a str,
249+ environment: &'a str,
250+ version: &'static str,
251+ platform: String,
252+ storage_origin: &'static str,
253+ #[serde(skip_serializing_if = "Option::is_none")]
254+ bucket: Option<&'a str>,
255+ #[serde(skip_serializing_if = "Option::is_none")]
256+ endpoint: Option<&'a str>,
257+ #[serde(skip_serializing_if = "Option::is_none")]
258+ region: Option<&'a str>,
259+}
260+
261+#[derive(Deserialize)]
262+struct CreateClaimResponse {
263+ device_code: String,
264+ verification_uri_complete: String,
265+ expires_in: u64,
266+ interval: u64,
267+}
268+
269+#[derive(Serialize)]
270+struct PollClaimRequest<'a> {
271+ device_code: &'a str,
272+}
273+
274+#[derive(Deserialize)]
275+struct PollClaimResponse {
276+ status: String,
277+ #[serde(default = "managed_storage_origin")]
278+ storage_origin: String,
279+ credential_handoff_id: Option<String>,
280+ credential_version: Option<u64>,
281+ instance_token: Option<String>,
282+ fleet_id: Option<String>,
283+ environment_id: Option<String>,
284+ bucket: Option<String>,
285+ endpoint: Option<String>,
286+ region: Option<String>,
287+ access_key_id: Option<String>,
288+ secret_access_key: Option<String>,
289+ session_token: Option<String>,
290+ interval: Option<u64>,
291+}
292+
293+#[derive(Deserialize)]
294+struct CredentialRotationResponse {
295+ status: String,
296+ credential_handoff_id: String,
297+ credential_version: u64,
298+ instance_token: String,
299+ bucket: String,
300+ endpoint: String,
301+ region: String,
302+ access_key_id: String,
303+ secret_access_key: String,
304+ session_token: Option<String>,
305+}
306+
307+#[derive(Deserialize)]
308+struct AgentCommandEnvelope {
309+ command: AgentCommand,
310+}
311+
312+#[derive(Deserialize)]
313+struct AgentCommand {
314+ id: String,
315+ #[serde(rename = "type")]
316+ kind: String,
317+ deployment: AgentDeployment,
318+}
319+
320+#[derive(Deserialize)]
321+struct AgentDeployment {
322+ script_name: String,
323+ version: String,
324+ manifest: Manifest,
325+ pointer: DeployPointer,
326+ modules: Vec<AgentModule>,
327+ #[serde(default)]
328+ assets: Option<AgentAssets>,
329+}
330+
331+#[derive(Deserialize)]
332+struct AgentModule {
333+ name: String,
334+ sha256: String,
335+ download_url: String,
336+}
337+
338+#[derive(Deserialize)]
339+struct AgentAssets {
340+ index_download_url: String,
341+ blob_download_base_url: String,
342+ sha256: String,
343+ file_count: u32,
344+ total_bytes: u64,
345+}
346+
347+#[derive(Serialize)]
348+struct CompleteCommandRequest<'a> {
349+ success: bool,
350+ error: Option<&'a str>,
351+}
352+
353+struct AppliedDeployment {
354+ id: String,
355+ script_name: String,
356+}
357+
358+pub async fn handle_connect_command(
359+ arguments: impl IntoIterator<Item = String>,
360+) -> anyhow::Result<()> {
361+ let mut options = options_from_env()?;
362+ let mut args = arguments.into_iter();
363+ while let Some(argument) = args.next() {
364+ match argument.as_str() {
365+ "--env" => {
366+ options.environment = args.next().context("--env requires a value")?;
367+ }
368+ "--control-url" => {
369+ options.control_url = args.next().context("--control-url requires a value")?;
370+ }
371+ "--force" => options.force = true,
372+ "--help" | "-h" => {
373+ if let Some(argument) = args.next() {
374+ return Err(anyhow!(
375+ "unexpected argument after connect --help: {argument}"
376+ ));
377+ }
378+ print_connect_help();
379+ return Ok(());
380+ }
381+ _ => return Err(anyhow!("unknown connect option: {argument}")),
382+ }
383+ }
384+ validate_environment(&options.environment)?;
385+ connect(options, true).await
386+}
387+
388+/// `celld token` — print the fleet's deploy token and the exact commands to
389+/// use it.
390+///
391+/// Wrangler expects deployment credentials in environment variables, so this
392+/// command exposes the connected fleet's short-lived token in a shell-friendly
393+/// form.
394+pub async fn handle_token_command(
395+ arguments: impl IntoIterator<Item = String>,
396+) -> anyhow::Result<()> {
397+ let arguments = arguments.into_iter().collect::<Vec<_>>();
398+ if matches!(arguments.as_slice(), [a] if a == "--help" || a == "-h") {
399+ println!(
400+ "Print this fleet's deploy token, and how to deploy with it.\n\n\
401+ USAGE:\n celld token [--format shell]\n\n\
402+ OPTIONS:\n --format shell Print only shell exports, suitable for `eval`.\n"
403+ );
404+ return Ok(());
405+ }
406+ let shell_only = match arguments.as_slice() {
407+ [] => false,
408+ [format, value] if format == "--format" && value == "shell" => true,
409+ _ => {
410+ return Err(anyhow!(
411+ "expected `celld token` or `celld token --format shell`; \
412+ run `celld token --help` for usage"
413+ ))
414+ }
415+ };
416+ let path = config_path()?;
417+ let contents = std::fs::read_to_string(&path).with_context(|| {
418+ format!(
419+ "read {}. This celld installation is not enrolled yet — run `celld` \
420+ and approve the link it prints.",
421+ path.display()
422+ )
423+ })?;
424+ let config: CloudConfig =
425+ serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?;
426+ let token = config.installation_token.as_deref().context(
427+ "this celld installation is not enrolled in the Managed Control Plane — \
428+ run `celld` and approve the link it prints",
429+ )?;
430+ let client = reqwest::Client::new();
431+ let response = client
432+ .post(format!("{}/api/agent/deploy-token", config.control_url))
433+ .bearer_auth(token)
434+ .send()
435+ .await
436+ .context("request a deploy token")?;
437+ if !response.status().is_success() {
438+ let status = response.status();
439+ let body = response.text().await.unwrap_or_default();
440+ return Err(anyhow!(
441+ "could not get a deploy token ({status}): {body}\n\
442+ If this installation was disconnected, run `celld` to re-enrol."
443+ ));
444+ }
445+ #[derive(serde::Deserialize)]
446+ struct DeployTokenResponse {
447+ token: String,
448+ account_id: String,
449+ api_base_url: String,
450+ }
451+ let issued: DeployTokenResponse = response.json().await.context("decode deploy token")?;
452+ print!(
453+ "{}",
454+ render_deploy_token(
455+ &issued.token,
456+ &issued.account_id,
457+ &issued.api_base_url,
458+ shell_only,
459+ )
460+ );
461+ Ok(())
462+}
463+
464+fn render_deploy_token(
465+ token: &str,
466+ account_id: &str,
467+ api_base_url: &str,
468+ shell_only: bool,
469+) -> String {
470+ let exports = format!(
471+ "export CLOUDFLARE_API_TOKEN={}\n\
472+ export CLOUDFLARE_ACCOUNT_ID={}\n\
473+ export CLOUDFLARE_API_BASE_URL={}\n",
474+ shell_quote(token),
475+ shell_quote(account_id),
476+ shell_quote(api_base_url),
477+ );
478+ if shell_only {
479+ return exports;
480+ }
481+ // Say what to do next, not merely what happened.
482+ format!(
483+ "Deploy token for this fleet:\n\n {token}\n\n\
484+ Deploy your app with:\n\n{exports}npx wrangler@4 deploy\n"
485+ )
486+}
487+
488+fn shell_quote(value: &str) -> String {
489+ format!("'{}'", value.replace('\'', "'\"'\"'"))
490+}
491+
492+pub async fn handle_credentials_command(
493+ arguments: impl IntoIterator<Item = String>,
494+) -> anyhow::Result<()> {
495+ let arguments = arguments.into_iter().collect::<Vec<_>>();
496+ if matches!(arguments.as_slice(), [argument] if argument == "--help" || argument == "-h") {
497+ print_credentials_help();
498+ return Ok(());
499+ }
500+ if !matches!(arguments.as_slice(), [command] if command == "refresh") {
501+ return Err(anyhow!(
502+ "expected `celld credentials refresh`; run `celld credentials --help` for usage"
503+ ));
504+ }
505+ refresh_credentials().await
506+}
507+
508+pub async fn handle_disconnect_command(
509+ arguments: impl IntoIterator<Item = String>,
510+) -> anyhow::Result<()> {
511+ let arguments = arguments.into_iter().collect::<Vec<_>>();
512+ if matches!(arguments.as_slice(), [argument] if argument == "--help" || argument == "-h") {
513+ print_disconnect_help();
514+ return Ok(());
515+ }
516+ if !matches!(arguments.as_slice(), [confirmation] if confirmation == "--yes") {
517+ return Err(anyhow!(
518+ "disconnect revokes every process sharing this installation; rerun `celld disconnect --yes` to confirm"
519+ ));
520+ }
521+ let path = config_path()?;
522+ let client = reqwest::Client::builder()
523+ .timeout(Duration::from_secs(15))
524+ .build()?;
525+ let archive = disconnect_at_path(path, &client).await?;
526+ println!(
527+ "Disconnected this installation from the Managed Control Plane.\nArchived its revoked local record at {}.",
528+ archive.display()
529+ );
530+ Ok(())
531+}
532+
533+async fn disconnect_at_path(path: PathBuf, client: &reqwest::Client) -> anyhow::Result<PathBuf> {
534+ let _lock = acquire_enrollment_lock(&path).await?;
535+ let contents =
536+ std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
537+ let config: CloudConfig =
538+ serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?;
539+ let token = config
540+ .installation_token
541+ .as_deref()
542+ .context("this celld installation is not enrolled in the Managed Control Plane")?;
543+ let response = client
544+ .post(format!(
545+ "{}/api/agent/credentials/revoke",
546+ config.control_url
547+ ))
548+ .bearer_auth(token)
549+ .json(&serde_json::json!({ "installation_id": config.installation_id }))
550+ .send()
551+ .await
552+ .context("revoke managed installation")?;
553+ if !response.status().is_success() {
554+ return Err(anyhow!(
555+ "managed installation revocation returned {}",
556+ response.status()
557+ ));
558+ }
559+
560+ // Keep a recoverable, permission-preserving record rather than deleting
561+ // secrets in place. The provider credential is already revoked, and bare
562+ // `celld` will create a fresh installation record on its next start.
563+ let file_name = path
564+ .file_name()
565+ .and_then(|value| value.to_str())
566+ .context("managed installation path has no UTF-8 file name")?;
567+ let archive = path.with_file_name(format!("{file_name}.disconnected-{}", current_time_ms()));
568+ std::fs::rename(&path, &archive).with_context(|| {
569+ format!(
570+ "archive revoked installation record as {}",
571+ archive.display()
572+ )
573+ })?;
574+ Ok(archive)
575+}
576+
577+async fn refresh_credentials() -> anyhow::Result<()> {
578+ let path = config_path()?;
579+ let client = reqwest::Client::builder()
580+ .timeout(Duration::from_secs(15))
581+ .build()?;
582+ refresh_credentials_at_path(path, &client).await
583+}
584+
585+async fn refresh_credentials_at_path(
586+ path: PathBuf,
587+ client: &reqwest::Client,
588+) -> anyhow::Result<()> {
589+ let _lock = acquire_enrollment_lock(&path).await?;
590+ let contents =
591+ std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
592+ let mut config: CloudConfig =
593+ serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?;
594+ let token = config
595+ .installation_token
596+ .as_deref()
597+ .context("this celld installation is not enrolled in the Managed Control Plane")?;
598+ let current_storage = config
599+ .storage
600+ .as_ref()
601+ .context("managed installation record has no storage credentials")?;
602+
603+ if let Some(handoff_id) = config.credential_handoff_id.clone() {
604+ acknowledge_credential_handoff(client, &config, &handoff_id)
605+ .await
606+ .context("finish previously saved credential refresh")?;
607+ config.credential_handoff_id = None;
608+ config.previous_credential = None;
609+ save_config(&path, &config)?;
610+ println!(
611+ "Managed credential refresh completed (version {}).",
612+ config.credential_version
613+ );
614+ return Ok(());
615+ }
616+
617+ let response = client
618+ .post(format!("{}/api/agent/credentials/next", config.control_url))
619+ .bearer_auth(token)
620+ .json(&serde_json::json!({}))
621+ .send()
622+ .await
623+ .context("request staged managed credential")?;
624+ if response.status() == reqwest::StatusCode::NO_CONTENT {
625+ println!("No managed credential rotation is pending.");
626+ return Ok(());
627+ }
628+ if response.status() == reqwest::StatusCode::UNAUTHORIZED {
629+ return Err(anyhow!(
630+ "this installation credential is revoked; enroll a new installation"
631+ ));
632+ }
633+ if !response.status().is_success() {
634+ return Err(anyhow!(
635+ "credential refresh endpoint returned {}",
636+ response.status()
637+ ));
638+ }
639+ let replacement: CredentialRotationResponse = response
640+ .json()
641+ .await
642+ .context("decode staged managed credential")?;
643+ validate_credential_rotation(&replacement, &config, current_storage)?;
644+
645+ config.previous_credential = Some(PreviousCredential {
646+ installation_token: token.to_string(),
647+ credential_version: config.credential_version,
648+ storage: current_storage.clone(),
649+ });
650+ config.installation_token = Some(replacement.instance_token);
651+ config.credential_version = replacement.credential_version;
652+ config.storage = Some(ManagedStorageConfig {
653+ bucket: replacement.bucket,
654+ endpoint: replacement.endpoint,
655+ region: replacement.region,
656+ access_key_id: replacement.access_key_id,
657+ secret_access_key: replacement.secret_access_key,
658+ session_token: replacement.session_token,
659+ });
660+ config.credential_handoff_id = Some(replacement.credential_handoff_id.clone());
661+
662+ // The replacement is persisted before acknowledgement. If this process is
663+ // killed after the rename, the marker makes the acknowledgement retryable.
664+ // The managed control plane keeps both token hashes valid until this
665+ // acknowledgement succeeds.
666+ save_config(&path, &config)?;
667+ acknowledge_credential_handoff(client, &config, &replacement.credential_handoff_id)
668+ .await
669+ .context(
670+ "replacement credential is saved, but acknowledgement is pending; rerun `celld credentials refresh`",
671+ )?;
672+ config.credential_handoff_id = None;
673+ config.previous_credential = None;
674+ save_config(&path, &config)?;
675+ println!(
676+ "Managed credential refresh completed (version {}).",
677+ config.credential_version
678+ );
679+ Ok(())
680+}
681+
682+fn validate_credential_rotation(
683+ replacement: &CredentialRotationResponse,
684+ config: &CloudConfig,
685+ current: &ManagedStorageConfig,
686+) -> anyhow::Result<()> {
687+ if replacement.status != "rotation_pending" {
688+ return Err(anyhow!(
689+ "unexpected credential refresh status: {}",
690+ replacement.status
691+ ));
692+ }
693+ if replacement.credential_version != config.credential_version.saturating_add(1) {
694+ return Err(anyhow!(
695+ "credential refresh version is not the next installation version"
696+ ));
697+ }
698+ if replacement.bucket != current.bucket
699+ || replacement.endpoint != current.endpoint
700+ || replacement.region != current.region
701+ {
702+ return Err(anyhow!(
703+ "credential refresh attempted to change the installation storage target"
704+ ));
705+ }
706+ for (name, value) in [
707+ (
708+ "credential handoff",
709+ replacement.credential_handoff_id.as_str(),
710+ ),
711+ ("installation token", replacement.instance_token.as_str()),
712+ ("storage access key", replacement.access_key_id.as_str()),
713+ ("storage secret key", replacement.secret_access_key.as_str()),
714+ ] {
715+ if value.is_empty() || value.len() > 500 {
716+ return Err(anyhow!("credential refresh returned an invalid {name}"));
717+ }
718+ }
719+ Ok(())
720+}
721+
722+pub async fn connect_on_startup_with_storage(
723+ byo_storage: Option<ByoStorageConfig>,
724+) -> anyhow::Result<()> {
725+ let mut options = options_from_env()?;
726+ options.byo_storage = byo_storage;
727+ validate_environment(&options.environment)?;
728+ connect(options, true).await
729+}
730+
731+pub fn installation_storage() -> anyhow::Result<InstallationStorageConfig> {
732+ installation_storage_with_version().map(|(storage, _)| storage)
733+}
734+
735+pub fn installation_storage_with_version() -> anyhow::Result<(InstallationStorageConfig, u64)> {
736+ let config = connected_config()?.context("managed installation is not connected")?;
737+ let credential_version = config.credential_version;
738+ let storage = match (config.storage, config.byo_storage) {
739+ (Some(storage), None) => InstallationStorageConfig::Managed(storage),
740+ (None, Some(storage)) => InstallationStorageConfig::Byo(storage),
741+ (None, None) => {
742+ return Err(anyhow!("managed installation record has no storage target"));
743+ }
744+ (Some(_), Some(_)) => {
745+ return Err(anyhow!(
746+ "managed installation record contains conflicting storage targets"
747+ ));
748+ }
749+ };
750+ Ok((storage, credential_version))
751+}
752+
753+pub type PresenceSnapshotFuture = Pin<Box<dyn Future<Output = Option<PresenceSnapshot>> + Send>>;
754+pub type PresenceSnapshotSource = Arc<dyn Fn() -> PresenceSnapshotFuture + Send + Sync>;
755+
756+/// Production WebSocket transport around a read-only projection supplied by
757+/// celld-logic. The control-plane adapter cannot mutate lifecycle state or
758+/// maintain its own resident inventory.
759+pub struct PresenceRuntime {
760+ pub s3: S3Client,
761+ pub bucket: String,
762+ pub replication: Option<crate::runtime::Replication>,
763+ pub node_session_id: String,
764+ pub advertise: String,
765+ pub listen: String,
766+ /// Credential version used to construct S3, lease, Litestream, explorer,
767+ /// and deployment adapters. This intentionally comes from the same config
768+ /// snapshot as those credentials, not from a later presence-agent read.
769+ pub credential_version: u64,
770+ pub snapshot: PresenceSnapshotSource,
771+}
772+
773+pub fn start_presence_agent(runtime: PresenceRuntime) -> bool {
774+ let config = match connected_config() {
775+ Ok(Some(config)) => config,
776+ Ok(None) => return false,
777+ Err(error) => {
778+ warn!(event = "control_plane_presence_configuration_error", %error);
779+ return false;
780+ }
781+ };
782+ let hostname = machine_hostname();
783+ tokio::spawn(async move {
784+ let mut consecutive_failures = 0_u32;
785+ loop {
786+ let started = Instant::now();
787+ let result = tokio::select! {
788+ result = presence_session(&config, &runtime, &hostname) => result,
789+ credential_version = wait_for_credential_rotation(runtime.credential_version) => {
790+ restart_for_credential_rotation(runtime.credential_version, credential_version);
791+ }
792+ };
793+ if started.elapsed() >= Duration::from_secs(30) {
794+ consecutive_failures = 0;
795+ }
796+ match result {
797+ Ok(()) => {}
798+ Err(error) if consecutive_failures == 0 => {
799+ report_managed_runtime_state(
800+ if error.is::<ManagedControlCredentialRevoked>() {
801+ ManagedRuntimeState::CredentialRevoked
802+ } else {
803+ ManagedRuntimeState::ControlPlaneUnavailable
804+ },
805+ );
806+ info!(
807+ event = "control_plane_presence_unavailable",
808+ %error,
809+ "Managed Control Plane presence unavailable; bucket-backed serving continues"
810+ );
811+ }
812+ Err(_) => {}
813+ }
814+ consecutive_failures = consecutive_failures.saturating_add(1);
815+ let exponent = consecutive_failures.saturating_sub(1).min(5);
816+ let seconds = 2_u64.saturating_mul(1_u64 << exponent).min(60);
817+ let jitter_ms = (rand::random::<u16>() as u64) % 1000;
818+ tokio::select! {
819+ _ = tokio::time::sleep(Duration::from_millis(seconds * 1000 + jitter_ms)) => {}
820+ credential_version = wait_for_credential_rotation(runtime.credential_version) => {
821+ restart_for_credential_rotation(runtime.credential_version, credential_version);
822+ }
823+ }
824+ }
825+ });
826+ true
827+}
828+
829+fn restart_for_credential_rotation(previous_version: u64, credential_version: u64) -> ! {
830+ info!(
831+ event = "control_plane_restart_for_credentials",
832+ previous_credential_version = previous_version,
833+ credential_version,
834+ "managed credential changed; restarting celld to rebuild every credentialed adapter"
835+ );
836+ restart_process("credential_rotation")
837+}
838+
839+/// Watch the durable installation record for the lifetime of the advisory
840+/// presence agent. `celld credentials refresh` persists the replacement before
841+/// acknowledging its handoff; seeing that version is therefore enough to
842+/// rebuild the complete adapter graph. Replacing only one S3 client here would
843+/// leave the lease pool, Litestream, explorer, or deploy agent on revoked
844+/// credentials.
845+async fn wait_for_credential_rotation(current_version: u64) -> u64 {
846+ let mut tick = tokio::time::interval(Duration::from_secs(1));
847+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
848+ let mut unavailable = false;
849+ loop {
850+ tick.tick().await;
851+ match connected_config() {
852+ Ok(Some(config)) => {
853+ if unavailable {
854+ info!(
855+ event = "control_plane_credential_watch_recovered",
856+ "managed installation record is readable again"
857+ );
858+ unavailable = false;
859+ }
860+ if config.credential_version != current_version {
861+ return config.credential_version;
862+ }
863+ }
864+ Ok(None) => {
865+ if !unavailable {
866+ warn!(
867+ event = "control_plane_credential_watch_unavailable",
868+ reason = "installation_not_connected",
869+ "cannot observe managed credential rotation"
870+ );
871+ unavailable = true;
872+ }
873+ }
874+ Err(error) => {
875+ if !unavailable {
876+ warn!(
877+ event = "control_plane_credential_watch_unavailable",
878+ reason = "installation_read_failed",
879+ %error,
880+ "cannot observe managed credential rotation"
881+ );
882+ unavailable = true;
883+ }
884+ }
885+ }
886+ }
887+}
888+
889+async fn presence_session(
890+ config: &CloudConfig,
891+ runtime: &PresenceRuntime,
892+ hostname: &str,
893+) -> anyhow::Result<()> {
894+ let request = presence_request(
895+ config,
896+ &runtime.node_session_id,
897+ &runtime.advertise,
898+ &runtime.listen,
899+ hostname,
900+ )?;
901+ let (mut socket, _) = match tokio_tungstenite::connect_async(request).await {
902+ Ok(connected) => connected,
903+ Err(tokio_tungstenite::tungstenite::Error::Http(response))
904+ if matches!(response.status().as_u16(), 401 | 403) =>
905+ {
906+ return Err(ManagedControlCredentialRevoked.into());
907+ }
908+ Err(error) => {
909+ return Err(error).context("connect Managed Control Plane presence");
910+ }
911+ };
912+ report_managed_runtime_state(ManagedRuntimeState::Connected);
913+ info!(
914+ event = "control_plane_presence_connected",
915+ node_session_id = %runtime.node_session_id,
916+ advertise = %runtime.advertise,
917+ "node session connected to the Managed Control Plane"
918+ );
919+ let heartbeat_period = std::env::var("CELLD_PRESENCE_HEARTBEAT_MS")
920+ .ok()
921+ .and_then(|value| value.parse::<u64>().ok())
922+ .filter(|value| (50..=30_000).contains(value))
923+ .map(Duration::from_millis)
924+ .unwrap_or(Duration::from_secs(30));
925+ let mut heartbeat = tokio::time::interval(heartbeat_period);
926+ heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
927+ let shadow_presence = std::env::var("CELLD_PRESENCE_SHADOW").as_deref() == Ok("on");
928+ loop {
929+ tokio::select! {
930+ _ = heartbeat.tick() => {
931+ let snapshot = (runtime.snapshot)()
932+ .await
933+ .context("celld core stopped before presence snapshot")?;
934+ let lease_shadow = if shadow_presence {
935+ Some(lease_shadow_observation(runtime).await)
936+ } else {
937+ None
938+ };
939+ let mut cells = snapshot
940+ .cells
941+ .iter()
942+ .filter(|cell| {
943+ !cell.id.is_empty()
944+ && cell.id.len() <= MAX_PRESENCE_CELL_ID_BYTES
945+ && !cell.id.chars().any(char::is_control)
946+ })
947+ .map(|cell| serde_json::json!({
948+ "id": cell.id,
949+ "epoch": cell.epoch,
950+ }))
951+ .collect::<Vec<_>>();
952+ let cells_truncated = cells.len() < snapshot.cells.len()
953+ || cells.len() > MAX_PRESENCE_CELLS;
954+ cells.truncate(MAX_PRESENCE_CELLS);
955+ let mut message = serde_json::json!({
956+ "serving": snapshot.serving,
957+ "owned_cells": snapshot.owned_cells(),
958+ "cells": cells,
959+ "cells_truncated": cells_truncated,
960+ "activity": {
961+ "acquired": snapshot.activity.acquired,
962+ "proxied": snapshot.activity.proxied,
963+ "expired_owner_leases": snapshot.activity.expired_owner_leases,
964+ "restored": snapshot.activity.restored,
965+ "advanced_epochs": snapshot.activity.advanced_epochs,
966+ },
967+ });
968+ if let Some(observation) = lease_shadow {
969+ message["lease_shadow"] = observation;
970+ }
971+ if !snapshot.lazy_lease_shadow.decisions.is_empty()
972+ || snapshot.lazy_lease_shadow.dropped > 0
973+ {
974+ message["lazy_lease_shadow"] =
975+ lazy_lease_shadow_json(&snapshot.lazy_lease_shadow);
976+ }
977+ socket
978+ .send(tokio_tungstenite::tungstenite::Message::Text(
979+ message.to_string().into(),
980+ ))
981+ .await?;
982+ }
983+ message = socket.next() => {
984+ match message {
985+ Some(Ok(tokio_tungstenite::tungstenite::Message::Ping(payload))) => {
986+ socket.send(
987+ tokio_tungstenite::tungstenite::Message::Pong(payload)
988+ ).await?;
989+ }
990+ Some(Ok(tokio_tungstenite::tungstenite::Message::Text(text))) => {
991+ let message = serde_json::from_str::<serde_json::Value>(&text).ok();
992+ let message_type = message.as_ref()
993+ .and_then(|value| value.get("type"))
994+ .and_then(|value| value.as_str())
995+ .map(str::to_string);
996+ match message_type.as_deref() {
997+ Some("explorer_request") => {
998+ let response = handle_explorer_request(
999+ message.as_ref().unwrap(),
1000+ runtime,
1001+ ).await;
1002+ socket
1003+ .send(tokio_tungstenite::tungstenite::Message::Text(
1004+ response.to_string().into(),
1005+ ))
1006+ .await?;
1007+ }
1008+ Some("deployment") => {
1009+ let client = reqwest::Client::builder()
1010+ .timeout(Duration::from_secs(30))
1011+ .build()?;
1012+ if poll_and_apply(
1013+ &client,
1014+ config,
1015+ &runtime.s3,
1016+ &runtime.bucket,
1017+ ).await?.is_some() && restart_on_deployment_enabled() {
1018+ restart_for_deployment();
1019+ }
1020+ }
1021+ Some("deployment_current") if restart_on_deployment_enabled() => {
1022+ restart_for_deployment();
1023+ }
1024+ _ => {}
1025+ }
1026+ }
1027+ Some(Ok(tokio_tungstenite::tungstenite::Message::Close(_))) | None => {
1028+ return Err(anyhow!("Managed Control Plane closed presence"));
1029+ }
1030+ Some(Ok(_)) => {}
1031+ Some(Err(error)) => return Err(error.into()),
1032+ }
1033+ }
1034+ }
1035+ }
1036+}
1037+
1038+fn lazy_lease_shadow_json(
1039+ batch: &celld_logic::LeaseLifecycleShadowBatch,
1040+) -> serde_json::Value {
1041+ let decisions = batch
1042+ .decisions
1043+ .iter()
1044+ .map(|decision| {
1045+ let snapshot = &decision.snapshot;
1046+ let mode = match snapshot.mode {
1047+ celld_logic::NodeLeaseMode::Continuous => "continuous",
1048+ celld_logic::NodeLeaseMode::Shadow => "shadow",
1049+ celld_logic::NodeLeaseMode::Lazy => "lazy",
1050+ };
1051+ let authority_action = match decision.expected.authority_action {
1052+ celld_logic::NodeLeaseAuthorityAction::Hold => "hold",
1053+ celld_logic::NodeLeaseAuthorityAction::Renew => "renew",
1054+ };
1055+ serde_json::json!({
1056+ "sequence": decision.sequence,
1057+ "observed_at_ms": decision.observed_at_ms,
1058+ "snapshot": {
1059+ "mode": mode,
1060+ "active_cells": snapshot.active_cells,
1061+ "serving_cells": snapshot.serving_cells,
1062+ "idle_ms": snapshot.idle_ms,
1063+ "linger_ms": snapshot.linger_ms,
1064+ "lease_active": snapshot.lease_active,
1065+ "elapsed_since_ok_ms": snapshot.elapsed_since_ok_ms,
1066+ "elapsed_since_renew_ms": snapshot.elapsed_since_renew_ms,
1067+ "ttl_ms": snapshot.ttl_ms,
1068+ "shadow_release_reported": snapshot.shadow_release_reported,
1069+ },
1070+ "expected": {
1071+ "shadow_release": decision.expected.shadow_release,
1072+ "authority_action": authority_action,
1073+ },
1074+ })
1075+ })
1076+ .collect::<Vec<_>>();
1077+ serde_json::json!({
1078+ "dropped": batch.dropped,
1079+ "decisions": decisions,
1080+ })
1081+}
1082+
1083+/// Independently observe bucket truth for rollout comparison. This is an
1084+/// off-by-default management diagnostic: it never feeds the lease record back
1085+/// into the core or changes whether the node serves.
1086+async fn lease_shadow_observation(runtime: &PresenceRuntime) -> serde_json::Value {
1087+ let checked_at_ms = crate::ownership_store::now_ms();
1088+ let ownership = crate::ownership_store::S3Ownership::new(
1089+ runtime.s3.clone(),
1090+ runtime.bucket.clone(),
1091+ runtime.node_session_id.clone(),
1092+ );
1093+ match ownership.read_node_lease(&runtime.node_session_id).await {
1094+ Ok(Some(record)) => serde_json::json!({
1095+ "bucket_status": if record.expires_ms > checked_at_ms { "live" } else { "expired" },
1096+ "node": record.node,
1097+ "advertise": record.addr,
1098+ "expires_ms": record.expires_ms,
1099+ "checked_at_ms": checked_at_ms,
1100+ }),
1101+ Ok(None) => serde_json::json!({
1102+ "bucket_status": "missing",
1103+ "node": null,
1104+ "advertise": null,
1105+ "expires_ms": null,
1106+ "checked_at_ms": checked_at_ms,
1107+ }),
1108+ Err(_) => serde_json::json!({
1109+ "bucket_status": "unavailable",
1110+ "node": null,
1111+ "advertise": null,
1112+ "expires_ms": null,
1113+ "checked_at_ms": checked_at_ms,
1114+ }),
1115+ }
1116+}
1117+
1118+async fn handle_explorer_request(
1119+ message: &serde_json::Value,
1120+ runtime: &PresenceRuntime,
1121+) -> serde_json::Value {
1122+ let request_id = message
1123+ .get("request_id")
1124+ .and_then(|value| value.as_str())
1125+ .filter(|value| {
1126+ !value.is_empty()
1127+ && value.len() <= 64
1128+ && value
1129+ .bytes()
1130+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
1131+ })
1132+ .unwrap_or("");
1133+ let operation = message.get("operation").and_then(|value| value.as_str());
1134+ let result = match operation {
1135+ Some("list_cells") => {
1136+ let cursor = match message.get("cursor") {
1137+ None | Some(serde_json::Value::Null) => None,
1138+ Some(serde_json::Value::String(cursor)) if cursor.len() <= 2_048 => {
1139+ Some(cursor.as_str())
1140+ }
1141+ _ => return explorer_error(request_id, "invalid_request"),
1142+ };
1143+ list_durable_cells(&runtime.s3, &runtime.bucket, cursor).await
1144+ }
1145+ Some("inspect_cell") => {
1146+ let Some(cell) = message
1147+ .get("cell_id")
1148+ .and_then(|value| value.as_str())
1149+ .filter(|cell| valid_explorer_cell_id(cell))
1150+ else {
1151+ return explorer_error(request_id, "invalid_request");
1152+ };
1153+ let table = match message.get("table") {
1154+ None | Some(serde_json::Value::Null) => None,
1155+ Some(serde_json::Value::String(table))
1156+ if !table.is_empty() && table.len() <= 200 =>
1157+ {
1158+ Some(table.clone())
1159+ }
1160+ _ => return explorer_error(request_id, "invalid_request"),
1161+ };
1162+ let Some(replication) = runtime.replication.clone() else {
1163+ return explorer_error(request_id, "snapshot_not_found");
1164+ };
1165+ let Some(snapshot) = (runtime.snapshot)().await else {
1166+ return explorer_error(request_id, "node_transport_unavailable");
1167+ };
1168+ let active_epoch = snapshot
1169+ .cells
1170+ .iter()
1171+ .find(|candidate| candidate.id == cell)
1172+ .map(|candidate| candidate.epoch);
1173+ if let Some(epoch) = active_epoch {
1174+ let cell = cell.to_string();
1175+ match tokio::task::spawn_blocking(move || {
1176+ let Some(snapshot) = replication.snapshot_active(&cell, epoch)? else {
1177+ return Ok(None);
1178+ };
1179+ inspect_snapshot(snapshot, &cell, table.as_deref(), "active").map(Some)
1180+ })
1181+ .await
1182+ {
1183+ Ok(Ok(Some(result))) => Ok(result),
1184+ Ok(Ok(None)) => {
1185+ return explorer_error(request_id, "active_snapshot_unavailable");
1186+ }
1187+ Ok(Err(error)) => Err(error.context("inspect active cell snapshot")),
1188+ Err(error) => Err(anyhow!("active inspection task failed: {error}")),
1189+ }
1190+ } else {
1191+ match replication.restore_snapshot(cell).await {
1192+ Ok(Some(snapshot)) => {
1193+ let cell = cell.to_string();
1194+ match tokio::task::spawn_blocking(move || {
1195+ inspect_snapshot(snapshot, &cell, table.as_deref(), "replicated")
1196+ })
1197+ .await
1198+ {
1199+ Ok(result) => result,
1200+ Err(error) => Err(anyhow!("inspection task failed: {error}")),
1201+ }
1202+ }
1203+ Ok(None) => return explorer_error(request_id, "snapshot_not_found"),
1204+ Err(error) => Err(error.context("restore replicated snapshot")),
1205+ }
1206+ }
1207+ }
1208+ _ => return explorer_error(request_id, "invalid_request"),
1209+ };
1210+ match result {
1211+ Ok(result) => serde_json::json!({
1212+ "type": "explorer_response",
1213+ "request_id": request_id,
1214+ "ok": true,
1215+ "result": result,
1216+ }),
1217+ Err(error) => {
1218+ let stable_error = if error
1219+ .chain()
1220+ .any(|cause| cause.to_string() == "table_not_found")
1221+ {
1222+ "table_not_found"
1223+ } else if error
1224+ .chain()
1225+ .any(|cause| cause.to_string() == "table_not_previewable")
1226+ {
1227+ "table_not_previewable"
1228+ } else {
1229+ "inspection_failed"
1230+ };
1231+ warn!(
1232+ event = "control_plane_explorer_request_failed",
1233+ request_id,
1234+ %error,
1235+ "read-only cell inspection failed"
1236+ );
1237+ explorer_error(request_id, stable_error)
1238+ }
1239+ }
1240+}
1241+
1242+fn explorer_error(request_id: &str, error: &str) -> serde_json::Value {
1243+ serde_json::json!({
1244+ "type": "explorer_response",
1245+ "request_id": request_id,
1246+ "ok": false,
1247+ "error": error,
1248+ })
1249+}
1250+
1251+fn valid_explorer_cell_id(cell: &str) -> bool {
1252+ !cell.is_empty()
1253+ && cell.len() <= MAX_PRESENCE_CELL_ID_BYTES
1254+ && !cell.contains('/')
1255+ && !cell.contains('\\')
1256+ && !cell.contains('?')
1257+ && !cell.contains('#')
1258+ && !cell.contains("..")
1259+ && cell.bytes().all(|byte| byte.is_ascii_graphic())
1260+}
1261+
1262+async fn list_durable_cells(
1263+ s3: &S3Client,
1264+ bucket: &str,
1265+ cursor: Option<&str>,
1266+) -> anyhow::Result<serde_json::Value> {
1267+ let mut request = s3
1268+ .list_objects_v2()
1269+ .bucket(bucket)
1270+ .prefix("cells/")
1271+ .delimiter("/")
1272+ .max_keys(MAX_EXPLORER_CELL_PAGE);
1273+ if let Some(cursor) = cursor {
1274+ request = request.continuation_token(cursor);
1275+ }
1276+ let page = request.send().await?;
1277+ let cells = page
1278+ .common_prefixes()
1279+ .iter()
1280+ .filter_map(|prefix| prefix.prefix())
1281+ .filter_map(|prefix| {
1282+ prefix
1283+ .strip_prefix("cells/")
1284+ .and_then(|cell| cell.strip_suffix('/'))
1285+ })
1286+ .filter(|cell| valid_explorer_cell_id(cell))
1287+ .map(str::to_string)
1288+ .collect::<Vec<_>>();
1289+ Ok(serde_json::json!({
1290+ "cells": cells,
1291+ "next_cursor": page.next_continuation_token(),
1292+ }))
1293+}
1294+
1295+fn inspect_snapshot(
1296+ snapshot: crate::replication::RestoredSnapshot,
1297+ cell: &str,
1298+ selected_table: Option<&str>,
1299+ source: &str,
1300+) -> anyhow::Result<serde_json::Value> {
1301+ let connection = Connection::open_with_flags(
1302+ snapshot.path(),
1303+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
1304+ )?;
1305+ let mut schema = connection.prepare(
1306+ "SELECT name, type, sql
1307+ FROM sqlite_schema
1308+ WHERE type IN ('table', 'view')
1309+ AND name NOT LIKE 'sqlite_%'
1310+ ORDER BY name
1311+ LIMIT ?1",
1312+ )?;
1313+ let mut rows = schema.query([i64::try_from(MAX_EXPLORER_TABLES + 1)?])?;
1314+ let mut tables = Vec::new();
1315+ let mut schema_bytes = 0_usize;
1316+ let mut tables_truncated = false;
1317+ while let Some(row) = rows.next()? {
1318+ if tables.len() >= MAX_EXPLORER_TABLES {
1319+ tables_truncated = true;
1320+ break;
1321+ }
1322+ let name: String = row.get(0)?;
1323+ let kind: String = row.get(1)?;
1324+ let sql: Option<String> = row.get(2)?;
1325+ let entry = serde_json::json!({
1326+ "name": name,
1327+ "kind": kind,
1328+ "sql": sql.map(|sql| truncate_utf8(&sql, 4 * 1024).0),
1329+ });
1330+ let entry_bytes = serde_json::to_vec(&entry)?.len();
1331+ if schema_bytes + entry_bytes > MAX_EXPLORER_RESPONSE_BYTES / 2 {
1332+ tables_truncated = true;
1333+ break;
1334+ }
1335+ schema_bytes += entry_bytes;
1336+ tables.push(entry);
1337+ }
1338+ drop(rows);
1339+ drop(schema);
1340+ let preview = match selected_table {
1341+ Some(table) => Some(preview_table(&connection, table)?),
1342+ None => None,
1343+ };
1344+ Ok(serde_json::json!({
1345+ "cell_id": cell,
1346+ "epoch": snapshot.epoch,
1347+ "source": source,
1348+ "tables": tables,
1349+ "tables_truncated": tables_truncated,
1350+ "preview": preview,
1351+ }))
1352+}
1353+
1354+fn preview_table(connection: &Connection, table: &str) -> anyhow::Result<serde_json::Value> {
1355+ let kind = connection
1356+ .query_row(
1357+ "SELECT type FROM sqlite_schema WHERE name = ?1 AND type IN ('table', 'view')",
1358+ [table],
1359+ |row| row.get::<_, String>(0),
1360+ )
1361+ .optional()?
1362+ .context("table_not_found")?;
1363+ if kind != "table" {
1364+ anyhow::bail!("table_not_previewable");
1365+ }
1366+ let quoted = table.replace('"', "\"\"");
1367+ let mut statement = connection.prepare(&format!(
1368+ "SELECT * FROM \"{quoted}\" LIMIT {}",
1369+ MAX_EXPLORER_ROWS + 1,
1370+ ))?;
1371+ let columns = statement
1372+ .column_names()
1373+ .iter()
1374+ .take(MAX_EXPLORER_COLUMNS)
1375+ .map(|name| truncate_utf8(name, 200).0)
1376+ .collect::<Vec<_>>();
1377+ let column_count = columns.len();
1378+ let all_column_count = statement.column_count();
1379+ let mut query = statement.query([])?;
1380+ let mut rows = Vec::new();
1381+ let mut response_bytes = 0_usize;
1382+ let mut truncated = all_column_count > MAX_EXPLORER_COLUMNS;
1383+ while let Some(row) = query.next()? {
1384+ if rows.len() >= MAX_EXPLORER_ROWS {
1385+ truncated = true;
1386+ break;
1387+ }
1388+ let mut values = Vec::with_capacity(column_count);
1389+ for index in 0..column_count {
1390+ values.push(explorer_value(row.get_ref(index)?));
1391+ }
1392+ let row_bytes = serde_json::to_vec(&values)?.len();
1393+ if response_bytes + row_bytes > MAX_EXPLORER_RESPONSE_BYTES / 2 {
1394+ truncated = true;
1395+ break;
1396+ }
1397+ response_bytes += row_bytes;
1398+ rows.push(values);
1399+ }
1400+ Ok(serde_json::json!({
1401+ "table": table,
1402+ "columns": columns,
1403+ "rows": rows,
1404+ "truncated": truncated,
1405+ }))
1406+}
1407+
1408+fn explorer_value(value: ValueRef<'_>) -> serde_json::Value {
1409+ match value {
1410+ ValueRef::Null => serde_json::json!({ "type": "null", "value": null }),
1411+ ValueRef::Integer(value) => {
1412+ serde_json::json!({ "type": "integer", "value": value.to_string() })
1413+ }
1414+ ValueRef::Real(value) => {
1415+ serde_json::json!({ "type": "real", "value": value.to_string() })
1416+ }
1417+ ValueRef::Text(value) => {
1418+ let text = String::from_utf8_lossy(value);
1419+ let (text, truncated) = truncate_utf8(&text, MAX_EXPLORER_VALUE_BYTES);
1420+ serde_json::json!({
1421+ "type": "text",
1422+ "value": text,
1423+ "bytes": value.len(),
1424+ "truncated": truncated,
1425+ })
1426+ }
1427+ ValueRef::Blob(value) => {
1428+ let shown = &value[..value.len().min(MAX_EXPLORER_VALUE_BYTES)];
1429+ serde_json::json!({
1430+ "type": "blob",
1431+ "value": hex(shown),
1432+ "bytes": value.len(),
1433+ "truncated": shown.len() < value.len(),
1434+ })
1435+ }
1436+ }
1437+}
1438+
1439+fn truncate_utf8(value: &str, max_bytes: usize) -> (String, bool) {
1440+ if value.len() <= max_bytes {
1441+ return (value.to_string(), false);
1442+ }
1443+ let mut end = max_bytes;
1444+ while !value.is_char_boundary(end) {
1445+ end -= 1;
1446+ }
1447+ (value[..end].to_string(), true)
1448+}
1449+
1450+fn hex(value: &[u8]) -> String {
1451+ const DIGITS: &[u8; 16] = b"0123456789abcdef";
1452+ let mut encoded = String::with_capacity(value.len() * 2);
1453+ for byte in value {
1454+ encoded.push(DIGITS[(byte >> 4) as usize] as char);
1455+ encoded.push(DIGITS[(byte & 0x0f) as usize] as char);
1456+ }
1457+ encoded
1458+}
1459+
1460+fn presence_request(
1461+ config: &CloudConfig,
1462+ node_session_id: &str,
1463+ advertise: &str,
1464+ listen: &str,
1465+ hostname: &str,
1466+) -> anyhow::Result<tokio_tungstenite::tungstenite::http::Request<()>> {
1467+ use tokio_tungstenite::tungstenite::client::IntoClientRequest;
1468+ use tokio_tungstenite::tungstenite::http::header::{HeaderName, HeaderValue, AUTHORIZATION};
1469+
1470+ let token = config
1471+ .installation_token
1472+ .as_deref()
1473+ .context("managed installation has no token")?;
1474+ let mut url = url::Url::parse(&config.control_url)?;
1475+ url.set_scheme(if url.scheme() == "https" { "wss" } else { "ws" })
1476+ .map_err(|_| anyhow!("invalid Managed Control Plane WebSocket scheme"))?;
1477+ url.set_path("/api/agent/presence");
1478+ url.query_pairs_mut()
1479+ .append_pair("node_session_id", node_session_id)
1480+ .append_pair("advertise", advertise)
1481+ .append_pair("listen", listen);
1482+ let mut request = url.as_str().into_client_request()?;
1483+ request.headers_mut().insert(
1484+ AUTHORIZATION,
1485+ HeaderValue::from_str(&format!("Bearer {token}"))?,
1486+ );
1487+ request.headers_mut().insert(
1488+ HeaderName::from_static("x-cells-version"),
1489+ HeaderValue::from_static(env!("CARGO_PKG_VERSION")),
1490+ );
1491+ request.headers_mut().insert(
1492+ HeaderName::from_static("x-cells-capabilities"),
1493+ HeaderValue::from_static("assets-v1,sqlite-explorer-v1,sqlite-explorer-v2"),
1494+ );
1495+ request.headers_mut().insert(
1496+ HeaderName::from_static("x-cells-hostname"),
1497+ HeaderValue::from_str(hostname)?,
1498+ );
1499+ request.headers_mut().insert(
1500+ HeaderName::from_static("x-cells-os"),
1501+ HeaderValue::from_static(std::env::consts::OS),
1502+ );
1503+ request.headers_mut().insert(
1504+ HeaderName::from_static("x-cells-arch"),
1505+ HeaderValue::from_static(std::env::consts::ARCH),
1506+ );
1507+ Ok(request)
1508+}
1509+
1510+pub fn start_deploy_agent(s3: S3Client, bucket: String, runtime_ready: Arc<AtomicBool>) -> bool {
1511+ let config = match connected_config() {
1512+ Ok(Some(config)) => config,
1513+ Ok(None) => return false,
1514+ Err(error) => {
1515+ warn!(event = "control_plane_agent_configuration_error", %error);
1516+ return false;
1517+ }
1518+ };
1519+ tokio::spawn(async move {
1520+ let client = match reqwest::Client::builder()
1521+ .timeout(Duration::from_secs(30))
1522+ .build()
1523+ {
1524+ Ok(client) => client,
1525+ Err(error) => {
1526+ warn!(event = "control_plane_agent_client_error", %error);
1527+ return;
1528+ }
1529+ };
1530+ let mut consecutive_failures = 0_u32;
1531+ loop {
1532+ let mut delay = Duration::from_secs(60);
1533+ match poll_and_apply(&client, &config, &s3, &bucket).await {
1534+ Ok(Some(applied)) => {
1535+ if consecutive_failures > 0 {
1536+ info!(
1537+ event = "control_plane_agent_reconnected",
1538+ failures = consecutive_failures,
1539+ "Managed Control Plane connection restored"
1540+ );
1541+ }
1542+ consecutive_failures = 0;
1543+ if runtime_ready.load(Ordering::SeqCst) && restart_on_deployment_enabled() {
1544+ info!(
1545+ event = "control_plane_restart_for_deploy",
1546+ deployment_id = %applied.id,
1547+ script_name = %applied.script_name,
1548+ "deployment applied; restarting celld to load it"
1549+ );
1550+ restart_for_deployment();
1551+ }
1552+ }
1553+ Ok(None) => {
1554+ if consecutive_failures > 0 {
1555+ info!(
1556+ event = "control_plane_agent_reconnected",
1557+ failures = consecutive_failures,
1558+ "Managed Control Plane connection restored"
1559+ );
1560+ }
1561+ consecutive_failures = 0;
1562+ }
1563+ Err(error) => {
1564+ if error.is::<ManagedControlCredentialRevoked>() {
1565+ report_managed_runtime_state(ManagedRuntimeState::CredentialRevoked);
1566+ }
1567+ consecutive_failures = consecutive_failures.saturating_add(1);
1568+ if consecutive_failures == 1 {
1569+ info!(
1570+ event = "control_plane_agent_unavailable",
1571+ %error,
1572+ "Managed Control Plane unavailable; bucket-backed serving continues"
1573+ );
1574+ }
1575+ let exponent = consecutive_failures.saturating_sub(1).min(5);
1576+ let seconds = 2_u64.saturating_mul(1_u64 << exponent).min(60);
1577+ let jitter_ms = (rand::random::<u16>() as u64) % 1000;
1578+ delay = Duration::from_millis(seconds * 1000 + jitter_ms);
1579+ }
1580+ }
1581+ tokio::time::sleep(delay).await;
1582+ }
1583+ });
1584+ true
1585+}
1586+
1587+pub async fn wait_for_initial_deployment(s3: &S3Client, bucket: &str) -> anyhow::Result<()> {
1588+ let config = connected_config()?.context("managed installation is not connected")?;
1589+ let client = reqwest::Client::builder()
1590+ .timeout(Duration::from_secs(30))
1591+ .build()?;
1592+ println!("Waiting for the first Managed Control Plane deployment...");
1593+ println!(
1594+ "Deploy from {}/control; this process will start automatically.",
1595+ config.control_url.trim_end_matches('/')
1596+ );
1597+ loop {
1598+ if deployment_exists(s3, bucket).await? {
1599+ return Ok(());
1600+ }
1601+ if poll_and_apply(&client, &config, s3, bucket)
1602+ .await?
1603+ .is_some()
1604+ {
1605+ return Ok(());
1606+ }
1607+ tokio::time::sleep(Duration::from_secs(2)).await;
1608+ }
1609+}
1610+
1611+async fn deployment_exists(s3: &S3Client, bucket: &str) -> anyhow::Result<bool> {
1612+ let response = s3
1613+ .list_objects_v2()
1614+ .bucket(bucket)
1615+ .prefix("deploy/")
1616+ .send()
1617+ .await
1618+ .context("discover managed deployment")?;
1619+ Ok(response
1620+ .contents()
1621+ .iter()
1622+ .filter_map(|object| object.key())
1623+ .any(|key| {
1624+ key == "deploy/current.json"
1625+ || key
1626+ .strip_prefix("deploy/")
1627+ .is_some_and(is_named_current_pointer)
1628+ }))
1629+}
1630+
1631+fn is_named_current_pointer(key: &str) -> bool {
1632+ let mut parts = key.split('/');
1633+ matches!(
1634+ (parts.next(), parts.next(), parts.next()),
1635+ (Some(_), Some("current.json"), None)
1636+ )
1637+}
1638+
1639+fn connected_config() -> anyhow::Result<Option<CloudConfig>> {
1640+ let path = config_path()?;
1641+ if !path.exists() {
1642+ return Ok(None);
1643+ }
1644+ let contents =
1645+ std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
1646+ let config: CloudConfig =
1647+ serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?;
1648+ if config.installation_token.is_some() {
1649+ Ok(Some(config))
1650+ } else {
1651+ Ok(None)
1652+ }
1653+}
1654+
1655+async fn poll_and_apply(
1656+ client: &reqwest::Client,
1657+ config: &CloudConfig,
1658+ s3: &S3Client,
1659+ bucket: &str,
1660+) -> anyhow::Result<Option<AppliedDeployment>> {
1661+ let token = config
1662+ .installation_token
1663+ .as_deref()
1664+ .context("cloud config has no instance token")?;
1665+ let response = client
1666+ .post(format!("{}/api/agent/commands/next", config.control_url))
1667+ .bearer_auth(token)
1668+ .json(&serde_json::json!({}))
1669+ .send()
1670+ .await
1671+ .context("poll deployment command")?;
1672+ if response.status() == reqwest::StatusCode::NO_CONTENT {
1673+ return Ok(None);
1674+ }
1675+ if matches!(response.status().as_u16(), 401 | 403) {
1676+ return Err(ManagedControlCredentialRevoked.into());
1677+ }
1678+ if !response.status().is_success() {
1679+ let status = response.status();
1680+ let body = response.text().await.unwrap_or_default();
1681+ return Err(anyhow!("deployment poll returned {status}: {body}"));
1682+ }
1683+ let envelope: AgentCommandEnvelope =
1684+ response.json().await.context("decode deployment command")?;
1685+ let command = envelope.command;
1686+ if command.kind != "deploy" {
1687+ return Err(anyhow!(
1688+ "unsupported control-plane command: {}",
1689+ command.kind
1690+ ));
1691+ }
1692+
1693+ let result = apply_deployment(client, token, s3, bucket, &command.deployment).await;
1694+ let failure = result.as_ref().err().map(|error| format!("{error:#}"));
1695+ let completion = client
1696+ .post(format!(
1697+ "{}/api/agent/commands/{}/complete",
1698+ config.control_url, command.id
1699+ ))
1700+ .bearer_auth(token)
1701+ .json(&CompleteCommandRequest {
1702+ success: result.is_ok(),
1703+ error: failure.as_deref(),
1704+ })
1705+ .send()
1706+ .await
1707+ .context("report deployment completion")?;
1708+ if !completion.status().is_success() {
1709+ let status = completion.status();
1710+ let body = completion.text().await.unwrap_or_default();
1711+ return Err(anyhow!("deployment completion returned {status}: {body}"));
1712+ }
1713+ result?;
1714+ Ok(Some(AppliedDeployment {
1715+ id: command.id,
1716+ script_name: command.deployment.script_name,
1717+ }))
1718+}
1719+
1720+async fn apply_deployment(
1721+ client: &reqwest::Client,
1722+ token: &str,
1723+ s3: &S3Client,
1724+ bucket: &str,
1725+ deployment: &AgentDeployment,
1726+) -> anyhow::Result<()> {
1727+ if deployment.pointer.version != deployment.version
1728+ || deployment.manifest.version != deployment.version
1729+ || deployment.manifest.script_name != deployment.script_name
1730+ {
1731+ return Err(anyhow!("control-plane deployment metadata is inconsistent"));
1732+ }
1733+ validate_managed_module_envelope(deployment)?;
1734+ validate_managed_class_migrations(&deployment.manifest)?;
1735+ for feature in &deployment.manifest.required_features {
1736+ if feature != "assets-v1" {
1737+ return Err(anyhow!("unsupported deployment feature: {feature}"));
1738+ }
1739+ }
1740+
1741+ let mut asset_files = 0_u32;
1742+ let mut asset_bytes = 0_u64;
1743+ let mut asset_blobs = 0_usize;
1744+ if let Some(reference) = &deployment.manifest.assets {
1745+ let assets = deployment
1746+ .assets
1747+ .as_ref()
1748+ .context("asset manifest has no control-plane transport")?;
1749+ if reference.index != "assets.json"
1750+ || reference.sha256 != assets.sha256
1751+ || reference.file_count != assets.file_count
1752+ || reference.total_bytes != assets.total_bytes
1753+ {
1754+ return Err(anyhow!("control-plane asset metadata is inconsistent"));
1755+ }
1756+ let response = client
1757+ .get(&assets.index_download_url)
1758+ .bearer_auth(token)
1759+ .send()
1760+ .await
1761+ .context("download asset index")?;
1762+ if !response.status().is_success() {
1763+ return Err(anyhow!(
1764+ "asset index download returned {}",
1765+ response.status()
1766+ ));
1767+ }
1768+ let index_bytes = response.bytes().await?;
1769+ let index_hash = format!("{:x}", Sha256::digest(&index_bytes));
1770+ if index_hash != assets.sha256 {
1771+ return Err(anyhow!("asset index checksum mismatch"));
1772+ }
1773+ let index: AssetIndex =
1774+ serde_json::from_slice(&index_bytes).context("decode asset index")?;
1775+ if index.schema_version != 1
1776+ || index.entries.len() != assets.file_count as usize
1777+ || index.entries.values().map(|entry| entry.bytes).sum::<u64>() != assets.total_bytes
1778+ {
1779+ return Err(anyhow!("asset index counts do not match deployment"));
1780+ }
1781+
1782+ let mut unique = std::collections::BTreeMap::<String, u64>::new();
1783+ for (path, entry) in &index.entries {
1784+ validate_asset_index_entry(path, &entry.sha256, entry.bytes)?;
1785+ if let Some(previous) = unique.insert(entry.sha256.clone(), entry.bytes) {
1786+ if previous != entry.bytes {
1787+ return Err(anyhow!(
1788+ "asset digest has conflicting sizes: {}",
1789+ entry.sha256
1790+ ));
1791+ }
1792+ }
1793+ }
1794+ for (sha256, bytes) in &unique {
1795+ let key =
1796+ asset_blob_key(sha256).ok_or_else(|| anyhow!("invalid asset digest: {sha256}"))?;
1797+ let existing = s3.head_object().bucket(bucket).key(&key).send().await;
1798+ if let Ok(existing) = existing {
1799+ if existing.content_length().unwrap_or(-1) == *bytes as i64
1800+ && existing
1801+ .metadata()
1802+ .and_then(|metadata| metadata.get("sha256"))
1803+ == Some(sha256)
1804+ {
1805+ continue;
1806+ }
1807+ tracing::warn!(
1808+ event = "asset_blob_repair_required",
1809+ %sha256,
1810+ "asset blob exists with invalid size or checksum metadata"
1811+ );
1812+ }
1813+
1814+ let response = client
1815+ .get(format!(
1816+ "{}/{}",
1817+ assets.blob_download_base_url.trim_end_matches('/'),
1818+ sha256
1819+ ))
1820+ .bearer_auth(token)
1821+ .send()
1822+ .await
1823+ .with_context(|| format!("download asset blob {sha256}"))?;
1824+ if !response.status().is_success() {
1825+ return Err(anyhow!(
1826+ "asset blob {sha256} download returned {}",
1827+ response.status()
1828+ ));
1829+ }
1830+ let body = response.bytes().await?;
1831+ if body.len() as u64 != *bytes {
1832+ return Err(anyhow!("asset blob {sha256} size mismatch"));
1833+ }
1834+ let hash = format!("{:x}", Sha256::digest(&body));
1835+ if hash != *sha256 {
1836+ return Err(anyhow!("asset blob {sha256} checksum mismatch"));
1837+ }
1838+ put_asset_object(s3, bucket, &key, sha256, body.to_vec()).await?;
1839+ }
1840+ put_bucket_object(
1841+ s3,
1842+ bucket,
1843+ &format!("{}/assets.json", deployment.pointer.prefix),
1844+ index_bytes.to_vec(),
1845+ )
1846+ .await?;
1847+ asset_files = assets.file_count;
1848+ asset_bytes = assets.total_bytes;
1849+ asset_blobs = unique.len();
1850+ } else if deployment.assets.is_some() {
1851+ return Err(anyhow!(
1852+ "control-plane sent asset transport for a manifest without assets"
1853+ ));
1854+ }
1855+
1856+ for module in &deployment.modules {
1857+ let response = client
1858+ .get(&module.download_url)
1859+ .bearer_auth(token)
1860+ .send()
1861+ .await
1862+ .with_context(|| format!("download module {}", module.name))?;
1863+ if !response.status().is_success() {
1864+ return Err(anyhow!(
1865+ "module {} download returned {}",
1866+ module.name,
1867+ response.status()
1868+ ));
1869+ }
1870+ let bytes = response.bytes().await?;
1871+ let expected_bytes = deployment
1872+ .manifest
1873+ .modules
1874+ .iter()
1875+ .find(|reference| reference.name == module.name)
1876+ .expect("managed module envelope validated above")
1877+ .bytes;
1878+ if bytes.len() != expected_bytes {
1879+ return Err(anyhow!("module {} size mismatch", module.name));
1880+ }
1881+ let hash = format!("{:x}", Sha256::digest(&bytes));
1882+ if hash != module.sha256 {
1883+ return Err(anyhow!("module {} checksum mismatch", module.name));
1884+ }
1885+ put_bucket_object(
1886+ s3,
1887+ bucket,
1888+ &format!("{}/{}", deployment.pointer.prefix, module.name),
1889+ bytes.to_vec(),
1890+ )
1891+ .await?;
1892+ }
1893+ put_bucket_object(
1894+ s3,
1895+ bucket,
1896+ &format!("{}/manifest.json", deployment.pointer.prefix),
1897+ serde_json::to_vec_pretty(&deployment.manifest)?,
1898+ )
1899+ .await?;
1900+ put_bucket_object(
1901+ s3,
1902+ bucket,
1903+ &format!("deploy/{}/current.json", deployment.script_name),
1904+ serde_json::to_vec_pretty(&deployment.pointer)?,
1905+ )
1906+ .await?;
1907+ // This fleet-wide pointer is the sole application selector. The named
1908+ // pointer above remains only for resolving service-binding components and
1909+ // for migrating buckets written by older celld releases.
1910+ put_bucket_object(
1911+ s3,
1912+ bucket,
1913+ "deploy/current.json",
1914+ serde_json::to_vec_pretty(&deployment.pointer)?,
1915+ )
1916+ .await?;
1917+ info!(
1918+ event = "control_plane_deployment_applied",
1919+ script_name = %deployment.script_name,
1920+ version = %deployment.version,
1921+ modules = deployment.modules.len(),
1922+ asset_files,
1923+ asset_bytes,
1924+ asset_blobs,
1925+ bucket,
1926+ "deployment artifacts written to fleet bucket"
1927+ );
1928+ Ok(())
1929+}
1930+
1931+fn validate_managed_module_envelope(deployment: &AgentDeployment) -> anyhow::Result<()> {
1932+ let expected_prefix = format!("deploy/{}/{}", deployment.script_name, deployment.version);
1933+ if deployment.pointer.script_name.as_deref() != Some(deployment.script_name.as_str())
1934+ || deployment.pointer.prefix != expected_prefix
1935+ || deployment.pointer.rollout.percent != 100
1936+ {
1937+ return Err(anyhow!(
1938+ "control-plane deployment pointer is inconsistent with its identity"
1939+ ));
1940+ }
1941+ let expected_schema = if deployment.manifest.assets.is_some() {
1942+ 2
1943+ } else {
1944+ 1
1945+ };
1946+ if deployment.manifest.schema_version != expected_schema {
1947+ return Err(anyhow!(
1948+ "control-plane manifest schema does not match its features"
1949+ ));
1950+ }
1951+ if deployment.manifest.modules.len() > MAX_MANAGED_MODULES
1952+ || deployment.modules.len() > MAX_MANAGED_MODULES
1953+ {
1954+ return Err(anyhow!("control-plane deployment has too many modules"));
1955+ }
1956+
1957+ let mut manifest_modules = std::collections::BTreeMap::new();
1958+ let mut total_bytes = 0_usize;
1959+ for module in &deployment.manifest.modules {
1960+ if !valid_managed_module_name(&module.name) || !valid_lower_hex(&module.sha256, 16) {
1961+ return Err(anyhow!(
1962+ "control-plane manifest has an invalid module reference: {:?}",
1963+ module.name
1964+ ));
1965+ }
1966+ total_bytes = total_bytes
1967+ .checked_add(module.bytes)
1968+ .filter(|bytes| *bytes <= MAX_MANAGED_MODULE_BYTES)
1969+ .ok_or_else(|| anyhow!("control-plane deployment modules are too large"))?;
1970+ if manifest_modules
1971+ .insert(module.name.as_str(), module)
1972+ .is_some()
1973+ {
1974+ return Err(anyhow!(
1975+ "control-plane manifest repeats module {:?}",
1976+ module.name
1977+ ));
1978+ }
1979+ }
1980+ match deployment.manifest.main_module.as_deref() {
1981+ Some(main) if !manifest_modules.contains_key(main) => {
1982+ return Err(anyhow!(
1983+ "control-plane manifest main module is not in its module list"
1984+ ));
1985+ }
1986+ None if deployment.manifest.assets.is_none() => {
1987+ return Err(anyhow!(
1988+ "control-plane manifest has neither a main module nor assets"
1989+ ));
1990+ }
1991+ _ => {}
1992+ }
1993+
1994+ let mut transport_modules = std::collections::BTreeMap::new();
1995+ for module in &deployment.modules {
1996+ if !valid_managed_module_name(&module.name) || !valid_lower_hex(&module.sha256, 64) {
1997+ return Err(anyhow!(
1998+ "control-plane transport has an invalid module reference: {:?}",
1999+ module.name
2000+ ));
2001+ }
2002+ if transport_modules
2003+ .insert(module.name.as_str(), module)
2004+ .is_some()
2005+ {
2006+ return Err(anyhow!(
2007+ "control-plane transport repeats module {:?}",
2008+ module.name
2009+ ));
2010+ }
2011+ }
2012+ if manifest_modules.keys().ne(transport_modules.keys()) {
2013+ return Err(anyhow!(
2014+ "control-plane transport modules do not match the manifest"
2015+ ));
2016+ }
2017+ for (name, manifest) in manifest_modules {
2018+ let transport = transport_modules
2019+ .get(name)
2020+ .expect("module name sets compared above");
2021+ if !transport.sha256.starts_with(&manifest.sha256) {
2022+ return Err(anyhow!(
2023+ "control-plane transport checksum does not match manifest module {name:?}"
2024+ ));
2025+ }
2026+ }
2027+ Ok(())
2028+}
2029+
2030+fn valid_managed_module_name(name: &str) -> bool {
2031+ !name.is_empty()
2032+ && name.len() <= 240
2033+ && !name.starts_with('/')
2034+ && !name.contains('\\')
2035+ && name
2036+ .split('/')
2037+ .all(|segment| !segment.is_empty() && segment != "." && segment != "..")
2038+}
2039+
2040+fn valid_lower_hex(value: &str, length: usize) -> bool {
2041+ value.len() == length
2042+ && value
2043+ .bytes()
2044+ .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2045+}
2046+
2047+fn validate_managed_class_migrations(manifest: &Manifest) -> anyhow::Result<()> {
2048+ let do_classes = manifest
2049+ .do_classes
2050+ .iter()
2051+ .map(|class| {
2052+ if class.is_empty() {
2053+ Err(anyhow!(
2054+ "managed manifest has an empty Durable Object class"
2055+ ))
2056+ } else {
2057+ Ok(class.as_str())
2058+ }
2059+ })
2060+ .collect::<anyhow::Result<std::collections::BTreeSet<_>>>()?;
2061+ let mut declared_sqlite = std::collections::BTreeSet::new();
2062+ for class in &manifest.sqlite_classes {
2063+ if class.is_empty() {
2064+ return Err(anyhow!("managed manifest has an empty SQLite class"));
2065+ }
2066+ if !do_classes.contains(class.as_str()) {
2067+ return Err(anyhow!(
2068+ "managed manifest SQLite class {class:?} is not a Durable Object class"
2069+ ));
2070+ }
2071+ if !declared_sqlite.insert(class.as_str()) {
2072+ return Err(anyhow!(
2073+ "managed manifest declares SQLite class {class:?} more than once"
2074+ ));
2075+ }
2076+ }
2077+
2078+ let metadata = manifest
2079+ .raw_metadata
2080+ .as_object()
2081+ .context("managed manifest raw_metadata must be an object")?;
2082+ let Some(migrations) = metadata.get("migrations") else {
2083+ if declared_sqlite.is_empty() {
2084+ return Ok(());
2085+ }
2086+ return Err(anyhow!(
2087+ "managed manifest SQLite classes do not match its migration metadata"
2088+ ));
2089+ };
2090+ let migrations = migrations
2091+ .as_object()
2092+ .context("managed manifest migrations must be an object")?;
2093+ let unsupported = migrations
2094+ .keys()
2095+ .filter(|key| !matches!(key.as_str(), "old_tag" | "new_tag" | "steps"))
2096+ .cloned()
2097+ .collect::<Vec<_>>();
2098+ if !unsupported.is_empty() {
2099+ return Err(anyhow!(
2100+ "unsupported managed migration keys: {}. Class rename, delete, transfer, and non-SQLite migration semantics need an explicit persisted-state contract before deployment",
2101+ unsupported.join(", ")
2102+ ));
2103+ }
2104+ for tag in ["old_tag", "new_tag"] {
2105+ if let Some(value) = migrations.get(tag) {
2106+ if !value.is_null() && !value.as_str().is_some_and(|value| !value.is_empty()) {
2107+ return Err(anyhow!(
2108+ "managed manifest migrations.{tag} must be null or a non-empty string"
2109+ ));
2110+ }
2111+ }
2112+ }
2113+ let steps = migrations
2114+ .get("steps")
2115+ .and_then(serde_json::Value::as_array)
2116+ .context("managed manifest migrations.steps must be an array")?;
2117+ let mut migrated_sqlite = std::collections::BTreeSet::new();
2118+ for (index, step) in steps.iter().enumerate() {
2119+ let step = step.as_object().with_context(|| {
2120+ format!("managed manifest migrations.steps[{index}] must be an object")
2121+ })?;
2122+ let unsupported = step
2123+ .keys()
2124+ .filter(|key| key.as_str() != "new_sqlite_classes")
2125+ .cloned()
2126+ .collect::<Vec<_>>();
2127+ if !unsupported.is_empty() {
2128+ return Err(anyhow!(
2129+ "unsupported managed migration keys: {}. Class rename, delete, transfer, and non-SQLite migration semantics need an explicit persisted-state contract before deployment",
2130+ unsupported.join(", ")
2131+ ));
2132+ }
2133+ let classes = step
2134+ .get("new_sqlite_classes")
2135+ .and_then(serde_json::Value::as_array)
2136+ .with_context(|| {
2137+ format!(
2138+ "managed manifest migrations.steps[{index}].new_sqlite_classes must be an array"
2139+ )
2140+ })?;
2141+ for (class_index, class) in classes.iter().enumerate() {
2142+ let class = class.as_str().filter(|class| !class.is_empty()).with_context(|| {
2143+ format!(
2144+ "managed manifest migrations.steps[{index}].new_sqlite_classes[{class_index}] must be a non-empty string"
2145+ )
2146+ })?;
2147+ if !migrated_sqlite.insert(class) {
2148+ return Err(anyhow!(
2149+ "managed migration introduces SQLite class {class:?} more than once"
2150+ ));
2151+ }
2152+ }
2153+ }
2154+ if migrated_sqlite != declared_sqlite {
2155+ return Err(anyhow!(
2156+ "managed manifest SQLite classes do not match its migration metadata"
2157+ ));
2158+ }
2159+ Ok(())
2160+}
2161+
2162+fn validate_asset_index_entry(path: &str, sha256: &str, bytes: u64) -> anyhow::Result<()> {
2163+ if !path.starts_with('/')
2164+ || path.len() > 1024
2165+ || path.contains('\\')
2166+ || path.contains('\0')
2167+ || path
2168+ .split('/')
2169+ .skip(1)
2170+ .any(|segment| segment.is_empty() || segment == "." || segment == "..")
2171+ {
2172+ return Err(anyhow!("invalid asset path in index: {path:?}"));
2173+ }
2174+ if asset_blob_key(sha256).is_none() {
2175+ return Err(anyhow!("invalid asset digest in index: {sha256:?}"));
2176+ }
2177+ if bytes > 25 * 1024 * 1024 {
2178+ return Err(anyhow!("asset exceeds runtime size limit: {path:?}"));
2179+ }
2180+ Ok(())
2181+}
2182+
2183+async fn put_asset_object(
2184+ s3: &S3Client,
2185+ bucket: &str,
2186+ key: &str,
2187+ sha256: &str,
2188+ body: Vec<u8>,
2189+) -> anyhow::Result<()> {
2190+ s3.put_object()
2191+ .bucket(bucket)
2192+ .key(key)
2193+ .metadata("sha256", sha256)
2194+ .body(ByteStream::from(body))
2195+ .send()
2196+ .await
2197+ .with_context(|| format!("write s3://{bucket}/{key}"))?;
2198+ Ok(())
2199+}
2200+
2201+async fn put_bucket_object(
2202+ s3: &S3Client,
2203+ bucket: &str,
2204+ key: &str,
2205+ body: Vec<u8>,
2206+) -> anyhow::Result<()> {
2207+ s3.put_object()
2208+ .bucket(bucket)
2209+ .key(key)
2210+ .body(ByteStream::from(body))
2211+ .send()
2212+ .await
2213+ .with_context(|| format!("write s3://{bucket}/{key}"))?;
2214+ Ok(())
2215+}
2216+
2217+async fn connect(options: ConnectOptions, wait: bool) -> anyhow::Result<()> {
2218+ let path = config_path()?;
2219+ connect_at_path(path, options, wait).await
2220+}
2221+
2222+async fn connect_at_path(path: PathBuf, options: ConnectOptions, wait: bool) -> anyhow::Result<()> {
2223+ let _lock = match try_acquire_enrollment_lock(&path).await? {
2224+ Some(lock) => lock,
2225+ None => wait_for_shared_enrollment(&path).await?,
2226+ };
2227+ let mut config = load_or_create_config(&path, &options)?;
2228+ let enrollment_byo = match (
2229+ config.storage.as_ref(),
2230+ config.byo_storage.as_ref(),
2231+ options.byo_storage.as_ref(),
2232+ ) {
2233+ (Some(_), None, Some(_)) => {
2234+ return Err(anyhow!(
2235+ "this installation is enrolled with managed storage; disconnect before changing storage origin"
2236+ ));
2237+ }
2238+ (None, Some(current), Some(requested)) if current != requested => {
2239+ return Err(anyhow!(
2240+ "the requested BYO bucket does not match this installation enrollment"
2241+ ));
2242+ }
2243+ (None, Some(current), _) => Some(current.clone()),
2244+ (None, None, requested) => requested.cloned(),
2245+ (Some(_), None, None) => None,
2246+ _ => {
2247+ return Err(anyhow!(
2248+ "managed installation record contains an invalid storage target"
2249+ ));
2250+ }
2251+ };
2252+ if config.installation_token.is_some()
2253+ && (config.storage.is_some() || config.byo_storage.is_some())
2254+ && !options.force
2255+ {
2256+ validate_requested_storage(&config, options.byo_storage.as_ref())?;
2257+ retry_credential_handoff_ack(path.clone(), config.clone());
2258+ info!(
2259+ event = "control_plane_already_connected",
2260+ installation_id = %config.installation_id,
2261+ environment = %config.environment,
2262+ control_url = %config.control_url,
2263+ "celld is already connected to the Managed Control Plane"
2264+ );
2265+ return Ok(());
2266+ }
2267+
2268+ config.control_url = normalized_control_url(&options.control_url)?;
2269+ config.environment = options.environment.clone();
2270+ config.installation_token = None;
2271+ config.fleet_id = None;
2272+ config.environment_id = None;
2273+ config.credential_handoff_id = None;
2274+ config.pending_claim = None;
2275+ config.storage = None;
2276+ config.byo_storage = enrollment_byo;
2277+ save_config(&path, &config)?;
2278+
2279+ let client = reqwest::Client::builder()
2280+ .timeout(Duration::from_secs(if wait { 15 } else { 3 }))
2281+ .build()?;
2282+ let claim_url = format!("{}/api/instances/claims", config.control_url);
2283+ let instance_name = instance_name();
2284+ let response = client
2285+ .post(claim_url)
2286+ .json(&CreateClaimRequest {
2287+ instance_id: &config.installation_id,
2288+ instance_name: &instance_name,
2289+ environment: &config.environment,
2290+ version: env!("CARGO_PKG_VERSION"),
2291+ platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
2292+ storage_origin: if config.byo_storage.is_some() {
2293+ "byo"
2294+ } else {
2295+ "managed_r2"
2296+ },
2297+ bucket: config
2298+ .byo_storage
2299+ .as_ref()
2300+ .map(|storage| storage.bucket.as_str()),
2301+ endpoint: config
2302+ .byo_storage
2303+ .as_ref()
2304+ .and_then(|storage| storage.endpoint.as_deref()),
2305+ region: config
2306+ .byo_storage
2307+ .as_ref()
2308+ .map(|storage| storage.region.as_str()),
2309+ })
2310+ .send()
2311+ .await
2312+ .context("request activation link")?;
2313+ if !response.status().is_success() {
2314+ let status = response.status();
2315+ let body = response.text().await.unwrap_or_default();
2316+ return Err(anyhow!("activation endpoint returned {status}: {body}"));
2317+ }
2318+ let claim: CreateClaimResponse = response.json().await.context("decode activation link")?;
2319+ config.pending_claim = Some(PendingClaim {
2320+ verification_uri_complete: claim.verification_uri_complete.clone(),
2321+ expires_at_ms: current_time_ms().saturating_add(claim.expires_in.saturating_mul(1000)),
2322+ });
2323+ save_config(&path, &config)?;
2324+
2325+ info!(
2326+ event = "control_plane_claim_pending",
2327+ installation_id = %config.installation_id,
2328+ environment = %config.environment,
2329+ verification_url = %claim.verification_uri_complete,
2330+ expires_in_seconds = claim.expires_in,
2331+ "authenticate to connect this celld instance"
2332+ );
2333+ println!(
2334+ "\nConnect this celld instance to the Managed Control Plane:\n\n {}\n\nEnvironment: {}\n",
2335+ claim.verification_uri_complete, config.environment
2336+ );
2337+
2338+ if wait {
2339+ wait_for_approval(client, path, config, claim).await
2340+ } else {
2341+ tokio::spawn(async move {
2342+ if let Err(error) = wait_for_approval(client, path, config, claim).await {
2343+ warn!(event = "control_plane_claim_failed", %error);
2344+ }
2345+ });
2346+ Ok(())
2347+ }
2348+}
2349+
2350+async fn wait_for_approval(
2351+ client: reqwest::Client,
2352+ path: PathBuf,
2353+ mut config: CloudConfig,
2354+ claim: CreateClaimResponse,
2355+) -> anyhow::Result<()> {
2356+ let deadline = Instant::now() + Duration::from_secs(claim.expires_in);
2357+ let poll_url = format!("{}/api/instances/claims/token", config.control_url);
2358+ let mut interval = claim.interval.max(1);
2359+ while Instant::now() < deadline {
2360+ tokio::time::sleep(Duration::from_secs(interval)).await;
2361+ let response = client
2362+ .post(&poll_url)
2363+ .json(&PollClaimRequest {
2364+ device_code: &claim.device_code,
2365+ })
2366+ .send()
2367+ .await
2368+ .context("poll activation")?;
2369+ if response.status() == reqwest::StatusCode::GONE {
2370+ return Err(anyhow!("activation link expired"));
2371+ }
2372+ if !response.status().is_success() {
2373+ let status = response.status();
2374+ let body = response.text().await.unwrap_or_default();
2375+ return Err(anyhow!("activation poll returned {status}: {body}"));
2376+ }
2377+ let result: PollClaimResponse =
2378+ response.json().await.context("decode activation status")?;
2379+ if result.status == "pending" {
2380+ interval = result.interval.unwrap_or(interval).max(1);
2381+ continue;
2382+ }
2383+ if result.status != "connected" {
2384+ return Err(anyhow!("unexpected activation status: {}", result.status));
2385+ }
2386+ config.installation_token = Some(
2387+ result
2388+ .instance_token
2389+ .context("activation response omitted instance token")?,
2390+ );
2391+ config.credential_version = result.credential_version.unwrap_or(1);
2392+ config.fleet_id = Some(
2393+ result
2394+ .fleet_id
2395+ .context("activation response omitted fleet")?,
2396+ );
2397+ config.environment_id = Some(
2398+ result
2399+ .environment_id
2400+ .context("activation response omitted environment")?,
2401+ );
2402+ let bucket = result
2403+ .bucket
2404+ .context("activation response omitted bucket")?;
2405+ let region = result
2406+ .region
2407+ .context("activation response omitted bucket region")?;
2408+ match result.storage_origin.as_str() {
2409+ "managed_r2" => {
2410+ if config.byo_storage.is_some() {
2411+ return Err(anyhow!(
2412+ "activation changed the requested BYO bucket to managed storage"
2413+ ));
2414+ }
2415+ config.storage = Some(ManagedStorageConfig {
2416+ bucket,
2417+ endpoint: result
2418+ .endpoint
2419+ .context("activation response omitted bucket endpoint")?,
2420+ region,
2421+ access_key_id: result
2422+ .access_key_id
2423+ .context("activation response omitted storage access key")?,
2424+ secret_access_key: result
2425+ .secret_access_key
2426+ .context("activation response omitted storage secret key")?,
2427+ session_token: result.session_token,
2428+ });
2429+ config.credential_handoff_id = Some(
2430+ result
2431+ .credential_handoff_id
2432+ .context("activation response omitted credential handoff")?,
2433+ );
2434+ }
2435+ "byo" => {
2436+ let storage = ByoStorageConfig {
2437+ bucket,
2438+ endpoint: result.endpoint,
2439+ region,
2440+ };
2441+ if config.byo_storage.as_ref() != Some(&storage) {
2442+ return Err(anyhow!(
2443+ "activation returned a different BYO storage target"
2444+ ));
2445+ }
2446+ if result.credential_handoff_id.is_some()
2447+ || result.access_key_id.is_some()
2448+ || result.secret_access_key.is_some()
2449+ || result.session_token.is_some()
2450+ {
2451+ return Err(anyhow!(
2452+ "activation returned managed credentials for a BYO bucket"
2453+ ));
2454+ }
2455+ config.storage = None;
2456+ config.byo_storage = Some(storage);
2457+ config.credential_handoff_id = None;
2458+ }
2459+ origin => {
2460+ return Err(anyhow!(
2461+ "activation returned unknown storage origin: {origin}"
2462+ ))
2463+ }
2464+ }
2465+ config.pending_claim = None;
2466+ save_config(&path, &config)?;
2467+ if let Some(handoff_id) = config.credential_handoff_id.clone() {
2468+ match acknowledge_credential_handoff(&client, &config, &handoff_id).await {
2469+ Ok(()) => {
2470+ config.credential_handoff_id = None;
2471+ save_config(&path, &config)?;
2472+ }
2473+ Err(error) => {
2474+ info!(
2475+ event = "control_plane_credential_ack_deferred",
2476+ %error,
2477+ "managed credential is saved; delivery acknowledgement will retry in the background"
2478+ );
2479+ retry_credential_handoff_ack(path.clone(), config.clone());
2480+ }
2481+ }
2482+ }
2483+ info!(
2484+ event = "control_plane_connected",
2485+ installation_id = %config.installation_id,
2486+ fleet_id = %config.fleet_id.as_deref().unwrap_or_default(),
2487+ environment_id = %config.environment_id.as_deref().unwrap_or_default(),
2488+ environment = %config.environment,
2489+ "celld connected to the Managed Control Plane"
2490+ );
2491+ println!(
2492+ "Connected to the Managed Control Plane ({}).\n\
2493+ Keep celld running. In your app directory, run `celld token`, apply the \
2494+ exports it prints, then run `npx wrangler@4 deploy`.",
2495+ config.environment
2496+ );
2497+ return Ok(());
2498+ }
2499+ // Make expiry visible so an unattended process cannot keep displaying a
2500+ // dead approval URL.
2501+ println!(
2502+ "\nThe activation link expired before it was approved.\n\
2503+ Restart celld to get a new one.\n"
2504+ );
2505+ Err(anyhow!(
2506+ "activation link expired before approval; restart celld for a new link"
2507+ ))
2508+}
2509+
2510+fn options_from_env() -> anyhow::Result<ConnectOptions> {
2511+ Ok(ConnectOptions {
2512+ control_url: std::env::var("CELLD_CONTROL_URL")
2513+ .unwrap_or_else(|_| DEFAULT_CONTROL_URL.to_string()),
2514+ environment: std::env::var("CELLD_ENV").unwrap_or_else(|_| DEFAULT_ENVIRONMENT.to_string()),
2515+ force: false,
2516+ byo_storage: None,
2517+ })
2518+}
2519+
2520+fn config_path() -> anyhow::Result<PathBuf> {
2521+ let base = if let Some(path) = std::env::var_os("CELLD_CONFIG_DIR") {
2522+ PathBuf::from(path)
2523+ } else if let Some(path) = std::env::var_os("XDG_CONFIG_HOME") {
2524+ PathBuf::from(path).join("celld")
2525+ } else if let Some(path) = std::env::var_os("HOME") {
2526+ PathBuf::from(path).join(".config").join("celld")
2527+ } else {
2528+ std::env::current_dir()?.join(".celld")
2529+ };
2530+ Ok(base.join("cloud.json"))
2531+}
2532+
2533+fn load_or_create_config(path: &Path, options: &ConnectOptions) -> anyhow::Result<CloudConfig> {
2534+ if path.exists() {
2535+ let contents =
2536+ std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2537+ return serde_json::from_str(&contents)
2538+ .with_context(|| format!("decode {}", path.display()));
2539+ }
2540+ let config = CloudConfig {
2541+ version: installation_schema_version(),
2542+ installation_id: random_instance_id(),
2543+ installation_token: None,
2544+ credential_version: initial_credential_version(),
2545+ fleet_id: None,
2546+ environment_id: None,
2547+ control_url: normalized_control_url(&options.control_url)?,
2548+ environment: options.environment.clone(),
2549+ storage: None,
2550+ byo_storage: None,
2551+ credential_handoff_id: None,
2552+ previous_credential: None,
2553+ pending_claim: None,
2554+ };
2555+ save_config(path, &config)?;
2556+ Ok(config)
2557+}
2558+
2559+fn retry_credential_handoff_ack(path: PathBuf, config: CloudConfig) {
2560+ let Some(handoff_id) = config.credential_handoff_id.clone() else {
2561+ return;
2562+ };
2563+ tokio::spawn(async move {
2564+ let client = match reqwest::Client::builder()
2565+ .timeout(Duration::from_secs(5))
2566+ .build()
2567+ {
2568+ Ok(client) => client,
2569+ Err(_) => return,
2570+ };
2571+ if acknowledge_credential_handoff(&client, &config, &handoff_id)
2572+ .await
2573+ .is_err()
2574+ {
2575+ return;
2576+ }
2577+ let Ok(_lock) = acquire_enrollment_lock(&path).await else {
2578+ return;
2579+ };
2580+ let Ok(contents) = std::fs::read_to_string(&path) else {
2581+ return;
2582+ };
2583+ let Ok(mut current) = serde_json::from_str::<CloudConfig>(&contents) else {
2584+ return;
2585+ };
2586+ if current.credential_handoff_id.as_deref() != Some(&handoff_id) {
2587+ return;
2588+ }
2589+ current.credential_handoff_id = None;
2590+ current.previous_credential = None;
2591+ if let Err(error) = save_config(&path, &current) {
2592+ warn!(
2593+ event = "control_plane_credential_ack_save_failed",
2594+ %error,
2595+ "credential delivery was acknowledged but the local marker could not be cleared"
2596+ );
2597+ }
2598+ });
2599+}
2600+
2601+async fn acknowledge_credential_handoff(
2602+ client: &reqwest::Client,
2603+ config: &CloudConfig,
2604+ handoff_id: &str,
2605+) -> anyhow::Result<()> {
2606+ let token = config
2607+ .installation_token
2608+ .as_deref()
2609+ .context("managed installation has no token")?;
2610+ let response = client
2611+ .post(format!("{}/api/agent/credentials/ack", config.control_url))
2612+ .bearer_auth(token)
2613+ .json(&serde_json::json!({ "handoff_id": handoff_id }))
2614+ .send()
2615+ .await
2616+ .context("acknowledge managed credential delivery")?;
2617+ if !response.status().is_success() {
2618+ return Err(anyhow!(
2619+ "credential acknowledgement returned {}",
2620+ response.status()
2621+ ));
2622+ }
2623+ Ok(())
2624+}
2625+
2626+fn save_config(path: &Path, config: &CloudConfig) -> anyhow::Result<()> {
2627+ let parent = path
2628+ .parent()
2629+ .context("cloud config has no parent directory")?;
2630+ std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
2631+ let temporary = path.with_extension("json.tmp");
2632+ std::fs::write(&temporary, serde_json::to_vec_pretty(config)?)
2633+ .with_context(|| format!("write {}", temporary.display()))?;
2634+ restrict_permissions(&temporary)?;
2635+ std::fs::rename(&temporary, path).with_context(|| format!("replace {}", path.display()))?;
2636+ Ok(())
2637+}
2638+
2639+#[cfg(unix)]
2640+fn restrict_permissions(path: &Path) -> anyhow::Result<()> {
2641+ use std::os::unix::fs::PermissionsExt;
2642+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
2643+ Ok(())
2644+}
2645+
2646+#[cfg(not(unix))]
2647+fn restrict_permissions(_path: &Path) -> anyhow::Result<()> {
2648+ Ok(())
2649+}
2650+
2651+fn random_instance_id() -> String {
2652+ let mut bytes = [0_u8; 16];
2653+ rand::rngs::OsRng.fill_bytes(&mut bytes);
2654+ let suffix = bytes
2655+ .iter()
2656+ .map(|byte| format!("{byte:02x}"))
2657+ .collect::<String>();
2658+ format!("inst_{suffix}")
2659+}
2660+
2661+fn installation_schema_version() -> u32 {
2662+ 1
2663+}
2664+
2665+fn initial_credential_version() -> u64 {
2666+ 1
2667+}
2668+
2669+fn managed_storage_origin() -> String {
2670+ "managed_r2".to_string()
2671+}
2672+
2673+fn validate_requested_storage(
2674+ config: &CloudConfig,
2675+ requested: Option<&ByoStorageConfig>,
2676+) -> anyhow::Result<()> {
2677+ match (config.storage.as_ref(), config.byo_storage.as_ref(), requested) {
2678+ (Some(_), None, None) | (None, Some(_), None) => Ok(()),
2679+ (Some(_), None, Some(_)) => Err(anyhow!(
2680+ "this installation is enrolled with managed storage; disconnect before changing storage origin"
2681+ )),
2682+ (None, Some(current), Some(requested)) if current == requested => Ok(()),
2683+ (None, Some(_), Some(_)) => Err(anyhow!(
2684+ "the requested BYO bucket does not match this installation enrollment"
2685+ )),
2686+ _ => Err(anyhow!(
2687+ "managed installation record contains an invalid storage target"
2688+ )),
2689+ }
2690+}
2691+
2692+struct EnrollmentLock {
2693+ _file: File,
2694+}
2695+
2696+async fn try_acquire_enrollment_lock(config: &Path) -> anyhow::Result<Option<EnrollmentLock>> {
2697+ let (file, lock_path) = open_enrollment_lock(config).await?;
2698+ tokio::task::spawn_blocking(move || match fs2::FileExt::try_lock_exclusive(&file) {
2699+ Ok(()) => Ok(Some(EnrollmentLock { _file: file })),
2700+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(None),
2701+ Err(error) => Err(error).with_context(|| format!("lock {}", lock_path.display())),
2702+ })
2703+ .await
2704+ .context("join enrollment try-lock task")?
2705+}
2706+
2707+async fn acquire_enrollment_lock(config: &Path) -> anyhow::Result<EnrollmentLock> {
2708+ let (file, lock_path) = open_enrollment_lock(config).await?;
2709+ tokio::task::spawn_blocking(move || {
2710+ fs2::FileExt::lock_exclusive(&file)
2711+ .with_context(|| format!("lock {}", lock_path.display()))?;
2712+ Ok(EnrollmentLock { _file: file })
2713+ })
2714+ .await
2715+ .context("join enrollment lock task")?
2716+}
2717+
2718+async fn open_enrollment_lock(config: &Path) -> anyhow::Result<(File, PathBuf)> {
2719+ let lock_path = config.with_extension("lock");
2720+ let parent = lock_path
2721+ .parent()
2722+ .context("managed installation lock has no parent directory")?
2723+ .to_path_buf();
2724+ tokio::task::spawn_blocking(move || {
2725+ std::fs::create_dir_all(&parent).with_context(|| format!("create {}", parent.display()))?;
2726+ let file = File::options()
2727+ .read(true)
2728+ .write(true)
2729+ .create(true)
2730+ .truncate(false)
2731+ .open(&lock_path)
2732+ .with_context(|| format!("open {}", lock_path.display()))?;
2733+ Ok((file, lock_path))
2734+ })
2735+ .await
2736+ .context("join enrollment lock open task")?
2737+}
2738+
2739+async fn wait_for_shared_enrollment(path: &Path) -> anyhow::Result<EnrollmentLock> {
2740+ loop {
2741+ if let Ok(contents) = std::fs::read_to_string(path) {
2742+ if let Ok(config) = serde_json::from_str::<CloudConfig>(&contents) {
2743+ if config.installation_token.is_some()
2744+ && (config.storage.is_some() || config.byo_storage.is_some())
2745+ {
2746+ return acquire_enrollment_lock(path).await;
2747+ }
2748+ if let Some(pending) = config.pending_claim {
2749+ if pending.expires_at_ms > current_time_ms() {
2750+ println!(
2751+ "\nConnect this celld installation to the Managed Control Plane:\n\n {}\n\nEnvironment: {}\n",
2752+ pending.verification_uri_complete, config.environment
2753+ );
2754+ return acquire_enrollment_lock(path).await;
2755+ }
2756+ }
2757+ }
2758+ }
2759+ if let Some(lock) = try_acquire_enrollment_lock(path).await? {
2760+ return Ok(lock);
2761+ }
2762+ tokio::time::sleep(Duration::from_millis(100)).await;
2763+ }
2764+}
2765+
2766+fn current_time_ms() -> u64 {
2767+ std::time::SystemTime::now()
2768+ .duration_since(std::time::UNIX_EPOCH)
2769+ .unwrap_or_default()
2770+ .as_millis() as u64
2771+}
2772+
2773+fn normalized_control_url(value: &str) -> anyhow::Result<String> {
2774+ let value = value.trim_end_matches('/');
2775+ let url = url::Url::parse(value).context("invalid control plane URL")?;
2776+ if url.scheme() != "https"
2777+ && !(url.scheme() == "http" && matches!(url.host_str(), Some("localhost" | "127.0.0.1")))
2778+ {
2779+ return Err(anyhow!("control plane URL must use HTTPS"));
2780+ }
2781+ if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
2782+ return Err(anyhow!(
2783+ "control plane URL must not contain a path, query, or fragment"
2784+ ));
2785+ }
2786+ Ok(value.to_string())
2787+}
2788+
2789+fn validate_environment(value: &str) -> anyhow::Result<()> {
2790+ if value.is_empty() || value.len() > 32 {
2791+ return Err(anyhow!("environment must be 1–32 characters"));
2792+ }
2793+ let mut characters = value.chars();
2794+ if !characters
2795+ .next()
2796+ .is_some_and(|character| character.is_ascii_lowercase())
2797+ || !characters.all(|character| {
2798+ character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-'
2799+ })
2800+ {
2801+ return Err(anyhow!(
2802+ "environment must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens"
2803+ ));
2804+ }
2805+ Ok(())
2806+}
2807+
2808+fn instance_name() -> String {
2809+ std::env::var("CELLD_INSTANCE_NAME").unwrap_or_else(|_| machine_hostname())
2810+}
2811+
2812+fn machine_hostname() -> String {
2813+ std::env::var("HOSTNAME")
2814+ .or_else(|_| std::env::var("COMPUTERNAME"))
2815+ .ok()
2816+ .or_else(|| {
2817+ std::process::Command::new("hostname")
2818+ .output()
2819+ .ok()
2820+ .filter(|output| output.status.success())
2821+ .and_then(|output| String::from_utf8(output.stdout).ok())
2822+ })
2823+ .map(|value| value.trim().to_string())
2824+ .filter(|value| {
2825+ !value.is_empty()
2826+ && value.len() <= 100
2827+ && value.is_ascii()
2828+ && !value.chars().any(char::is_control)
2829+ })
2830+ .unwrap_or_else(|| "celld".to_string())
2831+}
2832+
2833+fn print_connect_help() {
2834+ println!(
2835+ "Connect this celld installation to the Managed Control Plane.\n\nUSAGE:\n celld connect [--env prod] [--control-url https://celld.dev] [--force]"
2836+ );
2837+}
2838+
2839+fn print_credentials_help() {
2840+ println!(
2841+ "Refresh a staged Managed Control Plane credential.\n\nUSAGE:\n celld credentials refresh\n\nRunning celld processes sharing this installation automatically reload after the replacement is saved. Unix processes re-exec; other platforms exit 75 for their supervisor."
2842+ );
2843+}
2844+
2845+fn print_disconnect_help() {
2846+ println!(
2847+ "Revoke and disconnect this Managed Control Plane installation.\n\nUSAGE:\n celld disconnect --yes\n\nStop every celld process sharing this installation first. Other installations in the fleet are unaffected."
2848+ );
2849+}
addedcrates/celld/dead_node_gc.rs+387−0View file
@@ -1,0 +1,387 @@
1+//! Compatibility garbage collection for dead celld process generations.
2+//!
3+//! Wake entries and lazy ownership takeover provide serving correctness.
4+//! This adapter retires the historical `node-cells/` index debris and expired
5+//! node-session records left in fleet buckets shared with celld.
6+
7+use anyhow::Context as _;
8+use aws_sdk_s3::error::SdkError;
9+use aws_sdk_s3::Client;
10+use futures_util::stream::{self, StreamExt as _};
11+use serde::Deserialize;
12+use std::collections::{HashMap, HashSet};
13+use std::time::{Duration, Instant};
14+use tracing::{info, warn};
15+
16+const MARKER_GC_CONCURRENCY: usize = 64;
17+
18+#[derive(Deserialize)]
19+struct NodeWire {
20+ node: String,
21+ expires_ms: u64,
22+ #[serde(default, rename = "ownership_index_generation")]
23+ generation: String,
24+}
25+
26+#[derive(Clone, Debug)]
27+struct DeadNode {
28+ node: String,
29+ generation: String,
30+}
31+
32+#[derive(Default)]
33+struct IndexedOwnership {
34+ markers: Vec<String>,
35+}
36+
37+#[derive(Default)]
38+struct MarkerGcSummary {
39+ markers: usize,
40+ retired: usize,
41+ failures: usize,
42+}
43+
44+/// Process-local retry state for compatibility GC.
45+///
46+/// Durable marker deletions survive cancellation. `swept` avoids repeating a
47+/// fleet-wide marker scan when only conditional retirement of the node record
48+/// remains, while `retries` bounds a persistently failing marker store.
49+#[derive(Default)]
50+pub struct DeadNodeGc {
51+ swept: HashSet<String>,
52+ retries: HashMap<String, (String, u32, Instant)>,
53+}
54+
55+impl DeadNodeGc {
56+ /// Run one pass while renewing the advisory fleet-waker role. No task is
57+ /// spawned: the caller's existing wake-loop future polls both work and
58+ /// renewal, and dropping a lost-role pass cancels remaining I/O.
59+ pub async fn run_elected_pass(
60+ &mut self,
61+ client: &Client,
62+ bucket: &str,
63+ node: &str,
64+ tick_ms: u64,
65+ ) {
66+ let lease_ttl_ms = tick_ms.saturating_mul(3).min(i64::MAX as u64);
67+ if !crate::wake::try_hold_waker(
68+ client,
69+ bucket,
70+ node,
71+ crate::ownership_store::now_ms() as i64,
72+ lease_ttl_ms as i64,
73+ )
74+ .await
75+ {
76+ return;
77+ }
78+
79+ let renew_ms = (lease_ttl_ms / 3).max(1);
80+ let mut renewal = tokio::time::interval(Duration::from_millis(renew_ms));
81+ renewal.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
82+ renewal.tick().await;
83+ let pass = self.run_pass(client, bucket, tick_ms);
84+ tokio::pin!(pass);
85+ loop {
86+ tokio::select! {
87+ _ = &mut pass => return,
88+ _ = renewal.tick() => {
89+ if !crate::wake::try_hold_waker(
90+ client,
91+ bucket,
92+ node,
93+ crate::ownership_store::now_ms() as i64,
94+ lease_ttl_ms as i64,
95+ ).await {
96+ warn!("waker lease renewal failed; cancelling dead-node GC");
97+ return;
98+ }
99+ }
100+ }
101+ }
102+ }
103+
104+ async fn run_pass(&mut self, client: &Client, bucket: &str, tick_ms: u64) {
105+ let observed_ms = crate::ownership_store::now_ms();
106+ let dead = dead_nodes(client, bucket, observed_ms).await;
107+ let dead_names: HashSet<&str> = dead.iter().map(|record| record.node.as_str()).collect();
108+ self.swept.retain(|node| dead_names.contains(node.as_str()));
109+ self.retries
110+ .retain(|node, _| dead_names.contains(node.as_str()));
111+
112+ let retry_now = Instant::now();
113+ let indexed: HashMap<String, String> = dead
114+ .iter()
115+ .filter(|record| {
116+ !self.swept.contains(&record.node)
117+ && self
118+ .retries
119+ .get(&record.node)
120+ .is_none_or(|(generation, _, retry_at)| {
121+ generation != &record.generation || *retry_at <= retry_now
122+ })
123+ && !record.generation.is_empty()
124+ })
125+ .map(|record| (record.node.clone(), record.generation.clone()))
126+ .collect();
127+
128+ let indexed = if indexed.is_empty() {
129+ Some(HashMap::new())
130+ } else {
131+ match cells_indexed_by_nodes(client, bucket, &indexed).await {
132+ Ok(indexed) => Some(indexed),
133+ Err(error) => {
134+ warn!(%error, nodes = indexed.len(), "dead-node marker scan failed");
135+ None
136+ }
137+ }
138+ };
139+ let mut summaries = match indexed {
140+ Some(indexed) => gc_markers(client, bucket, indexed).await,
141+ None => HashMap::new(),
142+ };
143+
144+ for record in dead {
145+ let node = record.node;
146+ let generation = record.generation;
147+ if !self.swept.contains(&node) {
148+ let (markers, retired, failures, complete) = if generation.is_empty() {
149+ (0, 0, 0, true)
150+ } else {
151+ let Some(summary) = summaries.remove(&node) else {
152+ continue;
153+ };
154+ (
155+ summary.markers,
156+ summary.retired,
157+ summary.failures,
158+ summary.failures == 0,
159+ )
160+ };
161+ info!(
162+ event = "dead_node_reconciliation",
163+ %node,
164+ markers,
165+ retired,
166+ failures,
167+ complete,
168+ "dead-node marker GC complete"
169+ );
170+ if !complete {
171+ let failure_count = self
172+ .retries
173+ .get(&node)
174+ .filter(|(retry_generation, _, _)| retry_generation == &generation)
175+ .map_or(1, |(_, count, _)| count.saturating_add(1));
176+ let retry_ms = celld_logic::dead_node_reconciliation::retry_delay_ms(
177+ tick_ms,
178+ failure_count,
179+ );
180+ self.retries.insert(
181+ node,
182+ (
183+ generation,
184+ failure_count,
185+ Instant::now() + Duration::from_millis(retry_ms),
186+ ),
187+ );
188+ continue;
189+ }
190+ self.retries.remove(&node);
191+ self.swept.insert(node.clone());
192+ }
193+ match retire_dead_node(client, bucket, &node, observed_ms).await {
194+ Ok(_) => {
195+ self.swept.remove(&node);
196+ }
197+ Err(error) => warn!(%node, %error, "dead-node lease retirement failed"),
198+ }
199+ }
200+ }
201+}
202+
203+async fn dead_nodes(client: &Client, bucket: &str, now_ms: u64) -> Vec<DeadNode> {
204+ let mut dead = Vec::new();
205+ let mut token = None;
206+ loop {
207+ let mut request = client.list_objects_v2().bucket(bucket).prefix("nodes/");
208+ if let Some(token) = &token {
209+ request = request.continuation_token(token);
210+ }
211+ let page = match request.send().await {
212+ Ok(page) => page,
213+ Err(error) => {
214+ warn!(%error, "dead-node scan list failed");
215+ break;
216+ }
217+ };
218+ for object in page.contents() {
219+ let Some(key) = object.key() else { continue };
220+ let Some(node) = key
221+ .strip_prefix("nodes/")
222+ .and_then(|value| value.strip_suffix(".json"))
223+ else {
224+ continue;
225+ };
226+ match read_node(client, bucket, key).await {
227+ Ok(Some((record, _)))
228+ if celld_logic::dead_node_reconciliation::node_record_is_dead(
229+ node,
230+ &record.node,
231+ record.expires_ms,
232+ now_ms,
233+ ) =>
234+ {
235+ dead.push(DeadNode {
236+ node: node.to_string(),
237+ generation: record.generation,
238+ });
239+ }
240+ Ok(_) => {}
241+ Err(error) => warn!(%node, %error, "dead-node scan read failed"),
242+ }
243+ }
244+ match page.next_continuation_token() {
245+ Some(next) => token = Some(next.to_string()),
246+ None => break,
247+ }
248+ }
249+ dead
250+}
251+
252+async fn cells_indexed_by_nodes(
253+ client: &Client,
254+ bucket: &str,
255+ nodes: &HashMap<String, String>,
256+) -> anyhow::Result<HashMap<String, IndexedOwnership>> {
257+ let mut indexed: HashMap<String, IndexedOwnership> = nodes
258+ .keys()
259+ .cloned()
260+ .map(|node| (node, IndexedOwnership::default()))
261+ .collect();
262+ let mut token = None;
263+ loop {
264+ let mut request = client
265+ .list_objects_v2()
266+ .bucket(bucket)
267+ .prefix("node-cells/");
268+ if let Some(token) = &token {
269+ request = request.continuation_token(token);
270+ }
271+ let page = request.send().await?;
272+ for object in page.contents() {
273+ let Some(key) = object.key() else { continue };
274+ let Some((node, _)) = celld_logic::dead_node_reconciliation::parse_marker_key(key)
275+ else {
276+ continue;
277+ };
278+ if let Some(entry) = indexed.get_mut(node) {
279+ entry.markers.push(key.to_string());
280+ }
281+ }
282+ match page.next_continuation_token() {
283+ Some(next) => token = Some(next.to_string()),
284+ None => break,
285+ }
286+ }
287+ Ok(indexed)
288+}
289+
290+async fn gc_markers(
291+ client: &Client,
292+ bucket: &str,
293+ indexed: HashMap<String, IndexedOwnership>,
294+) -> HashMap<String, MarkerGcSummary> {
295+ let mut summaries = HashMap::new();
296+ let mut work = Vec::new();
297+ for (node, indexed) in indexed {
298+ summaries
299+ .entry(node.clone())
300+ .or_insert_with(|| MarkerGcSummary {
301+ markers: indexed.markers.len(),
302+ ..MarkerGcSummary::default()
303+ });
304+ for marker in indexed.markers {
305+ work.push((node.clone(), marker));
306+ }
307+ }
308+ let mut results = stream::iter(work)
309+ .map(|(node, marker)| async move {
310+ let result = client
311+ .delete_object()
312+ .bucket(bucket)
313+ .key(marker)
314+ .send()
315+ .await;
316+ (node, result)
317+ })
318+ .buffer_unordered(MARKER_GC_CONCURRENCY);
319+ while let Some((node, result)) = results.next().await {
320+ let summary = summaries.get_mut(&node).expect("work has a summary");
321+ match result {
322+ Ok(_) => summary.retired += 1,
323+ Err(error) => {
324+ if summary.failures == 0 {
325+ warn!(%node, %error, "dead-node marker delete failed");
326+ }
327+ summary.failures += 1;
328+ }
329+ }
330+ }
331+ summaries
332+}
333+
334+async fn retire_dead_node(
335+ client: &Client,
336+ bucket: &str,
337+ node: &str,
338+ now_ms: u64,
339+) -> anyhow::Result<bool> {
340+ let key = format!("nodes/{node}.json");
341+ let Some((record, etag)) = read_node(client, bucket, &key).await? else {
342+ return Ok(true);
343+ };
344+ if !celld_logic::dead_node_reconciliation::node_record_is_dead(
345+ node,
346+ &record.node,
347+ record.expires_ms,
348+ now_ms,
349+ ) {
350+ return Ok(false);
351+ }
352+ match client
353+ .delete_object()
354+ .bucket(bucket)
355+ .key(key)
356+ .if_match(etag)
357+ .send()
358+ .await
359+ {
360+ Ok(_) => Ok(true),
361+ Err(SdkError::ServiceError(error)) if error.raw().status().as_u16() == 412 => Ok(false),
362+ Err(error) => Err(error.into()),
363+ }
364+}
365+
366+async fn read_node(
367+ client: &Client,
368+ bucket: &str,
369+ key: &str,
370+) -> anyhow::Result<Option<(NodeWire, String)>> {
371+ match client.get_object().bucket(bucket).key(key).send().await {
372+ Ok(output) => {
373+ let etag = output.e_tag().unwrap_or_default().to_string();
374+ let bytes = output
375+ .body
376+ .collect()
377+ .await
378+ .with_context(|| format!("read body s3://{bucket}/{key}"))?
379+ .into_bytes();
380+ let record = serde_json::from_slice(&bytes)
381+ .with_context(|| format!("decode s3://{bucket}/{key}"))?;
382+ Ok(Some((record, etag)))
383+ }
384+ Err(SdkError::ServiceError(error)) if error.err().is_no_such_key() => Ok(None),
385+ Err(error) => Err(error.into()),
386+ }
387+}
addedcrates/celld/deploy.rs+1216−0View file
@@ -1,0 +1,1216 @@
1+//! `celld deploy` — build a Wrangler project and write it to the fleet bucket.
2+//!
3+//! Bundling is esbuild's job; this module does config, identity, and durable
4+//! bucket publication. Nothing here shells out to wrangler or speaks a
5+//! Cloudflare-shaped API. Config keys are an allowlist: anything we do not
6+//! model is refused, never silently dropped.
7+use crate::protocol::{
8+ asset_blob_key, AssetConfig, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest,
9+ ModuleRef, Rollout, RunWorkerFirst,
10+};
11+use anyhow::{anyhow, bail, Context};
12+use aws_sdk_s3::primitives::ByteStream;
13+use aws_sdk_s3::Client;
14+use flate2::write::GzEncoder;
15+use flate2::Compression;
16+use futures_util::{stream, StreamExt, TryStreamExt};
17+use serde_json::{json, Map, Value};
18+use sha2::Digest;
19+use sha2::Sha256;
20+use std::collections::{BTreeMap, BTreeSet};
21+use std::io::Write;
22+use std::path::{Path, PathBuf};
23+use std::process::Command;
24+use std::time::{Duration, Instant};
25+
26+/// Config keys we understand. Anything else is an error: refusing is
27+/// compat-safe, guessing produces confusing activation failures later.
28+const SUPPORTED_KEYS: &[&str] = &[
29+ "$schema",
30+ "name",
31+ "main",
32+ "compatibility_date",
33+ "compatibility_flags",
34+ "durable_objects",
35+ "migrations",
36+ "assets",
37+ "services",
38+ "vars",
39+];
40+
41+const MAX_ASSET_FILES: usize = 20_000;
42+const MAX_ASSET_BYTES: u64 = 1024 * 1024 * 1024;
43+const MAX_ASSET_FILE_BYTES: u64 = 25 * 1024 * 1024;
44+const MAX_ASSET_DIRECTIVE_BYTES: u64 = 100 * 1024;
45+const ASSET_UPLOAD_CONCURRENCY: usize = 16;
46+
47+pub struct Options {
48+ pub config: Option<PathBuf>,
49+ pub bucket: Option<String>,
50+ pub endpoint: Option<String>,
51+ pub region: Option<String>,
52+ pub dry_run: bool,
53+}
54+
55+pub fn print_help() {
56+ println!(
57+ "celld deploy — build a Worker with esbuild and write it to the fleet bucket\n\n\
58+USAGE:\n celld deploy [PROJECT] --bucket s3://NAME [OPTIONS]\n\n\
59+PROJECT is a directory or a Wrangler config; it defaults to the working\n\
60+directory, where celld looks for wrangler.jsonc or wrangler.json.\n\n\
61+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\
62+Credentials come from the standard AWS credential chain.\n\n\
63+Worker projects require `esbuild` on PATH; asset-only projects do not. Static\n\
64+assets, service bindings, and string vars are supported. Routes are not; use\n\
65+Wrangler for route configuration.\n\
66+Nodes load a deployment at startup, so an existing node keeps serving the old\n\
67+version until it restarts."
68+ );
69+}
70+
71+pub fn options_from_arguments(
72+ arguments: impl IntoIterator<Item = String>,
73+) -> anyhow::Result<Option<Options>> {
74+ let mut options = Options {
75+ config: None,
76+ bucket: None,
77+ endpoint: None,
78+ region: None,
79+ dry_run: false,
80+ };
81+ let mut arguments = arguments.into_iter();
82+ while let Some(argument) = arguments.next() {
83+ match argument.as_str() {
84+ "--help" | "-h" => return Ok(None),
85+ "--dry-run" => options.dry_run = true,
86+ "--config" => {
87+ options.config = Some(PathBuf::from(
88+ arguments.next().context("--config requires a value")?,
89+ ));
90+ }
91+ "--bucket" => {
92+ let value = arguments.next().context("--bucket requires a value")?;
93+ options.bucket = Some(value.trim_start_matches("s3://").to_string());
94+ }
95+ "--endpoint" => {
96+ options.endpoint = Some(arguments.next().context("--endpoint requires a value")?);
97+ }
98+ "--region" => {
99+ options.region = Some(arguments.next().context("--region requires a value")?);
100+ }
101+ other if other.starts_with('-') => {
102+ bail!("unknown argument for `celld deploy`: {other}")
103+ }
104+ other if options.config.is_none() => options.config = Some(PathBuf::from(other)),
105+ other => bail!("`celld deploy` takes one project path, and already has one: {other}"),
106+ }
107+ }
108+ Ok(Some(options))
109+}
110+
111+/// What a config resolves to once the allowlist has been applied.
112+struct Project {
113+ script_name: String,
114+ /// Entry relative to the project root. esbuild stamps this path into the
115+ /// bundle, so it must not depend on the working directory celld was
116+ /// invoked from — identical source would otherwise hash two ways.
117+ entry: Option<String>,
118+ assets: Option<ProjectAssets>,
119+ metadata: Value,
120+ do_classes: Vec<String>,
121+ sqlite_classes: Vec<String>,
122+}
123+
124+struct ProjectAssets {
125+ directory: PathBuf,
126+ config: AssetConfig,
127+ raw_metadata: Value,
128+}
129+
130+pub struct BuiltAssets {
131+ pub index: Vec<u8>,
132+ pub blobs: BTreeMap<String, Vec<u8>>,
133+ pub file_count: u32,
134+ pub total_bytes: u64,
135+}
136+
137+/// The built deployment, before anything is written.
138+pub struct Built {
139+ pub script_name: String,
140+ pub version: String,
141+ pub prefix: String,
142+ pub manifest: Manifest,
143+ pub modules: Vec<(String, Vec<u8>)>,
144+ pub assets: Option<BuiltAssets>,
145+ pub bundled_in: Duration,
146+}
147+
148+impl Built {
149+ pub fn bytes(&self) -> usize {
150+ self.modules.iter().map(|(_, body)| body.len()).sum()
151+ }
152+
153+ /// What the deployment weighs, the bindings it will have, and nothing we
154+ /// cannot stand behind: no URL, because celld routes nothing, and no
155+ /// startup time, because deploying does not start an isolate.
156+ pub fn report(&self) {
157+ println!(" celld {}", env!("CARGO_PKG_VERSION"));
158+ println!("{}", "─".repeat(47));
159+ println!(
160+ "Total Upload: {} / gzip: {}",
161+ kib(self.bytes()),
162+ kib(gzipped(&self.modules)),
163+ );
164+ if let Some(assets) = &self.assets {
165+ println!(
166+ "Static Assets: {} files / {} ({} unique bodies)",
167+ assets.file_count,
168+ kib(assets.total_bytes as usize),
169+ assets.blobs.len(),
170+ );
171+ }
172+ let bindings = self.bindings();
173+ if bindings.is_empty() {
174+ println!("Your Worker has no bindings.");
175+ } else {
176+ let width = bindings
177+ .iter()
178+ .map(|(binding, _)| binding.len())
179+ .chain(std::iter::once("Binding".len()))
180+ .max()
181+ .unwrap_or_default()
182+ + 6;
183+ println!("Your Worker has access to the following bindings:");
184+ println!("{:width$}Resource", "Binding");
185+ for (binding, resource) in bindings {
186+ println!("{binding:width$}{resource}");
187+ }
188+ }
189+ println!(
190+ "Bundled {} ({})",
191+ self.script_name,
192+ seconds(self.bundled_in)
193+ );
194+ }
195+
196+ /// `env.NAME (Class)` against the resource it resolves to, the way
197+ /// Wrangler renders it.
198+ fn bindings(&self) -> Vec<(String, String)> {
199+ self.manifest
200+ .raw_metadata
201+ .get("bindings")
202+ .and_then(Value::as_array)
203+ .map(Vec::as_slice)
204+ .unwrap_or_default()
205+ .iter()
206+ .filter_map(|binding| {
207+ let name = binding.get("name").and_then(Value::as_str)?;
208+ match binding.get("type").and_then(Value::as_str) {
209+ Some("assets") => {
210+ Some((format!("env.{name} (Assets)"), "Static Assets".to_string()))
211+ }
212+ Some("durable_object_namespace") => {
213+ let class = binding.get("class_name").and_then(Value::as_str)?;
214+ let sqlite = self.manifest.sqlite_classes.iter().any(|c| c == class);
215+ Some((
216+ format!("env.{name} ({class})"),
217+ match sqlite {
218+ true => "Durable Object (SQLite)".to_string(),
219+ false => "Durable Object".to_string(),
220+ },
221+ ))
222+ }
223+ Some("service") => {
224+ let service = binding.get("service").and_then(Value::as_str)?;
225+ let target = binding
226+ .get("entrypoint")
227+ .and_then(Value::as_str)
228+ .map_or_else(
229+ || service.to_string(),
230+ |entrypoint| format!("{service}#{entrypoint}"),
231+ );
232+ Some((format!("env.{name} (Service)"), target))
233+ }
234+ Some("plain_text") => Some((
235+ format!("env.{name} (Text)"),
236+ "Environment Variable".to_string(),
237+ )),
238+ _ => None,
239+ }
240+ })
241+ .collect()
242+ }
243+}
244+
245+fn kib(bytes: usize) -> String {
246+ format!("{:.2} KiB", bytes as f64 / 1024.0)
247+}
248+
249+fn seconds(elapsed: Duration) -> String {
250+ format!("{:.2} sec", elapsed.as_secs_f64())
251+}
252+
253+fn gzipped(modules: &[(String, Vec<u8>)]) -> usize {
254+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
255+ for (_, body) in modules {
256+ encoder.write_all(body).ok();
257+ }
258+ encoder.finish().map(|out| out.len()).unwrap_or_default()
259+}
260+
261+pub fn build(options: &Options) -> anyhow::Result<Built> {
262+ let config_path = resolve_config(options.config.clone())?;
263+ let root = config_path
264+ .parent()
265+ .filter(|path| !path.as_os_str().is_empty())
266+ .map(Path::to_path_buf)
267+ .unwrap_or_else(|| PathBuf::from("."));
268+ let project = read_project(&config_path, &root)?;
269+ let started = Instant::now();
270+ let built_assets = project.assets.as_ref().map(build_assets).transpose()?;
271+ let bundle = project
272+ .entry
273+ .as_deref()
274+ .map(|entry| run_esbuild(&root, entry))
275+ .transpose()?;
276+ let bundled_in = started.elapsed();
277+
278+ // esbuild emits one module, so the graph is always a single entry.
279+ let module_name = "index.js".to_string();
280+ let modules = bundle
281+ .map(|bundle| vec![(module_name.clone(), bundle)])
282+ .unwrap_or_default();
283+ // Identity is over the exact metadata bytes the manifest retains, so the
284+ // serialization happens once and is reused for both.
285+ let metadata_json = serde_json::to_vec(&project.metadata)?;
286+ let version = crate::protocol::deployment_version(
287+ &modules,
288+ &metadata_json,
289+ built_assets.as_ref().map(|assets| assets.index.as_slice()),
290+ );
291+ let prefix = format!("deploy/{}/{}", project.script_name, version);
292+ let asset_reference = built_assets.as_ref().map(|assets| AssetManifestRef {
293+ index: "assets.json".to_string(),
294+ sha256: format!("{:x}", Sha256::digest(&assets.index)),
295+ file_count: assets.file_count,
296+ total_bytes: assets.total_bytes,
297+ });
298+ let manifest = Manifest {
299+ schema_version: if asset_reference.is_some() { 2 } else { 1 },
300+ version: version.clone(),
301+ script_name: project.script_name.clone(),
302+ main_module: project.entry.as_ref().map(|_| module_name.clone()),
303+ do_classes: project.do_classes,
304+ sqlite_classes: project.sqlite_classes,
305+ modules: modules
306+ .iter()
307+ .map(|(name, bytes)| ModuleRef {
308+ name: name.clone(),
309+ bytes: bytes.len(),
310+ sha256: format!("{:x}", Sha256::digest(bytes))[..16].to_string(),
311+ })
312+ .collect(),
313+ assets: asset_reference,
314+ required_features: if built_assets.is_some() {
315+ vec!["assets-v1".to_string()]
316+ } else {
317+ Vec::new()
318+ },
319+ raw_metadata: project.metadata,
320+ };
321+ Ok(Built {
322+ script_name: project.script_name,
323+ version,
324+ prefix,
325+ manifest,
326+ modules,
327+ assets: built_assets,
328+ bundled_in,
329+ })
330+}
331+
332+pub async fn write(client: &Client, bucket: &str, built: &Built) -> anyhow::Result<()> {
333+ // Asset bodies are fleet-wide and content-addressed. Finish every body
334+ // before publishing the deployment-local index or manifest so a reader
335+ // can never observe a pointer whose assets are incomplete.
336+ if let Some(assets) = &built.assets {
337+ stream::iter(&assets.blobs)
338+ .map(|(sha256, body)| ensure_asset_blob(client, bucket, sha256, body))
339+ .buffer_unordered(ASSET_UPLOAD_CONCURRENCY)
340+ .try_collect::<Vec<_>>()
341+ .await?;
342+ }
343+ for (name, bytes) in &built.modules {
344+ put(
345+ client,
346+ bucket,
347+ &format!("{}/{name}", built.prefix),
348+ bytes.clone(),
349+ )
350+ .await?;
351+ }
352+ if let Some(assets) = &built.assets {
353+ put(
354+ client,
355+ bucket,
356+ &format!("{}/assets.json", built.prefix),
357+ assets.index.clone(),
358+ )
359+ .await?;
360+ }
361+ put(
362+ client,
363+ bucket,
364+ &format!("{}/manifest.json", built.prefix),
365+ serde_json::to_vec_pretty(&built.manifest)?,
366+ )
367+ .await?;
368+ let pointer = DeployPointer {
369+ script_name: Some(built.script_name.clone()),
370+ version: built.version.clone(),
371+ prefix: built.prefix.clone(),
372+ rollout: Rollout { percent: 100 },
373+ };
374+ let encoded = serde_json::to_vec_pretty(&pointer)?;
375+ // The named pointer resolves service-binding components; the fleet-wide
376+ // one is the sole application selector, so it moves last. A concurrent
377+ // deploy must produce a loser, not a lost write.
378+ put_pointer(
379+ client,
380+ bucket,
381+ &format!("deploy/{}/current.json", built.script_name),
382+ encoded.clone(),
383+ )
384+ .await?;
385+ put_pointer(client, bucket, "deploy/current.json", encoded).await?;
386+ Ok(())
387+}
388+
389+async fn ensure_asset_blob(
390+ client: &Client,
391+ bucket: &str,
392+ sha256: &str,
393+ body: &[u8],
394+) -> anyhow::Result<()> {
395+ let key = asset_blob_key(sha256).expect("built asset digest is valid");
396+ if let Ok(existing) = client.head_object().bucket(bucket).key(&key).send().await {
397+ if existing.content_length().unwrap_or(-1) == body.len() as i64
398+ && existing
399+ .metadata()
400+ .and_then(|metadata| metadata.get("sha256"))
401+ .is_some_and(|value| value == sha256)
402+ {
403+ return Ok(());
404+ }
405+ }
406+ client
407+ .put_object()
408+ .bucket(bucket)
409+ .key(&key)
410+ .metadata("sha256", sha256)
411+ .body(ByteStream::from(body.to_vec()))
412+ .send()
413+ .await
414+ .with_context(|| format!("write s3://{bucket}/{key}"))?;
415+ Ok(())
416+}
417+
418+/// Compare-and-swap on a pointer: create it if absent, otherwise replace
419+/// exactly the value we read.
420+async fn put_pointer(
421+ client: &Client,
422+ bucket: &str,
423+ key: &str,
424+ body: Vec<u8>,
425+) -> anyhow::Result<()> {
426+ let existing = client
427+ .head_object()
428+ .bucket(bucket)
429+ .key(key)
430+ .send()
431+ .await
432+ .ok();
433+ let request = client.put_object().bucket(bucket).key(key);
434+ let request = match existing.as_ref().and_then(|head| head.e_tag()) {
435+ Some(etag) => request.if_match(etag),
436+ None => request.if_none_match("*"),
437+ };
438+ request
439+ .body(ByteStream::from(body))
440+ .send()
441+ .await
442+ .map_err(|error| {
443+ anyhow!(
444+ "write s3://{bucket}/{key}: {error}\n\
445+ Another deploy may have landed first; re-run `celld deploy`."
446+ )
447+ })?;
448+ Ok(())
449+}
450+
451+async fn put(client: &Client, bucket: &str, key: &str, body: Vec<u8>) -> anyhow::Result<()> {
452+ client
453+ .put_object()
454+ .bucket(bucket)
455+ .key(key)
456+ .body(ByteStream::from(body))
457+ .send()
458+ .await
459+ .with_context(|| format!("write s3://{bucket}/{key}"))?;
460+ Ok(())
461+}
462+
463+/// A path may name the config itself or the directory holding it; with no
464+/// path at all, the working directory.
465+fn resolve_config(given: Option<PathBuf>) -> anyhow::Result<PathBuf> {
466+ let directory = match given {
467+ Some(path) if path.is_dir() => path,
468+ Some(path) if path.exists() => return Ok(path),
469+ Some(path) => bail!(
470+ "no Wrangler config or project directory at {}",
471+ path.display()
472+ ),
473+ None => PathBuf::from("."),
474+ };
475+ for candidate in ["wrangler.jsonc", "wrangler.json"] {
476+ let path = directory.join(candidate);
477+ if path.exists() {
478+ return Ok(path);
479+ }
480+ }
481+ if directory.join("wrangler.toml").exists() {
482+ bail!("wrangler.toml is not supported; convert it to wrangler.jsonc");
483+ }
484+ bail!(
485+ "no wrangler.jsonc or wrangler.json in {}",
486+ directory.display()
487+ )
488+}
489+
490+fn read_project(path: &Path, root: &Path) -> anyhow::Result<Project> {
491+ let source =
492+ std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
493+ let config: Value = serde_json::from_str(&strip_jsonc(&source))
494+ .with_context(|| format!("parse {}", path.display()))?;
495+ let object = config
496+ .as_object()
497+ .ok_or_else(|| anyhow!("{} is not a JSON object", path.display()))?;
498+
499+ let unsupported = object
500+ .keys()
501+ .filter(|key| !SUPPORTED_KEYS.contains(&key.as_str()))
502+ .cloned()
503+ .collect::<Vec<_>>();
504+ if !unsupported.is_empty() {
505+ bail!(
506+ "`celld deploy` does not support these config keys: {}.\n\
507+ Deploy this project with Wrangler instead, or remove them.",
508+ unsupported.join(", ")
509+ );
510+ }
511+
512+ let script_name = object
513+ .get("name")
514+ .and_then(Value::as_str)
515+ .ok_or_else(|| anyhow!("config has no `name`"))?
516+ .to_string();
517+ let main = object
518+ .get("main")
519+ .map(|value| {
520+ value
521+ .as_str()
522+ .ok_or_else(|| anyhow!("config `main` must be a string"))
523+ .and_then(|value| project_relative_path(value, "main"))
524+ })
525+ .transpose()?;
526+ if let Some(main) = &main {
527+ let entry = root.join(main);
528+ let metadata = std::fs::symlink_metadata(&entry)
529+ .with_context(|| format!("inspect entry point {}", entry.display()))?;
530+ if !metadata.file_type().is_file() {
531+ bail!("entry point {} is not a regular file", entry.display());
532+ }
533+ }
534+ let assets = object
535+ .get("assets")
536+ .map(|value| read_asset_project(value, root, object))
537+ .transpose()?;
538+ if main.is_none() && assets.is_none() {
539+ bail!("config has neither `main` nor `assets`");
540+ }
541+ if main.is_none()
542+ && assets.as_ref().is_some_and(|assets| {
543+ matches!(
544+ &assets.config.run_worker_first,
545+ RunWorkerFirst::Bool(true) | RunWorkerFirst::Routes(_)
546+ )
547+ })
548+ {
549+ bail!("an asset-only project cannot set `assets.run_worker_first`");
550+ }
551+
552+ let sqlite_classes = read_sqlite_classes(object)?;
553+
554+ // Wrangler-shaped upload metadata, so a manifest written here and one
555+ // written by the control plane describe a deployment the same way.
556+ let mut bindings = Vec::new();
557+ let mut do_classes = Vec::new();
558+ for binding in object
559+ .get("durable_objects")
560+ .and_then(|value| value.get("bindings"))
561+ .and_then(Value::as_array)
562+ .map(Vec::as_slice)
563+ .unwrap_or_default()
564+ {
565+ let name = binding
566+ .get("name")
567+ .and_then(Value::as_str)
568+ .ok_or_else(|| anyhow!("durable object binding has no `name`"))?;
569+ let class_name = binding
570+ .get("class_name")
571+ .and_then(Value::as_str)
572+ .ok_or_else(|| anyhow!("durable object binding {name} has no `class_name`"))?;
573+ do_classes.push(class_name.to_string());
574+ bindings.push(json!({
575+ "type": "durable_object_namespace",
576+ "name": name,
577+ "class_name": class_name,
578+ }));
579+ }
580+ let services = match object.get("services") {
581+ None => &[][..],
582+ Some(Value::Array(services)) => services.as_slice(),
583+ Some(_) => bail!("config `services` must be an array"),
584+ };
585+ let mut service_count = 0_usize;
586+ for service in services {
587+ let binding = service
588+ .get("binding")
589+ .and_then(Value::as_str)
590+ .ok_or_else(|| anyhow!("service binding has no `binding`"))?;
591+ if !valid_binding(binding) {
592+ bail!("invalid service binding name: {binding:?}");
593+ }
594+ let target = service
595+ .get("service")
596+ .and_then(Value::as_str)
597+ .ok_or_else(|| anyhow!("service binding {binding} has no `service`"))?;
598+ let entrypoint = service
599+ .get("entrypoint")
600+ .map(|value| {
601+ value.as_str().ok_or_else(|| {
602+ anyhow!("service binding {binding} `entrypoint` must be a string")
603+ })
604+ })
605+ .transpose()?;
606+ let mut encoded = json!({
607+ "type": "service",
608+ "name": binding,
609+ "service": target,
610+ });
611+ if let Some(entrypoint) = entrypoint {
612+ encoded["entrypoint"] = json!(entrypoint);
613+ }
614+ bindings.push(encoded);
615+ service_count += 1;
616+ }
617+ let vars = match object.get("vars") {
618+ None => None,
619+ Some(Value::Object(vars)) => Some(vars),
620+ Some(_) => bail!("config `vars` must be an object"),
621+ };
622+ let mut var_count = 0_usize;
623+ for (name, value) in vars.into_iter().flatten() {
624+ if !valid_binding(name) {
625+ bail!("invalid var binding name: {name:?}");
626+ }
627+ let value = value
628+ .as_str()
629+ .ok_or_else(|| anyhow!("var binding {name} must be a string"))?;
630+ bindings.push(json!({
631+ "type": "plain_text",
632+ "name": name,
633+ "text": value,
634+ }));
635+ var_count += 1;
636+ }
637+ if main.is_none()
638+ && (!do_classes.is_empty()
639+ || !sqlite_classes.is_empty()
640+ || service_count > 0
641+ || var_count > 0)
642+ {
643+ bail!("an asset-only project cannot declare Worker bindings");
644+ }
645+ if let Some(binding) = assets
646+ .as_ref()
647+ .and_then(|assets| assets.config.binding.as_ref())
648+ {
649+ bindings.push(json!({
650+ "type": "assets",
651+ "name": binding,
652+ }));
653+ }
654+ let mut metadata = Map::new();
655+ if main.is_some() {
656+ metadata.insert("main_module".into(), json!("index.js"));
657+ }
658+ if let Some(assets) = &assets {
659+ metadata.insert("assets".into(), assets.raw_metadata.clone());
660+ }
661+ if let Some(date) = object.get("compatibility_date") {
662+ metadata.insert("compatibility_date".into(), date.clone());
663+ }
664+ if let Some(flags) = object.get("compatibility_flags") {
665+ metadata.insert("compatibility_flags".into(), flags.clone());
666+ }
667+ metadata.insert("bindings".into(), Value::Array(bindings));
668+ if !sqlite_classes.is_empty() {
669+ metadata.insert(
670+ "migrations".into(),
671+ json!({ "new_sqlite_classes": sqlite_classes }),
672+ );
673+ }
674+
675+ Ok(Project {
676+ script_name,
677+ entry: main,
678+ assets,
679+ metadata: Value::Object(metadata),
680+ do_classes,
681+ sqlite_classes,
682+ })
683+}
684+
685+fn read_sqlite_classes(project: &Map<String, Value>) -> anyhow::Result<Vec<String>> {
686+ let Some(value) = project.get("migrations") else {
687+ return Ok(Vec::new());
688+ };
689+ let migrations = value
690+ .as_array()
691+ .ok_or_else(|| anyhow!("config `migrations` must be an array"))?;
692+ let mut tags = BTreeSet::new();
693+ let mut classes = BTreeSet::new();
694+ let mut result = Vec::new();
695+ for (index, migration) in migrations.iter().enumerate() {
696+ let migration = migration
697+ .as_object()
698+ .ok_or_else(|| anyhow!("config `migrations[{index}]` must be an object"))?;
699+ let unsupported = migration
700+ .keys()
701+ .filter(|key| !matches!(key.as_str(), "tag" | "new_sqlite_classes"))
702+ .cloned()
703+ .collect::<Vec<_>>();
704+ if !unsupported.is_empty() {
705+ bail!(
706+ "`celld deploy` does not support these migration keys: {}.\n\
707+ Class rename, delete, transfer, and non-SQLite migration semantics need an explicit persisted-state contract before deployment.",
708+ unsupported.join(", ")
709+ );
710+ }
711+ let tag = migration
712+ .get("tag")
713+ .and_then(Value::as_str)
714+ .filter(|tag| !tag.is_empty())
715+ .ok_or_else(|| {
716+ anyhow!("config `migrations[{index}].tag` must be a non-empty string")
717+ })?;
718+ if !tags.insert(tag.to_string()) {
719+ bail!("config has duplicate migration tag {tag:?}");
720+ }
721+ let Some(value) = migration.get("new_sqlite_classes") else {
722+ continue;
723+ };
724+ let new_classes = value.as_array().ok_or_else(|| {
725+ anyhow!("config `migrations[{index}].new_sqlite_classes` must be an array")
726+ })?;
727+ for (class_index, class) in new_classes.iter().enumerate() {
728+ let class = class.as_str().filter(|class| !class.is_empty()).ok_or_else(|| {
729+ anyhow!(
730+ "config `migrations[{index}].new_sqlite_classes[{class_index}]` must be a non-empty string"
731+ )
732+ })?;
733+ if !classes.insert(class.to_string()) {
734+ bail!("SQLite class {class:?} is introduced by more than one migration");
735+ }
736+ result.push(class.to_string());
737+ }
738+ }
739+ Ok(result)
740+}
741+
742+fn read_asset_project(
743+ value: &Value,
744+ root: &Path,
745+ project: &Map<String, Value>,
746+) -> anyhow::Result<ProjectAssets> {
747+ let object = value
748+ .as_object()
749+ .ok_or_else(|| anyhow!("config `assets` must be an object"))?;
750+ let supported = [
751+ "directory",
752+ "binding",
753+ "html_handling",
754+ "not_found_handling",
755+ "run_worker_first",
756+ ];
757+ let unsupported = object
758+ .keys()
759+ .filter(|key| !supported.contains(&key.as_str()))
760+ .cloned()
761+ .collect::<Vec<_>>();
762+ if !unsupported.is_empty() {
763+ bail!(
764+ "`celld deploy` does not support these assets keys: {}",
765+ unsupported.join(", ")
766+ );
767+ }
768+ let directory = object
769+ .get("directory")
770+ .and_then(Value::as_str)
771+ .ok_or_else(|| anyhow!("config `assets.directory` must be a string"))?;
772+ let directory = project_relative_path(directory, "assets.directory")?;
773+ let directory = root.join(directory);
774+ let metadata = std::fs::symlink_metadata(&directory)
775+ .with_context(|| format!("inspect asset directory {}", directory.display()))?;
776+ if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
777+ bail!(
778+ "asset directory {} is not a regular directory",
779+ directory.display()
780+ );
781+ }
782+
783+ let binding = object
784+ .get("binding")
785+ .map(|value| {
786+ value
787+ .as_str()
788+ .ok_or_else(|| anyhow!("config `assets.binding` must be a string"))
789+ .and_then(|binding| {
790+ if valid_binding(binding) {
791+ Ok(binding.to_string())
792+ } else {
793+ bail!("invalid asset binding name: {binding:?}")
794+ }
795+ })
796+ })
797+ .transpose()?;
798+ let html_handling = optional_asset_mode(
799+ object,
800+ "html_handling",
801+ "auto-trailing-slash",
802+ &[
803+ "auto-trailing-slash",
804+ "force-trailing-slash",
805+ "drop-trailing-slash",
806+ "none",
807+ ],
808+ )?;
809+ let not_found_handling = optional_asset_mode(
810+ object,
811+ "not_found_handling",
812+ "none",
813+ &["none", "single-page-application", "404-page"],
814+ )?;
815+ let run_worker_first = object
816+ .get("run_worker_first")
817+ .map(|value| {
818+ serde_json::from_value::<RunWorkerFirst>(value.clone())
819+ .context("config `assets.run_worker_first` must be a boolean or route list")
820+ })
821+ .transpose()?
822+ .unwrap_or_default();
823+ validate_worker_first(&run_worker_first)?;
824+
825+ let headers = read_asset_directive(&directory, "_headers")?;
826+ let redirects = read_asset_directive(&directory, "_redirects")?;
827+ let compatibility_date = project
828+ .get("compatibility_date")
829+ .map(|value| {
830+ value
831+ .as_str()
832+ .map(str::to_string)
833+ .ok_or_else(|| anyhow!("config `compatibility_date` must be a string"))
834+ })
835+ .transpose()?;
836+ let compatibility_flags = project
837+ .get("compatibility_flags")
838+ .map(|value| {
839+ value
840+ .as_array()
841+ .ok_or_else(|| anyhow!("config `compatibility_flags` must be an array"))?
842+ .iter()
843+ .map(|flag| {
844+ flag.as_str()
845+ .map(str::to_string)
846+ .ok_or_else(|| anyhow!("compatibility flags must be strings"))
847+ })
848+ .collect::<anyhow::Result<Vec<_>>>()
849+ })
850+ .transpose()?
851+ .unwrap_or_default();
852+
853+ // Retain the Wrangler-shaped upload metadata as well as the normalized
854+ // index config. Defaults and compatibility settings belong in the index;
855+ // upload metadata includes only the values Wrangler would send.
856+ let mut upload_config = Map::new();
857+ for key in ["html_handling", "not_found_handling", "run_worker_first"] {
858+ if let Some(value) = object.get(key) {
859+ upload_config.insert(key.to_string(), value.clone());
860+ }
861+ }
862+ if let Some(headers) = &headers {
863+ upload_config.insert("_headers".to_string(), Value::String(headers.clone()));
864+ }
865+ if let Some(redirects) = &redirects {
866+ upload_config.insert("_redirects".to_string(), Value::String(redirects.clone()));
867+ }
868+
869+ Ok(ProjectAssets {
870+ directory,
871+ config: AssetConfig {
872+ binding,
873+ html_handling: Some(html_handling),
874+ not_found_handling: Some(not_found_handling),
875+ run_worker_first,
876+ headers,
877+ redirects,
878+ compatibility_date,
879+ compatibility_flags,
880+ },
881+ raw_metadata: json!({ "config": Value::Object(upload_config) }),
882+ })
883+}
884+
885+fn project_relative_path(value: &str, key: &str) -> anyhow::Result<String> {
886+ let value = value.strip_prefix("./").unwrap_or(value);
887+ let path = Path::new(value);
888+ if value.is_empty()
889+ || path
890+ .components()
891+ .any(|component| !matches!(component, std::path::Component::Normal(_)))
892+ {
893+ bail!("config `{key}` must be a path inside the project");
894+ }
895+ Ok(value.to_string())
896+}
897+
898+fn optional_asset_mode(
899+ object: &Map<String, Value>,
900+ key: &str,
901+ default: &str,
902+ supported: &[&str],
903+) -> anyhow::Result<String> {
904+ let value = match object.get(key) {
905+ Some(value) => value
906+ .as_str()
907+ .ok_or_else(|| anyhow!("config `assets.{key}` must be a string"))?,
908+ None => default,
909+ };
910+ if !supported.contains(&value) {
911+ bail!("unsupported assets.{key} value: {value:?}");
912+ }
913+ Ok(value.to_string())
914+}
915+
916+fn valid_binding(binding: &str) -> bool {
917+ binding.len() <= 128
918+ && binding
919+ .chars()
920+ .next()
921+ .is_some_and(|value| value == '_' || value == '$' || value.is_ascii_alphabetic())
922+ && binding
923+ .chars()
924+ .skip(1)
925+ .all(|value| value == '_' || value == '$' || value.is_ascii_alphanumeric())
926+}
927+
928+fn validate_worker_first(value: &RunWorkerFirst) -> anyhow::Result<()> {
929+ let RunWorkerFirst::Routes(routes) = value else {
930+ return Ok(());
931+ };
932+ if routes.is_empty() || routes.len() > 100 {
933+ bail!("asset worker-first routes must contain between 1 and 100 rules");
934+ }
935+ let mut positive = false;
936+ let mut seen = std::collections::HashSet::new();
937+ for route in routes {
938+ if route.len() <= 1
939+ || route.len() > 100
940+ || route.contains(['\\', '\0'])
941+ || (!route.starts_with('/') && !route.starts_with("!/"))
942+ || !seen.insert(route)
943+ {
944+ bail!("invalid asset worker-first route: {route:?}");
945+ }
946+ positive |= route.starts_with('/');
947+ }
948+ if !positive {
949+ bail!("asset worker-first routes require a positive rule");
950+ }
951+ Ok(())
952+}
953+
954+fn read_asset_directive(directory: &Path, name: &str) -> anyhow::Result<Option<String>> {
955+ let path = directory.join(name);
956+ let metadata = match std::fs::symlink_metadata(&path) {
957+ Ok(metadata) => metadata,
958+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
959+ Err(error) => return Err(error).with_context(|| format!("inspect {}", path.display())),
960+ };
961+ if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
962+ bail!("asset directive {} is not a regular file", path.display());
963+ }
964+ if metadata.len() > MAX_ASSET_DIRECTIVE_BYTES {
965+ bail!("asset directive {} exceeds 100 KiB", path.display());
966+ }
967+ let contents =
968+ std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
969+ if contents.len() as u64 > MAX_ASSET_DIRECTIVE_BYTES {
970+ bail!("asset directive {} exceeds 100 KiB", path.display());
971+ }
972+ Ok(Some(contents))
973+}
974+
975+fn build_assets(project: &ProjectAssets) -> anyhow::Result<BuiltAssets> {
976+ let mut files = Vec::new();
977+ collect_asset_files(&project.directory, "", &mut files)?;
978+ files.sort_by(|left, right| left.0.cmp(&right.0));
979+ if files.len() > MAX_ASSET_FILES {
980+ bail!("asset directory exceeds the {MAX_ASSET_FILES}-file limit");
981+ }
982+
983+ let mut entries = BTreeMap::new();
984+ let mut blobs = BTreeMap::new();
985+ let mut total_bytes = 0_u64;
986+ for (relative, path) in files {
987+ let metadata =
988+ std::fs::metadata(&path).with_context(|| format!("inspect {}", path.display()))?;
989+ if metadata.len() > MAX_ASSET_FILE_BYTES {
990+ bail!("asset /{relative} exceeds the 25 MiB file limit");
991+ }
992+ total_bytes = total_bytes
993+ .checked_add(metadata.len())
994+ .context("asset byte count overflow")?;
995+ if total_bytes > MAX_ASSET_BYTES {
996+ bail!("asset directory exceeds the 1 GiB deployment limit");
997+ }
998+ let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
999+ if body.len() as u64 != metadata.len() {
1000+ bail!("asset changed while being read: {}", path.display());
1001+ }
1002+ let sha256 = format!("{:x}", Sha256::digest(&body));
1003+ blobs.entry(sha256.clone()).or_insert(body);
1004+ entries.insert(
1005+ format!("/{relative}"),
1006+ AssetEntry {
1007+ sha256,
1008+ bytes: metadata.len(),
1009+ content_type: asset_content_type(&path).map(str::to_string),
1010+ },
1011+ );
1012+ }
1013+ let file_count = u32::try_from(entries.len()).context("asset file count overflow")?;
1014+ let index = serde_json::to_vec(&AssetIndex {
1015+ schema_version: 1,
1016+ entries,
1017+ config: project.config.clone(),
1018+ })?;
1019+ Ok(BuiltAssets {
1020+ index,
1021+ blobs,
1022+ file_count,
1023+ total_bytes,
1024+ })
1025+}
1026+
1027+fn collect_asset_files(
1028+ directory: &Path,
1029+ relative: &str,
1030+ files: &mut Vec<(String, PathBuf)>,
1031+) -> anyhow::Result<()> {
1032+ let mut entries = std::fs::read_dir(directory)
1033+ .with_context(|| format!("read asset directory {}", directory.display()))?
1034+ .collect::<Result<Vec<_>, _>>()?;
1035+ entries.sort_by_key(std::fs::DirEntry::file_name);
1036+ for entry in entries {
1037+ let name = entry.file_name().into_string().map_err(|_| {
1038+ anyhow!(
1039+ "asset path contains a non-UTF-8 name under {}",
1040+ directory.display()
1041+ )
1042+ })?;
1043+ if relative.is_empty() && name == ".assetsignore" {
1044+ bail!(
1045+ "{} is not supported by `celld deploy`; remove it or deploy with Wrangler",
1046+ entry.path().display()
1047+ );
1048+ }
1049+ if relative.is_empty() && (name == "_worker.js" || name.starts_with("_worker.js/")) {
1050+ bail!(
1051+ "refusing to publish reserved Worker source as an asset: {}",
1052+ entry.path().display()
1053+ );
1054+ }
1055+ if relative.is_empty() && matches!(name.as_str(), "_headers" | "_redirects") {
1056+ continue;
1057+ }
1058+ if name.contains(['\\', '\0']) {
1059+ bail!("invalid asset path component: {name:?}");
1060+ }
1061+ let child_relative = if relative.is_empty() {
1062+ name
1063+ } else {
1064+ format!("{relative}/{name}")
1065+ };
1066+ if child_relative.len() + 1 > 1024 {
1067+ bail!("asset path exceeds 1024 bytes: /{child_relative}");
1068+ }
1069+ let file_type = entry
1070+ .file_type()
1071+ .with_context(|| format!("inspect asset {}", entry.path().display()))?;
1072+ if file_type.is_symlink() {
1073+ bail!(
1074+ "asset tree contains a symbolic link: {}",
1075+ entry.path().display()
1076+ );
1077+ } else if file_type.is_dir() {
1078+ collect_asset_files(&entry.path(), &child_relative, files)?;
1079+ } else if file_type.is_file() {
1080+ files.push((child_relative, entry.path()));
1081+ } else {
1082+ bail!(
1083+ "asset tree contains a special file: {}",
1084+ entry.path().display()
1085+ );
1086+ }
1087+ }
1088+ Ok(())
1089+}
1090+
1091+fn asset_content_type(path: &Path) -> Option<&'static str> {
1092+ let extension = path.extension()?.to_str()?.to_ascii_lowercase();
1093+ Some(match extension.as_str() {
1094+ "html" | "htm" => "text/html; charset=utf-8",
1095+ "css" => "text/css; charset=utf-8",
1096+ "js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
1097+ "json" | "map" => "application/json; charset=utf-8",
1098+ "txt" => "text/plain; charset=utf-8",
1099+ "xml" => "application/xml; charset=utf-8",
1100+ "svg" => "image/svg+xml",
1101+ "webmanifest" => "application/manifest+json; charset=utf-8",
1102+ "wasm" => "application/wasm",
1103+ "png" => "image/png",
1104+ "jpg" | "jpeg" => "image/jpeg",
1105+ "gif" => "image/gif",
1106+ "webp" => "image/webp",
1107+ "avif" => "image/avif",
1108+ "ico" => "image/x-icon",
1109+ "pdf" => "application/pdf",
1110+ "woff" => "font/woff",
1111+ "woff2" => "font/woff2",
1112+ "ttf" => "font/ttf",
1113+ "otf" => "font/otf",
1114+ "mp3" => "audio/mpeg",
1115+ "wav" => "audio/wav",
1116+ "ogg" => "audio/ogg",
1117+ "mp4" => "video/mp4",
1118+ "webm" => "video/webm",
1119+ "zip" => "application/zip",
1120+ "gz" => "application/gzip",
1121+ "br" => "application/octet-stream",
1122+ _ => return None,
1123+ })
1124+}
1125+
1126+fn run_esbuild(root: &Path, entry: &str) -> anyhow::Result<Vec<u8>> {
1127+ // node: builtins stay external. Wrangler polyfills them with unenv; celld
1128+ // implements the workerd `nodejs_compat` subset itself, so the runtime
1129+ // provides them.
1130+ let binary = std::env::var("CELLD_ESBUILD").unwrap_or_else(|_| "esbuild".to_string());
1131+ let output = Command::new(&binary)
1132+ .current_dir(root)
1133+ .arg(entry)
1134+ .arg("--bundle")
1135+ .arg("--format=esm")
1136+ .arg("--platform=browser")
1137+ .arg("--target=es2024")
1138+ .arg("--conditions=workerd,worker,browser")
1139+ .arg("--external:node:*")
1140+ .arg("--external:cloudflare:*")
1141+ .output()
1142+ .map_err(|error| {
1143+ if error.kind() == std::io::ErrorKind::NotFound {
1144+ anyhow!(
1145+ "esbuild not found ({binary}).\n\
1146+ `celld deploy` bundles with esbuild; install it and retry,\n\
1147+ or set CELLD_ESBUILD to its path."
1148+ )
1149+ } else {
1150+ anyhow!("run esbuild: {error}")
1151+ }
1152+ })?;
1153+ if !output.status.success() {
1154+ bail!(
1155+ "esbuild failed:\n{}",
1156+ String::from_utf8_lossy(&output.stderr).trim()
1157+ );
1158+ }
1159+ Ok(output.stdout)
1160+}
1161+
1162+/// Minimal JSONC support: line and block comments, and trailing commas.
1163+/// String contents are preserved verbatim.
1164+fn strip_jsonc(source: &str) -> String {
1165+ let mut out = String::with_capacity(source.len());
1166+ let mut chars = source.chars().peekable();
1167+ let mut in_string = false;
1168+ let mut escaped = false;
1169+ while let Some(c) = chars.next() {
1170+ if in_string {
1171+ out.push(c);
1172+ if escaped {
1173+ escaped = false;
1174+ } else if c == '\\' {
1175+ escaped = true;
1176+ } else if c == '"' {
1177+ in_string = false;
1178+ }
1179+ continue;
1180+ }
1181+ match c {
1182+ '"' => {
1183+ in_string = true;
1184+ out.push(c);
1185+ }
1186+ '/' if chars.peek() == Some(&'/') => {
1187+ for c in chars.by_ref() {
1188+ if c == '\n' {
1189+ out.push('\n');
1190+ break;
1191+ }
1192+ }
1193+ }
1194+ '/' if chars.peek() == Some(&'*') => {
1195+ chars.next();
1196+ let mut previous = '\0';
1197+ for c in chars.by_ref() {
1198+ if previous == '*' && c == '/' {
1199+ break;
1200+ }
1201+ previous = c;
1202+ }
1203+ }
1204+ '}' | ']' => {
1205+ // The comma this closes is trailing; drop it, keep the layout.
1206+ let trimmed = out.trim_end().len();
1207+ if out[..trimmed].ends_with(',') {
1208+ out.remove(trimmed - 1);
1209+ }
1210+ out.push(c);
1211+ }
1212+ _ => out.push(c),
1213+ }
1214+ }
1215+ out
1216+}
addedcrates/celld/fault.rs+315−0View file
@@ -1,0 +1,315 @@
1+//! Test-only SQLite fault injection: a wrapper VFS that delegates to the
2+//! process default VFS but fails writes with `SQLITE_IOERR` while the current
3+//! thread has armed the fault. Compiled only into test builds —
4+//! production binaries contain none of this code and no seam for it.
5+use rusqlite::ffi;
6+use std::cell::Cell;
7+use std::ffi::c_char;
8+use std::ffi::c_int;
9+use std::ffi::c_void;
10+use std::mem::size_of;
11+use std::sync::Once;
12+
13+const FAULT_VFS_NAME: &std::ffi::CStr = c"cells-fault-vfs";
14+
15+thread_local! {
16+ static WRITE_FAULT: Cell<bool> = const { Cell::new(false) };
17+}
18+
19+pub fn set_write_fault(enabled: bool) {
20+ WRITE_FAULT.with(|flag| flag.set(enabled));
21+}
22+
23+fn write_fault_armed() -> bool {
24+ WRITE_FAULT.try_with(Cell::get).unwrap_or(false)
25+}
26+
27+/// The shim's per-file state: SQLite allocates `szOsFile` bytes, we use the
28+/// front for this header and hand the tail to the real VFS as its file.
29+#[repr(C)]
30+struct ShimFile {
31+ base: ffi::sqlite3_file,
32+ real: *mut ffi::sqlite3_file,
33+}
34+
35+unsafe fn real_file(file: *mut ffi::sqlite3_file) -> *mut ffi::sqlite3_file {
36+ (*file.cast::<ShimFile>()).real
37+}
38+
39+unsafe fn real_vfs(vfs: *mut ffi::sqlite3_vfs) -> *mut ffi::sqlite3_vfs {
40+ (*vfs).pAppData.cast()
41+}
42+
43+macro_rules! file_delegate {
44+ ($file:ident, $method:ident $(, $arg:expr)*) => {{
45+ let real = real_file($file);
46+ ((*(*real).pMethods).$method.expect("real io method"))(real $(, $arg)*)
47+ }};
48+}
49+
50+macro_rules! vfs_delegate {
51+ ($vfs:ident, $method:ident $(, $arg:expr)*) => {{
52+ let real = real_vfs($vfs);
53+ ((*real).$method.expect("real vfs method"))(real $(, $arg)*)
54+ }};
55+}
56+
57+unsafe extern "C" fn shim_close(file: *mut ffi::sqlite3_file) -> c_int {
58+ file_delegate!(file, xClose)
59+}
60+unsafe extern "C" fn shim_read(
61+ file: *mut ffi::sqlite3_file,
62+ buf: *mut c_void,
63+ amt: c_int,
64+ offset: i64,
65+) -> c_int {
66+ file_delegate!(file, xRead, buf, amt, offset)
67+}
68+unsafe extern "C" fn shim_write(
69+ file: *mut ffi::sqlite3_file,
70+ buf: *const c_void,
71+ amt: c_int,
72+ offset: i64,
73+) -> c_int {
74+ if write_fault_armed() {
75+ return ffi::SQLITE_IOERR;
76+ }
77+ file_delegate!(file, xWrite, buf, amt, offset)
78+}
79+unsafe extern "C" fn shim_truncate(
80+ file: *mut ffi::sqlite3_file,
81+ size: i64,
82+) -> c_int {
83+ file_delegate!(file, xTruncate, size)
84+}
85+unsafe extern "C" fn shim_sync(
86+ file: *mut ffi::sqlite3_file,
87+ flags: c_int,
88+) -> c_int {
89+ file_delegate!(file, xSync, flags)
90+}
91+unsafe extern "C" fn shim_file_size(
92+ file: *mut ffi::sqlite3_file,
93+ size: *mut i64,
94+) -> c_int {
95+ file_delegate!(file, xFileSize, size)
96+}
97+unsafe extern "C" fn shim_lock(
98+ file: *mut ffi::sqlite3_file,
99+ level: c_int,
100+) -> c_int {
101+ file_delegate!(file, xLock, level)
102+}
103+unsafe extern "C" fn shim_unlock(
104+ file: *mut ffi::sqlite3_file,
105+ level: c_int,
106+) -> c_int {
107+ file_delegate!(file, xUnlock, level)
108+}
109+unsafe extern "C" fn shim_check_reserved_lock(
110+ file: *mut ffi::sqlite3_file,
111+ out: *mut c_int,
112+) -> c_int {
113+ file_delegate!(file, xCheckReservedLock, out)
114+}
115+unsafe extern "C" fn shim_file_control(
116+ file: *mut ffi::sqlite3_file,
117+ op: c_int,
118+ arg: *mut c_void,
119+) -> c_int {
120+ file_delegate!(file, xFileControl, op, arg)
121+}
122+unsafe extern "C" fn shim_sector_size(file: *mut ffi::sqlite3_file) -> c_int {
123+ file_delegate!(file, xSectorSize)
124+}
125+unsafe extern "C" fn shim_device_characteristics(
126+ file: *mut ffi::sqlite3_file,
127+) -> c_int {
128+ file_delegate!(file, xDeviceCharacteristics)
129+}
130+unsafe extern "C" fn shim_shm_map(
131+ file: *mut ffi::sqlite3_file,
132+ region: c_int,
133+ size: c_int,
134+ extend: c_int,
135+ out: *mut *mut c_void,
136+) -> c_int {
137+ file_delegate!(file, xShmMap, region, size, extend, out)
138+}
139+unsafe extern "C" fn shim_shm_lock(
140+ file: *mut ffi::sqlite3_file,
141+ offset: c_int,
142+ count: c_int,
143+ flags: c_int,
144+) -> c_int {
145+ file_delegate!(file, xShmLock, offset, count, flags)
146+}
147+unsafe extern "C" fn shim_shm_barrier(file: *mut ffi::sqlite3_file) {
148+ file_delegate!(file, xShmBarrier)
149+}
150+unsafe extern "C" fn shim_shm_unmap(
151+ file: *mut ffi::sqlite3_file,
152+ delete_flag: c_int,
153+) -> c_int {
154+ file_delegate!(file, xShmUnmap, delete_flag)
155+}
156+unsafe extern "C" fn shim_fetch(
157+ file: *mut ffi::sqlite3_file,
158+ offset: i64,
159+ amt: c_int,
160+ out: *mut *mut c_void,
161+) -> c_int {
162+ file_delegate!(file, xFetch, offset, amt, out)
163+}
164+unsafe extern "C" fn shim_unfetch(
165+ file: *mut ffi::sqlite3_file,
166+ offset: i64,
167+ page: *mut c_void,
168+) -> c_int {
169+ file_delegate!(file, xUnfetch, offset, page)
170+}
171+
172+static SHIM_IO_METHODS: ffi::sqlite3_io_methods = ffi::sqlite3_io_methods {
173+ iVersion: 3,
174+ xClose: Some(shim_close),
175+ xRead: Some(shim_read),
176+ xWrite: Some(shim_write),
177+ xTruncate: Some(shim_truncate),
178+ xSync: Some(shim_sync),
179+ xFileSize: Some(shim_file_size),
180+ xLock: Some(shim_lock),
181+ xUnlock: Some(shim_unlock),
182+ xCheckReservedLock: Some(shim_check_reserved_lock),
183+ xFileControl: Some(shim_file_control),
184+ xSectorSize: Some(shim_sector_size),
185+ xDeviceCharacteristics: Some(shim_device_characteristics),
186+ xShmMap: Some(shim_shm_map),
187+ xShmLock: Some(shim_shm_lock),
188+ xShmBarrier: Some(shim_shm_barrier),
189+ xShmUnmap: Some(shim_shm_unmap),
190+ xFetch: Some(shim_fetch),
191+ xUnfetch: Some(shim_unfetch),
192+};
193+
194+unsafe extern "C" fn shim_open(
195+ vfs: *mut ffi::sqlite3_vfs,
196+ name: *const c_char,
197+ file: *mut ffi::sqlite3_file,
198+ flags: c_int,
199+ out_flags: *mut c_int,
200+) -> c_int {
201+ let real = real_vfs(vfs);
202+ let shim = file.cast::<ShimFile>();
203+ let inner = file.cast::<u8>().add(size_of::<ShimFile>()).cast();
204+ (*shim).base.pMethods = std::ptr::null();
205+ (*shim).real = inner;
206+ let open = (*real).xOpen.expect("real vfs xOpen");
207+ let rc = open(real, name, inner, flags, out_flags);
208+ if !(*inner).pMethods.is_null() {
209+ (*shim).base.pMethods = &SHIM_IO_METHODS;
210+ }
211+ rc
212+}
213+unsafe extern "C" fn shim_delete(
214+ vfs: *mut ffi::sqlite3_vfs,
215+ name: *const c_char,
216+ sync_dir: c_int,
217+) -> c_int {
218+ vfs_delegate!(vfs, xDelete, name, sync_dir)
219+}
220+unsafe extern "C" fn shim_access(
221+ vfs: *mut ffi::sqlite3_vfs,
222+ name: *const c_char,
223+ flags: c_int,
224+ out: *mut c_int,
225+) -> c_int {
226+ vfs_delegate!(vfs, xAccess, name, flags, out)
227+}
228+unsafe extern "C" fn shim_full_pathname(
229+ vfs: *mut ffi::sqlite3_vfs,
230+ name: *const c_char,
231+ length: c_int,
232+ out: *mut c_char,
233+) -> c_int {
234+ vfs_delegate!(vfs, xFullPathname, name, length, out)
235+}
236+unsafe extern "C" fn shim_randomness(
237+ vfs: *mut ffi::sqlite3_vfs,
238+ length: c_int,
239+ out: *mut c_char,
240+) -> c_int {
241+ vfs_delegate!(vfs, xRandomness, length, out)
242+}
243+unsafe extern "C" fn shim_sleep(
244+ vfs: *mut ffi::sqlite3_vfs,
245+ microseconds: c_int,
246+) -> c_int {
247+ vfs_delegate!(vfs, xSleep, microseconds)
248+}
249+unsafe extern "C" fn shim_current_time(
250+ vfs: *mut ffi::sqlite3_vfs,
251+ out: *mut f64,
252+) -> c_int {
253+ vfs_delegate!(vfs, xCurrentTime, out)
254+}
255+unsafe extern "C" fn shim_get_last_error(
256+ vfs: *mut ffi::sqlite3_vfs,
257+ length: c_int,
258+ out: *mut c_char,
259+) -> c_int {
260+ vfs_delegate!(vfs, xGetLastError, length, out)
261+}
262+unsafe extern "C" fn shim_current_time_int64(
263+ vfs: *mut ffi::sqlite3_vfs,
264+ out: *mut i64,
265+) -> c_int {
266+ vfs_delegate!(vfs, xCurrentTimeInt64, out)
267+}
268+
269+fn install() {
270+ static INSTALL: Once = Once::new();
271+ INSTALL.call_once(|| {
272+ // SAFETY: the default VFS outlives the process; the shim is leaked so
273+ // SQLite may hold it forever. Registration is not made the default,
274+ // so only connections opened by name route through the shim.
275+ unsafe {
276+ let real = ffi::sqlite3_vfs_find(std::ptr::null());
277+ assert!(!real.is_null(), "no default SQLite VFS");
278+ let vfs = Box::leak(Box::new(ffi::sqlite3_vfs {
279+ iVersion: 2,
280+ szOsFile: (*real).szOsFile + size_of::<ShimFile>() as c_int,
281+ mxPathname: (*real).mxPathname,
282+ pNext: std::ptr::null_mut(),
283+ zName: FAULT_VFS_NAME.as_ptr(),
284+ pAppData: real.cast(),
285+ xOpen: Some(shim_open),
286+ xDelete: Some(shim_delete),
287+ xAccess: Some(shim_access),
288+ xFullPathname: Some(shim_full_pathname),
289+ xDlOpen: None,
290+ xDlError: None,
291+ xDlSym: None,
292+ xDlClose: None,
293+ xRandomness: Some(shim_randomness),
294+ xSleep: Some(shim_sleep),
295+ xCurrentTime: Some(shim_current_time),
296+ xGetLastError: Some(shim_get_last_error),
297+ xCurrentTimeInt64: Some(shim_current_time_int64),
298+ xSetSystemCall: None,
299+ xGetSystemCall: None,
300+ xNextSystemCall: None,
301+ }));
302+ assert_eq!(ffi::sqlite3_vfs_register(vfs, 0), ffi::SQLITE_OK);
303+ }
304+ });
305+}
306+
307+/// Open `path` through the fault-injection VFS.
308+pub fn open_database(path: &str) -> rusqlite::Result<rusqlite::Connection> {
309+ install();
310+ rusqlite::Connection::open_with_flags_and_vfs(
311+ path,
312+ rusqlite::OpenFlags::default(),
313+ FAULT_VFS_NAME.to_str().unwrap(),
314+ )
315+}
addedcrates/celld/fleet.rs+590−0View file
@@ -1,0 +1,590 @@
1+//! Production bucket deployment adapters reused by the clean-sheet host.
2+
3+use crate::deploy;
4+use crate::js::WorkerConfigOptions;
5+use crate::protocol::{DeployPointer, Manifest};
6+use anyhow::{bail, Context};
7+use aws_sdk_s3::error::SdkError;
8+use aws_sdk_s3::Client;
9+use serde::Deserialize;
10+use std::collections::BTreeMap;
11+use std::time::Duration;
12+use tracing::info;
13+
14+pub async fn s3_client(endpoint: Option<&str>, region: &str) -> Client {
15+ s3_client_with_credentials(endpoint, region, None).await
16+}
17+
18+/// Build the authority-heartbeat client on its own HTTP connection pool.
19+///
20+/// Node lease traffic must not queue behind ordinary ownership, deployment,
21+/// or replica requests. The distinct application name also makes the safety
22+/// lane observable in black-box storage traces.
23+pub async fn s3_lease_client_with_credentials(
24+ endpoint: Option<&str>,
25+ region: &str,
26+ managed: Option<&crate::control_plane::ManagedStorageConfig>,
27+) -> Client {
28+ s3_client_with_transport(endpoint, region, managed, true).await
29+}
30+
31+pub async fn s3_client_with_credentials(
32+ endpoint: Option<&str>,
33+ region: &str,
34+ managed: Option<&crate::control_plane::ManagedStorageConfig>,
35+) -> Client {
36+ s3_client_with_transport(endpoint, region, managed, false).await
37+}
38+
39+async fn s3_client_with_transport(
40+ endpoint: Option<&str>,
41+ region: &str,
42+ managed: Option<&crate::control_plane::ManagedStorageConfig>,
43+ isolated_transport: bool,
44+) -> Client {
45+ let timeouts = aws_config::timeout::TimeoutConfig::builder()
46+ .connect_timeout(Duration::from_secs(3))
47+ .read_timeout(Duration::from_secs(10))
48+ .operation_attempt_timeout(Duration::from_secs(15))
49+ .operation_timeout(Duration::from_secs(30))
50+ .build();
51+ let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest())
52+ .timeout_config(timeouts)
53+ .region(aws_config::Region::new(region.to_string()));
54+ if isolated_transport {
55+ let http_client = aws_smithy_http_client::Builder::new()
56+ .tls_provider(aws_smithy_http_client::tls::Provider::Rustls(
57+ aws_smithy_http_client::tls::rustls_provider::CryptoMode::AwsLc,
58+ ))
59+ .build_https();
60+ loader = loader
61+ .http_client(http_client)
62+ .app_name(aws_config::AppName::new("celld-lease").expect("valid lease app name"));
63+ }
64+ if let Some(endpoint) = endpoint {
65+ loader = loader.endpoint_url(endpoint);
66+ }
67+ if let Some(managed) = managed {
68+ loader = loader.credentials_provider(aws_credential_types::Credentials::new(
69+ managed.access_key_id.clone(),
70+ managed.secret_access_key.clone(),
71+ managed.session_token.clone(),
72+ None,
73+ "managed-installation",
74+ ));
75+ }
76+ let shared = loader.load().await;
77+ let config = aws_sdk_s3::config::Builder::from(&shared)
78+ .force_path_style(endpoint.is_some())
79+ .build();
80+ Client::from_conf(config)
81+}
82+
83+pub async fn validate_bucket(client: &Client, bucket: &str) -> anyhow::Result<()> {
84+ client
85+ .head_bucket()
86+ .bucket(bucket)
87+ .send()
88+ .await
89+ .with_context(|| format!("bucket unavailable or inaccessible: s3://{bucket}"))?;
90+ Ok(())
91+}
92+
93+/// Validate storage issued by the Managed Control Plane and preserve the
94+/// operator-visible failure vocabulary. Newly issued provider credentials can
95+/// take a moment to propagate, so only the final rejection is authoritative.
96+pub async fn validate_managed_bucket(client: &Client, bucket: &str) -> anyhow::Result<()> {
97+ const RETRIES: u32 = 5;
98+ for attempt in 1..=RETRIES {
99+ match validate_managed_bucket_once(client, bucket, attempt == RETRIES).await {
100+ Ok(()) => return Ok(()),
101+ Err(error) if attempt == RETRIES => return Err(error),
102+ Err(_) => {
103+ info!(bucket, attempt, "storage credential not accepted yet; retrying");
104+ tokio::time::sleep(Duration::from_millis(500 * u64::from(attempt))).await;
105+ }
106+ }
107+ }
108+ unreachable!("loop returns on the final attempt")
109+}
110+
111+async fn validate_managed_bucket_once(
112+ client: &Client,
113+ bucket: &str,
114+ report: bool,
115+) -> anyhow::Result<()> {
116+ match client.head_bucket().bucket(bucket).send().await {
117+ Ok(_) => Ok(()),
118+ Err(SdkError::ServiceError(error))
119+ if matches!(error.raw().status().as_u16(), 401 | 403) =>
120+ {
121+ if report {
122+ crate::control_plane::report_managed_runtime_state(
123+ crate::control_plane::ManagedRuntimeState::CredentialRevoked,
124+ );
125+ bail!("managed storage credential was rejected or revoked for s3://{bucket}");
126+ }
127+ bail!("managed storage credential was not accepted yet for s3://{bucket}");
128+ }
129+ Err(error) => {
130+ if report {
131+ crate::control_plane::report_managed_runtime_state(
132+ crate::control_plane::ManagedRuntimeState::BucketUnavailable,
133+ );
134+ }
135+ Err(error).with_context(|| format!("bucket unavailable or inaccessible: s3://{bucket}"))
136+ }
137+ }
138+}
139+
140+#[derive(Deserialize)]
141+pub(crate) struct DiagnosticNode {
142+ pub(crate) node: String,
143+ pub(crate) expires_ms: u64,
144+ pub(crate) addr: String,
145+ #[serde(default)]
146+ pub(crate) probe_public_key: String,
147+ #[serde(default)]
148+ pub(crate) peer_protocol: u16,
149+ #[serde(default)]
150+ pub(crate) load: crate::ownership_store::NodeLoadWire,
151+}
152+
153+pub async fn diagnose(
154+ client: &Client,
155+ bucket: &str,
156+ peers: Vec<String>,
157+ unsafe_public_advertise: bool,
158+) -> anyhow::Result<()> {
159+ validate_bucket(client, bucket).await?;
160+ println!("ok bucket s3://{bucket}");
161+
162+ let enumerated = peers.is_empty();
163+ let peers = if enumerated {
164+ let peers = diagnostic_node_ids(client, bucket).await?;
165+ println!("ok fleet {} node lease(s) enumerated", peers.len());
166+ peers
167+ } else {
168+ peers
169+ };
170+ if peers.is_empty() {
171+ return Ok(());
172+ }
173+ let http = reqwest::Client::builder()
174+ .connect_timeout(Duration::from_secs(3))
175+ .timeout(Duration::from_secs(5))
176+ .redirect(reqwest::redirect::Policy::none())
177+ .build()
178+ .context("build peer diagnostic client")?;
179+ let auth = crate::peer_auth::PeerAuth::new(
180+ crate::peer_auth::load_existing(client, bucket).await?,
181+ "diagnostic",
182+ )?;
183+ let mut failures = 0_usize;
184+ let mut expired = 0_usize;
185+ for peer in peers {
186+ let node = match diagnostic_node(client, bucket, &peer).await {
187+ Ok(Some(node)) => node,
188+ Ok(None) if enumerated => {
189+ expired += 1;
190+ println!("skip peer {peer}: lease is expired");
191+ continue;
192+ }
193+ Ok(None) => {
194+ failures += 1;
195+ eprintln!("fail peer {peer}: node {peer} lease is expired");
196+ continue;
197+ }
198+ Err(error) => {
199+ failures += 1;
200+ eprintln!("fail peer {peer}: {error}");
201+ continue;
202+ }
203+ };
204+ let advertise = match crate::startup::parse_advertise(&node.addr) {
205+ Ok(advertise) => advertise,
206+ Err(error) => {
207+ failures += 1;
208+ eprintln!(
209+ "fail peer {peer}: malformed advertise address {:?}: {error}",
210+ node.addr
211+ );
212+ continue;
213+ }
214+ };
215+ if advertise.is_public_ip() && !unsafe_public_advertise {
216+ failures += 1;
217+ eprintln!(
218+ "fail peer {peer}: unsafe public advertise address {}; use a private overlay or --unsafe-public-advertise",
219+ node.addr
220+ );
221+ continue;
222+ }
223+ if let Err(error) = crate::peer_probe::probe(&http, &node, &auth).await {
224+ failures += 1;
225+ eprintln!("fail peer {peer} at {}: {error}", node.addr);
226+ continue;
227+ }
228+ let load_age_ms = if node.load.sampled_ms == 0 {
229+ "unknown".to_string()
230+ } else {
231+ crate::ownership_store::now_ms()
232+ .saturating_sub(node.load.sampled_ms)
233+ .to_string()
234+ };
235+ println!(
236+ "ok peer {} at {} (signed direct probe) protocol={} resident_cells={} \
237+ websockets={} rss_bytes={} cpu_percent={:.2} fds={}/{} pressured={} \
238+ shed_cells={} load_age_ms={}",
239+ node.node,
240+ node.addr,
241+ node.peer_protocol,
242+ node.load.resident_cells,
243+ node.load.host_websockets,
244+ node.load.rss_bytes,
245+ node.load.cpu_percent_x100 as f64 / 100.0,
246+ node.load.open_fds,
247+ node.load.fd_limit,
248+ node.load.pressured,
249+ node.load.shed_cells,
250+ load_age_ms,
251+ );
252+ }
253+ if expired > 0 {
254+ println!("ok fleet skipped {expired} expired node lease(s)");
255+ }
256+ if failures > 0 {
257+ bail!("fleet diagnostics failed for {failures} peer(s)");
258+ }
259+ Ok(())
260+}
261+
262+async fn diagnostic_node(
263+ client: &Client,
264+ bucket: &str,
265+ peer: &str,
266+) -> anyhow::Result<Option<DiagnosticNode>> {
267+ let key = format!("nodes/{peer}.json");
268+ let node: DiagnosticNode = serde_json::from_str(&get_string(client, bucket, &key).await?)
269+ .with_context(|| format!("decode s3://{bucket}/{key}"))?;
270+ if node.node != peer {
271+ bail!(
272+ "node lease {key} identifies unexpected node {:?}",
273+ node.node
274+ );
275+ }
276+ if node.expires_ms <= crate::ownership_store::now_ms() {
277+ return Ok(None);
278+ }
279+ if node.addr.is_empty() {
280+ bail!("node {peer} lease has no advertised address");
281+ }
282+ Ok(Some(node))
283+}
284+
285+async fn diagnostic_node_ids(client: &Client, bucket: &str) -> anyhow::Result<Vec<String>> {
286+ let mut nodes = Vec::new();
287+ let mut token: Option<String> = None;
288+ loop {
289+ let mut request = client.list_objects_v2().bucket(bucket).prefix("nodes/");
290+ if let Some(token) = &token {
291+ request = request.continuation_token(token);
292+ }
293+ let page = request.send().await.context("enumerate node leases")?;
294+ for object in page.contents() {
295+ let Some(node) = object
296+ .key()
297+ .and_then(|key| key.strip_prefix("nodes/"))
298+ .and_then(|key| key.strip_suffix(".json"))
299+ else {
300+ continue;
301+ };
302+ if !node.is_empty() {
303+ nodes.push(node.to_string());
304+ }
305+ }
306+ match page.next_continuation_token() {
307+ Some(next) => token = Some(next.to_string()),
308+ None => break,
309+ }
310+ }
311+ nodes.sort();
312+ nodes.dedup();
313+ Ok(nodes)
314+}
315+
316+pub async fn run_deploy(arguments: Vec<String>) -> anyhow::Result<()> {
317+ let Some(mut options) = deploy::options_from_arguments(arguments)? else {
318+ deploy::print_help();
319+ return Ok(());
320+ };
321+ let env = |name: &str| {
322+ std::env::var(name)
323+ .ok()
324+ .filter(|value| !value.trim().is_empty())
325+ };
326+ if options.bucket.is_none() {
327+ options.bucket =
328+ env("CELLD_BUCKET").map(|value| value.trim_start_matches("s3://").to_string());
329+ }
330+ if options.endpoint.is_none() {
331+ options.endpoint = env("S3_ENDPOINT");
332+ }
333+ if !options.dry_run && options.bucket.is_none() {
334+ bail!("celld deploy requires --bucket s3://NAME (or CELLD_BUCKET)");
335+ }
336+ let built = deploy::build(&options)?;
337+ built.report();
338+ if options.dry_run {
339+ println!(
340+ "Current Version ID: {} (dry run; nothing written)",
341+ built.version
342+ );
343+ return Ok(());
344+ }
345+
346+ let bucket = options.bucket.expect("validated deployment bucket");
347+ let region = options
348+ .region
349+ .or_else(|| env("AWS_REGION"))
350+ .or_else(|| env("AWS_DEFAULT_REGION"))
351+ .unwrap_or_else(|| "us-east-1".to_string());
352+ let client = s3_client(options.endpoint.as_deref(), &region).await;
353+ validate_bucket(&client, &bucket).await?;
354+ let started = std::time::Instant::now();
355+ deploy::write(&client, &bucket, &built).await?;
356+ println!(
357+ "Uploaded {} ({:.2} sec)",
358+ built.script_name,
359+ started.elapsed().as_secs_f64()
360+ );
361+ println!(" s3://{bucket}/{}", built.prefix);
362+ println!("Current Version ID: {}", built.version);
363+ println!("Nodes load a deployment at startup; restart them to serve this version.");
364+ Ok(())
365+}
366+
367+async fn get_string(client: &Client, bucket: &str, key: &str) -> anyhow::Result<String> {
368+ let object = client
369+ .get_object()
370+ .bucket(bucket)
371+ .key(key)
372+ .send()
373+ .await
374+ .with_context(|| format!("read s3://{bucket}/{key}"))?;
375+ let bytes = object
376+ .body
377+ .collect()
378+ .await
379+ .with_context(|| format!("read body s3://{bucket}/{key}"))?
380+ .into_bytes();
381+ String::from_utf8(bytes.to_vec()).context("deployment module is not UTF-8")
382+}
383+
384+pub async fn load_current_worker(
385+ client: &Client,
386+ bucket: &str,
387+ node: String,
388+) -> anyhow::Result<LoadedDeployment> {
389+ load_worker_from_pointer(client, bucket, "deploy/current.json", node).await
390+}
391+
392+pub async fn load_named_worker(
393+ client: &Client,
394+ bucket: &str,
395+ script: &str,
396+ node: String,
397+) -> anyhow::Result<LoadedDeployment> {
398+ load_worker_from_pointer(
399+ client,
400+ bucket,
401+ &format!("deploy/{script}/current.json"),
402+ node,
403+ )
404+ .await
405+}
406+
407+async fn load_worker_from_pointer(
408+ client: &Client,
409+ bucket: &str,
410+ pointer_key: &str,
411+ node: String,
412+) -> anyhow::Result<LoadedDeployment> {
413+ let pointer: DeployPointer =
414+ serde_json::from_str(&get_string(client, bucket, pointer_key).await?)
415+ .with_context(|| format!("decode {pointer_key}"))?;
416+ let manifest: Manifest = serde_json::from_str(
417+ &get_string(client, bucket, &format!("{}/manifest.json", pointer.prefix)).await?,
418+ )
419+ .context("decode deployment manifest")?;
420+ let src = match manifest.main_module.as_deref() {
421+ Some(main) => get_string(client, bucket, &format!("{}/{main}", pointer.prefix)).await?,
422+ None if manifest.assets.is_some() => {
423+ // Ingress is handled by the immutable asset resolver. Keeping a
424+ // synthetic Worker makes the runtime construction path uniform
425+ // and is a fail-closed guard if an asset-only request escapes it.
426+ "export default { fetch() { return new Response('Not found', { status: 404 }); } };"
427+ .to_string()
428+ }
429+ None => bail!("deployment has neither a main module nor assets"),
430+ };
431+ let mut text = Vec::new();
432+ for module in &manifest.modules {
433+ if manifest.main_module.as_deref() == Some(module.name.as_str()) {
434+ continue;
435+ }
436+ let source = get_string(
437+ client,
438+ bucket,
439+ &format!("{}/{}", pointer.prefix, module.name),
440+ )
441+ .await?;
442+ text.push((format!("./{}", module.name), source));
443+ }
444+ let do_bindings = bindings(&manifest, "durable_object_namespace")
445+ .filter_map(|binding| {
446+ Some((
447+ binding.get("name")?.as_str()?.to_string(),
448+ binding.get("class_name")?.as_str()?.to_string(),
449+ ))
450+ })
451+ .collect();
452+ let r2_bindings = bindings(&manifest, "r2_bucket")
453+ .filter_map(|binding| binding.get("name")?.as_str().map(str::to_string))
454+ .collect();
455+ let ai_binding = configured_ai_binding(
456+ bindings(&manifest, "ai")
457+ .find_map(|binding| binding.get("name")?.as_str().map(str::to_string)),
458+ );
459+ let services = service_bindings(&manifest);
460+ let vars = worker_vars(&manifest)?;
461+ let compat = crate::worker_compat(&manifest.raw_metadata);
462+ let assets = match &manifest.assets {
463+ Some(reference) => Some(
464+ crate::assets::AssetResolver::load(
465+ client,
466+ bucket,
467+ &pointer.prefix,
468+ reference,
469+ manifest.main_module.is_none(),
470+ )
471+ .await?,
472+ ),
473+ None => None,
474+ };
475+ let asset_binding = assets
476+ .as_ref()
477+ .and_then(crate::assets::AssetResolver::binding_name)
478+ .map(str::to_string);
479+ let script_name = manifest.script_name.clone();
480+ Ok(LoadedDeployment {
481+ options: WorkerConfigOptions {
482+ src,
483+ script_name: script_name.clone(),
484+ do_classes: manifest.do_classes,
485+ bindings: do_bindings,
486+ r2_bindings,
487+ ai_binding,
488+ vars,
489+ node,
490+ text,
491+ compat,
492+ },
493+ script_name,
494+ asset_binding,
495+ assets,
496+ services,
497+ })
498+}
499+
500+/// Apply celld's manifest-first precedence for the optional AI binding.
501+pub fn configured_ai_binding(manifest_binding: Option<String>) -> Option<String> {
502+ manifest_binding
503+ .or_else(|| std::env::var("CELLD_AI_BINDING").ok())
504+ .or_else(|| std::env::var_os("CELLD_AI_URL").map(|_| "AI".to_string()))
505+}
506+
507+pub struct LoadedDeployment {
508+ pub options: WorkerConfigOptions,
509+ pub script_name: String,
510+ pub asset_binding: Option<String>,
511+ pub assets: Option<crate::assets::AssetResolver>,
512+ pub services: Vec<(String, String, Option<String>)>,
513+}
514+
515+fn bindings<'a>(
516+ manifest: &'a Manifest,
517+ kind: &'a str,
518+) -> impl Iterator<Item = &'a serde_json::Value> {
519+ manifest
520+ .raw_metadata
521+ .get("bindings")
522+ .and_then(serde_json::Value::as_array)
523+ .into_iter()
524+ .flatten()
525+ .filter(move |binding| {
526+ binding.get("type").and_then(serde_json::Value::as_str) == Some(kind)
527+ })
528+}
529+
530+fn service_bindings(manifest: &Manifest) -> Vec<(String, String, Option<String>)> {
531+ bindings(manifest, "service")
532+ .filter_map(|binding| {
533+ Some((
534+ binding.get("name")?.as_str()?.to_string(),
535+ binding.get("service")?.as_str()?.to_string(),
536+ binding
537+ .get("entrypoint")
538+ .and_then(serde_json::Value::as_str)
539+ .map(str::to_string),
540+ ))
541+ })
542+ .collect()
543+}
544+
545+fn worker_vars(manifest: &Manifest) -> anyhow::Result<Vec<(String, String)>> {
546+ let mut vars = BTreeMap::new();
547+ for binding in bindings(manifest, "plain_text") {
548+ if let (Some(name), Some(value)) = (
549+ binding.get("name").and_then(serde_json::Value::as_str),
550+ binding.get("text").and_then(serde_json::Value::as_str),
551+ ) {
552+ vars.insert(name.to_string(), value.to_string());
553+ }
554+ }
555+ if let Ok(path) = std::env::var("CELLD_VARS_FILE") {
556+ let contents = std::fs::read_to_string(&path)
557+ .with_context(|| format!("read Worker vars file {path}"))?;
558+ for line in contents.lines().map(str::trim) {
559+ if line.is_empty() || line.starts_with('#') {
560+ continue;
561+ }
562+ let Some((name, raw)) = line.split_once('=') else {
563+ continue;
564+ };
565+ let name = name.trim();
566+ if name.is_empty() {
567+ continue;
568+ }
569+ let raw = raw.trim();
570+ let value = raw
571+ .strip_prefix('"')
572+ .and_then(|value| value.strip_suffix('"'))
573+ .or_else(|| {
574+ raw.strip_prefix('\'')
575+ .and_then(|value| value.strip_suffix('\''))
576+ })
577+ .unwrap_or(raw);
578+ vars.insert(name.to_string(), value.to_string());
579+ }
580+ }
581+ for (name, value) in std::env::vars() {
582+ if let Some(name) = name
583+ .strip_prefix("CELLD_VAR_")
584+ .filter(|name| !name.is_empty())
585+ {
586+ vars.insert(name.to_string(), value);
587+ }
588+ }
589+ Ok(vars.into_iter().collect())
590+}
addedcrates/celld/js.rs+7812−0View file
@@ -1,0 +1,7812 @@
1+//! The JS engine: rusty_v8 directly. One isolate per cell.
2+//!
3+//! This slice runs actual Durable Objects: the worker's default-export `fetch`
4+//! receives an `env` whose bindings are DO namespaces; `env.NS.get(id).fetch()`
5+//! instantiates the exported DO class (once per id) with a `state` whose
6+//! `storage` is backed by the cell's SQLite (crate::storage). DO storage is
7+//! async in JS, synchronous underneath — the ops are sync Rust, wrapped in
8+//! `async` by the JS harness.
9+use crate::asyncrt;
10+use crate::storage;
11+use anyhow::{anyhow, Result};
12+use futures_util::StreamExt as _;
13+use std::cell::RefCell;
14+use std::collections::{HashMap, HashSet};
15+use std::pin::Pin;
16+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
17+use std::sync::{Arc, Mutex, OnceLock};
18+use std::time::{Duration, Instant};
19+use tokio::task::JoinSet;
20+use v8::{ValueDeserializerHelper, ValueSerializerHelper};
21+
22+/// The pending exception text from a TryCatch scope (a macro so it needs no
23+/// bound on the crate-private scope traits).
24+macro_rules! exc {
25+ ($tc:expr) => {
26+ $tc.exception()
27+ .map(|e| e.to_rust_string_lossy(&*$tc))
28+ .unwrap_or_else(|| "<none>".into())
29+ };
30+}
31+
32+/// A cross-node dispatch: the isolate hit `env.NS.get(id)` for a cell this node
33+/// does not own. The op hands this to the tokio runtime, which resolves the
34+/// owner and HTTP-proxies the fetch, replying on `reply` (an async oneshot the
35+/// async-op future awaits — the JS thread is never blocked).
36+pub struct DoCallReq {
37+ pub request_id: Option<RequestId>,
38+ pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
39+ pub scope: String,
40+ pub name: Option<String>,
41+ pub url: String,
42+ pub method: String,
43+ pub body: Vec<u8>,
44+ pub headers: Vec<(String, String)>,
45+ pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
46+}
47+static DO_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<DoCallReq>> = OnceLock::new();
48+
49+/// An output-gate request for the co-hosted (same-isolate) Durable Object fast
50+/// path. That path runs a resident DO's `fetch` inline, bypassing
51+/// `dispatch_do_call` where the gate lives; the inline handler samples the
52+/// cell's committed-write position and, on a write, asks the actor to hold the
53+/// inline response here until the cell is durable. `position` is the sampled
54+/// committed-write position (the same signal the routed gate uses).
55+pub struct GateReq {
56+ pub scope: String,
57+ pub position: u64,
58+ pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>,
59+}
60+static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new();
61+pub fn set_gate_tx(tx: tokio::sync::mpsc::UnboundedSender<GateReq>) {
62+ let _ = GATE_TX.set(tx);
63+}
64+
65+/// A service-binding call: `env.NAME.fetch()`. Unlike a Durable Object call
66+/// there is no identity to resolve — any isolate running `script` will do — so
67+/// the runtime hands this straight to that script's worker pool.
68+pub struct SvcCallReq {
69+ /// Fires when the caller's request signal aborts, so the router stops
70+ /// waiting on the target instead of leaving the call outstanding.
71+ pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
72+ pub script: String,
73+ pub url: String,
74+ pub method: String,
75+ pub body: Vec<u8>,
76+ pub headers: Vec<(String, String)>,
77+ pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
78+}
79+static SVC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcCallReq>> = OnceLock::new();
80+
81+/// A Worker assets-binding call. The script name selects the immutable asset
82+/// index loaded for that Worker; unlike ingress this never falls back into the
83+/// Worker and therefore cannot recurse.
84+pub struct AssetCallReq {
85+ pub script: String,
86+ pub url: String,
87+ pub method: String,
88+ pub headers: Vec<(String, String)>,
89+ pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
90+}
91+static ASSET_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<AssetCallReq>> = OnceLock::new();
92+
93+/// An RPC call on a named `WorkerEntrypoint` of another script. Arguments and
94+/// the result cross as V8 structured-clone bytes.
95+pub struct SvcRpcReq {
96+ pub script: String,
97+ pub entrypoint: String,
98+ pub method: String,
99+ pub args: Vec<u8>,
100+ pub reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
101+}
102+static SVC_RPC_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcRpcReq>> = OnceLock::new();
103+pub fn set_svc_rpc_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcRpcReq>) {
104+ let _ = SVC_RPC_TX.set(tx);
105+}
106+pub fn set_svc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcCallReq>) {
107+ let _ = SVC_CALL_TX.set(tx);
108+}
109+pub fn set_asset_call_tx(tx: tokio::sync::mpsc::UnboundedSender<AssetCallReq>) {
110+ let _ = ASSET_CALL_TX.set(tx);
111+}
112+pub fn set_do_call_tx(tx: tokio::sync::mpsc::UnboundedSender<DoCallReq>) {
113+ let _ = DO_CALL_TX.set(tx);
114+}
115+
116+/// Hand a Durable Object call to the dispatcher. Public HTTP ingress uses the
117+/// same queue a Worker's `env.NAME.get(id).fetch()` does, so both resolve
118+/// ownership, forward, and redispatch by one policy rather than two.
119+#[must_use]
120+pub fn submit_do_call(call: DoCallReq) -> bool {
121+ DO_CALL_TX.get().is_some_and(|tx| tx.send(call).is_ok())
122+}
123+
124+/// The arm-time wake-entry gate, output-gate style (matching Durable
125+/// Objects): `setAlarm()` resolves optimistically on the committed local
126+/// write — it never yields the cell's event scheduling to remote I/O — and
127+/// the cell's response edge is withheld until every pending wake-entry PUT
128+/// has landed. Invariant: an arm the caller has OBSERVED acknowledged
129+/// (received the response) is covered by a durable entry.
130+pub struct ArmGate {
131+ pub c: aws_sdk_s3::Client,
132+ pub bucket: String,
133+ pub flusher: Arc<crate::wake::WakeFlusher>,
134+}
135+static ARM_GATE: OnceLock<ArmGate> = OnceLock::new();
136+pub fn set_arm_gate(gate: ArmGate) {
137+ let _ = ARM_GATE.set(gate);
138+}
139+
140+/// Whether this node still holds a wake entry for `cell`.
141+pub fn wake_entry_tracked(cell: &str) -> bool {
142+ ARM_GATE
143+ .get()
144+ .is_some_and(|gate| gate.flusher.tracks(cell))
145+}
146+
147+/// Adopt the wake entry a restored alarm implies, so consuming that alarm
148+/// deletes it rather than orphaning it.
149+pub fn adopt_wake_entry(cell: &str, at_ms: i64) {
150+ if let Some(gate) = ARM_GATE.get() {
151+ gate.flusher.adopt(cell, at_ms);
152+ }
153+}
154+
155+/// Bring the bucket's wake entry for `cell` into line with its alarm.
156+///
157+/// Arming writes an entry; something has to take it away again once the alarm
158+/// has been consumed, or the entry outlives its alarm and every later due scan
159+/// finds it and wakes a cell with nothing to do. `consume_durable` gates that
160+/// final delete on the consuming commit being replicated -- removing the hint
161+/// while the commit that consumed the alarm is still only local would lose
162+/// both the alarm and the record that could have revived it.
163+pub async fn reconcile_wake_entry(cell: &str, next_alarm_ms: i64, consume_durable: bool) {
164+ let Some(gate) = ARM_GATE.get() else {
165+ return;
166+ };
167+ gate.flusher
168+ .reconcile(&gate.c, &gate.bucket, cell, next_alarm_ms, consume_durable)
169+ .await;
170+}
171+
172+type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>;
173+static PENDING_ARM_GATES: OnceLock<Mutex<HashMap<String, Vec<ArmGateRx>>>> = OnceLock::new();
174+fn pending_arm_gates() -> &'static Mutex<HashMap<String, Vec<ArmGateRx>>> {
175+ PENDING_ARM_GATES.get_or_init(Default::default)
176+}
177+
178+/// A committed alarm tightened the durable wake bound: launch the entry PUT
179+/// and register it against the cell's output gate. No-op when the bound
180+/// already covers it or no gate is configured (unit tests).
181+fn spawn_arm_gate(cell: &str, at_ms: i64) {
182+ let Some(gate) = ARM_GATE.get() else { return };
183+ let Some(celld_logic::wake::Op::Put { key, due_ms }) = gate.flusher.arm_op(cell, at_ms) else {
184+ return;
185+ };
186+ let cell_ = cell.to_string();
187+ let (tx, rx) = tokio::sync::oneshot::channel();
188+ {
189+ let mut pending = pending_arm_gates().lock().unwrap();
190+ let gates = pending.entry(cell_.clone()).or_default();
191+ // Arms with no response edge to drain them (alarm handlers,
192+ // WebSocket events) must not accumulate: drop already-settled gates.
193+ gates.retain_mut(|gate| {
194+ matches!(
195+ gate.try_recv(),
196+ Err(tokio::sync::oneshot::error::TryRecvError::Empty)
197+ )
198+ });
199+ gates.push(rx);
200+ }
201+ asyncrt::op_handle().spawn(async move {
202+ let gate = ARM_GATE.get().unwrap();
203+ // The core may have demanded this PUT because the tracked entry's
204+ // consume-delete is already on the wire; the PUT must land after
205+ // that delete, not race it (S3 orders concurrent same-key writes
206+ // arbitrarily).
207+ gate.flusher.await_no_inflight_delete(&cell_).await;
208+ let body = format!("{{\"cell\":{cell_:?},\"due_ms\":{due_ms}}}");
209+ let result = gate
210+ .c
211+ .put_object()
212+ .bucket(&gate.bucket)
213+ .key(&key)
214+ .body(aws_sdk_s3::primitives::ByteStream::from(body.into_bytes()))
215+ .send()
216+ .await
217+ .map(|_| gate.flusher.confirm_arm(&cell_, due_ms, key))
218+ .map_err(|e| format!("setAlarm wake entry: {e}"));
219+ let _ = tx.send(result);
220+ });
221+}
222+
223+/// Await the cell's pending wake-entry PUTs — the output-gate drain a
224+/// response edge performs before releasing its reply. An error means an arm
225+/// the response would acknowledge is not durably covered; the caller must
226+/// fail the response rather than lie (the flusher retries the entry).
227+pub async fn drain_arm_gates(cell: &str) -> Result<(), String> {
228+ let gates = pending_arm_gates().lock().unwrap().remove(cell);
229+ let Some(gates) = gates else { return Ok(()) };
230+ for gate in gates {
231+ match gate.await {
232+ Ok(Ok(())) => {}
233+ Ok(Err(error)) => return Err(error),
234+ Err(_) => return Err("wake-entry gate task dropped".into()),
235+ }
236+ }
237+ Ok(())
238+}
239+
240+pub type RequestId = u128;
241+
242+#[derive(Clone, Copy)]
243+pub struct FetchRequest<'a> {
244+ pub url: &'a str,
245+ pub method: &'a str,
246+ pub body: &'a [u8],
247+ pub headers: &'a [(String, String)],
248+ pub request_id: Option<RequestId>,
249+}
250+
251+/// Allocate an id for an ingress or service-binding request so it can be
252+/// aborted mid-flight.
253+pub fn next_request_id() -> RequestId {
254+ next_do_request_id()
255+}
256+
257+static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
258+static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new();
259+static DO_CALL_CANCELS: OnceLock<
260+ std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>>,
261+> = OnceLock::new();
262+fn do_call_cancels(
263+) -> &'static std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>> {
264+ DO_CALL_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
265+}
266+
267+fn next_do_request_id() -> RequestId {
268+ let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| {
269+ let mut bytes = [0; 8];
270+ getrandom::fill(&mut bytes).expect("OS random source unavailable");
271+ u64::from_ne_bytes(bytes)
272+ });
273+ let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
274+ (u128::from(prefix) << 64) | u128::from(sequence)
275+}
276+
277+pub fn request_id_string(request_id: RequestId) -> String {
278+ format!("{request_id:032x}")
279+}
280+
281+pub fn parse_request_id(value: &str) -> Option<RequestId> {
282+ u128::from_str_radix(value, 16).ok()
283+}
284+
285+struct DoCallCancelGuard(RequestId);
286+
287+impl Drop for DoCallCancelGuard {
288+ fn drop(&mut self) {
289+ do_call_cancels().lock().unwrap().remove(&self.0);
290+ }
291+}
292+
293+/// An RPC payload crossing the host boundary. JS stubs marshal by V8
294+/// structured clone (`V8`); the legacy cross-node JSON envelope and the test
295+/// harness use `Json`. `__dispatchRpc` answers in the flavor it was asked in.
296+pub enum RpcData {
297+ Json(String),
298+ V8(Vec<u8>),
299+}
300+
301+/// A native Durable Object RPC call (`stub.someMethod(...args)`).
302+/// Routing/activation is identical to fetch calls.
303+pub struct RpcCallReq {
304+ pub scope: String,
305+ pub name: Option<String>,
306+ pub method: String,
307+ pub args: RpcData,
308+ pub reply: tokio::sync::oneshot::Sender<Result<RpcData>>,
309+}
310+static RPC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<RpcCallReq>> = OnceLock::new();
311+pub fn set_rpc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<RpcCallReq>) {
312+ let _ = RPC_CALL_TX.set(tx);
313+}
314+
315+pub struct OutboundWsReq {
316+ pub scope: String,
317+ pub id: u64,
318+ pub url: String,
319+ pub protocols: Vec<String>,
320+ /// Present for an isolate-polled (Worker) socket. Created and registered
321+ /// on the JS thread before the request is sent, so `__ws_next` can never
322+ /// run ahead of its own queue.
323+ pub pull: Option<WsPullSender>,
324+ /// Extra request headers, for the `fetch()` upgrade form.
325+ pub headers: Vec<(String, String)>,
326+ /// A `fetch()` upgrade wants the whole handshake outcome, including the
327+ /// ordinary response a server that declines to upgrade sent instead.
328+ pub want_response: bool,
329+ pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>,
330+}
331+
332+/// The ordinary HTTP response a server sent instead of upgrading. `fetch()`
333+/// returns it verbatim rather than turning it into a connection error.
334+pub struct DeclinedUpgrade {
335+ pub status: u16,
336+ pub headers: Vec<(String, String)>,
337+ pub body: Vec<u8>,
338+}
339+
340+/// What an outbound handshake produced.
341+pub struct OutboundWsOpen {
342+ pub protocol: Option<String>,
343+ pub declined: Option<DeclinedUpgrade>,
344+}
345+static OUTBOUND_WS_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> =
346+ OnceLock::new();
347+pub fn set_outbound_ws_tx(tx: tokio::sync::mpsc::UnboundedSender<OutboundWsReq>) {
348+ let _ = OUTBOUND_WS_TX.set(tx);
349+}
350+
351+static NEXT_TIMER_ID: AtomicU64 = AtomicU64::new(1);
352+static TIMER_CANCELS: OnceLock<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>> =
353+ OnceLock::new();
354+fn timer_cancels() -> &'static std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>> {
355+ TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
356+}
357+static NEXT_HTTP_STREAM_ID: AtomicU64 = AtomicU64::new(1);
358+enum HttpStreamSource {
359+ Response(reqwest::Response),
360+ Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>),
361+ Stream(HttpChunkStream),
362+}
363+struct HttpStreamEntry {
364+ created: Instant,
365+ source: Option<HttpStreamSource>,
366+ cancelled: tokio::sync::watch::Sender<bool>,
367+}
368+static HTTP_STREAMS: OnceLock<std::sync::Mutex<HashMap<u64, HttpStreamEntry>>> = OnceLock::new();
369+fn http_streams() -> &'static std::sync::Mutex<HashMap<u64, HttpStreamEntry>> {
370+ HTTP_STREAMS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
371+}
372+fn register_http_stream(stream_id: u64, source: HttpStreamSource) {
373+ let (cancelled, _) = tokio::sync::watch::channel(false);
374+ let mut streams = http_streams().lock().unwrap();
375+ streams.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60));
376+ streams.insert(
377+ stream_id,
378+ HttpStreamEntry {
379+ created: Instant::now(),
380+ source: Some(source),
381+ cancelled,
382+ },
383+ );
384+}
385+struct ResponseStreamWriter {
386+ created: Instant,
387+ writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>,
388+ finished: tokio::sync::watch::Sender<bool>,
389+}
390+static RESPONSE_STREAM_WRITERS: OnceLock<std::sync::Mutex<HashMap<u64, ResponseStreamWriter>>> =
391+ OnceLock::new();
392+fn response_stream_writers() -> &'static std::sync::Mutex<HashMap<u64, ResponseStreamWriter>> {
393+ RESPONSE_STREAM_WRITERS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
394+}
395+
396+pub type HttpChunkStream =
397+ Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>;
398+
399+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
400+pub struct WsTarget {
401+ pub id: u64,
402+ pub scope: String,
403+ #[serde(default, skip_serializing_if = "Option::is_none")]
404+ pub peer_node: Option<String>,
405+ #[serde(default, skip_serializing_if = "Option::is_none")]
406+ pub peer_addr: Option<String>,
407+ #[serde(default, skip_serializing_if = "Option::is_none")]
408+ pub peer_epoch: Option<u64>,
409+}
410+
411+/// Encode a cell/service response for the JS side. A text body crosses as a
412+/// JS string (cheap, lossless), binary as a byte array, and a streaming body
413+/// by id — serializing a Vec<u8> as a JSON number array is the dominant cost
414+/// for real DO responses. `ws_target` is carried only by the DO path.
415+fn encode_http_response(mut response: HttpResponse, ws_target: bool) -> String {
416+ let mut obj = serde_json::json!({
417+ "status": response.status,
418+ "headers": response.headers,
419+ });
420+ if ws_target {
421+ obj["wsTarget"] = serde_json::json!(response.ws);
422+ }
423+ if let Some(stream) = response.stream.take() {
424+ let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
425+ register_http_stream(stream_id, HttpStreamSource::Stream(stream));
426+ obj["streamId"] = serde_json::json!(stream_id);
427+ } else {
428+ match std::str::from_utf8(&response.body) {
429+ Ok(text) => obj["body"] = serde_json::Value::String(text.into()),
430+ Err(_) => obj["bodyBytes"] = serde_json::json!(response.body),
431+ }
432+ }
433+ obj.to_string()
434+}
435+
436+pub struct HttpResponse {
437+ pub status: u16,
438+ pub body: Vec<u8>,
439+ /// A final Worker response that directly forwards an outbound fetch body.
440+ /// Main hands this reqwest stream to Axum without materializing it.
441+ pub stream: Option<HttpChunkStream>,
442+ pub headers: Vec<(String, String)>,
443+ pub ws: Option<WsTarget>,
444+ /// The cell's committed-write position after the handler ran, for a local
445+ /// Durable Object request. The shell gates the response on durability when
446+ /// this advanced past the cell's last seen position. `None` for responses
447+ /// with no cell storage (Worker, asset, or proxied remote).
448+ pub write_position: Option<u64>,
449+}
450+
451+/// Jobs accepted by one resident cell isolate. While a handler awaits an
452+/// outbound operation, the isolate may service another event, matching the
453+/// Durable Objects event-loop semantics and allowing RPC call-backs (A→B→A).
454+pub enum CellJob {
455+ Fetch {
456+ request_id: Option<RequestId>,
457+ scope: String,
458+ name: Option<String>,
459+ url: String,
460+ method: String,
461+ body: Vec<u8>,
462+ headers: Vec<(String, String)>,
463+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
464+ },
465+ /// Run the worker's `export default fetch` INSIDE this cell isolate. When
466+ /// the worker routes `env.NS.get(id)` to a scope this isolate owns, the DO
467+ /// call resolves in-isolate, avoiding the `__do_call` host round trip.
468+ WorkerFetch {
469+ request_id: RequestId,
470+ url: String,
471+ method: String,
472+ body: Vec<u8>,
473+ headers: Vec<(String, String)>,
474+ /// Keeps the landing cell unavailable to another top-level Worker
475+ /// request until this event, including post-response work, is done.
476+ inline_activity: crate::CellActivityGuard,
477+ /// If this job is observed while another event is already driving the
478+ /// landing isolate, run it on the ordinary stateless Worker pool. A
479+ /// Worker fetch cannot be nested in the same V8 isolate, but its DO
480+ /// calls may safely re-enter this cell through the normal host path.
481+ fallback_workers: Arc<crate::WorkerPool>,
482+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
483+ },
484+ Rpc {
485+ scope: String,
486+ name: Option<String>,
487+ method: String,
488+ args: RpcData,
489+ reply: tokio::sync::oneshot::Sender<Result<RpcData>>,
490+ },
491+ WsOpen {
492+ scope: String,
493+ ws_id: u64,
494+ protocol: String,
495+ reply: tokio::sync::oneshot::Sender<Result<()>>,
496+ },
497+ WsMessage {
498+ scope: String,
499+ ws_id: u64,
500+ data: WsIn,
501+ reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>,
502+ },
503+ WsClosed {
504+ scope: String,
505+ ws_id: u64,
506+ code: u16,
507+ reason: String,
508+ was_clean: bool,
509+ reply: tokio::sync::oneshot::Sender<Result<()>>,
510+ },
511+ AbortFetch {
512+ request_id: RequestId,
513+ },
514+ Alarm {
515+ scope: String,
516+ scheduled_ms: i64,
517+ reply: tokio::sync::oneshot::Sender<Result<Option<i64>>>,
518+ },
519+ Shutdown,
520+}
521+
522+/// Outbound WebSocket traffic from a DO's `ws.send`/`ws.close`. The host holds
523+/// the socket in a task decoupled from the isolate (so the cell can hibernate
524+/// while the socket lives); `ws.send` routes here by wsId.
525+pub enum WsOut {
526+ Text(String),
527+ Binary(Vec<u8>),
528+ Close(u16, String),
529+}
530+
531+/// The result of delivering one `webSocketMessage`. `frames` are the outbound
532+/// frames the handler produced, captured by the output gate; `write_position`
533+/// is the cell's committed-write count after the handler when it advanced past
534+/// where it stood before — i.e. the handler wrote, and its frames must be held
535+/// until that position is durable. `None` means no write: flush the frames.
536+pub struct WsDispatch {
537+ pub frames: Vec<(u64, WsOut)>,
538+ pub write_position: Option<u64>,
539+}
540+
541+/// One inbound event on a socket the ISOLATE polls, rather than one the host
542+/// pushes into a cell.
543+///
544+/// A Durable Object socket must survive between events and wake a hibernated
545+/// cell, so its frames arrive as `CellJob`s. A Worker socket cannot work that
546+/// way: the stateless pool has no addressable isolate, and `asyncrt`'s region
547+/// aborts every pending op when the request ends. That is not a limitation to
548+/// route around — it is exactly the lifetime Cloudflare gives a Worker socket,
549+/// which lives and dies with its `IoContext`. So the isolate pulls, the same
550+/// way it already pulls a streamed response body.
551+pub enum WsPull {
552+ Open(String),
553+ Text(String),
554+ Binary(Vec<u8>),
555+ Close(u16, String, bool),
556+}
557+
558+/// Tags for the byte frame `__ws_next` resolves with. A tagged buffer keeps a
559+/// binary message on its fast path instead of base64 through a JSON envelope.
560+const WS_PULL_TAG_TEXT: u8 = 0;
561+const WS_PULL_TAG_BINARY: u8 = 1;
562+const WS_PULL_TAG_OPEN: u8 = 2;
563+const WS_PULL_TAG_CLOSE: u8 = 3;
564+
565+impl WsPull {
566+ fn encode(self) -> Vec<u8> {
567+ let (tag, mut body) = match self {
568+ WsPull::Text(text) => (WS_PULL_TAG_TEXT, text.into_bytes()),
569+ WsPull::Binary(bytes) => (WS_PULL_TAG_BINARY, bytes),
570+ WsPull::Open(protocol) => (WS_PULL_TAG_OPEN, protocol.into_bytes()),
571+ WsPull::Close(code, reason, was_clean) => (
572+ WS_PULL_TAG_CLOSE,
573+ serde_json::json!({
574+ "code": code,
575+ "reason": reason,
576+ "wasClean": was_clean,
577+ })
578+ .to_string()
579+ .into_bytes(),
580+ ),
581+ };
582+ let mut framed = Vec::with_capacity(body.len() + 1);
583+ framed.push(tag);
584+ framed.append(&mut body);
585+ framed
586+ }
587+}
588+
589+pub type WsPullReceiver = tokio::sync::mpsc::UnboundedReceiver<WsPull>;
590+pub type WsPullSender = tokio::sync::mpsc::UnboundedSender<WsPull>;
591+
592+/// One socket's inbound queue. Shared so an op can await it without holding
593+/// the registry lock; one isolate polls a given socket serially.
594+type WsPullQueue = Arc<tokio::sync::Mutex<WsPullReceiver>>;
595+type WsPullRegistry = std::sync::Mutex<HashMap<u64, WsPullQueue>>;
596+
597+/// Inbound queues for isolate-polled sockets, keyed by wsId.
598+static WS_PULL: OnceLock<WsPullRegistry> = OnceLock::new();
599+
600+fn ws_pull() -> &'static WsPullRegistry {
601+ WS_PULL.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
602+}
603+
604+pub fn ws_pull_register(id: u64, rx: WsPullReceiver) {
605+ ws_pull()
606+ .lock()
607+ .unwrap()
608+ .insert(id, Arc::new(tokio::sync::Mutex::new(rx)));
609+}
610+
611+pub fn ws_pull_unregister(id: u64) {
612+ ws_pull().lock().unwrap().remove(&id);
613+}
614+
615+thread_local! {
616+ /// Sockets opened by the region currently running on this thread, one
617+ /// frame per nested region. `asyncrt` aborts a region's pending ops on
618+ /// exit; these are the host-side resources that abort cannot reach, so
619+ /// the region closes them itself.
620+ static WS_PULL_REGION: RefCell<Vec<Vec<u64>>> = const { RefCell::new(Vec::new()) };
621+ /// Sockets opened before the region exists. A handler runs synchronously
622+ /// up to its first await BEFORE its run loop is entered, so a socket
623+ /// constructed at the top of a handler is created with no frame to belong
624+ /// to. The loop adopts these when it starts.
625+ static WS_PULL_PENDING: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
626+}
627+
628+pub fn ws_region_enter() {
629+ let adopted =
630+ WS_PULL_PENDING.with(|pending| pending.borrow_mut().drain(..).collect::<Vec<_>>());
631+ WS_PULL_REGION.with(|regions| regions.borrow_mut().push(adopted));
632+}
633+
634+/// Close every isolate-polled socket the closing region opened. A Worker
635+/// socket lives and dies with its request, exactly as it does on Cloudflare.
636+pub fn ws_region_exit() {
637+ let opened = WS_PULL_REGION.with(|regions| regions.borrow_mut().pop().unwrap_or_default());
638+ for id in opened {
639+ ws_emit(id, WsOut::Close(1001, "request ended".into()));
640+ ws_pull_unregister(id);
641+ ws_unregister(id);
642+ }
643+}
644+
645+fn ws_region_track(id: u64) {
646+ WS_PULL_REGION.with(|regions| {
647+ if let Some(current) = regions.borrow_mut().last_mut() {
648+ current.push(id);
649+ return;
650+ }
651+ WS_PULL_PENDING.with(|pending| pending.borrow_mut().push(id));
652+ });
653+}
654+pub enum WsIn {
655+ Text(String),
656+ Binary(Vec<u8>),
657+}
658+struct WsMeta {
659+ scope: String,
660+ hibernatable: bool,
661+ tags: Vec<String>,
662+ attachment: Option<String>,
663+ pending: Vec<WsOut>,
664+}
665+#[derive(Default)]
666+struct WsRegistry {
667+ outputs: HashMap<u64, tokio::sync::mpsc::UnboundedSender<WsOut>>,
668+ metadata: HashMap<u64, WsMeta>,
669+}
670+impl WsRegistry {
671+ fn register(&mut self, id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) {
672+ if let Some(meta) = self.metadata.get_mut(&id) {
673+ for pending in meta.pending.drain(..) {
674+ let _ = tx.send(pending);
675+ }
676+ }
677+ self.outputs.insert(id, tx);
678+ }
679+
680+ fn unregister(&mut self, id: u64) -> Option<WsMeta> {
681+ self.outputs.remove(&id);
682+ self.metadata.remove(&id)
683+ }
684+
685+ fn emit(&mut self, id: u64, out: WsOut) {
686+ if let Some(tx) = self.outputs.get(&id) {
687+ tracing::debug!(ws_id = id, "queued outbound WebSocket frame");
688+ let _ = tx.send(out);
689+ } else if let Some(meta) = self.metadata.get_mut(&id) {
690+ tracing::debug!(ws_id = id, "buffered pre-upgrade WebSocket frame");
691+ meta.pending.push(out);
692+ } else {
693+ // The socket is gone and the frame has nowhere to go. Silence here
694+ // is what made a held frame indistinguishable from a sent one.
695+ tracing::warn!(ws_id = id, "dropped a frame for a closed WebSocket");
696+ }
697+ }
698+}
699+static WS_REGISTRY: OnceLock<std::sync::Mutex<WsRegistry>> = OnceLock::new();
700+static REGULAR_WS_COUNTS: OnceLock<std::sync::Mutex<HashMap<String, usize>>> = OnceLock::new();
701+static NEXT_WS_ID: AtomicU64 = AtomicU64::new(1);
702+fn ws_registry() -> &'static std::sync::Mutex<WsRegistry> {
703+ WS_REGISTRY.get_or_init(|| std::sync::Mutex::new(WsRegistry::default()))
704+}
705+fn regular_ws_counts() -> &'static std::sync::Mutex<HashMap<String, usize>> {
706+ REGULAR_WS_COUNTS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
707+}
708+fn increment_regular_ws(scope: &str) {
709+ *regular_ws_counts()
710+ .lock()
711+ .unwrap()
712+ .entry(scope.to_string())
713+ .or_default() += 1;
714+}
715+fn decrement_regular_ws(scope: &str) {
716+ let mut counts = regular_ws_counts().lock().unwrap();
717+ let Some(count) = counts.get_mut(scope) else {
718+ return;
719+ };
720+ *count = count.saturating_sub(1);
721+ if *count == 0 {
722+ counts.remove(scope);
723+ }
724+}
725+pub fn has_regular_websocket(scope: &str) -> bool {
726+ regular_ws_counts()
727+ .lock()
728+ .unwrap()
729+ .get(scope)
730+ .is_some_and(|count| *count > 0)
731+}
732+pub fn ws_hibernatable(id: u64) -> Option<bool> {
733+ ws_registry()
734+ .lock()
735+ .unwrap()
736+ .metadata
737+ .get(&id)
738+ .map(|meta| meta.hibernatable)
739+}
740+pub fn ws_next_id() -> u64 {
741+ NEXT_WS_ID.fetch_add(1, Ordering::Relaxed)
742+}
743+pub fn ws_register(id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) {
744+ ws_registry().lock().unwrap().register(id, tx);
745+}
746+pub fn ws_register_outbound(id: u64, scope: &str) {
747+ let inserted = {
748+ let mut registry = ws_registry().lock().unwrap();
749+ if let std::collections::hash_map::Entry::Vacant(entry) = registry.metadata.entry(id) {
750+ entry.insert(WsMeta {
751+ scope: scope.to_string(),
752+ hibernatable: false,
753+ tags: Vec::new(),
754+ attachment: None,
755+ pending: Vec::new(),
756+ });
757+ true
758+ } else {
759+ false
760+ }
761+ };
762+ if inserted {
763+ increment_regular_ws(scope);
764+ }
765+}
766+pub fn ws_unregister(id: u64) {
767+ let meta = ws_registry().lock().unwrap().unregister(id);
768+ if let Some(meta) = meta.filter(|meta| !meta.hibernatable) {
769+ decrement_regular_ws(&meta.scope);
770+ }
771+}
772+thread_local! {
773+ // Output-gate capture. While a `webSocketMessage` runs, its outbound frames
774+ // are collected here instead of hitting the wire, so the shell can hold them
775+ // until the message's write is durable. A stack: a reentrant event pushes
776+ // its own buffer, and frames nested inside a capturing event land on top.
777+ //
778+ // What may be captured is decided per socket, by `ws_gate_may_hold`, and
779+ // that check is what keeps this from deadlocking. Delivering a message runs
780+ // the isolate's event loop, which drives every ready task on this thread,
781+ // not just this handler -- so anything captured here is withheld for as
782+ // long as that loop runs.
783+ static WS_CAPTURE: RefCell<Vec<Vec<(u64, WsOut)>>> = const { RefCell::new(Vec::new()) };
784+}
785+
786+fn ws_capture_begin() {
787+ WS_CAPTURE.with(|c| c.borrow_mut().push(Vec::new()));
788+}
789+
790+fn ws_capture_take() -> Vec<(u64, WsOut)> {
791+ WS_CAPTURE.with(|c| c.borrow_mut().pop().unwrap_or_default())
792+}
793+
794+/// Whether a socket is one the output gate may hold frames for: a hibernatable
795+/// transport, whose messages the host pushes into the cell.
796+///
797+/// A socket the isolate opened and polls itself is not. Its handler runs inside
798+/// the isolate's event loop, and that loop is what a held frame would be
799+/// waiting on: the reply to a frame the gate is withholding never arrives, so
800+/// the loop never finishes, so the frame is never released. Frames from those
801+/// sockets go straight out, as they did before the gate existed.
802+fn ws_gate_may_hold(id: u64) -> bool {
803+ let registry = ws_registry().lock().unwrap();
804+ registry.metadata.get(&id).is_some_and(|meta| meta.hibernatable)
805+}
806+
807+fn ws_emit(id: u64, out: WsOut) {
808+ let capturing = WS_CAPTURE.with(|c| !c.borrow().is_empty());
809+ if capturing && ws_gate_may_hold(id) {
810+ WS_CAPTURE.with(|c| c.borrow_mut().last_mut().unwrap().push((id, out)));
811+ return;
812+ }
813+ ws_registry().lock().unwrap().emit(id, out);
814+}
815+
816+/// Flush frames the output gate held: send each to its socket's task. Called
817+/// from the actor thread once the gating write is proved durable.
818+pub fn ws_emit_batch(frames: Vec<(u64, WsOut)>) {
819+ let mut registry = ws_registry().lock().unwrap();
820+ for (id, out) in frames {
821+ registry.emit(id, out);
822+ }
823+}
824+
825+/// Break a cell's sockets: the output gate could not prove a write durable, so
826+/// close every socket the cell owns rather than let a client keep a connection
827+/// whose acknowledged effects may not have persisted (a reset DO).
828+pub fn ws_close_scope(scope: &str, code: u16, reason: &str) {
829+ tracing::warn!(scope, code, "PROBE close_scope");
830+ let mut registry = ws_registry().lock().unwrap();
831+ let ids: Vec<u64> = registry
832+ .metadata
833+ .iter()
834+ .filter(|(_, meta)| meta.scope == scope)
835+ .map(|(id, _)| *id)
836+ .collect();
837+ for id in ids {
838+ registry.emit(id, WsOut::Close(code, reason.to_string()));
839+ }
840+}
841+
842+
843+thread_local! {
844+ // JS promise resolvers awaiting an async op, keyed by the op's id.
845+ static PROMISES: RefCell<HashMap<u64, v8::Global<v8::PromiseResolver>>> =
846+ RefCell::new(HashMap::new());
847+ // One outbound HTTP client per JS thread — building it per fetch rebuilds
848+ // the TLS stack every call (async-op-hazards.md).
849+ static HTTP: reqwest::Client = reqwest::Client::new();
850+ static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder()
851+ .redirect(reqwest::redirect::Policy::none()).build().unwrap();
852+ static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new());
853+ static CANCELLED_REQUESTS: RefCell<HashSet<RequestId>> = RefCell::new(HashSet::new());
854+}
855+fn promise_store(id: u64, r: v8::Global<v8::PromiseResolver>) {
856+ PROMISES.with(|p| {
857+ p.borrow_mut().insert(id, r);
858+ });
859+}
860+
861+/// Resolve or reject op `id`'s promise with its outcome.
862+fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) {
863+ let g = match PROMISES.with(|p| p.borrow_mut().remove(&id)) {
864+ Some(g) => g,
865+ None => return,
866+ };
867+ let r = v8::Local::new(tc, g);
868+ match res {
869+ Ok(asyncrt::OpOut::Str(v)) => {
870+ let s = v8::String::new(tc, &v).unwrap();
871+ r.resolve(tc, s.into());
872+ }
873+ Ok(asyncrt::OpOut::Bytes(b)) => {
874+ let v = bytes_value(tc, b);
875+ r.resolve(tc, v);
876+ }
877+ Err(e) => {
878+ let s = v8::String::new(tc, &e).unwrap();
879+ let ex = v8::Exception::error(tc, s);
880+ r.reject(tc, ex);
881+ }
882+ }
883+}
884+
885+/// Move `bytes` into a `Uint8Array` without copying.
886+fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> {
887+ let len = bytes.len();
888+ let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();
889+ let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);
890+ v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into()
891+}
892+
893+fn handler_budget() -> Duration {
894+ static BUDGET: OnceLock<Duration> = OnceLock::new();
895+ *BUDGET.get_or_init(|| {
896+ Duration::from_secs(
897+ std::env::var("CELLD_HANDLER_BUDGET_S")
898+ .ok()
899+ .and_then(|value| value.parse().ok())
900+ .filter(|seconds| *seconds > 0)
901+ .unwrap_or(300),
902+ )
903+ })
904+}
905+
906+/// Aborts raised on another thread — an HTTP or service-binding caller
907+/// disconnecting while the target runs in a worker pool. Durable Object aborts
908+/// also arrive as a reentrant `CellJob::AbortFetch` when a cell thread can
909+/// service its own channel; a pool worker is blocked inside its handler, so
910+/// the abort has to be visible from wherever the loop happens to be.
911+///
912+/// The counter keeps the common path to one relaxed atomic load per loop turn:
913+/// with nothing pending, the mutex is never taken.
914+static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> =
915+ OnceLock::new();
916+static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
917+
918+fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> {
919+ PENDING_ABORTS.get_or_init(Default::default)
920+}
921+
922+/// Mark an in-flight request cancelled from any thread.
923+pub fn abort_request(request_id: RequestId) {
924+ if pending_aborts().lock().unwrap().insert(request_id) {
925+ PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed);
926+ }
927+}
928+
929+fn clear_request_cancellation(request_id: RequestId) {
930+ let _ = take_pending_abort(request_id);
931+}
932+
933+fn take_pending_abort(request_id: RequestId) -> bool {
934+ if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 {
935+ return false;
936+ }
937+ if pending_aborts().lock().unwrap().remove(&request_id) {
938+ PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed);
939+ return true;
940+ }
941+ false
942+}
943+
944+fn take_request_cancellation(request_id: Option<RequestId>) -> bool {
945+ request_id.is_some_and(|request_id| {
946+ CANCELLED_REQUESTS.with(|requests| requests.borrow_mut().remove(&request_id))
947+ || take_pending_abort(request_id)
948+ })
949+}
950+
951+enum RunLoopOutcome<T> {
952+ Complete(T),
953+ RequestCancelled,
954+}
955+
956+/// Drive a promise and apply `on_fulfilled` as soon as it settles. The callback
957+/// may return a composite waitUntil promise after publishing its response.
958+/// Top-level fetches retain only registered waitUntil work; Durable Object
959+/// events additionally drain I/O started by the handler because libraries
960+/// commonly launch that work from synchronous callbacks.
961+///
962+/// Every exit path drops the region and purges unresolved host promises. A
963+/// panicked/aborted op is rejected into JS rather than hanging the isolate.
964+fn run_loop_then<'s, T, F>(
965+ tc: &mut v8::PinScope<'s, '_>,
966+ promise: v8::Local<v8::Promise>,
967+ cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
968+ actor_scope: Option<&str>,
969+ request_id: Option<RequestId>,
970+ drain_spawned_ops: bool,
971+ on_fulfilled: F,
972+) -> Result<RunLoopOutcome<T>>
973+where
974+ F: FnOnce(
975+ &mut v8::PinScope<'s, '_>,
976+ v8::Local<'s, v8::Value>,
977+ ) -> Result<(T, Option<v8::Local<'s, v8::Promise>>)>,
978+{
979+ let mut region: JoinSet<(u64, Result<asyncrt::OpOut, String>)> = JoinSet::new();
980+ ws_region_enter();
981+ // Paired with `ws_region_exit` on the close path below, which every exit
982+ // from this function reaches.
983+ struct WsRegionGuard;
984+ impl Drop for WsRegionGuard {
985+ fn drop(&mut self) {
986+ ws_region_exit();
987+ }
988+ }
989+ let _ws_region = WsRegionGuard;
990+ let mut idmap: HashMap<tokio::task::Id, u64> = HashMap::new();
991+ let started = Instant::now();
992+ let budget = handler_budget();
993+ let mut on_fulfilled = Some(on_fulfilled);
994+ let mut output = None;
995+ let mut background = None;
996+ let mut request_cancelled = false;
997+ // Unknown until the handler first suspends. Cache the deadline so an actor
998+ // with pending async I/O does not query SQLite on every 10 ms input-gate
999+ // wakeup. Reentrant events invalidate it because they may change the alarm.
1000+ let mut next_alarm_at: Option<Option<i64>> = None;
1001+ let result = loop {
1002+ let mut published_this_turn = false;
1003+ if !request_cancelled && take_request_cancellation(request_id) {
1004+ request_cancelled = true;
1005+ if let Some(id) = request_id {
1006+ let _ = abort_incoming_request(tc, id);
1007+ }
1008+ background = end_event_context(tc)?;
1009+ }
1010+ for (id, fut) in asyncrt::drain_spawns() {
1011+ let h = region.spawn_on(async move { (id, fut.await) }, &asyncrt::op_handle());
1012+ idmap.insert(h.id(), id);
1013+ }
1014+ tc.perform_microtask_checkpoint(); // fire .then chains; they may enqueue ops
1015+ if let Some(error) = take_execution_termination(tc) {
1016+ break Err(error);
1017+ }
1018+ for (id, fut) in asyncrt::drain_spawns() {
1019+ let h = region.spawn_on(async move { (id, fut.await) }, &asyncrt::op_handle());
1020+ idmap.insert(h.id(), id);
1021+ }
1022+ if !request_cancelled && output.is_none() {
1023+ match promise.state() {
1024+ v8::PromiseState::Fulfilled => {
1025+ let callback = on_fulfilled.take().expect("handler callback used once");
1026+ let (value, wait_until) = callback(tc, promise.result(tc))?;
1027+ published_this_turn = wait_until.is_some();
1028+ output = Some(value);
1029+ background = wait_until;
1030+ }
1031+ v8::PromiseState::Rejected => {
1032+ break Err(anyhow!("rejected: {}", reject_reason(tc, promise)))
1033+ }
1034+ v8::PromiseState::Pending => {}
1035+ }
1036+ }
1037+ // Reentrant jobs are serviced before AND after the response publishes:
1038+ // post-response waitUntil work may call back into this cell (A→A), and
1039+ // a pending job would otherwise stall until the handler budget.
1040+ if let Some(rx) = cell_rx {
1041+ let mut serviced_event = false;
1042+ while service_reentrant(tc, rx)? {
1043+ serviced_event = true;
1044+ // Adopt ops the job just enqueued (an AbortFetch's abort
1045+ // listener registering waitUntil work, say) BEFORE the next
1046+ // job runs: a reentrant dispatch drains the shared spawn
1047+ // queue into its own region and aborts the survivors on
1048+ // exit, so an op left queued here would be silently killed
1049+ // and its promise purged — this event then waits on it
1050+ // forever.
1051+ for (id, fut) in asyncrt::drain_spawns() {
1052+ let h = region.spawn_on(async move { (id, fut.await) }, &asyncrt::op_handle());
1053+ idmap.insert(h.id(), id);
1054+ }
1055+ }
1056+ if output.is_none() && !request_cancelled && take_request_cancellation(request_id) {
1057+ request_cancelled = true;
1058+ if let Some(id) = request_id {
1059+ let _ = abort_incoming_request(tc, id);
1060+ }
1061+ background = end_event_context(tc)?;
1062+ }
1063+ if serviced_event {
1064+ next_alarm_at = None;
1065+ }
1066+ tc.perform_microtask_checkpoint();
1067+ if let Some(error) = take_execution_termination(tc) {
1068+ break Err(error);
1069+ }
1070+ if !request_cancelled && output.is_none() {
1071+ match promise.state() {
1072+ v8::PromiseState::Fulfilled => {
1073+ let callback = on_fulfilled.take().expect("handler callback used once");
1074+ let (value, wait_until) = callback(tc, promise.result(tc))?;
1075+ published_this_turn = wait_until.is_some();
1076+ output = Some(value);
1077+ background = wait_until;
1078+ }
1079+ v8::PromiseState::Rejected => {
1080+ break Err(anyhow!("rejected: {}", reject_reason(tc, promise)))
1081+ }
1082+ v8::PromiseState::Pending => {}
1083+ }
1084+ }
1085+ }
1086+ // Response marshalling can start a bounded JS-to-host body pump and
1087+ // register it with waitUntil. Drive the pump once and move its native
1088+ // ops into this event region before checking whether the region is
1089+ // empty. Pending handlers pay only the branch above.
1090+ if published_this_turn {
1091+ tc.perform_microtask_checkpoint();
1092+ if let Some(error) = take_execution_termination(tc) {
1093+ break Err(error);
1094+ }
1095+ for (id, fut) in asyncrt::drain_spawns() {
1096+ let h = region.spawn_on(async move { (id, fut.await) }, &asyncrt::op_handle());
1097+ idmap.insert(h.id(), id);
1098+ }
1099+ }
1100+ if request_cancelled || output.is_some() {
1101+ let event_done = match background {
1102+ None => true,
1103+ Some(wait_until) => match wait_until.state() {
1104+ v8::PromiseState::Fulfilled => true,
1105+ v8::PromiseState::Rejected => {
1106+ tracing::warn!(
1107+ error = %reject_reason(tc, wait_until),
1108+ "waitUntil aggregate rejected",
1109+ );
1110+ true
1111+ }
1112+ v8::PromiseState::Pending => false,
1113+ },
1114+ };
1115+ if event_done && (request_cancelled || !drain_spawned_ops || region.is_empty()) {
1116+ if request_cancelled {
1117+ break Ok(RunLoopOutcome::RequestCancelled);
1118+ }
1119+ break Ok(RunLoopOutcome::Complete(output.take().unwrap()));
1120+ }
1121+ }
1122+ if !request_cancelled && output.is_none() {
1123+ if let Some(scope) = actor_scope {
1124+ let alarm_at = *next_alarm_at.get_or_insert_with(|| storage::get_alarm(scope));
1125+ if alarm_at.is_some_and(|alarm_at| alarm_at <= unix_now_ms()) {
1126+ service_due_alarm(tc, scope, cell_rx.expect("actor events have a receiver"))?;
1127+ next_alarm_at = None;
1128+ continue;
1129+ }
1130+ }
1131+ }
1132+ if region.is_empty() {
1133+ if request_cancelled {
1134+ tracing::warn!("request-cancellation waitUntil stalled with no pending op");
1135+ break Ok(RunLoopOutcome::RequestCancelled);
1136+ }
1137+ if output.is_none() {
1138+ if let (Some(rx), Some(Some(alarm_at))) = (cell_rx, next_alarm_at) {
1139+ let elapsed = started.elapsed();
1140+ if elapsed >= budget {
1141+ break Err(anyhow!("handler exceeded {}s budget", budget.as_secs()));
1142+ }
1143+ let until_alarm =
1144+ Duration::from_millis(alarm_at.saturating_sub(unix_now_ms()).max(0) as u64);
1145+ let wait = (budget - elapsed).min(until_alarm);
1146+ match rx.recv_timeout(wait) {
1147+ Ok(job) => {
1148+ if !handle_reentrant_job(tc, rx, job)? {
1149+ break Err(anyhow!("cell shutting down"));
1150+ }
1151+ next_alarm_at = None;
1152+ }
1153+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
1154+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
1155+ break Err(anyhow!("cell channel disconnected"));
1156+ }
1157+ }
1158+ continue;
1159+ }
1160+ }
1161+ break match output.take() {
1162+ Some(_) => Err(anyhow!("waitUntil stalled with no pending op")),
1163+ None => Err(anyhow!("handler stalled: awaited work with no pending op")),
1164+ };
1165+ }
1166+ let elapsed = started.elapsed();
1167+ if elapsed >= budget {
1168+ if request_cancelled {
1169+ tracing::warn!("request-cancellation waitUntil exceeded handler budget");
1170+ break Ok(RunLoopOutcome::RequestCancelled);
1171+ }
1172+ break Err(anyhow!("handler exceeded {}s budget", budget.as_secs()));
1173+ }
1174+ // block until one op completes (or the remaining budget elapses). The
1175+ // timeout must be built INSIDE the runtime context, hence the async {}.
1176+ let remaining = budget - elapsed;
1177+ // An abortable ingress or service-binding request has to notice a
1178+ // cancellation raised on another thread, so its wait is bounded the
1179+ // same way an actor's is. Non-abortable internal fetches retain the
1180+ // uncapped wait.
1181+ let mut wait = if cell_rx.is_some() || request_id.is_some() {
1182+ remaining.min(Duration::from_millis(10))
1183+ } else {
1184+ remaining
1185+ };
1186+ if let Some(Some(alarm_at)) = next_alarm_at {
1187+ wait = wait.min(Duration::from_millis(
1188+ alarm_at.saturating_sub(unix_now_ms()).max(0) as u64,
1189+ ));
1190+ }
1191+ let joined = asyncrt::block_on(async {
1192+ tokio::time::timeout(wait, region.join_next_with_id()).await
1193+ });
1194+ match joined {
1195+ Ok(Some(Ok((tid, (id, res))))) => {
1196+ idmap.remove(&tid);
1197+ resolve_res(tc, id, res);
1198+ next_alarm_at = None;
1199+ }
1200+ Ok(Some(Err(je))) => {
1201+ // op panicked/aborted → reject its promise
1202+ if let Some(id) = idmap.remove(&je.id()) {
1203+ resolve_res(tc, id, Err("op aborted".into()));
1204+ next_alarm_at = None;
1205+ }
1206+ }
1207+ Ok(None) => {} // region drained concurrently; loop re-checks
1208+ Err(_) if cell_rx.is_some() || request_id.is_some() => continue,
1209+ Err(_) => break Err(anyhow!("handler exceeded {}s budget", budget.as_secs())),
1210+ }
1211+ };
1212+ // region close: `region` drops here (aborts survivors); purge resolvers for
1213+ // anything still pending or enqueued-but-unspawned so PROMISES can't leak.
1214+ for id in idmap.values() {
1215+ PROMISES.with(|p| {
1216+ p.borrow_mut().remove(id);
1217+ });
1218+ }
1219+ for (id, _) in asyncrt::drain_spawns() {
1220+ PROMISES.with(|p| {
1221+ p.borrow_mut().remove(&id);
1222+ });
1223+ }
1224+ result
1225+}
1226+
1227+fn run_loop<'s>(
1228+ tc: &mut v8::PinScope<'s, '_>,
1229+ promise: v8::Local<v8::Promise>,
1230+ cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
1231+) -> Result<v8::Local<'s, v8::Value>> {
1232+ match run_loop_then(tc, promise, cell_rx, None, None, false, |_tc, value| {
1233+ Ok((value, None))
1234+ })? {
1235+ RunLoopOutcome::Complete(value) => Ok(value),
1236+ RunLoopOutcome::RequestCancelled => Err(anyhow!("The client has disconnected")),
1237+ }
1238+}
1239+
1240+fn resolved_promise<'s>(
1241+ tc: &mut v8::PinScope<'s, '_>,
1242+ value: v8::Local<'s, v8::Value>,
1243+) -> Result<v8::Local<'s, v8::Promise>> {
1244+ let resolver =
1245+ v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?;
1246+ resolver.resolve(tc, value);
1247+ Ok(resolver.get_promise(tc))
1248+}
1249+
1250+/// Publish a fetch response when the handler settles, then keep driving the
1251+/// event region so waitUntil work can complete without delaying headers or a
1252+/// streaming body.
1253+fn complete_fetch_event<'s>(
1254+ tc: &mut v8::PinScope<'s, '_>,
1255+ ret: v8::Local<'s, v8::Value>,
1256+ cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
1257+ critical_scope: Option<&str>,
1258+ // The cell's committed-write position sampled before the handler ran. The
1259+ // response's `write_position` is set only if the handler advanced it, so
1260+ // the output gate sees a per-request write and ignores celld's own
1261+ // activation-time writes (the DO actor name, alarm bookkeeping).
1262+ writes_before: Option<u64>,
1263+ request_id: Option<RequestId>,
1264+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
1265+) {
1266+ let promise = match ret.try_cast::<v8::Promise>() {
1267+ Ok(promise) => Ok(promise),
1268+ Err(_) => resolved_promise(tc, ret),
1269+ };
1270+ let mut reply = Some(reply);
1271+ let result = promise.and_then(|promise| {
1272+ run_loop_then(
1273+ tc,
1274+ promise,
1275+ cell_rx,
1276+ critical_scope,
1277+ request_id,
1278+ false,
1279+ |tc, value| {
1280+ if let Some(error) = critical_scope.and_then(storage::sql_critical_error) {
1281+ return Err(anyhow!(error));
1282+ }
1283+ let mut response = read_response(tc, value, cell_rx)?;
1284+ // Gate on durability only if this handler advanced the cell's
1285+ // committed-write position past where it was before the handler
1286+ // ran -- a per-request write, not celld's activation writes.
1287+ response.write_position = match (writes_before, critical_scope.and_then(storage::write_position)) {
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+ // Load FULL, 16-byte-aligned ICU data before V8 init — the rusty_v8
1844+ // prebuilt ships a reduced ICU that lacks regex property-of-strings
1845+ // tables (e.g. /\p{RGI_Emoji}/v) real bundles use.
1846+ //
1847+ // The symbol carries V8's internal ICU major, which went 77 -> 78 with
1848+ // v8 152. The data blob did not change: rusty_v8 152's
1849+ // `third_party/icu/common/icudtl.dat` is byte-identical to the one
1850+ // `deno_core_icudata` ships, so the crate stays.
1851+ if let Err(e) = v8::icu::set_common_data_78(deno_core_icudata::ICU_DATA) {
1852+ tracing::warn!(code = e, "ICU set_common_data_78 failed");
1853+ }
1854+ let platform = v8::new_default_platform(0, false).make_shared();
1855+ v8::V8::initialize_platform(platform);
1856+ v8::V8::initialize();
1857+ }
1858+}
1859+
1860+/// Per-worker compatibility switches, derived from the manifest's
1861+/// compatibility date and flags (Workerd compatibility-date.capnp). `Default`
1862+/// is every switch off; production derives real values in `main`.
1863+#[derive(Clone, Copy, Default)]
1864+pub struct Compat {
1865+ pub delete_all_deletes_alarm: bool,
1866+ /// `js_rpc`: RPC on a Durable Object class that does not extend
1867+ /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()).
1868+ pub js_rpc: bool,
1869+ /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`,
1870+ /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/
1871+ /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher).
1872+ pub fetcher_get_put_delete: bool,
1873+ /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and
1874+ /// a binary message arrives as a `Blob`, per the WHATWG default. Without
1875+ /// it celld keeps the historical `"arraybuffer"`.
1876+ pub websocket_standard_binary_type: bool,
1877+}
1878+
1879+pub struct WorkerConfig {
1880+ src: String,
1881+ script_name: String,
1882+ do_classes: Vec<String>,
1883+ bindings: Vec<(String, String)>,
1884+ r2_bindings: Vec<String>,
1885+ ai_binding: Option<String>,
1886+ vars: Vec<(String, String)>,
1887+ node: String,
1888+ text: Vec<(String, String)>,
1889+ compat: Compat,
1890+ /// `[[services]]`: (binding name, target script, optional entrypoint).
1891+ /// The target runs in this process; see [[service-bindings]].
1892+ services: Vec<(String, String, Option<String>)>,
1893+ asset_binding: Option<String>,
1894+ /// `env` name of the Worker Loader binding, if this Worker may spawn
1895+ /// dynamic isolates.
1896+ loader_binding: Option<String>,
1897+ /// Ambient outbound authority. Loaded workers may be denied.
1898+ egress: EgressPolicy,
1899+ /// Extra `env` values a loaded worker was handed, as a JSON object string
1900+ /// merged onto its `env`. Loader-only; empty for normal workers.
1901+ loader_env: Option<String>,
1902+ /// A loaded worker's non-main modules as (name, source), so the main module
1903+ /// can import siblings. Loader-only; empty for normal single-file bundles.
1904+ loader_modules: Vec<(String, String)>,
1905+}
1906+
1907+pub struct WorkerConfigOptions {
1908+ pub src: String,
1909+ pub script_name: String,
1910+ pub do_classes: Vec<String>,
1911+ pub bindings: Vec<(String, String)>,
1912+ pub r2_bindings: Vec<String>,
1913+ pub ai_binding: Option<String>,
1914+ pub vars: Vec<(String, String)>,
1915+ pub node: String,
1916+ pub text: Vec<(String, String)>,
1917+ pub compat: Compat,
1918+}
1919+
1920+impl WorkerConfig {
1921+ pub fn new(options: WorkerConfigOptions) -> Self {
1922+ let WorkerConfigOptions {
1923+ src,
1924+ script_name,
1925+ do_classes,
1926+ bindings,
1927+ r2_bindings,
1928+ ai_binding,
1929+ vars,
1930+ node,
1931+ text,
1932+ compat,
1933+ } = options;
1934+ Self {
1935+ src,
1936+ script_name,
1937+ do_classes,
1938+ bindings,
1939+ r2_bindings,
1940+ ai_binding,
1941+ vars,
1942+ node,
1943+ text,
1944+ compat,
1945+ services: Vec::new(),
1946+ asset_binding: None,
1947+ loader_binding: None,
1948+ egress: EgressPolicy::Allow,
1949+ loader_env: None,
1950+ loader_modules: Vec::new(),
1951+ }
1952+ }
1953+
1954+ /// Grant this Worker a Worker Loader binding at `env` name `binding`.
1955+ pub fn with_loader(mut self, binding: Option<String>) -> Self {
1956+ self.loader_binding = binding;
1957+ self
1958+ }
1959+
1960+ /// Set this Worker's ambient outbound authority (loaded workers only).
1961+ fn with_egress(mut self, egress: EgressPolicy) -> Self {
1962+ self.egress = egress;
1963+ self
1964+ }
1965+
1966+ /// Merge `env` (a JSON object string) onto a loaded worker's `env`.
1967+ fn with_loader_env(mut self, env: Option<String>) -> Self {
1968+ self.loader_env = env;
1969+ self
1970+ }
1971+
1972+ /// Non-main modules a loaded worker's main module may import.
1973+ fn with_loader_modules(mut self, modules: Vec<(String, String)>) -> Self {
1974+ self.loader_modules = modules;
1975+ self
1976+ }
1977+
1978+ /// Declare the service bindings this Worker may call.
1979+ pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self {
1980+ self.services = services;
1981+ self
1982+ }
1983+
1984+ pub fn with_asset_binding(mut self, binding: Option<String>) -> Self {
1985+ self.asset_binding = binding;
1986+ self
1987+ }
1988+}
1989+
1990+pub struct Worker {
1991+ inner: Option<WorkerIsolate>,
1992+ config: Arc<WorkerConfig>,
1993+ owned: Arc<[String]>,
1994+}
1995+
1996+pub struct WorkerIsolate {
1997+ isolate: v8::OwnedIsolate,
1998+ context: v8::Global<v8::Context>,
1999+ fetch: v8::Global<v8::Function>,
2000+ original_heap_limit: usize,
2001+ runtime_state: Arc<ActorRuntimeState>,
2002+}
2003+
2004+impl std::ops::Deref for Worker {
2005+ type Target = WorkerIsolate;
2006+
2007+ fn deref(&self) -> &Self::Target {
2008+ self.inner.as_ref().expect("Worker isolate unavailable")
2009+ }
2010+}
2011+
2012+impl std::ops::DerefMut for Worker {
2013+ fn deref_mut(&mut self) -> &mut Self::Target {
2014+ self.inner.as_mut().expect("Worker isolate unavailable")
2015+ }
2016+}
2017+
2018+const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024;
2019+const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024;
2020+
2021+#[derive(Default)]
2022+struct HeapLimitState {
2023+ excessively_exceeded: AtomicBool,
2024+}
2025+
2026+type SerializedPut = (String, Vec<u8>);
2027+type PendingPuts = HashMap<String, Vec<SerializedPut>>;
2028+
2029+/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a
2030+/// Worker Loader can hand a loaded worker `Deny` (globalOutbound: null) so its
2031+/// global `fetch()` throws and it must reach the world through `env`
2032+/// capabilities.
2033+#[derive(Clone, Copy, Default, PartialEq)]
2034+enum EgressPolicy {
2035+ #[default]
2036+ Allow,
2037+ Deny,
2038+}
2039+
2040+#[derive(Default)]
2041+struct ActorRuntimeState {
2042+ termination: std::sync::Mutex<Option<ExecutionTermination>>,
2043+ pending_puts: std::sync::Mutex<PendingPuts>,
2044+ worker_exit_requested: AtomicBool,
2045+ egress: EgressPolicy,
2046+}
2047+
2048+struct ExecutionTermination {
2049+ error: String,
2050+ actor_scope: Option<String>,
2051+}
2052+
2053+fn finish_terminated_actor_event(scope: &mut v8::PinScope, actor_scope: &str) {
2054+ let global = scope.get_current_context().global(scope);
2055+ let key = v8::String::new(scope, "__endTerminatedActorEvent").unwrap();
2056+ let Some(value) = global.get(scope, key.into()) else {
2057+ return;
2058+ };
2059+ let Ok(function) = v8::Local::<v8::Function>::try_from(value) else {
2060+ return;
2061+ };
2062+ let actor_scope = v8::String::new(scope, actor_scope).unwrap();
2063+ let recv = v8::undefined(scope).into();
2064+ let _ = function.call(scope, recv, &[actor_scope.into()]);
2065+}
2066+
2067+fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> {
2068+ let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned();
2069+ let termination = state.and_then(|state| state.termination.lock().ok()?.take());
2070+ let is_terminating = scope.is_execution_terminating();
2071+ if termination.is_some() || is_terminating {
2072+ scope.cancel_terminate_execution();
2073+ }
2074+ if let Some(termination) = termination {
2075+ if let Some(actor_scope) = termination.actor_scope {
2076+ finish_terminated_actor_event(scope, &actor_scope);
2077+ }
2078+ return Some(anyhow!(termination.error));
2079+ }
2080+ is_terminating.then(|| anyhow!("JavaScript execution was terminated"))
2081+}
2082+
2083+extern "C" fn near_heap_limit(
2084+ data: *mut std::ffi::c_void,
2085+ current_heap_limit: usize,
2086+ _initial_heap_limit: usize,
2087+) -> usize {
2088+ // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop
2089+ // removes this callback before the isolate (and its slots) are destroyed.
2090+ let state = unsafe { &*(data as *const HeapLimitState) };
2091+ state.excessively_exceeded.store(true, Ordering::Relaxed);
2092+ // V8 fatally aborts the process if a near-limit callback does not extend
2093+ // the limit. This reserve lets JS observe condemnation and unwind.
2094+ current_heap_limit.saturating_add(V8_HEAP_EMERGENCY_BYTES)
2095+}
2096+
2097+fn v8_heap_limit_bytes() -> usize {
2098+ std::env::var("CELLD_V8_HEAP_LIMIT_MB")
2099+ .ok()
2100+ .and_then(|value| value.parse::<usize>().ok())
2101+ .and_then(|megabytes| megabytes.checked_mul(1024 * 1024))
2102+ .filter(|bytes| *bytes > 0)
2103+ .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES)
2104+}
2105+
2106+impl Drop for WorkerIsolate {
2107+ fn drop(&mut self) {
2108+ self.isolate
2109+ .remove_near_heap_limit_callback(near_heap_limit, self.original_heap_limit);
2110+ }
2111+}
2112+
2113+#[derive(Debug)]
2114+pub struct AlarmRunError {
2115+ source: anyhow::Error,
2116+ counts_against_limit: bool,
2117+}
2118+
2119+impl AlarmRunError {
2120+ fn infrastructure(source: anyhow::Error) -> Self {
2121+ Self {
2122+ source,
2123+ counts_against_limit: false,
2124+ }
2125+ }
2126+
2127+ fn user(source: anyhow::Error) -> Self {
2128+ Self {
2129+ source,
2130+ counts_against_limit: true,
2131+ }
2132+ }
2133+
2134+ pub fn counts_against_limit(&self) -> bool {
2135+ self.counts_against_limit
2136+ }
2137+}
2138+
2139+impl std::fmt::Display for AlarmRunError {
2140+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2141+ self.source.fmt(formatter)
2142+ }
2143+}
2144+
2145+impl std::error::Error for AlarmRunError {
2146+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2147+ self.source.source()
2148+ }
2149+}
2150+
2151+impl Worker {
2152+ /// Compile the worker module, wire the DO harness, and extract the entry
2153+ /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding
2154+ /// name to a DO class name (from wrangler metadata).
2155+ ///
2156+ /// The runtime builds a `WorkerConfig` directly; this helper is
2157+ /// test-only.
2158+ #[cfg(test)]
2159+ pub fn load(options: WorkerConfigOptions, owned: &[String]) -> Result<Worker> {
2160+ let config = Arc::new(WorkerConfig::new(options));
2161+ Self::load_config(config, owned)
2162+ }
2163+
2164+ pub fn load_config(config: Arc<WorkerConfig>, owned: &[String]) -> Result<Worker> {
2165+ Self::load_config_owned(config, Arc::from(owned.to_vec()))
2166+ }
2167+
2168+ fn load_config_owned(config: Arc<WorkerConfig>, owned: Arc<[String]>) -> Result<Worker> {
2169+ let src = config.src.as_str();
2170+ let script_name = config.script_name.as_str();
2171+ let do_classes = config.do_classes.as_slice();
2172+ let node = config.node.as_str();
2173+ let text = config.text.as_slice();
2174+ let compat = config.compat;
2175+ let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes());
2176+ let mut isolate = v8::Isolate::new(params);
2177+ // Dynamic `import()` of builtin specifiers; per-import()-call only.
2178+ isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically);
2179+ let original_heap_limit = isolate.get_heap_statistics().heap_size_limit();
2180+ let heap_limit_state = Arc::new(HeapLimitState::default());
2181+ let runtime_state = Arc::new(ActorRuntimeState {
2182+ egress: config.egress,
2183+ ..Default::default()
2184+ });
2185+ let heap_limit_state_ptr =
2186+ Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void;
2187+ isolate.set_slot(heap_limit_state);
2188+ isolate.set_slot(runtime_state.clone());
2189+ isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr);
2190+ let (context, fetch) = {
2191+ v8::scope!(let hs, &mut isolate);
2192+ let context = v8::Context::new(hs, Default::default());
2193+ let cs = &mut v8::ContextScope::new(hs, context);
2194+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2195+ let scope = &mut tc.init();
2196+
2197+ install_ops(scope, context);
2198+ install_prelude(scope)?; // Web Platform APIs
2199+ install_harness(scope)?; // DO object model + minimal Response
2200+ install_lazy_globals(scope)?;
2201+ // A global, so it must exist before the module evaluates: bundles
2202+ // read Cloudflare.compatibilityFlags at module scope.
2203+ inject_compatibility_flags(scope, compat)?;
2204+ inject_storage_compatibility(scope, compat)?;
2205+
2206+ let module = match compile_module(scope, "worker.js", src) {
2207+ Some(m) => m,
2208+ None => return Err(anyhow!("compile: {}", exc!(scope))),
2209+ };
2210+ register_stubs(scope, src, text); // cloudflare:*/node:* + text modules
2211+ if !config.loader_modules.is_empty() {
2212+ register_loader_modules(scope, &config.loader_modules);
2213+ }
2214+ module
2215+ .instantiate_module(scope, resolve_external)
2216+ .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?;
2217+ let ev = match module.evaluate(scope) {
2218+ Some(value) => value,
2219+ None => {
2220+ if let Some(error) = take_execution_termination(scope) {
2221+ return Err(error);
2222+ }
2223+ return Err(anyhow!("evaluate: {}", exc!(scope)));
2224+ }
2225+ };
2226+ if let Some(error) = take_execution_termination(scope) {
2227+ return Err(error);
2228+ }
2229+ if let Ok(p) = ev.try_cast::<v8::Promise>() {
2230+ if p.state() == v8::PromiseState::Rejected {
2231+ let r = p.result(scope);
2232+ let stk = r
2233+ .to_object(scope)
2234+ .and_then(|o| {
2235+ let k = v8::String::new(scope, "stack")?;
2236+ o.get(scope, k.into())
2237+ })
2238+ .map(|s| s.to_rust_string_lossy(scope))
2239+ .unwrap_or_default();
2240+ return Err(anyhow!(
2241+ "top-level rejected: {} | {}",
2242+ r.to_rust_string_lossy(scope),
2243+ stk.lines().take(4).collect::<Vec<_>>().join(" <- ")
2244+ ));
2245+ }
2246+ }
2247+
2248+ let ns = module
2249+ .get_module_namespace()
2250+ .to_object(scope)
2251+ .ok_or_else(|| anyhow!("ns"))?;
2252+
2253+ // register each exported DO class into the harness registry
2254+ for cn in do_classes {
2255+ let key = v8::String::new(scope, cn).unwrap();
2256+ let cls = ns
2257+ .get(scope, key.into())
2258+ .ok_or_else(|| anyhow!("DO class {cn} not exported"))?;
2259+ register_class(scope, cn, cls)?;
2260+ }
2261+ inject_namespace_keys(scope, script_name, do_classes)?;
2262+ populate_cf_exports(scope, ns, do_classes)?;
2263+ register_entrypoints(scope, ns)?;
2264+ // build env from bindings and stash it in the harness
2265+ build_env(scope, &config)?;
2266+ // tell the harness which cells are local (route the rest cross-node)
2267+ inject_routing(scope, owned.as_ref(), node)?;
2268+
2269+ // entry fetch
2270+ let dk = v8::String::new(scope, "default").unwrap();
2271+ let default = ns
2272+ .get(scope, dk.into())
2273+ .ok_or_else(|| anyhow!("no default export"))?
2274+ .to_object(scope)
2275+ .ok_or_else(|| anyhow!("default not object"))?;
2276+ let fk = v8::String::new(scope, "fetch").unwrap();
2277+ let f: v8::Local<v8::Function> = default
2278+ .get(scope, fk.into())
2279+ .ok_or_else(|| anyhow!("no fetch"))?
2280+ .try_into()
2281+ .map_err(|_| anyhow!("fetch not fn"))?;
2282+
2283+ // Lets a self-targeted service binding invoke the handler in
2284+ // this isolate instead of crossing to a pool thread.
2285+ {
2286+ let cell_key = v8::String::new(scope, "__cell").unwrap();
2287+ if let Some(cell) = context
2288+ .global(scope)
2289+ .get(scope, cell_key.into())
2290+ .and_then(|value| value.to_object(scope))
2291+ {
2292+ let key = v8::String::new(scope, "selfFetch").unwrap();
2293+ cell.set(scope, key.into(), f.into());
2294+ // Optional scheduled handler, reached by a self-targeted
2295+ // service binding's scheduled().
2296+ let sk = v8::String::new(scope, "scheduled").unwrap();
2297+ if let Some(handler) = default.get(scope, sk.into()) {
2298+ if handler.is_function() {
2299+ let key_ = v8::String::new(scope, "selfScheduled").unwrap();
2300+ cell.set(scope, key_.into(), handler);
2301+ }
2302+ }
2303+ }
2304+ }
2305+ (v8::Global::new(scope, context), v8::Global::new(scope, f))
2306+ };
2307+ Ok(Worker {
2308+ inner: Some(WorkerIsolate {
2309+ isolate,
2310+ context,
2311+ fetch,
2312+ original_heap_limit,
2313+ runtime_state,
2314+ }),
2315+ config,
2316+ owned,
2317+ })
2318+ }
2319+
2320+ fn reload_after_process_exit(&mut self) -> Result<()> {
2321+ if !self
2322+ .runtime_state
2323+ .worker_exit_requested
2324+ .load(Ordering::Relaxed)
2325+ {
2326+ return Ok(());
2327+ }
2328+ let config = self.config.clone();
2329+ let owned = self.owned.clone();
2330+ drop(self.inner.take());
2331+ let replacement = Self::load_config_owned(config, owned)
2332+ .map_err(|error| anyhow!("reload after process.exit: {error:#}"))?;
2333+ self.inner = replacement.inner;
2334+ Ok(())
2335+ }
2336+
2337+ /// Restore an idFromName() actor's human-readable identity before its
2338+ /// constructor runs. The host calls this on activation and before a named
2339+ /// request is dispatched.
2340+ pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> {
2341+ let context_g = self.context.clone();
2342+ v8::scope!(let hs, &mut self.isolate);
2343+ let context = v8::Local::new(hs, context_g);
2344+ let cs = &mut v8::ContextScope::new(hs, context);
2345+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2346+ register_actor_name(&mut tc.init(), scope, Some(name))
2347+ }
2348+
2349+ /// Fire the DO's alarm() handler for `scope`. Returns Ok on success, Err if
2350+ /// the handler threw (caller retries per the at-least-once contract).
2351+ pub fn fire_alarm(
2352+ &mut self,
2353+ scope: &str,
2354+ retry: i64,
2355+ rx: &std::sync::mpsc::Receiver<CellJob>,
2356+ ) -> std::result::Result<(), AlarmRunError> {
2357+ let scheduled_time = storage::active_alarm_scheduled_time(scope).ok_or_else(|| {
2358+ AlarmRunError::infrastructure(anyhow!(
2359+ "alarm handler started without a scheduled alarm",
2360+ ))
2361+ })?;
2362+ let context_g = self.context.clone();
2363+ v8::scope!(let hs, &mut self.isolate);
2364+ let context = v8::Local::new(hs, context_g);
2365+ let cs = &mut v8::ContextScope::new(hs, context);
2366+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2367+ let result = call_fire_alarm(&mut tc.init(), scope, scheduled_time, retry, rx);
2368+ if let Some(error) = storage::sql_critical_error(scope) {
2369+ return Err(AlarmRunError::user(anyhow!(error)));
2370+ }
2371+ result
2372+ }
2373+
2374+ /// Run a specific DO instance's fetch, addressed by its scope — the target
2375+ /// of a cross-node proxy hop. Bypasses the Worker's default export (which
2376+ /// would re-route). Called on the owner node via the `/__do/<scope>` endpoint.
2377+ pub fn dispatch_to_and_reply(
2378+ &mut self,
2379+ scope: &str,
2380+ request: FetchRequest<'_>,
2381+ rx: &std::sync::mpsc::Receiver<CellJob>,
2382+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2383+ ) {
2384+ let context_g = self.context.clone();
2385+ v8::scope!(let hs, &mut self.isolate);
2386+ let context = v8::Local::new(hs, context_g);
2387+ let cs = &mut v8::ContextScope::new(hs, context);
2388+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2389+ let tc = &mut tc.init();
2390+ let global = context.global(tc);
2391+ let key = v8::String::new(tc, "__dispatchTo").unwrap();
2392+ let f: v8::Local<v8::Function> = match global
2393+ .get(tc, key.into())
2394+ .ok_or_else(|| anyhow!("no __dispatchTo"))
2395+ .and_then(|value| value.try_into().map_err(|_| anyhow!("not fn")))
2396+ {
2397+ Ok(f) => f,
2398+ Err(error) => {
2399+ let _ = reply.send(Err(error));
2400+ return;
2401+ }
2402+ };
2403+ let sc = v8::String::new(tc, scope).unwrap();
2404+ let u = v8::String::new(tc, request.url).unwrap();
2405+ let m = v8::String::new(tc, request.method).unwrap();
2406+ let b = bytes_value(tc, request.body.to_vec());
2407+ let headers = match serde_json::to_string(request.headers) {
2408+ Ok(headers) => v8::String::new(tc, &headers).unwrap(),
2409+ Err(error) => {
2410+ let _ = reply.send(Err(error.into()));
2411+ return;
2412+ }
2413+ };
2414+ let request_id_value: v8::Local<v8::Value> = match request.request_id {
2415+ Some(request_id) => v8::String::new(tc, &request_id_string(request_id))
2416+ .unwrap()
2417+ .into(),
2418+ None => v8::null(tc).into(),
2419+ };
2420+ let recv = v8::undefined(tc).into();
2421+ // Sample the committed-write position before the handler runs, so the
2422+ // output gate can tell an app write from celld's own activation writes.
2423+ let writes_before = storage::write_position(scope);
2424+ if let Err(error) = begin_event_context(tc) {
2425+ let _ = reply.send(Err(error));
2426+ return;
2427+ }
2428+ let Some(ret) = f.call(
2429+ tc,
2430+ recv,
2431+ &[
2432+ sc.into(),
2433+ u.into(),
2434+ m.into(),
2435+ b,
2436+ headers.into(),
2437+ request_id_value,
2438+ ],
2439+ ) else {
2440+ let _ = end_event_context(tc);
2441+ let _ = reply.send(Err(anyhow!("dispatchTo threw: {}", exc!(tc))));
2442+ return;
2443+ };
2444+ complete_fetch_event(
2445+ tc,
2446+ ret,
2447+ Some(rx),
2448+ Some(scope),
2449+ writes_before,
2450+ request.request_id,
2451+ reply,
2452+ );
2453+ }
2454+
2455+ /// Invoke one public method on a DO instance (Cloudflare native RPC),
2456+ /// with arguments and result in either `RpcData` flavor.
2457+ pub fn dispatch_rpc_data(
2458+ &mut self,
2459+ scope: &str,
2460+ method: &str,
2461+ args: RpcData,
2462+ rx: &std::sync::mpsc::Receiver<CellJob>,
2463+ ) -> Result<RpcData> {
2464+ let context_g = self.context.clone();
2465+ v8::scope!(let hs, &mut self.isolate);
2466+ let context = v8::Local::new(hs, context_g);
2467+ let cs = &mut v8::ContextScope::new(hs, context);
2468+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2469+ let tc = &mut tc.init();
2470+ let global = context.global(tc);
2471+ let key = v8::String::new(tc, "__dispatchRpc").unwrap();
2472+ let f: v8::Local<v8::Function> = global
2473+ .get(tc, key.into())
2474+ .ok_or_else(|| anyhow!("no __dispatchRpc"))?
2475+ .try_into()
2476+ .map_err(|_| anyhow!("not fn"))?;
2477+ let sc = v8::String::new(tc, scope).unwrap();
2478+ let method = v8::String::new(tc, method).unwrap();
2479+ let args = rpc_data_value(tc, args);
2480+ let recv = v8::undefined(tc).into();
2481+ begin_event_context(tc)?;
2482+ let Some(ret) = f.call(tc, recv, &[sc.into(), method.into(), args]) else {
2483+ let _ = end_event_context(tc);
2484+ return Err(anyhow!("dispatchRpc threw: {}", exc!(tc)));
2485+ };
2486+ let ret = run_event_value(tc, ret, Some(rx), Some(scope), None);
2487+ if let Some(error) = storage::sql_critical_error(scope) {
2488+ return Err(anyhow!(error));
2489+ }
2490+ let ret = ret?;
2491+ Ok(rpc_data_ret(tc, ret))
2492+ }
2493+
2494+ /// JSON-flavored `dispatch_rpc_data`, the test harness's entry point.
2495+ #[cfg(test)]
2496+ pub fn dispatch_rpc(
2497+ &mut self,
2498+ scope: &str,
2499+ method: &str,
2500+ args: &str,
2501+ rx: &std::sync::mpsc::Receiver<CellJob>,
2502+ ) -> Result<String> {
2503+ let args = RpcData::Json(args.into());
2504+ match self.dispatch_rpc_data(scope, method, args, rx)? {
2505+ RpcData::Json(json) => Ok(json),
2506+ RpcData::V8(_) => Err(anyhow!("JSON RPC answered bytes")),
2507+ }
2508+ }
2509+
2510+ /// Invoke `method` on the named `WorkerEntrypoint`. The service-binding
2511+ /// counterpart of `dispatch_rpc_data`: no actor scope, so no cell
2512+ /// receiver and no SQL critical-error check. Arguments and result are V8
2513+ /// structured-clone bytes.
2514+ pub fn dispatch_entrypoint_rpc(
2515+ &mut self,
2516+ entrypoint: &str,
2517+ method: &str,
2518+ args: Vec<u8>,
2519+ ) -> Result<Vec<u8>> {
2520+ let context_g = self.context.clone();
2521+ v8::scope!(let hs, &mut self.isolate);
2522+ let context = v8::Local::new(hs, context_g);
2523+ let cs = &mut v8::ContextScope::new(hs, context);
2524+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2525+ let tc = &mut tc.init();
2526+ let global = context.global(tc);
2527+ let key = v8::String::new(tc, "__dispatchEntrypointRpc").unwrap();
2528+ let f: v8::Local<v8::Function> = global
2529+ .get(tc, key.into())
2530+ .ok_or_else(|| anyhow!("no __dispatchEntrypointRpc"))?
2531+ .try_into()
2532+ .map_err(|_| anyhow!("not fn"))?;
2533+ let entrypoint = v8::String::new(tc, entrypoint).unwrap();
2534+ let method = v8::String::new(tc, method).unwrap();
2535+ let args = bytes_value(tc, args);
2536+ let recv = v8::undefined(tc).into();
2537+ begin_event_context(tc)?;
2538+ let Some(ret) = f.call(tc, recv, &[entrypoint.into(), method.into(), args]) else {
2539+ let _ = end_event_context(tc);
2540+ return Err(anyhow!("entrypoint RPC threw: {}", exc!(tc)));
2541+ };
2542+ let ret = run_event_value(tc, ret, None, None, None)?;
2543+ view_bytes(ret).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes"))
2544+ }
2545+
2546+ pub fn dispatch_ws_open(
2547+ &mut self,
2548+ scope: &str,
2549+ ws_id: u64,
2550+ protocol: &str,
2551+ rx: &std::sync::mpsc::Receiver<CellJob>,
2552+ ) -> Result<()> {
2553+ let context_g = self.context.clone();
2554+ v8::scope!(let hs, &mut self.isolate);
2555+ let context = v8::Local::new(hs, context_g);
2556+ let cs = &mut v8::ContextScope::new(hs, context);
2557+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2558+ let tc = &mut tc.init();
2559+ call_dispatch_ws_open(tc, scope, ws_id, protocol, rx)
2560+ }
2561+
2562+ /// Deliver a WebSocket message to the cell's DO (`webSocketMessage`). The
2563+ /// socket lives in the host; `ws.send` inside the handler routes back out by
2564+ /// wsId. The isolate may have been hibernated between messages — the host
2565+ /// re-activates before calling this.
2566+ pub fn dispatch_ws(
2567+ &mut self,
2568+ scope: &str,
2569+ ws_id: u64,
2570+ data: WsIn,
2571+ rx: &std::sync::mpsc::Receiver<CellJob>,
2572+ ) -> Result<WsDispatch> {
2573+ let context_g = self.context.clone();
2574+ v8::scope!(let hs, &mut self.isolate);
2575+ let context = v8::Local::new(hs, context_g);
2576+ let cs = &mut v8::ContextScope::new(hs, context);
2577+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2578+ let tc = &mut tc.init();
2579+ call_dispatch_ws(tc, scope, ws_id, data, rx)
2580+ }
2581+
2582+ pub fn dispatch_ws_closed(
2583+ &mut self,
2584+ scope: &str,
2585+ ws_id: u64,
2586+ code: u16,
2587+ reason: &str,
2588+ was_clean: bool,
2589+ rx: &std::sync::mpsc::Receiver<CellJob>,
2590+ ) -> Result<()> {
2591+ let context_g = self.context.clone();
2592+ v8::scope!(let hs, &mut self.isolate);
2593+ let context = v8::Local::new(hs, context_g);
2594+ let cs = &mut v8::ContextScope::new(hs, context);
2595+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2596+ let tc = &mut tc.init();
2597+ let global = context.global(tc);
2598+ let key = v8::String::new(tc, "__wsClosed").unwrap();
2599+ let f: v8::Local<v8::Function> = global
2600+ .get(tc, key.into())
2601+ .ok_or_else(|| anyhow!("no __wsClosed"))?
2602+ .try_into()
2603+ .map_err(|_| anyhow!("not fn"))?;
2604+ let sc = v8::String::new(tc, scope).unwrap();
2605+ let id = v8::Number::new(tc, ws_id as f64);
2606+ let code = v8::Number::new(tc, f64::from(code));
2607+ let reason = v8::String::new(tc, reason).unwrap();
2608+ let was_clean = v8::Boolean::new(tc, was_clean);
2609+ let recv = v8::undefined(tc).into();
2610+ begin_event_context(tc)?;
2611+ let Some(ret) = f.call(
2612+ tc,
2613+ recv,
2614+ &[
2615+ sc.into(),
2616+ id.into(),
2617+ code.into(),
2618+ reason.into(),
2619+ was_clean.into(),
2620+ ],
2621+ ) else {
2622+ let _ = end_event_context(tc);
2623+ return Err(anyhow!("wsClosed threw: {}", exc!(tc)));
2624+ };
2625+ let result = run_event_value(tc, ret, Some(rx), Some(scope), None);
2626+ if let Some(error) = storage::sql_critical_error(scope) {
2627+ return Err(anyhow!(error));
2628+ }
2629+ result?;
2630+ Ok(())
2631+ }
2632+
2633+ /// Run the worker `fetch` and reply on the oneshot. Test-only: it drives
2634+ /// one request at a time and registers no signal, so the shipped binary
2635+ /// never needs it.
2636+ #[cfg(all(test, celld_internal_tests))]
2637+ pub fn fetch_and_reply(
2638+ &mut self,
2639+ url: &str,
2640+ method: &str,
2641+ body: &[u8],
2642+ headers: &[(String, String)],
2643+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2644+ ) -> Result<()> {
2645+ self.fetch_and_reply_id(url, method, body, headers, None, reply)
2646+ }
2647+
2648+ /// As `fetch_and_reply`, but the request's signal is registered under
2649+ /// `request_id` so an HTTP or service-binding caller that disconnects
2650+ /// reaches the target's `request.signal` mid-flight.
2651+ pub fn fetch_and_reply_id(
2652+ &mut self,
2653+ url: &str,
2654+ method: &str,
2655+ body: &[u8],
2656+ headers: &[(String, String)],
2657+ request_id: Option<RequestId>,
2658+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2659+ ) -> Result<()> {
2660+ self.fetch_and_reply_inner(url, method, body, headers, request_id, reply);
2661+ self.reload_after_process_exit()
2662+ }
2663+
2664+ fn fetch_and_reply_inner(
2665+ &mut self,
2666+ url: &str,
2667+ method: &str,
2668+ body: &[u8],
2669+ headers: &[(String, String)],
2670+ request_id: Option<RequestId>,
2671+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2672+ ) {
2673+ let context_g = self.context.clone();
2674+ let fetch = self.fetch.clone();
2675+ v8::scope!(let hs, &mut self.isolate);
2676+ let context = v8::Local::new(hs, context_g);
2677+ let cs = &mut v8::ContextScope::new(hs, context);
2678+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2679+ let tc = &mut tc.init();
2680+
2681+ let built = match request_id {
2682+ Some(_) => make_incoming_request(tc, url, method, body, headers),
2683+ None => make_request(tc, url, method, body, headers),
2684+ };
2685+ let req = match built {
2686+ Ok(req) => req,
2687+ Err(error) => {
2688+ let _ = reply.send(Err(error));
2689+ return;
2690+ }
2691+ };
2692+ // env comes from the harness (globalThis.__cell.env)
2693+ let env = match harness_env(tc) {
2694+ Ok(env) => env,
2695+ Err(error) => {
2696+ let _ = reply.send(Err(error));
2697+ return;
2698+ }
2699+ };
2700+ let recv = v8::undefined(tc).into();
2701+ let f = v8::Local::new(tc, fetch);
2702+ let execution_ctx = match begin_event_context(tc) {
2703+ Ok(execution_ctx) => execution_ctx,
2704+ Err(error) => {
2705+ let _ = reply.send(Err(error));
2706+ return;
2707+ }
2708+ };
2709+ let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else {
2710+ let error = take_execution_termination(tc)
2711+ .unwrap_or_else(|| anyhow!("fetch threw: {}", exc!(tc)));
2712+ let _ = end_event_context(tc);
2713+ let _ = reply.send(Err(error));
2714+ return;
2715+ };
2716+ let active_request_id = match request_id {
2717+ Some(request_id)
2718+ if ret
2719+ .try_cast::<v8::Promise>()
2720+ .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) =>
2721+ {
2722+ if let Err(error) = register_incoming_request(tc, request_id, req) {
2723+ clear_request_cancellation(request_id);
2724+ let _ = end_event_context(tc);
2725+ let _ = reply.send(Err(error));
2726+ return;
2727+ }
2728+ Some(request_id)
2729+ }
2730+ Some(request_id) => {
2731+ clear_request_cancellation(request_id);
2732+ None
2733+ }
2734+ None => None,
2735+ };
2736+ complete_fetch_event(tc, ret, None, None, None, active_request_id, reply);
2737+ if let Some(request_id) = active_request_id {
2738+ finish_incoming_request(tc, request_id);
2739+ }
2740+ }
2741+
2742+ /// Run the worker `fetch` in a CELL isolate, pumping this cell's job
2743+ /// receiver so an in-isolate `env.NS.get(ownScope).fetch()` resolves without
2744+ /// a host hop. Identical to `fetch_and_reply_id` except the event loop is
2745+ /// driven with `Some(rx)`.
2746+ pub fn worker_fetch_and_reply(
2747+ &mut self,
2748+ request: FetchRequest<'_>,
2749+ rx: &std::sync::mpsc::Receiver<CellJob>,
2750+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2751+ ) -> Result<()> {
2752+ self.worker_fetch_and_reply_inner(request, rx, reply);
2753+ self.reload_after_process_exit()
2754+ }
2755+
2756+ fn worker_fetch_and_reply_inner(
2757+ &mut self,
2758+ request: FetchRequest<'_>,
2759+ rx: &std::sync::mpsc::Receiver<CellJob>,
2760+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
2761+ ) {
2762+ let context_g = self.context.clone();
2763+ let fetch = self.fetch.clone();
2764+ v8::scope!(let hs, &mut self.isolate);
2765+ let context = v8::Local::new(hs, context_g);
2766+ let cs = &mut v8::ContextScope::new(hs, context);
2767+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
2768+ let tc = &mut tc.init();
2769+ let built = match request.request_id {
2770+ Some(_) => make_incoming_request(
2771+ tc,
2772+ request.url,
2773+ request.method,
2774+ request.body,
2775+ request.headers,
2776+ ),
2777+ None => make_request(
2778+ tc,
2779+ request.url,
2780+ request.method,
2781+ request.body,
2782+ request.headers,
2783+ ),
2784+ };
2785+ let req = match built {
2786+ Ok(req) => req,
2787+ Err(error) => {
2788+ let _ = reply.send(Err(error));
2789+ return;
2790+ }
2791+ };
2792+ let env = match harness_env(tc) {
2793+ Ok(env) => env,
2794+ Err(error) => {
2795+ let _ = reply.send(Err(error));
2796+ return;
2797+ }
2798+ };
2799+ let recv = v8::undefined(tc).into();
2800+ let f = v8::Local::new(tc, fetch);
2801+ let execution_ctx = match begin_event_context(tc) {
2802+ Ok(execution_ctx) => execution_ctx,
2803+ Err(error) => {
2804+ let _ = reply.send(Err(error));
2805+ return;
2806+ }
2807+ };
2808+ let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else {
2809+ let error = take_execution_termination(tc)
2810+ .unwrap_or_else(|| anyhow!("fetch threw: {}", exc!(tc)));
2811+ let _ = end_event_context(tc);
2812+ let _ = reply.send(Err(error));
2813+ return;
2814+ };
2815+ let active_request_id = match request.request_id {
2816+ Some(request_id)
2817+ if ret
2818+ .try_cast::<v8::Promise>()
2819+ .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) =>
2820+ {
2821+ if let Err(error) = register_incoming_request(tc, request_id, req) {
2822+ clear_request_cancellation(request_id);
2823+ let _ = end_event_context(tc);
2824+ let _ = reply.send(Err(error));
2825+ return;
2826+ }
2827+ Some(request_id)
2828+ }
2829+ Some(request_id) => {
2830+ clear_request_cancellation(request_id);
2831+ None
2832+ }
2833+ None => None,
2834+ };
2835+ complete_fetch_event(tc, ret, Some(rx), None, None, active_request_id, reply);
2836+ if let Some(request_id) = active_request_id {
2837+ finish_incoming_request(tc, request_id);
2838+ }
2839+ }
2840+}
2841+
2842+// ---- native ops exposed to JS ----
2843+
2844+/// Host ops, defined non-enumerable. They are runtime internals: a bundle
2845+/// walking `globalThis` must not find them, let alone `new` one — `for (const
2846+/// k in globalThis) new globalThis[k]()` used to reach `__actor_abort` and
2847+/// kill the actor.
2848+macro_rules! ops {
2849+ ($scope:expr, $global:expr, $($name:literal => $op:path),* $(,)?) => {
2850+ $({
2851+ let f = v8::Function::new($scope, $op).unwrap();
2852+ let k = v8::String::new($scope, $name).unwrap();
2853+ $global.define_own_property(
2854+ $scope, k.into(), f.into(), v8::PropertyAttribute::DONT_ENUM);
2855+ })*
2856+ };
2857+}
2858+
2859+fn install_ops(scope: &mut v8::PinScope, context: v8::Local<v8::Context>) {
2860+ let global = context.global(scope);
2861+ ops! { scope, global,
2862+ "__heap_limit_excessively_exceeded" =>
2863+ op_heap_limit_excessively_exceeded,
2864+ "__ws_send" => op_ws_send,
2865+ "__ws_send_binary" => op_ws_send_binary,
2866+ "__ws_close" => op_ws_close,
2867+ "__ws_alloc" => op_ws_alloc,
2868+ "__ws_accept" => op_ws_accept,
2869+ "__ws_accept_regular" => op_ws_accept_regular,
2870+ "__ws_list" => op_ws_list,
2871+ "__ws_attachment_set" => op_ws_attachment_set,
2872+ "__ws_connect" => op_ws_connect,
2873+ "__ws_next" => op_ws_next,
2874+ "__ws_upgrade" => op_ws_upgrade,
2875+ "__storage_get" => op_storage_get,
2876+ "__storage_get_many" => op_storage_get_many,
2877+ "__sql_exec" => op_sql_exec,
2878+ "__sql_ingest" => op_sql_ingest,
2879+ "__sql_cursor_start" => op_sql_cursor_start,
2880+ "__sql_cursor_next" => op_sql_cursor_next,
2881+ "__sql_cursor_close" => op_sql_cursor_close,
2882+ "__sql_database_size" => op_sql_database_size,
2883+ "__storage_transaction_control" => op_storage_transaction_control,
2884+ "__log" => op_log,
2885+ "__storage_put" => op_storage_put,
2886+ "__storage_put_many" => op_storage_put_many,
2887+ "__storage_queue_put" => op_storage_queue_put,
2888+ "__storage_queue_put_many" => op_storage_queue_put_many,
2889+ "__storage_put_serialized" => op_storage_put_serialized,
2890+ "__storage_queue_put_serialized" => op_storage_queue_put_serialized,
2891+ "__storage_flush_pending_puts" => op_storage_flush_pending_puts,
2892+ "__storage_cancel_pending_puts" => op_storage_cancel_pending_puts,
2893+ "__actor_abort" => op_actor_abort,
2894+ "__process_exit" => op_process_exit,
2895+ "__storage_delete" => op_storage_delete,
2896+ "__storage_delete_many" => op_storage_delete_many,
2897+ "__storage_list" => op_storage_list,
2898+ "__storage_sync_list_start" => op_storage_sync_list_start,
2899+ "__storage_sync_list_next" => op_storage_sync_list_next,
2900+ "__storage_delete_all" => op_storage_delete_all,
2901+ "$$urlParse" => op_url_parse,
2902+ "$$urlPatternParse" => op_urlpattern_parse,
2903+ "$$urlPatternMatchInput" => op_urlpattern_match_input,
2904+ "$$atob" => op_atob,
2905+ "$$btoa" => op_btoa,
2906+ "$$textDecoderLabel" => op_text_decoder_label,
2907+ "$$textDecoderNew" => op_text_decoder_new,
2908+ "$$textDecoderDecode" => op_text_decoder_decode,
2909+ "$$textDecoderFree" => op_text_decoder_free,
2910+ "__alarm_set" => op_alarm_set,
2911+ "__alarm_get" => op_alarm_get,
2912+ "__alarm_delete" => op_alarm_delete,
2913+ "__loader_load" => op_loader_load,
2914+ "__loader_fetch" => op_loader_fetch,
2915+ "__loader_rpc" => op_loader_rpc,
2916+ "__loader_drop" => op_loader_drop,
2917+ "__do_call" => op_do_call,
2918+ "__writePosition" => op_write_position,
2919+ "__gateWrite" => op_gate_write,
2920+ "__svc_call" => op_svc_call,
2921+ "__svc_call_cancellable" => op_svc_call_cancellable,
2922+ "__svc_rpc" => op_svc_rpc,
2923+ "__do_call_cancellable" => op_do_call_cancellable,
2924+ "__do_call_cancel" => op_do_call_cancel,
2925+ "__do_id" => op_do_id,
2926+ "__rpc_call" => op_rpc_call,
2927+ "__sc_encode" => op_sc_encode,
2928+ "__sc_decode" => op_sc_decode,
2929+ "__op_fetch" => op_fetch,
2930+ "__asset_fetch" => op_asset_fetch,
2931+ "__http_stream_read" => op_http_stream_read,
2932+ "__http_stream_cancel" => op_http_stream_cancel,
2933+ "__http_stream_tee" => op_http_stream_tee,
2934+ "__response_stream_create" => op_response_stream_create,
2935+ "__response_stream_write" => op_response_stream_write,
2936+ "__response_stream_closed" => op_response_stream_closed,
2937+ "__response_stream_close" => op_response_stream_close,
2938+ "__op_timer" => op_timer,
2939+ "__timer_alloc" => op_timer_alloc,
2940+ "__timer_cancel" => op_timer_cancel,
2941+ "__crypto_operation" => op_crypto_operation,
2942+ "$$randomValues" => op_webcrypto_random,
2943+ "$$digest" => op_webcrypto_digest,
2944+ "$$hmacSign" => op_webcrypto_hmac_sign,
2945+ "$$hmacVerify" => op_webcrypto_hmac_verify,
2946+ "$$aesEncrypt" => op_webcrypto_aes_encrypt,
2947+ "$$aesDecrypt" => op_webcrypto_aes_decrypt,
2948+ "$$pbkdf2" => op_node_pbkdf2,
2949+ "$$hkdf" => op_node_hkdf,
2950+ "__als_get" => op_als_get,
2951+ "__als_set" => op_als_set,
2952+ "__util_type_flags" => op_util_type_flags,
2953+ "__util_constructor_name" => op_util_constructor_name,
2954+ "__util_proxy_details" => op_util_proxy_details,
2955+ "__util_promise_details" => op_util_promise_details,
2956+ "__util_preview_entries" => op_util_preview_entries,
2957+ "__builtin_module" => op_builtin_module,
2958+ "__zlib" => op_zlib,
2959+ "__zlib_stream_new" => op_zlib_stream_new,
2960+ "__zlib_stream_push" => op_zlib_stream_push,
2961+ "__zlib_stream_end" => op_zlib_stream_end,
2962+ "__zlib_stream_drop" => op_zlib_stream_drop,
2963+ }
2964+ #[cfg(all(test, celld_internal_tests))]
2965+ ops! { scope, global,
2966+ "__test_gc" => op_test_gc,
2967+ "__loader_count" => op_loader_count,
2968+ "__test_set_heap_limit_excessively_exceeded" =>
2969+ op_test_set_heap_limit_excessively_exceeded,
2970+ "__sql_set_max_page_count_for_test" =>
2971+ op_sql_set_max_page_count_for_test,
2972+ "__sql_set_write_fault_for_test" => op_sql_set_write_fault_for_test,
2973+ "__sql_set_cache_size_for_test" => op_sql_set_cache_size_for_test,
2974+ "__sql_set_interrupt_fault_for_test" =>
2975+ op_sql_set_interrupt_fault_for_test,
2976+ "__sql_register_nomem_function_for_test" =>
2977+ op_sql_register_nomem_function_for_test,
2978+ }
2979+}
2980+
2981+/// Create a JS promise for an async op `id` and return it to JS.
2982+fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> {
2983+ let resolver = v8::PromiseResolver::new(scope).unwrap();
2984+ let promise = resolver.get_promise(scope);
2985+ promise_store(id, v8::Global::new(scope, resolver));
2986+ promise.into()
2987+}
2988+
2989+/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await
2990+/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON
2991+/// `{status, body, headers}` string the harness turns back into a Response.
2992+/// `__svc_rpc(script, entrypoint, method, argsSc)` -> Promise<Uint8Array>;
2993+/// arguments and result are V8 structured-clone bytes.
2994+fn op_svc_rpc(
2995+ scope: &mut v8::PinScope,
2996+ args: v8::FunctionCallbackArguments,
2997+ mut rv: v8::ReturnValue<v8::Value>,
2998+) {
2999+ let script = args.get(0).to_rust_string_lossy(scope);
3000+ let entrypoint = args.get(1).to_rust_string_lossy(scope);
3001+ let method = args.get(2).to_rust_string_lossy(scope);
3002+ let call_args = view_bytes(args.get(3)).unwrap_or_default();
3003+ let (tx, rx) = tokio::sync::oneshot::channel();
3004+ let sent = SVC_RPC_TX
3005+ .get()
3006+ .map(|t| {
3007+ t.send(SvcRpcReq {
3008+ script,
3009+ entrypoint,
3010+ method,
3011+ args: call_args,
3012+ reply: tx,
3013+ })
3014+ .is_ok()
3015+ })
3016+ .unwrap_or(false);
3017+ let id = asyncrt::enqueue(async move {
3018+ if !sent {
3019+ return Err("no service binding channel".into());
3020+ }
3021+ match rx.await {
3022+ Ok(Ok(result)) => Ok(result),
3023+ Ok(Err(error)) => Err(format!("{error}")),
3024+ Err(error) => Err(format!("service dropped: {error}")),
3025+ }
3026+ });
3027+ rv.set(promise_for(scope, id));
3028+}
3029+
3030+/// `__svc_call(script, url, method, body, headersJson)` -> Promise<json>.
3031+/// The service-binding equivalent of `__do_call`: no scope to resolve and no
3032+/// cancellation token, just a handoff to the target script's pool.
3033+fn op_svc_call(
3034+ scope: &mut v8::PinScope,
3035+ args: v8::FunctionCallbackArguments,
3036+ mut rv: v8::ReturnValue<v8::Value>,
3037+) {
3038+ op_svc_call_impl(scope, args, &mut rv, false);
3039+}
3040+
3041+fn op_svc_call_cancellable(
3042+ scope: &mut v8::PinScope,
3043+ args: v8::FunctionCallbackArguments,
3044+ mut rv: v8::ReturnValue<v8::Value>,
3045+) {
3046+ op_svc_call_impl(scope, args, &mut rv, true);
3047+}
3048+
3049+fn op_svc_call_impl(
3050+ scope: &mut v8::PinScope,
3051+ args: v8::FunctionCallbackArguments,
3052+ rv: &mut v8::ReturnValue<v8::Value>,
3053+ cancellable: bool,
3054+) {
3055+ let script = args.get(0).to_rust_string_lossy(scope);
3056+ let url = args.get(1).to_rust_string_lossy(scope);
3057+ let method = args.get(2).to_rust_string_lossy(scope);
3058+ let body = view_bytes(args.get(3)).unwrap_or_default();
3059+ let headers =
3060+ serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default();
3061+ let (tx, rx) = tokio::sync::oneshot::channel();
3062+ // Shares the Durable Object cancel registry, so `__do_call_cancel` works
3063+ // unchanged for a service call.
3064+ let (request_id, cancel, cancel_guard) = if cancellable {
3065+ let request_id = next_do_request_id();
3066+ let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
3067+ do_call_cancels()
3068+ .lock()
3069+ .unwrap()
3070+ .insert(request_id, cancel_sender);
3071+ (
3072+ Some(request_id),
3073+ Some(cancel_receiver),
3074+ Some(DoCallCancelGuard(request_id)),
3075+ )
3076+ } else {
3077+ (None, None, None)
3078+ };
3079+ let sent = SVC_CALL_TX
3080+ .get()
3081+ .map(|t| {
3082+ t.send(SvcCallReq {
3083+ cancel,
3084+ script,
3085+ url,
3086+ method,
3087+ body,
3088+ headers,
3089+ reply: tx,
3090+ })
3091+ .is_ok()
3092+ })
3093+ .unwrap_or(false);
3094+ let id = asyncrt::enqueue(async move {
3095+ let _cancel_guard = cancel_guard;
3096+ if !sent {
3097+ return Err("no service binding channel".into());
3098+ }
3099+ match rx.await {
3100+ Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3101+ Ok(Err(error)) => Err(format!("{error}")),
3102+ Err(error) => Err(format!("service dropped: {error}")),
3103+ }
3104+ });
3105+ let promise = promise_for(scope, id);
3106+ if let Some(request_id) = request_id {
3107+ if let Some(object) = promise.to_object(scope) {
3108+ let key = v8::String::new(scope, "__celldCancelId").unwrap();
3109+ let value = v8::String::new(scope, &request_id.to_string()).unwrap();
3110+ object.set(scope, key.into(), value.into());
3111+ }
3112+ }
3113+ rv.set(promise);
3114+}
3115+
3116+// --- Worker Loader: dynamic isolates for Code Mode ---
3117+// A running Worker spawns a fresh isolate from code it supplies at runtime and
3118+// invokes it. Walking skeleton: `env.LOADER.load(code)` -> stub;
3119+// `stub.getEntrypoint().fetch(req)` runs the loaded worker's default fetch,
3120+// reusing the co-hosted-worker thread model and `__svc_call` response
3121+// marshalling. Capability-scoped env, controlled outbound, named-entrypoint
3122+// RPC, and memoized `get(name, getCode)` are not yet wired.
3123+
3124+// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total
3125+// module bytes, 1 MiB env. Messages match so the conformance cases pass.
3126+const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024;
3127+const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024;
3128+
3129+enum LoaderJob {
3130+ Fetch {
3131+ url: String,
3132+ method: String,
3133+ body: Vec<u8>,
3134+ headers: Vec<(String, String)>,
3135+ reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
3136+ },
3137+ // Named-entrypoint RPC: args and result are V8 structured-clone bytes,
3138+ // like the service-binding `__svc_rpc` path.
3139+ Rpc {
3140+ entrypoint: String,
3141+ method: String,
3142+ args: Vec<u8>,
3143+ reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
3144+ },
3145+}
3146+
3147+type LoaderRegistry = HashMap<u64, std::sync::mpsc::Sender<LoaderJob>>;
3148+static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new();
3149+static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1);
3150+
3151+fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> {
3152+ LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
3153+}
3154+
3155+fn loader_throw(scope: &mut v8::PinScope, message: &str) {
3156+ let message = v8::String::new(scope, message).unwrap();
3157+ let exception = v8::Exception::error(scope, message);
3158+ scope.throw_exception(exception);
3159+}
3160+
3161+/// `__loader_load(codeJson)` -> stub id. Builds a WorkerConfig from the
3162+/// supplied modules, spawns a fresh isolate on its own thread (isolates are
3163+/// pinned per thread), and registers its job channel. The isolate compiles
3164+/// asynchronously; jobs queue until it is ready, and a load failure drains
3165+/// queued jobs with the error rather than dropping their reply channels.
3166+fn op_loader_load(
3167+ scope: &mut v8::PinScope,
3168+ args: v8::FunctionCallbackArguments,
3169+ mut rv: v8::ReturnValue<v8::Value>,
3170+) {
3171+ let code_json = args.get(0).to_rust_string_lossy(scope);
3172+ let code: serde_json::Value = match serde_json::from_str(&code_json) {
3173+ Ok(code) => code,
3174+ Err(e) => return loader_throw(scope, &format!("worker loader: {e}")),
3175+ };
3176+ let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else {
3177+ return loader_throw(scope, "worker loader: missing mainModule");
3178+ };
3179+ let Some(src) = code
3180+ .get("modules")
3181+ .and_then(|m| m.get(main))
3182+ .and_then(|v| v.as_str())
3183+ .map(str::to_string)
3184+ else {
3185+ return loader_throw(
3186+ scope,
3187+ &format!("worker loader: module {main:?} missing or not a string"),
3188+ );
3189+ };
3190+ // Every module other than the main one is a sibling the main module may
3191+ // import.
3192+ let loader_modules: Vec<(String, String)> = code
3193+ .get("modules")
3194+ .and_then(|m| m.as_object())
3195+ .map(|m| {
3196+ m.iter()
3197+ .filter(|(name, _)| name.as_str() != main)
3198+ .filter_map(|(name, v)| v.as_str().map(|s| (name.clone(), s.to_string())))
3199+ .collect()
3200+ })
3201+ .unwrap_or_default();
3202+ // Total module bytes, checked before compiling anything (the oversized
3203+ // module is never parsed) — the extra modules are not yet loaded but do
3204+ // count against the ceiling, as upstream.
3205+ let code_size: usize = code
3206+ .get("modules")
3207+ .and_then(|m| m.as_object())
3208+ .map(|m| m.values().filter_map(|v| v.as_str()).map(str::len).sum())
3209+ .unwrap_or(0);
3210+ if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE {
3211+ return loader_throw(
3212+ scope,
3213+ &format!(
3214+ "Dynamic Worker code size ({code_size} bytes) exceeds the \
3215+ maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes."
3216+ ),
3217+ );
3218+ }
3219+ // Plain JSON `env` values merge onto the loaded worker's env; capability
3220+ // stubs are not yet supported and would fail to serialize upstream in JS.
3221+ let loader_env = code
3222+ .get("env")
3223+ .filter(|v| !v.is_null())
3224+ .map(|v| v.to_string());
3225+ if let Some(env) = &loader_env {
3226+ if env.len() > MAX_DYNAMIC_WORKER_ENV_SIZE {
3227+ return loader_throw(
3228+ scope,
3229+ &format!(
3230+ "Dynamic Worker env size ({} bytes) exceeds the maximum \
3231+ allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.",
3232+ env.len()
3233+ ),
3234+ );
3235+ }
3236+ }
3237+ // globalOutbound: absent inherits the caller's authority, null denies
3238+ // ambient egress, a Fetcher (broker) is not implemented yet.
3239+ let egress = match code.get("globalOutbound") {
3240+ None => actor_runtime_state(scope).egress,
3241+ Some(v) if v.is_null() => EgressPolicy::Deny,
3242+ Some(_) => {
3243+ return loader_throw(
3244+ scope,
3245+ "worker loader: globalOutbound broker is not implemented yet",
3246+ );
3247+ }
3248+ };
3249+ // Bound live loaded workers so a runaway agent loop cannot exhaust
3250+ // threads and isolates. Evicted workers (dropped stubs) free their slot.
3251+ let max = std::env::var("CELLD_MAX_LOADED_WORKERS")
3252+ .ok()
3253+ .and_then(|v| v.parse::<usize>().ok())
3254+ .unwrap_or(256);
3255+ if loader_registry().lock().unwrap().len() >= max {
3256+ return loader_throw(
3257+ scope,
3258+ &format!("worker loader: too many loaded workers (limit {max})"),
3259+ );
3260+ }
3261+ // Honor the WorkerCode's declared compatibility (workerd worker_compat
3262+ // reads snake_case keys); Code Mode workers keep RPC on regardless.
3263+ let mut compat = crate::worker_compat(&serde_json::json!({
3264+ "compatibility_date": code.get("compatibilityDate"),
3265+ "compatibility_flags": code.get("compatibilityFlags"),
3266+ }));
3267+ compat.js_rpc = true;
3268+ let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed);
3269+ let config = Arc::new(
3270+ WorkerConfig::new(WorkerConfigOptions {
3271+ src,
3272+ script_name: format!("__loader:{id}"),
3273+ do_classes: Vec::new(),
3274+ bindings: Vec::new(),
3275+ r2_bindings: Vec::new(),
3276+ ai_binding: None,
3277+ vars: Vec::new(),
3278+ node: String::new(),
3279+ text: Vec::new(),
3280+ compat,
3281+ })
3282+ .with_egress(egress)
3283+ .with_loader_env(loader_env)
3284+ .with_loader_modules(loader_modules),
3285+ );
3286+ let (tx, rx) = std::sync::mpsc::channel::<LoaderJob>();
3287+ loader_registry().lock().unwrap().insert(id, tx);
3288+ std::thread::spawn(move || {
3289+ asyncrt::init();
3290+ let mut w = match Worker::load_config(config, &[]) {
3291+ Ok(w) => w,
3292+ Err(e) => return drain_loader_load_error(rx, &format!("{e}")),
3293+ };
3294+ for job in rx {
3295+ match job {
3296+ LoaderJob::Fetch {
3297+ url,
3298+ method,
3299+ body,
3300+ headers,
3301+ reply,
3302+ } => {
3303+ if w.fetch_and_reply_id(&url, &method, &body, &headers, None, reply)
3304+ .is_err()
3305+ {
3306+ break;
3307+ }
3308+ }
3309+ LoaderJob::Rpc {
3310+ entrypoint,
3311+ method,
3312+ args,
3313+ reply,
3314+ } => {
3315+ let _ = reply.send(w.dispatch_entrypoint_rpc(&entrypoint, &method, args));
3316+ }
3317+ }
3318+ }
3319+ });
3320+ rv.set(v8::Number::new(scope, id as f64).into());
3321+}
3322+
3323+/// Reply to every queued job with the load error, so a worker that failed to
3324+/// compile rejects its callers cleanly instead of dropping their channels.
3325+fn drain_loader_load_error(rx: std::sync::mpsc::Receiver<LoaderJob>, error: &str) {
3326+ for job in rx {
3327+ match job {
3328+ LoaderJob::Fetch { reply, .. } => {
3329+ let _ = reply.send(Err(anyhow!("{error}")));
3330+ }
3331+ LoaderJob::Rpc { reply, .. } => {
3332+ let _ = reply.send(Err(anyhow!("{error}")));
3333+ }
3334+ }
3335+ }
3336+}
3337+
3338+/// `__loader_fetch(id, url, method, body, headersJson)` -> Promise<json>. The
3339+/// loaded-worker analog of `__svc_call`: encodes the response the same way.
3340+fn op_loader_fetch(
3341+ scope: &mut v8::PinScope,
3342+ args: v8::FunctionCallbackArguments,
3343+ mut rv: v8::ReturnValue<v8::Value>,
3344+) {
3345+ let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3346+ let url = args.get(1).to_rust_string_lossy(scope);
3347+ let method = args.get(2).to_rust_string_lossy(scope);
3348+ let body = view_bytes(args.get(3)).unwrap_or_default();
3349+ let headers =
3350+ serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default();
3351+ let (tx, rx) = tokio::sync::oneshot::channel();
3352+ let sent = loader_registry()
3353+ .lock()
3354+ .unwrap()
3355+ .get(&id)
3356+ .map(|s| {
3357+ s.send(LoaderJob::Fetch {
3358+ url,
3359+ method,
3360+ body,
3361+ headers,
3362+ reply: tx,
3363+ })
3364+ .is_ok()
3365+ })
3366+ .unwrap_or(false);
3367+ let async_id = asyncrt::enqueue(async move {
3368+ if !sent {
3369+ return Err("worker loader: unknown worker".into());
3370+ }
3371+ match rx.await {
3372+ Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3373+ Ok(Err(error)) => Err(format!("{error}")),
3374+ Err(error) => Err(format!("loaded worker dropped: {error}")),
3375+ }
3376+ });
3377+ rv.set(promise_for(scope, async_id));
3378+}
3379+
3380+/// `__loader_rpc(id, entrypoint, method, argsSc)` -> Promise<Uint8Array>. The
3381+/// loaded-worker analog of `__svc_rpc`: a named-entrypoint method call whose
3382+/// args and result are V8 structured-clone bytes.
3383+fn op_loader_rpc(
3384+ scope: &mut v8::PinScope,
3385+ args: v8::FunctionCallbackArguments,
3386+ mut rv: v8::ReturnValue<v8::Value>,
3387+) {
3388+ let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3389+ let entrypoint = args.get(1).to_rust_string_lossy(scope);
3390+ let method = args.get(2).to_rust_string_lossy(scope);
3391+ let call_args = view_bytes(args.get(3)).unwrap_or_default();
3392+ let (tx, rx) = tokio::sync::oneshot::channel();
3393+ let sent = loader_registry()
3394+ .lock()
3395+ .unwrap()
3396+ .get(&id)
3397+ .map(|s| {
3398+ s.send(LoaderJob::Rpc {
3399+ entrypoint,
3400+ method,
3401+ args: call_args,
3402+ reply: tx,
3403+ })
3404+ .is_ok()
3405+ })
3406+ .unwrap_or(false);
3407+ let async_id = asyncrt::enqueue(async move {
3408+ if !sent {
3409+ return Err("worker loader: unknown worker".into());
3410+ }
3411+ match rx.await {
3412+ Ok(Ok(result)) => Ok(result),
3413+ Ok(Err(error)) => Err(format!("{error}")),
3414+ Err(error) => Err(format!("loaded worker dropped: {error}")),
3415+ }
3416+ });
3417+ rv.set(promise_for(scope, async_id));
3418+}
3419+
3420+/// `__loader_drop(id)` — evict a loaded worker. Called from a
3421+/// FinalizationRegistry when its stub is GC'd: removing the registry entry
3422+/// drops the job-channel Sender, so the worker thread's receive loop ends and
3423+/// the isolate is dropped on that thread. Without this every load() would leak
3424+/// a thread and isolate.
3425+fn op_loader_drop(
3426+ scope: &mut v8::PinScope,
3427+ args: v8::FunctionCallbackArguments,
3428+ _rv: v8::ReturnValue<v8::Value>,
3429+) {
3430+ let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3431+ loader_registry().lock().unwrap().remove(&id);
3432+}
3433+
3434+/// `__loader_count()` -> live loaded-worker count, for eviction tests.
3435+#[cfg(all(test, celld_internal_tests))]
3436+fn op_loader_count(
3437+ scope: &mut v8::PinScope,
3438+ _args: v8::FunctionCallbackArguments,
3439+ mut rv: v8::ReturnValue<v8::Value>,
3440+) {
3441+ let n = loader_registry().lock().unwrap().len();
3442+ rv.set(v8::Number::new(scope, n as f64).into());
3443+}
3444+
3445+/// `__writePosition(scope)` -> the cell's committed-write position (a number),
3446+/// or `null` when the scope has no open connection. The co-hosted DO fast path
3447+/// samples this around an inline `fetch` to tell a write from a read.
3448+fn op_write_position(
3449+ scope: &mut v8::PinScope,
3450+ args: v8::FunctionCallbackArguments,
3451+ mut rv: v8::ReturnValue<v8::Value>,
3452+) {
3453+ let cell = args.get(0).to_rust_string_lossy(scope);
3454+ match storage::write_position(&cell) {
3455+ Some(position) => rv.set(v8::Number::new(scope, position as f64).into()),
3456+ None => rv.set(v8::null(scope).into()),
3457+ }
3458+}
3459+
3460+/// `__gateWrite(scope, position)` -> a promise that resolves once the cell is
3461+/// durable and rejects if durability cannot be proved. The co-hosted DO fast
3462+/// path awaits this before returning an inline write's response, so the caller
3463+/// never observes a write the node cannot prove durable — the routed output
3464+/// gate, applied where the inline write actually happens.
3465+fn op_gate_write(
3466+ scope: &mut v8::PinScope,
3467+ args: v8::FunctionCallbackArguments,
3468+ mut rv: v8::ReturnValue<v8::Value>,
3469+) {
3470+ let cell = args.get(0).to_rust_string_lossy(scope);
3471+ let position = args.get(1).to_integer(scope).map(|n| n.value() as u64).unwrap_or(0);
3472+ let (tx, receive) = tokio::sync::oneshot::channel();
3473+ let sent = GATE_TX
3474+ .get()
3475+ .map(|gate| gate.send(GateReq { scope: cell, position, reply: tx }).is_ok())
3476+ .unwrap_or(false);
3477+ let id = asyncrt::enqueue(async move {
3478+ if !sent {
3479+ return Err("no output-gate channel".into());
3480+ }
3481+ match receive.await {
3482+ Ok(Ok(())) => Ok(String::new()),
3483+ Ok(Err(error)) => Err(format!("{error:?}")),
3484+ Err(_) => Err("output gate dropped".into()),
3485+ }
3486+ });
3487+ rv.set(promise_for(scope, id));
3488+}
3489+
3490+fn op_do_call(
3491+ scope: &mut v8::PinScope,
3492+ args: v8::FunctionCallbackArguments,
3493+ mut rv: v8::ReturnValue<v8::Value>,
3494+) {
3495+ op_do_call_impl(scope, args, &mut rv, false);
3496+}
3497+
3498+fn op_do_call_cancellable(
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, true);
3504+}
3505+
3506+fn op_do_call_impl(
3507+ scope: &mut v8::PinScope,
3508+ args: v8::FunctionCallbackArguments,
3509+ rv: &mut v8::ReturnValue<v8::Value>,
3510+ cancellable: bool,
3511+) {
3512+ let cell = args.get(0).to_rust_string_lossy(scope);
3513+ let name_value = args.get(1);
3514+ let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
3515+ let url = args.get(2).to_rust_string_lossy(scope);
3516+ let method = args.get(3).to_rust_string_lossy(scope);
3517+ let body = view_bytes(args.get(4)).unwrap_or_default();
3518+ let headers =
3519+ serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)).unwrap_or_default();
3520+ let (tx, rx) = tokio::sync::oneshot::channel();
3521+ let (request_id, cancel, cancel_guard) = if cancellable {
3522+ let request_id = next_do_request_id();
3523+ let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
3524+ do_call_cancels()
3525+ .lock()
3526+ .unwrap()
3527+ .insert(request_id, cancel_sender);
3528+ (
3529+ Some(request_id),
3530+ Some(cancel_receiver),
3531+ Some(DoCallCancelGuard(request_id)),
3532+ )
3533+ } else {
3534+ (None, None, None)
3535+ };
3536+ let sent = DO_CALL_TX
3537+ .get()
3538+ .map(|t| {
3539+ t.send(DoCallReq {
3540+ request_id,
3541+ cancel,
3542+ scope: cell,
3543+ name,
3544+ url,
3545+ method,
3546+ body,
3547+ headers,
3548+ reply: tx,
3549+ })
3550+ .is_ok()
3551+ })
3552+ .unwrap_or(false);
3553+ let id = asyncrt::enqueue(async move {
3554+ let _cancel_guard = cancel_guard;
3555+ if !sent {
3556+ return Err("no proxy channel".into());
3557+ }
3558+ match rx.await {
3559+ Ok(Ok(response)) => Ok(encode_http_response(response, true)),
3560+ Ok(Err(e)) => Err(format!("{e}")),
3561+ Err(e) => Err(format!("proxy dropped: {e}")),
3562+ }
3563+ });
3564+ let p = promise_for(scope, id);
3565+ if let Some(request_id) = request_id {
3566+ if let Some(promise) = p.to_object(scope) {
3567+ let key = v8::String::new(scope, "__celldCancelId").unwrap();
3568+ let request_id = v8::String::new(scope, &request_id_string(request_id)).unwrap();
3569+ promise.set(scope, key.into(), request_id.into());
3570+ }
3571+ }
3572+ rv.set(p);
3573+}
3574+
3575+fn op_do_call_cancel(
3576+ scope: &mut v8::PinScope,
3577+ args: v8::FunctionCallbackArguments,
3578+ _rv: v8::ReturnValue<v8::Value>,
3579+) {
3580+ let request_id = args.get(0).to_rust_string_lossy(scope);
3581+ let Some(request_id) = parse_request_id(&request_id) else {
3582+ return;
3583+ };
3584+ if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) {
3585+ let _ = cancel.send(());
3586+ }
3587+}
3588+
3589+/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>;
3590+/// arguments and result are V8 structured-clone bytes.
3591+fn op_rpc_call(
3592+ scope: &mut v8::PinScope,
3593+ args: v8::FunctionCallbackArguments,
3594+ mut rv: v8::ReturnValue<v8::Value>,
3595+) {
3596+ let cell = args.get(0).to_rust_string_lossy(scope);
3597+ let name_value = args.get(1);
3598+ let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
3599+ let method = args.get(2).to_rust_string_lossy(scope);
3600+ let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default());
3601+ let (tx, rx) = tokio::sync::oneshot::channel();
3602+ let sent = RPC_CALL_TX
3603+ .get()
3604+ .map(|t| {
3605+ t.send(RpcCallReq {
3606+ scope: cell,
3607+ name,
3608+ method,
3609+ args,
3610+ reply: tx,
3611+ })
3612+ .is_ok()
3613+ })
3614+ .unwrap_or(false);
3615+ let id = asyncrt::enqueue(async move {
3616+ if !sent {
3617+ return Err("no RPC channel".into());
3618+ }
3619+ match rx.await {
3620+ Ok(Ok(RpcData::V8(bytes))) => Ok(bytes),
3621+ Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()),
3622+ Ok(Err(e)) => Err(format!("{e}")),
3623+ Err(e) => Err(format!("RPC proxy dropped: {e}")),
3624+ }
3625+ });
3626+ let p = promise_for(scope, id);
3627+ rv.set(p);
3628+}
3629+
3630+/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON
3631+/// `{status, body, headers}` string. Streaming is a later layer.
3632+fn op_fetch(
3633+ scope: &mut v8::PinScope,
3634+ args: v8::FunctionCallbackArguments,
3635+ mut rv: v8::ReturnValue<v8::Value>,
3636+) {
3637+ // A loaded worker with globalOutbound: null has no ambient egress: it must
3638+ // reach the world through `env` capabilities. Message matches workerd.
3639+ if actor_runtime_state(scope).egress == EgressPolicy::Deny {
3640+ return loader_throw(
3641+ scope,
3642+ "This worker is not permitted to access the internet via global \
3643+ functions like fetch(). It must use capabilities (such as \
3644+ bindings in 'env') to talk to the outside world.",
3645+ );
3646+ }
3647+ let method = args.get(0).to_rust_string_lossy(scope);
3648+ let url = args.get(1).to_rust_string_lossy(scope);
3649+ let b = args.get(2);
3650+ let body: Option<Vec<u8>> = if b.is_undefined() || b.is_null() {
3651+ None
3652+ } else {
3653+ serde_json::from_str(&b.to_rust_string_lossy(scope)).ok()
3654+ };
3655+ let headers: Vec<(String, String)> =
3656+ serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
3657+ let redirect = args.get(4).to_rust_string_lossy(scope);
3658+ let client = if redirect == "manual" {
3659+ HTTP_MANUAL.with(|client| client.clone())
3660+ } else {
3661+ HTTP.with(|client| client.clone())
3662+ };
3663+ let id = asyncrt::enqueue(async move {
3664+ let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET);
3665+ // a timeout bounds a black-hole host: the future settles (Err) instead
3666+ // of parking run_loop forever — the hang the Drop guard can't catch.
3667+ let fetch_timeout = std::env::var("CELLD_FETCH_TIMEOUT_S")
3668+ .ok()
3669+ .and_then(|value| value.parse().ok())
3670+ .filter(|seconds| *seconds > 0)
3671+ .unwrap_or(120);
3672+ let mut rb = client
3673+ .request(m, &url)
3674+ .timeout(std::time::Duration::from_secs(fetch_timeout));
3675+ for (name, value) in headers {
3676+ rb = rb.header(name, value);
3677+ }
3678+ if let Some(b) = body {
3679+ rb = rb.body(b);
3680+ }
3681+ match rb.send().await {
3682+ Ok(resp) => {
3683+ let status = resp.status().as_u16();
3684+ let headers = resp
3685+ .headers()
3686+ .iter()
3687+ .map(|(name, value)| {
3688+ (
3689+ name.as_str().to_string(),
3690+ value.to_str().unwrap_or_default().to_string(),
3691+ )
3692+ })
3693+ .collect::<Vec<_>>();
3694+ let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3695+ register_http_stream(stream_id, HttpStreamSource::Response(resp));
3696+ Ok(serde_json::json!({
3697+ "status": status, "streamId": stream_id, "headers": headers,
3698+ })
3699+ .to_string())
3700+ }
3701+ Err(e) => Err(format!("fetch: {e}")),
3702+ }
3703+ });
3704+ let p = promise_for(scope, id);
3705+ rv.set(p);
3706+}
3707+
3708+fn op_asset_fetch(
3709+ scope: &mut v8::PinScope,
3710+ args: v8::FunctionCallbackArguments,
3711+ mut rv: v8::ReturnValue<v8::Value>,
3712+) {
3713+ let script = args.get(0).to_rust_string_lossy(scope);
3714+ let method = args.get(1).to_rust_string_lossy(scope);
3715+ let url = args.get(2).to_rust_string_lossy(scope);
3716+ let headers: Vec<(String, String)> =
3717+ serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
3718+ let (tx, rx) = tokio::sync::oneshot::channel();
3719+ let sent = ASSET_CALL_TX.get().is_some_and(|sender| {
3720+ sender
3721+ .send(AssetCallReq {
3722+ script,
3723+ url,
3724+ method,
3725+ headers,
3726+ reply: tx,
3727+ })
3728+ .is_ok()
3729+ });
3730+ let id = asyncrt::enqueue(async move {
3731+ if !sent {
3732+ return Err("no asset resolver channel".to_string());
3733+ }
3734+ match rx.await {
3735+ Ok(Ok(response)) => {
3736+ let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3737+ let (body_tx, body_rx) = tokio::sync::mpsc::channel(1);
3738+ if !response.body.is_empty() {
3739+ let _ = body_tx.send(Ok(response.body)).await;
3740+ }
3741+ drop(body_tx);
3742+ register_http_stream(stream_id, HttpStreamSource::Receiver(body_rx));
3743+ Ok(serde_json::json!({
3744+ "status": response.status,
3745+ "streamId": stream_id,
3746+ "headers": response.headers,
3747+ })
3748+ .to_string())
3749+ }
3750+ Ok(Err(error)) => Err(format!("asset fetch: {error}")),
3751+ Err(error) => Err(format!("asset resolver dropped: {error}")),
3752+ }
3753+ });
3754+ rv.set(promise_for(scope, id));
3755+}
3756+
3757+async fn next_http_stream_chunk(source: &mut HttpStreamSource) -> Result<Option<Vec<u8>>, String> {
3758+ match source {
3759+ HttpStreamSource::Response(response) => response
3760+ .chunk()
3761+ .await
3762+ .map(|chunk| chunk.map(|bytes| bytes.to_vec()))
3763+ .map_err(|error| format!("response stream: {error}")),
3764+ HttpStreamSource::Receiver(receiver) => match receiver.recv().await {
3765+ Some(Ok(bytes)) => Ok(Some(bytes)),
3766+ Some(Err(error)) => Err(error),
3767+ None => Ok(None),
3768+ },
3769+ HttpStreamSource::Stream(stream) => stream.next().await.transpose(),
3770+ }
3771+}
3772+
3773+/// Move a host response source into a directly-polled stream. No pump task is
3774+/// needed: the eventual HTTP or JS consumer supplies the backpressure.
3775+fn http_chunk_stream(source: HttpStreamSource) -> HttpChunkStream {
3776+ match source {
3777+ HttpStreamSource::Response(response) => Box::pin(response.bytes_stream().map(|chunk| {
3778+ chunk
3779+ .map(|bytes| bytes.to_vec())
3780+ .map_err(|error| format!("response stream: {error}"))
3781+ })),
3782+ HttpStreamSource::Receiver(receiver) => {
3783+ Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver))
3784+ }
3785+ HttpStreamSource::Stream(stream) => stream,
3786+ }
3787+}
3788+
3789+/// Host-native tee for an outbound response. Both branches are represented by
3790+/// stream IDs, so one can be returned through Axum while JS independently
3791+/// scans the other for observability or usage accounting.
3792+fn tee_http_stream(mut source: HttpStreamSource) -> (u64, u64) {
3793+ let (tx1, rx1) = tokio::sync::mpsc::channel(16);
3794+ let (tx2, rx2) = tokio::sync::mpsc::channel(16);
3795+ let id1 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3796+ let id2 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3797+ register_http_stream(id1, HttpStreamSource::Receiver(rx1));
3798+ register_http_stream(id2, HttpStreamSource::Receiver(rx2));
3799+ asyncrt::op_handle().spawn(async move {
3800+ loop {
3801+ match next_http_stream_chunk(&mut source).await {
3802+ Ok(Some(bytes)) => {
3803+ let first = tx1.send(Ok(bytes.clone())).await.is_ok();
3804+ let second = tx2.send(Ok(bytes)).await.is_ok();
3805+ if !first && !second {
3806+ break;
3807+ }
3808+ }
3809+ Ok(None) => break,
3810+ Err(error) => {
3811+ let _ = tx1.send(Err(error.clone())).await;
3812+ let _ = tx2.send(Err(error)).await;
3813+ break;
3814+ }
3815+ }
3816+ }
3817+ });
3818+ (id1, id2)
3819+}
3820+
3821+fn op_http_stream_read(
3822+ scope: &mut v8::PinScope,
3823+ args: v8::FunctionCallbackArguments,
3824+ mut rv: v8::ReturnValue<v8::Value>,
3825+) {
3826+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3827+ let source = http_streams()
3828+ .lock()
3829+ .unwrap()
3830+ .get_mut(&stream_id)
3831+ .and_then(|stream| {
3832+ stream
3833+ .source
3834+ .take()
3835+ .map(|source| (source, stream.cancelled.subscribe()))
3836+ });
3837+ let id = asyncrt::enqueue(async move {
3838+ let Some((mut source, mut cancelled)) = source else {
3839+ return Ok(serde_json::json!({ "done": true }).to_string());
3840+ };
3841+ let next = tokio::select! {
3842+ result = next_http_stream_chunk(&mut source) => Some(result),
3843+ _ = cancelled.changed() => None,
3844+ };
3845+ match next {
3846+ None => Ok(serde_json::json!({ "done": true }).to_string()),
3847+ Some(Ok(Some(bytes))) => {
3848+ if let Some(stream) = http_streams().lock().unwrap().get_mut(&stream_id) {
3849+ stream.created = Instant::now();
3850+ stream.source = Some(source);
3851+ }
3852+ Ok(serde_json::json!({ "done": false, "bytes": bytes }).to_string())
3853+ }
3854+ Some(Ok(None)) => {
3855+ http_streams().lock().unwrap().remove(&stream_id);
3856+ Ok(serde_json::json!({ "done": true }).to_string())
3857+ }
3858+ Some(Err(error)) => {
3859+ http_streams().lock().unwrap().remove(&stream_id);
3860+ Err(error)
3861+ }
3862+ }
3863+ });
3864+ rv.set(promise_for(scope, id));
3865+}
3866+
3867+fn op_http_stream_tee(
3868+ scope: &mut v8::PinScope,
3869+ args: v8::FunctionCallbackArguments,
3870+ mut rv: v8::ReturnValue<v8::Value>,
3871+) {
3872+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3873+ let source = http_streams()
3874+ .lock()
3875+ .unwrap()
3876+ .remove(&stream_id)
3877+ .and_then(|stream| stream.source);
3878+ let Some(source) = source else {
3879+ let message = v8::String::new(scope, "response stream is no longer available").unwrap();
3880+ let exception = v8::Exception::type_error(scope, message);
3881+ scope.throw_exception(exception);
3882+ return;
3883+ };
3884+ let ids = tee_http_stream(source);
3885+ let json = serde_json::to_string(&ids).unwrap();
3886+ rv.set(v8::String::new(scope, &json).unwrap().into());
3887+}
3888+
3889+fn op_http_stream_cancel(
3890+ scope: &mut v8::PinScope,
3891+ args: v8::FunctionCallbackArguments,
3892+ _rv: v8::ReturnValue<v8::Value>,
3893+) {
3894+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3895+ if let Some(stream) = http_streams().lock().unwrap().remove(&stream_id) {
3896+ let _ = stream.cancelled.send(true);
3897+ }
3898+}
3899+
3900+fn op_response_stream_create(
3901+ scope: &mut v8::PinScope,
3902+ _args: v8::FunctionCallbackArguments,
3903+ mut rv: v8::ReturnValue<v8::Value>,
3904+) {
3905+ let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
3906+ let (writer, receiver) = tokio::sync::mpsc::channel(1);
3907+ let (finished, _) = tokio::sync::watch::channel(false);
3908+ let now = Instant::now();
3909+ register_http_stream(stream_id, HttpStreamSource::Receiver(receiver));
3910+ let mut writers = response_stream_writers().lock().unwrap();
3911+ writers.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60));
3912+ writers.insert(
3913+ stream_id,
3914+ ResponseStreamWriter {
3915+ created: now,
3916+ writer,
3917+ finished,
3918+ },
3919+ );
3920+ rv.set(v8::Number::new(scope, stream_id as f64).into());
3921+}
3922+
3923+fn op_response_stream_write(
3924+ scope: &mut v8::PinScope,
3925+ args: v8::FunctionCallbackArguments,
3926+ mut rv: v8::ReturnValue<v8::Value>,
3927+) {
3928+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3929+ let bytes = args
3930+ .get(1)
3931+ .try_cast::<v8::ArrayBufferView>()
3932+ .ok()
3933+ .map(|view| {
3934+ let mut bytes = vec![0; view.byte_length()];
3935+ view.copy_contents(&mut bytes);
3936+ bytes
3937+ });
3938+ let writer = response_stream_writers()
3939+ .lock()
3940+ .unwrap()
3941+ .get_mut(&stream_id)
3942+ .map(|stream| {
3943+ stream.created = Instant::now();
3944+ stream.writer.clone()
3945+ });
3946+ let id = asyncrt::enqueue(async move {
3947+ let Some(bytes) = bytes else {
3948+ return Err("response stream chunks must be ArrayBuffer views".into());
3949+ };
3950+ let Some(writer) = writer else {
3951+ return Err("response stream consumer canceled".into());
3952+ };
3953+ if writer.send(Ok(bytes)).await.is_err() {
3954+ response_stream_writers().lock().unwrap().remove(&stream_id);
3955+ return Err("response stream consumer canceled".into());
3956+ }
3957+ Ok(String::new())
3958+ });
3959+ rv.set(promise_for(scope, id));
3960+}
3961+
3962+fn op_response_stream_closed(
3963+ scope: &mut v8::PinScope,
3964+ args: v8::FunctionCallbackArguments,
3965+ mut rv: v8::ReturnValue<v8::Value>,
3966+) {
3967+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3968+ let (writer, mut finished) = response_stream_writers()
3969+ .lock()
3970+ .unwrap()
3971+ .get(&stream_id)
3972+ .map(|stream| (stream.writer.clone(), stream.finished.subscribe()))
3973+ .unzip();
3974+ let id = asyncrt::enqueue(async move {
3975+ let cancelled = match (writer, finished.as_mut()) {
3976+ (Some(writer), Some(finished)) => tokio::select! {
3977+ biased;
3978+ result = finished.changed() => result.is_err(),
3979+ _ = writer.closed() => true,
3980+ },
3981+ _ => false,
3982+ };
3983+ Ok(String::from(if cancelled {
3984+ "cancelled"
3985+ } else {
3986+ "finished"
3987+ }))
3988+ });
3989+ rv.set(promise_for(scope, id));
3990+}
3991+
3992+fn op_response_stream_close(
3993+ scope: &mut v8::PinScope,
3994+ args: v8::FunctionCallbackArguments,
3995+ mut rv: v8::ReturnValue<v8::Value>,
3996+) {
3997+ let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3998+ let error = args.get(1).to_rust_string_lossy(scope);
3999+ let stream = response_stream_writers().lock().unwrap().remove(&stream_id);
4000+ let id = asyncrt::enqueue(async move {
4001+ if let Some(stream) = stream {
4002+ let _ = stream.finished.send(true);
4003+ if !error.is_empty() {
4004+ let _ = stream.writer.send(Err(error)).await;
4005+ }
4006+ }
4007+ Ok(String::new())
4008+ });
4009+ rv.set(promise_for(scope, id));
4010+}
4011+
4012+pub fn reqwest_response_stream(response: reqwest::Response) -> HttpChunkStream {
4013+ http_chunk_stream(HttpStreamSource::Response(response))
4014+}
4015+
4016+/// Timer op behind `setTimeout`: a promise resolving after `ms`.
4017+fn op_timer(
4018+ scope: &mut v8::PinScope,
4019+ args: v8::FunctionCallbackArguments,
4020+ mut rv: v8::ReturnValue<v8::Value>,
4021+) {
4022+ let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4023+ let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64;
4024+ let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
4025+ timer_cancels().lock().unwrap().insert(timer_id, cancel_tx);
4026+ let id = asyncrt::enqueue(async move {
4027+ tokio::select! {
4028+ _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {}
4029+ _ = &mut cancel_rx => {}
4030+ }
4031+ timer_cancels().lock().unwrap().remove(&timer_id);
4032+ Ok(String::new())
4033+ });
4034+ let p = promise_for(scope, id);
4035+ rv.set(p);
4036+}
4037+
4038+fn op_timer_alloc(
4039+ scope: &mut v8::PinScope,
4040+ _args: v8::FunctionCallbackArguments,
4041+ mut rv: v8::ReturnValue<v8::Value>,
4042+) {
4043+ let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64);
4044+ rv.set(id.into());
4045+}
4046+
4047+fn op_timer_cancel(
4048+ scope: &mut v8::PinScope,
4049+ args: v8::FunctionCallbackArguments,
4050+ _rv: v8::ReturnValue<v8::Value>,
4051+) {
4052+ let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4053+ if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) {
4054+ let _ = cancel.send(());
4055+ }
4056+}
4057+
4058+fn durable_object_id_key(namespace_key: &str) -> [u8; 32] {
4059+ DO_ID_KEYS.with(|keys| {
4060+ if let Some(key) = keys.borrow().get(namespace_key) {
4061+ return *key;
4062+ }
4063+ use sha2::Digest;
4064+ let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into();
4065+ keys.borrow_mut().insert(namespace_key.to_string(), key);
4066+ key
4067+ })
4068+}
4069+
4070+fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> {
4071+ use hmac::Mac;
4072+ let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key)
4073+ .expect("SHA-256 accepts any HMAC key");
4074+ mac.update(input);
4075+ mac
4076+}
4077+
4078+fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] {
4079+ use hmac::Mac;
4080+
4081+ let key = durable_object_id_key(namespace_key);
4082+ let mut id = [0_u8; 32];
4083+ let digest = durable_object_id_hmac(&key, name.as_bytes())
4084+ .finalize()
4085+ .into_bytes();
4086+ id[..16].copy_from_slice(&digest[..16]);
4087+ let digest = durable_object_id_hmac(&key, &id[..16])
4088+ .finalize()
4089+ .into_bytes();
4090+ id[16..].copy_from_slice(&digest[..16]);
4091+ id
4092+}
4093+
4094+fn durable_object_id_hex(bytes: &[u8; 32]) -> String {
4095+ const HEX: &[u8; 16] = b"0123456789abcdef";
4096+ let mut output = String::with_capacity(64);
4097+ for byte in bytes {
4098+ output.push(HEX[(byte >> 4) as usize] as char);
4099+ output.push(HEX[(byte & 0x0f) as usize] as char);
4100+ }
4101+ output
4102+}
4103+
4104+fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> {
4105+ if value.len() != 64 {
4106+ return None;
4107+ }
4108+ let mut output = [0_u8; 32];
4109+ for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
4110+ let nibble = |byte| match byte {
4111+ b'0'..=b'9' => Some(byte - b'0'),
4112+ b'a'..=b'f' => Some(byte - b'a' + 10),
4113+ b'A'..=b'F' => Some(byte - b'A' + 10),
4114+ _ => None,
4115+ };
4116+ output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
4117+ }
4118+ Some(output)
4119+}
4120+
4121+fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) {
4122+ let message = v8::String::new(scope, message).unwrap();
4123+ let exception = v8::Exception::type_error(scope, message);
4124+ scope.throw_exception(exception);
4125+}
4126+
4127+fn register_actor_name(
4128+ scope: &mut v8::PinScope,
4129+ actor_scope: &str,
4130+ name: Option<&str>,
4131+) -> Result<()> {
4132+ let Some(name) = name else {
4133+ return Ok(());
4134+ };
4135+ let context = scope.get_current_context();
4136+ let global = context.global(scope);
4137+ let cell_key = v8::String::new(scope, "__cell").unwrap();
4138+ let cell = global
4139+ .get(scope, cell_key.into())
4140+ .and_then(|value| value.to_object(scope))
4141+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
4142+ let names_key = v8::String::new(scope, "idNames").unwrap();
4143+ let names = cell
4144+ .get(scope, names_key.into())
4145+ .and_then(|value| value.to_object(scope))
4146+ .ok_or_else(|| anyhow!("missing Durable Object name registry"))?;
4147+ let actor_scope_key = v8::String::new(scope, actor_scope).unwrap();
4148+ if let Some(existing) = names.get(scope, actor_scope_key.into()) {
4149+ if !existing.is_undefined() {
4150+ if existing.to_rust_string_lossy(scope) == name {
4151+ return Ok(());
4152+ }
4153+ anyhow::bail!("actor name conflicts with active identity for {actor_scope}");
4154+ }
4155+ }
4156+
4157+ let (class_name, id) = actor_scope
4158+ .split_once(':')
4159+ .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?;
4160+ let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
4161+ let namespace_keys = cell
4162+ .get(scope, namespace_keys_key.into())
4163+ .and_then(|value| value.to_object(scope))
4164+ .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
4165+ let class_name_key = v8::String::new(scope, class_name).unwrap();
4166+ let namespace_key = namespace_keys
4167+ .get(scope, class_name_key.into())
4168+ .filter(|value| value.is_string())
4169+ .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))?
4170+ .to_rust_string_lossy(scope);
4171+ let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name));
4172+ if id != expected {
4173+ anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}");
4174+ }
4175+ storage::set_actor_name(actor_scope, name)?;
4176+
4177+ let name_value = v8::String::new(scope, name).unwrap();
4178+ if !names
4179+ .set(scope, actor_scope_key.into(), name_value.into())
4180+ .unwrap_or(false)
4181+ {
4182+ anyhow::bail!("could not register Durable Object name");
4183+ }
4184+ Ok(())
4185+}
4186+
4187+fn op_do_id(
4188+ scope: &mut v8::PinScope,
4189+ args: v8::FunctionCallbackArguments,
4190+ mut rv: v8::ReturnValue<v8::Value>,
4191+) {
4192+ use hmac::Mac;
4193+
4194+ let namespace_key = args.get(0).to_rust_string_lossy(scope);
4195+ let operation = args.get(1).to_rust_string_lossy(scope);
4196+ let input = args.get(2).to_rust_string_lossy(scope);
4197+ let key = durable_object_id_key(&namespace_key);
4198+ let mut id = [0_u8; 32];
4199+
4200+ match operation.as_str() {
4201+ "name" => {
4202+ id = durable_object_id_for_name(&namespace_key, &input);
4203+ rv.set(
4204+ v8::String::new(scope, &durable_object_id_hex(&id))
4205+ .unwrap()
4206+ .into(),
4207+ );
4208+ return;
4209+ }
4210+ "unique" => {
4211+ if getrandom::fill(&mut id[..16]).is_err() {
4212+ throw_durable_object_id_error(scope, "secure random generation failed");
4213+ return;
4214+ }
4215+ }
4216+ "validate" => {
4217+ let Some(decoded) = decode_durable_object_id(&input) else {
4218+ throw_durable_object_id_error(
4219+ scope,
4220+ "Invalid Durable Object ID: must be 64 hex digits",
4221+ );
4222+ return;
4223+ };
4224+ if durable_object_id_hmac(&key, &decoded[..16])
4225+ .verify_truncated_left(&decoded[16..])
4226+ .is_err()
4227+ {
4228+ throw_durable_object_id_error(
4229+ scope,
4230+ "Durable Object ID is not valid for this namespace",
4231+ );
4232+ return;
4233+ }
4234+ rv.set(
4235+ v8::String::new(scope, &input.to_ascii_lowercase())
4236+ .unwrap()
4237+ .into(),
4238+ );
4239+ return;
4240+ }
4241+ _ => {
4242+ throw_durable_object_id_error(scope, "unknown Durable Object ID operation");
4243+ return;
4244+ }
4245+ }
4246+
4247+ let digest = durable_object_id_hmac(&key, &id[..16])
4248+ .finalize()
4249+ .into_bytes();
4250+ id[16..].copy_from_slice(&digest[..16]);
4251+ rv.set(
4252+ v8::String::new(scope, &durable_object_id_hex(&id))
4253+ .unwrap()
4254+ .into(),
4255+ );
4256+}
4257+
4258+fn crypto_bytes(value: &serde_json::Value, name: &str) -> Result<Vec<u8>> {
4259+ serde_json::from_value(value.get(name).cloned().unwrap_or_default())
4260+ .map_err(|_| anyhow!("invalid {name} bytes"))
4261+}
4262+
4263+fn rsa_jwk_uint(value: &serde_json::Value, name: &str) -> Result<rsa::BigUint> {
4264+ use base64::Engine;
4265+ let encoded = value
4266+ .get(name)
4267+ .and_then(|value| value.as_str())
4268+ .ok_or_else(|| anyhow!("RSA JWK missing {name}"))?;
4269+ let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
4270+ .decode(encoded)
4271+ .map_err(|_| anyhow!("invalid RSA JWK {name}"))?;
4272+ Ok(rsa::BigUint::from_bytes_be(&bytes))
4273+}
4274+
4275+fn rsa_jwk_encode(value: &rsa::BigUint) -> String {
4276+ use base64::Engine;
4277+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value.to_bytes_be())
4278+}
4279+
4280+fn crypto_operation(operation: &str, args: &serde_json::Value) -> Result<serde_json::Value> {
4281+ match operation {
4282+ "hmac-sign" => {
4283+ use hmac::Mac;
4284+ let key = crypto_bytes(args, "key")?;
4285+ let data = crypto_bytes(args, "data")?;
4286+ let hash = args
4287+ .get("hash")
4288+ .and_then(|value| value.as_str())
4289+ .unwrap_or("SHA-256");
4290+ if !hash.eq_ignore_ascii_case("SHA-256") && !hash.eq_ignore_ascii_case("SHA256") {
4291+ return Err(anyhow!("unsupported HMAC hash"));
4292+ }
4293+ let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(&key)
4294+ .map_err(|_| anyhow!("invalid HMAC key"))?;
4295+ mac.update(&data);
4296+ Ok(serde_json::json!({ "bytes": mac.finalize().into_bytes().to_vec() }))
4297+ }
4298+ "aes-gcm-encrypt" | "aes-gcm-decrypt" => {
4299+ use aes_gcm::aead::{Aead, KeyInit};
4300+ let key = crypto_bytes(args, "key")?;
4301+ let iv = crypto_bytes(args, "iv")?;
4302+ let data = crypto_bytes(args, "data")?;
4303+ let cipher = aes_gcm::Aes256Gcm::new_from_slice(&key)
4304+ .map_err(|_| anyhow!("AES-GCM requires a 256-bit key"))?;
4305+ let nonce = aes_gcm::Nonce::from_slice(&iv);
4306+ let bytes = if operation == "aes-gcm-encrypt" {
4307+ cipher.encrypt(nonce, data.as_ref())
4308+ } else {
4309+ cipher.decrypt(nonce, data.as_ref())
4310+ }
4311+ .map_err(|_| anyhow!("AES-GCM operation failed"))?;
4312+ Ok(serde_json::json!({ "bytes": bytes }))
4313+ }
4314+ "ed25519-sign" => {
4315+ use ed25519_dalek::pkcs8::DecodePrivateKey;
4316+ use ed25519_dalek::Signer;
4317+ let key = crypto_bytes(args, "key")?;
4318+ let data = crypto_bytes(args, "data")?;
4319+ let key = ed25519_dalek::SigningKey::from_pkcs8_der(&key)
4320+ .map_err(|_| anyhow!("invalid Ed25519 PKCS#8 key"))?;
4321+ Ok(serde_json::json!({ "bytes": key.sign(&data).to_bytes().to_vec() }))
4322+ }
4323+ "p256-sign" => {
4324+ use p256::ecdsa::signature::Signer;
4325+ use p256::pkcs8::DecodePrivateKey;
4326+ let key = crypto_bytes(args, "key")?;
4327+ let data = crypto_bytes(args, "data")?;
4328+ let key = p256::ecdsa::SigningKey::from_pkcs8_der(&key)
4329+ .map_err(|_| anyhow!("invalid P-256 PKCS#8 key"))?;
4330+ let signature: p256::ecdsa::Signature = key.sign(&data);
4331+ Ok(serde_json::json!({ "bytes": signature.to_bytes().to_vec() }))
4332+ }
4333+ "rsa-generate" => {
4334+ use rsa::traits::{PrivateKeyParts, PublicKeyParts};
4335+ let mut rng = rand::rngs::OsRng;
4336+ let mut private = rsa::RsaPrivateKey::new(&mut rng, 2048)?;
4337+ private.precompute()?;
4338+ let public = rsa::RsaPublicKey::from(&private);
4339+ let public_jwk = serde_json::json!({
4340+ "kty": "RSA",
4341+ "n": rsa_jwk_encode(public.n()),
4342+ "e": rsa_jwk_encode(public.e()),
4343+ "alg": "RSA-OAEP-256",
4344+ "ext": true,
4345+ "key_ops": ["encrypt"],
4346+ });
4347+ let private_jwk = serde_json::json!({
4348+ "kty": "RSA",
4349+ "n": rsa_jwk_encode(private.n()),
4350+ "e": rsa_jwk_encode(private.e()),
4351+ "d": rsa_jwk_encode(private.d()),
4352+ "p": rsa_jwk_encode(&private.primes()[0]),
4353+ "q": rsa_jwk_encode(&private.primes()[1]),
4354+ "alg": "RSA-OAEP-256",
4355+ "ext": true,
4356+ "key_ops": ["decrypt"],
4357+ });
4358+ Ok(serde_json::json!({ "publicKey": public_jwk, "privateKey": private_jwk }))
4359+ }
4360+ "rsa-oaep-decrypt" => {
4361+ let jwk = args.get("jwk").ok_or_else(|| anyhow!("missing RSA JWK"))?;
4362+ let n = rsa_jwk_uint(jwk, "n")?;
4363+ let e = rsa_jwk_uint(jwk, "e")?;
4364+ let d = rsa_jwk_uint(jwk, "d")?;
4365+ let p = rsa_jwk_uint(jwk, "p")?;
4366+ let q = rsa_jwk_uint(jwk, "q")?;
4367+ let mut key = rsa::RsaPrivateKey::from_components(n, e, d, vec![p, q])?;
4368+ key.precompute()?;
4369+ let data = crypto_bytes(args, "data")?;
4370+ let bytes = key.decrypt(rsa::Oaep::new::<sha2::Sha256>(), &data)?;
4371+ Ok(serde_json::json!({ "bytes": bytes }))
4372+ }
4373+ _ => Err(anyhow!("unsupported crypto operation")),
4374+ }
4375+}
4376+
4377+fn op_crypto_operation(
4378+ scope: &mut v8::PinScope,
4379+ args: v8::FunctionCallbackArguments,
4380+ mut rv: v8::ReturnValue<v8::Value>,
4381+) {
4382+ let operation = args.get(0).to_rust_string_lossy(scope);
4383+ let input: serde_json::Value =
4384+ serde_json::from_str(&args.get(1).to_rust_string_lossy(scope)).unwrap_or_default();
4385+ match crypto_operation(&operation, &input) {
4386+ Ok(value) => {
4387+ let json = value.to_string();
4388+ rv.set(v8::String::new(scope, &json).unwrap().into());
4389+ }
4390+ Err(error) => {
4391+ let message = v8::String::new(scope, &format!("crypto: {error}")).unwrap();
4392+ let exception = v8::Exception::error(scope, message);
4393+ scope.throw_exception(exception);
4394+ }
4395+ }
4396+}
4397+
4398+fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> {
4399+ let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
4400+ let mut bytes = vec![0_u8; view.byte_length()];
4401+ view.copy_contents(&mut bytes);
4402+ Some(bytes)
4403+}
4404+
4405+fn webcrypto_return_bytes(
4406+ scope: &mut v8::PinScope,
4407+ mut rv: v8::ReturnValue<v8::Value>,
4408+ bytes: &[u8],
4409+) {
4410+ let buffer = v8::ArrayBuffer::new(scope, bytes.len());
4411+ if !bytes.is_empty() {
4412+ let store = buffer.get_backing_store();
4413+ let destination = unsafe {
4414+ std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len())
4415+ };
4416+ destination.copy_from_slice(bytes);
4417+ }
4418+ let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap();
4419+ rv.set(view.into());
4420+}
4421+
4422+/// Fill an existing integer typed array in-place. JS performs the WebCrypto
4423+/// type and 65,536-byte quota checks before entering this host op.
4424+fn op_webcrypto_random(
4425+ scope: &mut v8::PinScope,
4426+ args: v8::FunctionCallbackArguments,
4427+ _rv: v8::ReturnValue<v8::Value>,
4428+) {
4429+ let Ok(view) = v8::Local::<v8::ArrayBufferView>::try_from(args.get(0)) else {
4430+ return;
4431+ };
4432+ let Some(buffer) = view.buffer(scope) else {
4433+ return;
4434+ };
4435+ let store = buffer.get_backing_store();
4436+ let offset = view.byte_offset();
4437+ let len = view.byte_length();
4438+ let bytes = unsafe {
4439+ std::slice::from_raw_parts_mut(store[offset..offset + len].as_ptr() as *mut u8, len)
4440+ };
4441+ if getrandom::fill(bytes).is_err() {
4442+ let message = v8::String::new(scope, "secure random generation failed").unwrap();
4443+ let exception = v8::Exception::error(scope, message);
4444+ scope.throw_exception(exception);
4445+ }
4446+}
4447+
4448+/// WebCrypto digest: (algorithm, ArrayBufferView) -> Uint8Array.
4449+fn op_webcrypto_digest(
4450+ scope: &mut v8::PinScope,
4451+ args: v8::FunctionCallbackArguments,
4452+ rv: v8::ReturnValue<v8::Value>,
4453+) {
4454+ use sha2::Digest;
4455+ let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
4456+ let Some(bytes) = view_bytes(args.get(1)) else {
4457+ return;
4458+ };
4459+ let digest = match algorithm.as_str() {
4460+ "MD5" => md5::Md5::digest(&bytes).to_vec(),
4461+ "SHA-1" => sha1::Sha1::digest(&bytes).to_vec(),
4462+ "SHA-224" => sha2::Sha224::digest(&bytes).to_vec(),
4463+ "SHA-256" => sha2::Sha256::digest(&bytes).to_vec(),
4464+ "SHA-384" => sha2::Sha384::digest(&bytes).to_vec(),
4465+ "SHA-512" => sha2::Sha512::digest(&bytes).to_vec(),
4466+ _ => return,
4467+ };
4468+ webcrypto_return_bytes(scope, rv, &digest);
4469+}
4470+
4471+fn op_webcrypto_hmac_sign(
4472+ scope: &mut v8::PinScope,
4473+ args: v8::FunctionCallbackArguments,
4474+ rv: v8::ReturnValue<v8::Value>,
4475+) {
4476+ use hmac::Mac;
4477+ let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
4478+ let Some(key) = view_bytes(args.get(1)) else {
4479+ return;
4480+ };
4481+ let Some(data) = view_bytes(args.get(2)) else {
4482+ return;
4483+ };
4484+ macro_rules! sign {
4485+ ($digest:ty) => {{
4486+ let Ok(mut mac) = <hmac::Hmac<$digest> as hmac::Mac>::new_from_slice(&key) else {
4487+ return;
4488+ };
4489+ mac.update(&data);
4490+ mac.finalize().into_bytes().to_vec()
4491+ }};
4492+ }
4493+ let signature = match algorithm.as_str() {
4494+ "MD5" => sign!(md5::Md5),
4495+ "SHA-1" => sign!(sha1::Sha1),
4496+ "SHA-224" => sign!(sha2::Sha224),
4497+ "SHA-256" => sign!(sha2::Sha256),
4498+ "SHA-384" => sign!(sha2::Sha384),
4499+ "SHA-512" => sign!(sha2::Sha512),
4500+ _ => return,
4501+ };
4502+ webcrypto_return_bytes(scope, rv, &signature);
4503+}
4504+
4505+/// HMAC-based KDF cores for node:crypto. Manual PBKDF2 (RFC 2898) and HKDF
4506+/// (RFC 5869) over the hmac crate — no extra dependencies. The JS layer has
4507+/// already validated the digest name and the 255×hashLen output cap.
4508+fn hmac_once<D>(key: &[u8], parts: &[&[u8]]) -> Vec<u8>
4509+where
4510+ D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
4511+{
4512+ use hmac::Mac;
4513+ let mut mac = <hmac::SimpleHmac<D> as hmac::Mac>::new_from_slice(key)
4514+ .expect("HMAC accepts any key length");
4515+ for part in parts {
4516+ mac.update(part);
4517+ }
4518+ mac.finalize().into_bytes().to_vec()
4519+}
4520+
4521+fn pbkdf2_kdf<D>(password: &[u8], salt: &[u8], iterations: u32, keylen: usize) -> Vec<u8>
4522+where
4523+ D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
4524+{
4525+ let mut out = Vec::with_capacity(keylen);
4526+ let mut block: u32 = 1;
4527+ while out.len() < keylen {
4528+ let mut u = hmac_once::<D>(password, &[salt, &block.to_be_bytes()]);
4529+ let mut t = u.clone();
4530+ for _ in 1..iterations {
4531+ u = hmac_once::<D>(password, &[&u]);
4532+ for (t_, u_) in t.iter_mut().zip(&u) {
4533+ *t_ ^= u_;
4534+ }
4535+ }
4536+ out.extend_from_slice(&t);
4537+ block += 1;
4538+ }
4539+ out.truncate(keylen);
4540+ out
4541+}
4542+
4543+fn hkdf_kdf<D>(ikm: &[u8], salt: &[u8], info: &[u8], length: usize) -> Vec<u8>
4544+where
4545+ D: hmac::digest::Digest + hmac::digest::core_api::BlockSizeUser,
4546+{
4547+ let prk = hmac_once::<D>(salt, &[ikm]);
4548+ let mut out = Vec::with_capacity(length);
4549+ let mut t: Vec<u8> = Vec::new();
4550+ let mut counter: u8 = 1;
4551+ while out.len() < length {
4552+ t = hmac_once::<D>(&prk, &[&t, info, &[counter]]);
4553+ out.extend_from_slice(&t);
4554+ counter += 1;
4555+ }
4556+ out.truncate(length);
4557+ out
4558+}
4559+
4560+macro_rules! dispatch_digest {
4561+ ($name:expr, $fn:ident, ($($arg:expr),*)) => {
4562+ match $name {
4563+ "MD5" => Some($fn::<md5::Md5>($($arg),*)),
4564+ "SHA-1" => Some($fn::<sha1::Sha1>($($arg),*)),
4565+ "SHA-224" => Some($fn::<sha2::Sha224>($($arg),*)),
4566+ "SHA-256" => Some($fn::<sha2::Sha256>($($arg),*)),
4567+ "SHA-384" => Some($fn::<sha2::Sha384>($($arg),*)),
4568+ "SHA-512" => Some($fn::<sha2::Sha512>($($arg),*)),
4569+ _ => None,
4570+ }
4571+ };
4572+}
4573+
4574+/// `$$pbkdf2(algorithm, password, salt, iterations, keylen)` -> Uint8Array
4575+fn op_node_pbkdf2(
4576+ scope: &mut v8::PinScope,
4577+ args: v8::FunctionCallbackArguments,
4578+ rv: v8::ReturnValue<v8::Value>,
4579+) {
4580+ let algorithm = args.get(0).to_rust_string_lossy(scope);
4581+ let Some(password) = view_bytes(args.get(1)) else {
4582+ return;
4583+ };
4584+ let Some(salt) = view_bytes(args.get(2)) else {
4585+ return;
4586+ };
4587+ let iterations = args.get(3).uint32_value(scope).unwrap_or(0).max(1);
4588+ let keylen = args.get(4).uint32_value(scope).unwrap_or(0) as usize;
4589+ let out = dispatch_digest!(
4590+ algorithm.as_str(),
4591+ pbkdf2_kdf,
4592+ (&password, &salt, iterations, keylen)
4593+ );
4594+ if let Some(out) = out {
4595+ webcrypto_return_bytes(scope, rv, &out);
4596+ }
4597+}
4598+
4599+/// `$$hkdf(algorithm, ikm, salt, info, length)` -> Uint8Array
4600+fn op_node_hkdf(
4601+ scope: &mut v8::PinScope,
4602+ args: v8::FunctionCallbackArguments,
4603+ rv: v8::ReturnValue<v8::Value>,
4604+) {
4605+ let algorithm = args.get(0).to_rust_string_lossy(scope);
4606+ let Some(ikm) = view_bytes(args.get(1)) else {
4607+ return;
4608+ };
4609+ let Some(salt) = view_bytes(args.get(2)) else {
4610+ return;
4611+ };
4612+ let Some(info) = view_bytes(args.get(3)) else {
4613+ return;
4614+ };
4615+ let length = args.get(4).uint32_value(scope).unwrap_or(0) as usize;
4616+ let out = dispatch_digest!(algorithm.as_str(), hkdf_kdf, (&ikm, &salt, &info, length));
4617+ if let Some(out) = out {
4618+ webcrypto_return_bytes(scope, rv, &out);
4619+ }
4620+}
4621+
4622+fn op_webcrypto_hmac_verify(
4623+ scope: &mut v8::PinScope,
4624+ args: v8::FunctionCallbackArguments,
4625+ mut rv: v8::ReturnValue<v8::Value>,
4626+) {
4627+ use hmac::Mac;
4628+ let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
4629+ let Some(key) = view_bytes(args.get(1)) else {
4630+ return;
4631+ };
4632+ let Some(signature) = view_bytes(args.get(2)) else {
4633+ return;
4634+ };
4635+ let Some(data) = view_bytes(args.get(3)) else {
4636+ return;
4637+ };
4638+ macro_rules! verify {
4639+ ($digest:ty) => {{
4640+ let Ok(mut mac) = <hmac::Hmac<$digest> as hmac::Mac>::new_from_slice(&key) else {
4641+ return;
4642+ };
4643+ mac.update(&data);
4644+ mac.verify_slice(&signature).is_ok()
4645+ }};
4646+ }
4647+ let valid = match algorithm.as_str() {
4648+ "SHA-1" => verify!(sha1::Sha1),
4649+ "SHA-256" => verify!(sha2::Sha256),
4650+ "SHA-384" => verify!(sha2::Sha384),
4651+ "SHA-512" => verify!(sha2::Sha512),
4652+ _ => return,
4653+ };
4654+ rv.set(v8::Boolean::new(scope, valid).into());
4655+}
4656+
4657+fn op_webcrypto_aes_encrypt(
4658+ scope: &mut v8::PinScope,
4659+ args: v8::FunctionCallbackArguments,
4660+ rv: v8::ReturnValue<v8::Value>,
4661+) {
4662+ use aes_gcm::aead::{Aead, KeyInit};
4663+ let Some(key) = view_bytes(args.get(0)) else {
4664+ return;
4665+ };
4666+ let Some(iv) = view_bytes(args.get(1)) else {
4667+ return;
4668+ };
4669+ let Some(data) = view_bytes(args.get(2)) else {
4670+ return;
4671+ };
4672+ if iv.len() != 12 {
4673+ return;
4674+ }
4675+ let nonce = aes_gcm::Nonce::from_slice(&iv);
4676+ let encrypted = match key.len() {
4677+ 16 => {
4678+ let Ok(cipher) = aes_gcm::Aes128Gcm::new_from_slice(&key) else {
4679+ return;
4680+ };
4681+ cipher.encrypt(nonce, data.as_ref())
4682+ }
4683+ 32 => {
4684+ let Ok(cipher) = aes_gcm::Aes256Gcm::new_from_slice(&key) else {
4685+ return;
4686+ };
4687+ cipher.encrypt(nonce, data.as_ref())
4688+ }
4689+ _ => return,
4690+ };
4691+ let Ok(encrypted) = encrypted else { return };
4692+ webcrypto_return_bytes(scope, rv, &encrypted);
4693+}
4694+
4695+fn op_webcrypto_aes_decrypt(
4696+ scope: &mut v8::PinScope,
4697+ args: v8::FunctionCallbackArguments,
4698+ rv: v8::ReturnValue<v8::Value>,
4699+) {
4700+ use aes_gcm::aead::{Aead, KeyInit};
4701+ let Some(key) = view_bytes(args.get(0)) else {
4702+ return;
4703+ };
4704+ let Some(iv) = view_bytes(args.get(1)) else {
4705+ return;
4706+ };
4707+ let Some(data) = view_bytes(args.get(2)) else {
4708+ return;
4709+ };
4710+ if iv.len() != 12 {
4711+ return;
4712+ }
4713+ let nonce = aes_gcm::Nonce::from_slice(&iv);
4714+ let decrypted = match key.len() {
4715+ 16 => {
4716+ let Ok(cipher) = aes_gcm::Aes128Gcm::new_from_slice(&key) else {
4717+ return;
4718+ };
4719+ cipher.decrypt(nonce, data.as_ref())
4720+ }
4721+ 32 => {
4722+ let Ok(cipher) = aes_gcm::Aes256Gcm::new_from_slice(&key) else {
4723+ return;
4724+ };
4725+ cipher.decrypt(nonce, data.as_ref())
4726+ }
4727+ _ => return,
4728+ };
4729+ let Ok(decrypted) = decrypted else { return };
4730+ webcrypto_return_bytes(scope, rv, &decrypted);
4731+}
4732+
4733+fn op_zlib(
4734+ scope: &mut v8::PinScope,
4735+ args: v8::FunctionCallbackArguments,
4736+ mut rv: v8::ReturnValue<v8::Value>,
4737+) {
4738+ use std::io::{Read, Write};
4739+ let mode = args.get(0).to_rust_string_lossy(scope);
4740+ let bytes: Vec<u8> =
4741+ serde_json::from_str(&args.get(1).to_rust_string_lossy(scope)).unwrap_or_default();
4742+ let result = (|| -> Result<Vec<u8>> {
4743+ match mode.as_str() {
4744+ "gzip" => {
4745+ let mut encoder =
4746+ flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
4747+ encoder.write_all(&bytes)?;
4748+ Ok(encoder.finish()?)
4749+ }
4750+ "gunzip" => {
4751+ let mut decoder = flate2::read::GzDecoder::new(bytes.as_slice());
4752+ let mut out = Vec::new();
4753+ decoder.read_to_end(&mut out)?;
4754+ Ok(out)
4755+ }
4756+ "deflate" => {
4757+ let mut encoder =
4758+ flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
4759+ encoder.write_all(&bytes)?;
4760+ Ok(encoder.finish()?)
4761+ }
4762+ "inflate" => {
4763+ let mut decoder = flate2::read::ZlibDecoder::new(bytes.as_slice());
4764+ let mut out = Vec::new();
4765+ decoder.read_to_end(&mut out)?;
4766+ Ok(out)
4767+ }
4768+ "deflateRaw" => {
4769+ let mut encoder =
4770+ flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
4771+ encoder.write_all(&bytes)?;
4772+ Ok(encoder.finish()?)
4773+ }
4774+ "inflateRaw" => {
4775+ let mut decoder = flate2::read::DeflateDecoder::new(bytes.as_slice());
4776+ let mut out = Vec::new();
4777+ decoder.read_to_end(&mut out)?;
4778+ Ok(out)
4779+ }
4780+ _ => Err(anyhow!("unsupported zlib operation")),
4781+ }
4782+ })();
4783+ match result {
4784+ Ok(bytes) => {
4785+ let json = serde_json::to_string(&bytes).unwrap();
4786+ rv.set(v8::String::new(scope, &json).unwrap().into());
4787+ }
4788+ Err(error) => {
4789+ let message = v8::String::new(scope, &format!("zlib: {error}")).unwrap();
4790+ let exception = v8::Exception::error(scope, message);
4791+ scope.throw_exception(exception);
4792+ }
4793+ }
4794+}
4795+
4796+/// One live `CompressionStream`/`DecompressionStream`: a stateful flate2
4797+/// writer whose `Vec` sink is drained after every push, so output streams
4798+/// chunk by chunk instead of arriving once at close.
4799+enum ZlibStream {
4800+ GzipEncode(flate2::write::GzEncoder<Vec<u8>>),
4801+ GzipDecode(flate2::write::GzDecoder<Vec<u8>>),
4802+ ZlibEncode(flate2::write::ZlibEncoder<Vec<u8>>),
4803+ ZlibDecode(flate2::write::ZlibDecoder<Vec<u8>>),
4804+ RawEncode(flate2::write::DeflateEncoder<Vec<u8>>),
4805+ RawDecode(flate2::write::DeflateDecoder<Vec<u8>>),
4806+}
4807+
4808+/// The six writer types share `write`/`flush`/`get_mut`/`finish` but no
4809+/// trait, so dispatch once here.
4810+macro_rules! zlib_each {
4811+ ($stream:expr, $w:ident => $body:expr) => {
4812+ match $stream {
4813+ ZlibStream::GzipEncode($w) => $body,
4814+ ZlibStream::GzipDecode($w) => $body,
4815+ ZlibStream::ZlibEncode($w) => $body,
4816+ ZlibStream::ZlibDecode($w) => $body,
4817+ ZlibStream::RawEncode($w) => $body,
4818+ ZlibStream::RawDecode($w) => $body,
4819+ }
4820+ };
4821+}
4822+
4823+impl ZlibStream {
4824+ fn new(format: &str, decompress: bool) -> Option<ZlibStream> {
4825+ use flate2::write as z;
4826+ let level = flate2::Compression::default();
4827+ let sink = Vec::new;
4828+ Some(match (format, decompress) {
4829+ ("gzip", false) => Self::GzipEncode(z::GzEncoder::new(sink(), level)),
4830+ ("gzip", true) => Self::GzipDecode(z::GzDecoder::new(sink())),
4831+ ("deflate", false) => Self::ZlibEncode(z::ZlibEncoder::new(sink(), level)),
4832+ ("deflate", true) => Self::ZlibDecode(z::ZlibDecoder::new(sink())),
4833+ ("deflate-raw", false) => Self::RawEncode(z::DeflateEncoder::new(sink(), level)),
4834+ ("deflate-raw", true) => Self::RawDecode(z::DeflateDecoder::new(sink())),
4835+ _ => return None,
4836+ })
4837+ }
4838+
4839+ fn decompress(&self) -> bool {
4840+ matches!(
4841+ self,
4842+ Self::GzipDecode(_) | Self::ZlibDecode(_) | Self::RawDecode(_)
4843+ )
4844+ }
4845+
4846+ /// Workerd's canonical message, matched by its conformance suite.
4847+ fn failure(&self) -> &'static str {
4848+ if self.decompress() {
4849+ "Decompression failed."
4850+ } else {
4851+ "Compression failed."
4852+ }
4853+ }
4854+
4855+ /// Write one chunk and return whatever output it produced. Decoded
4856+ /// output flows per chunk; encoders hold theirs until a full buffer
4857+ /// accumulates (matching Workerd, whose suite reads a small message
4858+ /// back as one chunk), with the rest arriving from `finish`. A
4859+ /// decoder that stops consuming input has hit the end of the
4860+ /// compressed stream, so leftover bytes are trailing garbage —
4861+ /// Workerd's strict_compression_checks.
4862+ fn push(&mut self, mut input: &[u8]) -> Result<Vec<u8>> {
4863+ use std::io::Write;
4864+ const ENCODER_CHUNK: usize = 32 * 1024;
4865+ let failure = self.failure();
4866+ let held = if self.decompress() { 0 } else { ENCODER_CHUNK };
4867+ zlib_each!(self, w => {
4868+ while !input.is_empty() {
4869+ let n = w.write(input).map_err(|_| anyhow!(failure))?;
4870+ if n == 0 { return Err(anyhow!(failure)); }
4871+ input = &input[n..];
4872+ }
4873+ if w.get_ref().len() < held { return Ok(Vec::new()); }
4874+ Ok(std::mem::take(w.get_mut()))
4875+ })
4876+ }
4877+
4878+ /// Terminate the stream and return the final output. For gzip this
4879+ /// also validates the trailer, so a truncated stream errors here.
4880+ fn finish(self) -> Result<Vec<u8>> {
4881+ let failure = self.failure();
4882+ zlib_each!(self, w => w.finish().map_err(|_| anyhow!(failure)))
4883+ }
4884+}
4885+
4886+thread_local! {
4887+ static ZLIB_STREAMS: std::cell::RefCell<
4888+ std::collections::HashMap<u64, ZlibStream>> = Default::default();
4889+ static ZLIB_STREAM_NEXT: std::cell::Cell<u64> =
4890+ const { std::cell::Cell::new(1) };
4891+}
4892+
4893+fn zlib_stream_return(
4894+ scope: &mut v8::PinScope,
4895+ rv: v8::ReturnValue<v8::Value>,
4896+ result: Result<Vec<u8>>,
4897+) {
4898+ match result {
4899+ Ok(bytes) => webcrypto_return_bytes(scope, rv, &bytes),
4900+ Err(error) => {
4901+ let message = v8::String::new(scope, &error.to_string()).unwrap();
4902+ let exception = v8::Exception::type_error(scope, message);
4903+ scope.throw_exception(exception);
4904+ }
4905+ }
4906+}
4907+
4908+/// `__zlib_stream_new(format, decompress)` -> id. JS validates the format
4909+/// and throws the spec TypeError, so an unknown one here is a bug.
4910+fn op_zlib_stream_new(
4911+ scope: &mut v8::PinScope,
4912+ args: v8::FunctionCallbackArguments,
4913+ mut rv: v8::ReturnValue<v8::Value>,
4914+) {
4915+ let format = args.get(0).to_rust_string_lossy(scope);
4916+ let decompress = args.get(1).boolean_value(scope);
4917+ let stream = ZlibStream::new(&format, decompress).expect("JS validated the compression format");
4918+ let id = ZLIB_STREAM_NEXT.with(|next| {
4919+ let id = next.get();
4920+ next.set(id + 1);
4921+ id
4922+ });
4923+ ZLIB_STREAMS.with(|streams| streams.borrow_mut().insert(id, stream));
4924+ rv.set(v8::Number::new(scope, id as f64).into());
4925+}
4926+
4927+/// `__zlib_stream_push(id, view)` -> Uint8Array (possibly empty). An
4928+/// error poisons the stream: its native state is dropped and the
4929+/// TypeError errors both sides of the transform.
4930+fn op_zlib_stream_push(
4931+ scope: &mut v8::PinScope,
4932+ args: v8::FunctionCallbackArguments,
4933+ rv: v8::ReturnValue<v8::Value>,
4934+) {
4935+ let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
4936+ let bytes = view_bytes(args.get(1)).unwrap_or_default();
4937+ let result = ZLIB_STREAMS.with(|streams| {
4938+ let mut streams = streams.borrow_mut();
4939+ let stream = streams
4940+ .get_mut(&id)
4941+ .ok_or_else(|| anyhow!("zlib stream already closed"))?;
4942+ let out = stream.push(&bytes);
4943+ if out.is_err() {
4944+ streams.remove(&id);
4945+ }
4946+ out
4947+ });
4948+ zlib_stream_return(scope, rv, result);
4949+}
4950+
4951+/// `__zlib_stream_end(id)` -> the final Uint8Array. Consumes the stream.
4952+fn op_zlib_stream_end(
4953+ scope: &mut v8::PinScope,
4954+ args: v8::FunctionCallbackArguments,
4955+ rv: v8::ReturnValue<v8::Value>,
4956+) {
4957+ let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
4958+ let result = ZLIB_STREAMS.with(|streams| {
4959+ streams
4960+ .borrow_mut()
4961+ .remove(&id)
4962+ .ok_or_else(|| anyhow!("zlib stream already closed"))
4963+ });
4964+ zlib_stream_return(scope, rv, result.and_then(ZlibStream::finish));
4965+}
4966+
4967+/// `__zlib_stream_drop(id)` — cancelled/aborted transform cleanup.
4968+fn op_zlib_stream_drop(
4969+ scope: &mut v8::PinScope,
4970+ args: v8::FunctionCallbackArguments,
4971+ _rv: v8::ReturnValue<v8::Value>,
4972+) {
4973+ let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
4974+ ZLIB_STREAMS.with(|streams| streams.borrow_mut().remove(&id));
4975+}
4976+
4977+fn op_ws_send(
4978+ scope: &mut v8::PinScope,
4979+ args: v8::FunctionCallbackArguments,
4980+ _rv: v8::ReturnValue<v8::Value>,
4981+) {
4982+ let id = args
4983+ .get(0)
4984+ .to_integer(scope)
4985+ .map(|n| n.value() as u64)
4986+ .unwrap_or(0);
4987+ let data = args.get(1).to_rust_string_lossy(scope);
4988+ ws_emit(id, WsOut::Text(data));
4989+}
4990+fn op_ws_send_binary(
4991+ scope: &mut v8::PinScope,
4992+ args: v8::FunctionCallbackArguments,
4993+ _rv: v8::ReturnValue<v8::Value>,
4994+) {
4995+ let id = args
4996+ .get(0)
4997+ .to_integer(scope)
4998+ .map(|n| n.value() as u64)
4999+ .unwrap_or(0);
5000+ let data = view_bytes(args.get(1)).unwrap_or_default();
5001+ ws_emit(id, WsOut::Binary(data));
5002+}
5003+fn op_ws_close(
5004+ scope: &mut v8::PinScope,
5005+ args: v8::FunctionCallbackArguments,
5006+ _rv: v8::ReturnValue<v8::Value>,
5007+) {
5008+ let id = args
5009+ .get(0)
5010+ .to_integer(scope)
5011+ .map(|n| n.value() as u64)
5012+ .unwrap_or(0);
5013+ let code = args.get(1).uint32_value(scope).unwrap_or(1000) as u16;
5014+ let reason = args.get(2).to_rust_string_lossy(scope);
5015+ ws_emit(id, WsOut::Close(code, reason));
5016+}
5017+fn op_ws_alloc(
5018+ scope: &mut v8::PinScope,
5019+ _args: v8::FunctionCallbackArguments,
5020+ mut rv: v8::ReturnValue<v8::Value>,
5021+) {
5022+ rv.set(v8::Number::new(scope, ws_next_id() as f64).into());
5023+}
5024+/// `fetch(url, { headers: { Upgrade: "websocket" } })`. Returns a JSON
5025+/// envelope: either an upgraded socket, or the ordinary response a server sent
5026+/// instead, which the caller returns unchanged.
5027+fn op_ws_upgrade(
5028+ scope: &mut v8::PinScope,
5029+ args: v8::FunctionCallbackArguments,
5030+ mut rv: v8::ReturnValue<v8::Value>,
5031+) {
5032+ if actor_runtime_state(scope).egress == EgressPolicy::Deny {
5033+ return loader_throw(
5034+ scope,
5035+ "This worker is not permitted to access the internet via global functions.",
5036+ );
5037+ }
5038+ let id = args
5039+ .get(0)
5040+ .to_integer(scope)
5041+ .map(|n| n.value() as u64)
5042+ .unwrap_or(0);
5043+ let cell = args.get(1).to_rust_string_lossy(scope);
5044+ let url = args.get(2).to_rust_string_lossy(scope);
5045+ let headers: Vec<(String, String)> =
5046+ serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
5047+ let protocols: Vec<String> = headers
5048+ .iter()
5049+ .find(|(name, _)| name.eq_ignore_ascii_case("sec-websocket-protocol"))
5050+ .map(|(_, value)| value.split(',').map(|p| p.trim().to_string()).collect())
5051+ .unwrap_or_default();
5052+ let pull = cell.is_empty().then(|| {
5053+ let (pull_tx, pull_rx) = tokio::sync::mpsc::unbounded_channel();
5054+ ws_pull_register(id, pull_rx);
5055+ ws_region_track(id);
5056+ pull_tx
5057+ });
5058+ let (tx, rx) = tokio::sync::oneshot::channel();
5059+ let sent = OUTBOUND_WS_TX.get().is_some_and(|sender| {
5060+ sender
5061+ .send(OutboundWsReq {
5062+ scope: cell,
5063+ id,
5064+ url,
5065+ protocols,
5066+ pull,
5067+ headers,
5068+ want_response: true,
5069+ reply: tx,
5070+ })
5071+ .is_ok()
5072+ });
5073+ let async_id = asyncrt::enqueue(async move {
5074+ if !sent {
5075+ return Err("no outbound WebSocket channel".into());
5076+ }
5077+ let open = match rx.await {
5078+ Ok(Ok(open)) => open,
5079+ Ok(Err(error)) => return Err(format!("WebSocket upgrade failed: {error}")),
5080+ Err(error) => return Err(format!("WebSocket connector dropped: {error}")),
5081+ };
5082+ Ok(match open.declined {
5083+ Some(declined) => serde_json::json!({
5084+ "upgraded": false,
5085+ "status": declined.status,
5086+ "headers": declined.headers,
5087+ "body": declined.body,
5088+ })
5089+ .to_string(),
5090+ None => serde_json::json!({
5091+ "upgraded": true,
5092+ "protocol": open.protocol.unwrap_or_default(),
5093+ })
5094+ .to_string(),
5095+ })
5096+ });
5097+ rv.set(promise_for(scope, async_id));
5098+}
5099+
5100+/// Await the next inbound event on an isolate-polled socket. Resolves with a
5101+/// tagged buffer; a closed queue resolves as a 1006 close so the JS pump always
5102+/// terminates rather than hanging on a dropped sender.
5103+fn op_ws_next(
5104+ scope: &mut v8::PinScope,
5105+ args: v8::FunctionCallbackArguments,
5106+ mut rv: v8::ReturnValue<v8::Value>,
5107+) {
5108+ let id = args
5109+ .get(0)
5110+ .to_integer(scope)
5111+ .map(|n| n.value() as u64)
5112+ .unwrap_or(0);
5113+ let queue = ws_pull().lock().unwrap().get(&id).cloned();
5114+ let async_id = asyncrt::enqueue(async move {
5115+ let Some(queue) = queue else {
5116+ return Ok(WsPull::Close(1006, "socket is not registered".into(), false).encode());
5117+ };
5118+ let mut queue = queue.lock().await;
5119+ Ok(queue
5120+ .recv()
5121+ .await
5122+ .unwrap_or_else(|| WsPull::Close(1006, String::new(), false))
5123+ .encode())
5124+ });
5125+ rv.set(promise_for(scope, async_id));
5126+}
5127+
5128+fn op_ws_connect(
5129+ scope: &mut v8::PinScope,
5130+ args: v8::FunctionCallbackArguments,
5131+ mut rv: v8::ReturnValue<v8::Value>,
5132+) {
5133+ if actor_runtime_state(scope).egress == EgressPolicy::Deny {
5134+ return loader_throw(
5135+ scope,
5136+ "This worker is not permitted to access the internet via global functions.",
5137+ );
5138+ }
5139+ let id = args
5140+ .get(0)
5141+ .to_integer(scope)
5142+ .map(|n| n.value() as u64)
5143+ .unwrap_or(0);
5144+ let cell = args.get(1).to_rust_string_lossy(scope);
5145+ let url = args.get(2).to_rust_string_lossy(scope);
5146+ let protocols: Vec<String> =
5147+ serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
5148+ // No cell means a Worker socket: the isolate polls it, so register the
5149+ // queue here on the JS thread and track it against the running region.
5150+ let pull = cell.is_empty().then(|| {
5151+ let (pull_tx, pull_rx) = tokio::sync::mpsc::unbounded_channel();
5152+ ws_pull_register(id, pull_rx);
5153+ ws_region_track(id);
5154+ pull_tx
5155+ });
5156+ let (tx, rx) = tokio::sync::oneshot::channel();
5157+ let sent = OUTBOUND_WS_TX.get().is_some_and(|sender| {
5158+ sender
5159+ .send(OutboundWsReq {
5160+ scope: cell,
5161+ id,
5162+ url,
5163+ protocols,
5164+ pull,
5165+ headers: Vec::new(),
5166+ want_response: false,
5167+ reply: tx,
5168+ })
5169+ .is_ok()
5170+ });
5171+ let async_id = asyncrt::enqueue(async move {
5172+ if !sent {
5173+ return Err("no outbound WebSocket channel".into());
5174+ }
5175+ match rx.await {
5176+ Ok(Ok(open)) => Ok(open.protocol.unwrap_or_default()),
5177+ Ok(Err(error)) => Err(format!("WebSocket connection failed: {error}")),
5178+ Err(error) => Err(format!("WebSocket connector dropped: {error}")),
5179+ }
5180+ });
5181+ rv.set(promise_for(scope, async_id));
5182+}
5183+fn op_ws_accept(
5184+ scope: &mut v8::PinScope,
5185+ args: v8::FunctionCallbackArguments,
5186+ _rv: v8::ReturnValue<v8::Value>,
5187+) {
5188+ let id = args
5189+ .get(0)
5190+ .to_integer(scope)
5191+ .map(|n| n.value() as u64)
5192+ .unwrap_or(0);
5193+ let cell = args.get(1).to_rust_string_lossy(scope);
5194+ let tags: Vec<String> =
5195+ serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)).unwrap_or_default();
5196+ let replaced_regular_scope = {
5197+ let mut registry = ws_registry().lock().unwrap();
5198+ let sockets = &mut registry.metadata;
5199+ let replaced_regular_scope = sockets
5200+ .get(&id)
5201+ .filter(|meta| !meta.hibernatable)
5202+ .map(|meta| meta.scope.clone());
5203+ sockets
5204+ .entry(id)
5205+ .and_modify(|meta| {
5206+ meta.scope = cell.clone();
5207+ meta.hibernatable = true;
5208+ meta.tags = tags.clone();
5209+ })
5210+ .or_insert(WsMeta {
5211+ scope: cell.clone(),
5212+ hibernatable: true,
5213+ tags,
5214+ attachment: None,
5215+ pending: Vec::new(),
5216+ });
5217+ replaced_regular_scope
5218+ };
5219+ if let Some(scope) = replaced_regular_scope {
5220+ decrement_regular_ws(&scope);
5221+ }
5222+ tracing::info!(ws_id = id, scope = %cell, "accepted hibernatable WebSocket");
5223+}
5224+fn op_ws_accept_regular(
5225+ scope: &mut v8::PinScope,
5226+ args: v8::FunctionCallbackArguments,
5227+ _rv: v8::ReturnValue<v8::Value>,
5228+) {
5229+ let id = args
5230+ .get(0)
5231+ .to_integer(scope)
5232+ .map(|n| n.value() as u64)
5233+ .unwrap_or(0);
5234+ let cell = args.get(1).to_rust_string_lossy(scope);
5235+ let inserted = {
5236+ let mut registry = ws_registry().lock().unwrap();
5237+ let sockets = &mut registry.metadata;
5238+ if let std::collections::hash_map::Entry::Vacant(entry) = sockets.entry(id) {
5239+ entry.insert(WsMeta {
5240+ scope: cell.clone(),
5241+ hibernatable: false,
5242+ tags: Vec::new(),
5243+ attachment: None,
5244+ pending: Vec::new(),
5245+ });
5246+ true
5247+ } else {
5248+ false
5249+ }
5250+ };
5251+ if inserted {
5252+ increment_regular_ws(&cell);
5253+ }
5254+ tracing::info!(ws_id = id, scope = %cell, "accepted regular WebSocket");
5255+}
5256+fn op_ws_list(
5257+ scope: &mut v8::PinScope,
5258+ args: v8::FunctionCallbackArguments,
5259+ mut rv: v8::ReturnValue<v8::Value>,
5260+) {
5261+ let cell = args.get(0).to_rust_string_lossy(scope);
5262+ let tag = args.get(1);
5263+ let tag = if tag.is_undefined() || tag.is_null() {
5264+ None
5265+ } else {
5266+ Some(tag.to_rust_string_lossy(scope))
5267+ };
5268+ let rows = ws_registry()
5269+ .lock()
5270+ .unwrap()
5271+ .metadata
5272+ .iter()
5273+ .filter(|(_, meta)| {
5274+ meta.hibernatable
5275+ && meta.scope == cell
5276+ && tag.as_ref().is_none_or(|tag| meta.tags.contains(tag))
5277+ })
5278+ .map(|(id, meta)| {
5279+ serde_json::json!({
5280+ "id": id,
5281+ "tags": meta.tags,
5282+ "attachment": meta.attachment,
5283+ })
5284+ })
5285+ .collect::<Vec<_>>();
5286+ let json = serde_json::to_string(&rows).unwrap();
5287+ rv.set(v8::String::new(scope, &json).unwrap().into());
5288+}
5289+fn op_ws_attachment_set(
5290+ scope: &mut v8::PinScope,
5291+ args: v8::FunctionCallbackArguments,
5292+ _rv: v8::ReturnValue<v8::Value>,
5293+) {
5294+ let id = args
5295+ .get(0)
5296+ .to_integer(scope)
5297+ .map(|n| n.value() as u64)
5298+ .unwrap_or(0);
5299+ let attachment = args.get(1).to_rust_string_lossy(scope);
5300+ if let Some(meta) = ws_registry().lock().unwrap().metadata.get_mut(&id) {
5301+ meta.attachment = Some(attachment);
5302+ }
5303+}
5304+
5305+#[cfg(all(test, celld_internal_tests))]
5306+mod websocket_registry_private {
5307+ include!(env!("CELLD_CONFORMANCE_WEBSOCKET_REGISTRY_TESTS"));
5308+}
5309+fn op_storage_get(
5310+ scope: &mut v8::PinScope,
5311+ args: v8::FunctionCallbackArguments,
5312+ mut rv: v8::ReturnValue<v8::Value>,
5313+) {
5314+ let scope_s = args.get(0).to_rust_string_lossy(scope);
5315+ let key = args.get(1).to_rust_string_lossy(scope);
5316+ match storage::get_stored(&scope_s, &key) {
5317+ Ok(Some(value)) => {
5318+ if let Some((value, _)) = deserialize_stored(scope, value, args.get(2)) {
5319+ rv.set(value);
5320+ }
5321+ }
5322+ Ok(None) => rv.set(v8::undefined(scope).into()),
5323+ Err(error) => throw_storage_error(scope, "get", error),
5324+ }
5325+}
5326+fn op_storage_get_many(
5327+ scope: &mut v8::PinScope,
5328+ args: v8::FunctionCallbackArguments,
5329+ mut rv: v8::ReturnValue<v8::Value>,
5330+) {
5331+ let cell = args.get(0).to_rust_string_lossy(scope);
5332+ let keys = match storage_string_array(scope, args.get(1)) {
5333+ Ok(keys) => keys,
5334+ Err(error) => {
5335+ throw_storage_error(scope, "get", error);
5336+ return;
5337+ }
5338+ };
5339+ match storage::get_many_stored(&cell, &keys) {
5340+ Ok(entries) => {
5341+ let sentinel = args.get(2);
5342+ if let Some((map, tagged)) = storage_entries_map(scope, entries, sentinel) {
5343+ rv.set(if tagged {
5344+ wrap_stored(scope, sentinel, map.into())
5345+ } else {
5346+ map.into()
5347+ });
5348+ }
5349+ }
5350+ Err(error) => throw_storage_error(scope, "get", error),
5351+ }
5352+}
5353+fn op_storage_put(
5354+ scope: &mut v8::PinScope,
5355+ args: v8::FunctionCallbackArguments,
5356+ _rv: v8::ReturnValue<v8::Value>,
5357+) {
5358+ let s = args.get(0).to_rust_string_lossy(scope);
5359+ let k = args.get(1).to_rust_string_lossy(scope);
5360+ let Some(value) = serialize_storage_value(scope, args.get(2)) else {
5361+ return;
5362+ };
5363+ if let Err(error) = storage::put_serialized(&s, &k, &value) {
5364+ throw_storage_error(scope, "put", error);
5365+ }
5366+}
5367+fn op_storage_put_many(
5368+ scope: &mut v8::PinScope,
5369+ args: v8::FunctionCallbackArguments,
5370+ _rv: v8::ReturnValue<v8::Value>,
5371+) {
5372+ let cell = args.get(0).to_rust_string_lossy(scope);
5373+ let Ok(entries) = v8::Local::<v8::Array>::try_from(args.get(1)) else {
5374+ throw_storage_error(scope, "put", "entries must be an array");
5375+ return;
5376+ };
5377+ let mut serialized = Vec::with_capacity(entries.length() as usize);
5378+ for index in 0..entries.length() {
5379+ let Some(entry) = entries.get_index(scope, index) else {
5380+ return;
5381+ };
5382+ let Ok(entry) = v8::Local::<v8::Array>::try_from(entry) else {
5383+ throw_storage_error(scope, "put", "entry must be a key/value pair");
5384+ return;
5385+ };
5386+ let Some(key) = entry.get_index(scope, 0) else {
5387+ return;
5388+ };
5389+ let Some(value) = entry.get_index(scope, 1) else {
5390+ return;
5391+ };
5392+ let Some(value) = serialize_storage_value(scope, value) else {
5393+ return;
5394+ };
5395+ serialized.push((key.to_rust_string_lossy(scope), value));
5396+ }
5397+ if let Err(error) = storage::put_many_serialized(&cell, &serialized) {
5398+ throw_storage_error(scope, "put", error);
5399+ }
5400+}
5401+
5402+/// `__storage_put_serialized(cell, key, bytes)`: write pre-encoded row
5403+/// bytes verbatim — the stored-stub envelope (or a plain clone) built by
5404+/// the JS storage wrapper after a plain clone failed. Never on the fast
5405+/// path.
5406+fn op_storage_put_serialized(
5407+ scope: &mut v8::PinScope,
5408+ args: v8::FunctionCallbackArguments,
5409+ _rv: v8::ReturnValue<v8::Value>,
5410+) {
5411+ let cell = args.get(0).to_rust_string_lossy(scope);
5412+ let key = args.get(1).to_rust_string_lossy(scope);
5413+ let Some(bytes) = view_bytes(args.get(2)) else {
5414+ throw_storage_error(scope, "put", "serialized row must be bytes");
5415+ return;
5416+ };
5417+ if let Err(error) = storage::put_serialized(&cell, &key, &bytes) {
5418+ throw_storage_error(scope, "put", error);
5419+ }
5420+}
5421+
5422+/// The queued flavor of [`op_storage_put_serialized`], joining the same
5423+/// pending-puts batch the plain queue ops feed.
5424+fn op_storage_queue_put_serialized(
5425+ scope: &mut v8::PinScope,
5426+ args: v8::FunctionCallbackArguments,
5427+ _rv: v8::ReturnValue<v8::Value>,
5428+) {
5429+ let cell = args.get(0).to_rust_string_lossy(scope);
5430+ let key = args.get(1).to_rust_string_lossy(scope);
5431+ let Some(bytes) = view_bytes(args.get(2)) else {
5432+ throw_storage_error(scope, "put", "serialized row must be bytes");
5433+ return;
5434+ };
5435+ queue_serialized_puts(scope, cell, vec![(key, bytes)]);
5436+}
5437+
5438+fn actor_runtime_state(scope: &mut v8::PinScope) -> Arc<ActorRuntimeState> {
5439+ scope
5440+ .get_slot::<Arc<ActorRuntimeState>>()
5441+ .expect("actor runtime state slot")
5442+ .clone()
5443+}
5444+
5445+fn queue_serialized_puts(scope: &mut v8::PinScope, cell: String, entries: Vec<(String, Vec<u8>)>) {
5446+ actor_runtime_state(scope)
5447+ .pending_puts
5448+ .lock()
5449+ .expect("pending puts lock poisoned")
5450+ .entry(cell)
5451+ .or_default()
5452+ .extend(entries);
5453+}
5454+
5455+fn op_storage_queue_put(
5456+ scope: &mut v8::PinScope,
5457+ args: v8::FunctionCallbackArguments,
5458+ _rv: v8::ReturnValue<v8::Value>,
5459+) {
5460+ let cell = args.get(0).to_rust_string_lossy(scope);
5461+ let key = args.get(1).to_rust_string_lossy(scope);
5462+ let Some(value) = serialize_storage_value(scope, args.get(2)) else {
5463+ return;
5464+ };
5465+ queue_serialized_puts(scope, cell, vec![(key, value)]);
5466+}
5467+
5468+fn op_storage_queue_put_many(
5469+ scope: &mut v8::PinScope,
5470+ args: v8::FunctionCallbackArguments,
5471+ _rv: v8::ReturnValue<v8::Value>,
5472+) {
5473+ let cell = args.get(0).to_rust_string_lossy(scope);
5474+ let Ok(entries) = v8::Local::<v8::Array>::try_from(args.get(1)) else {
5475+ throw_storage_error(scope, "put", "entries must be an array");
5476+ return;
5477+ };
5478+ let mut serialized = Vec::with_capacity(entries.length() as usize);
5479+ for index in 0..entries.length() {
5480+ let Some(entry) = entries.get_index(scope, index) else {
5481+ return;
5482+ };
5483+ let Ok(entry) = v8::Local::<v8::Array>::try_from(entry) else {
5484+ throw_storage_error(scope, "put", "entry must be a key/value pair");
5485+ return;
5486+ };
5487+ let Some(key) = entry.get_index(scope, 0) else {
5488+ return;
5489+ };
5490+ let Some(value) = entry.get_index(scope, 1) else {
5491+ return;
5492+ };
5493+ let Some(value) = serialize_storage_value(scope, value) else {
5494+ return;
5495+ };
5496+ serialized.push((key.to_rust_string_lossy(scope), value));
5497+ }
5498+ queue_serialized_puts(scope, cell, serialized);
5499+}
5500+
5501+fn op_storage_flush_pending_puts(
5502+ scope: &mut v8::PinScope,
5503+ args: v8::FunctionCallbackArguments,
5504+ _rv: v8::ReturnValue<v8::Value>,
5505+) {
5506+ let cell = args.get(0).to_rust_string_lossy(scope);
5507+ let entries = actor_runtime_state(scope)
5508+ .pending_puts
5509+ .lock()
5510+ .expect("pending puts lock poisoned")
5511+ .remove(&cell)
5512+ .unwrap_or_default();
5513+ if entries.is_empty() {
5514+ return;
5515+ }
5516+ if let Err(error) = storage::put_many_serialized(&cell, &entries) {
5517+ throw_storage_error(scope, "put", error);
5518+ }
5519+}
5520+
5521+fn op_storage_cancel_pending_puts(
5522+ scope: &mut v8::PinScope,
5523+ args: v8::FunctionCallbackArguments,
5524+ _rv: v8::ReturnValue<v8::Value>,
5525+) {
5526+ let cell = args.get(0).to_rust_string_lossy(scope);
5527+ actor_runtime_state(scope)
5528+ .pending_puts
5529+ .lock()
5530+ .expect("pending puts lock poisoned")
5531+ .remove(&cell);
5532+}
5533+
5534+fn op_actor_abort(
5535+ scope: &mut v8::PinScope,
5536+ args: v8::FunctionCallbackArguments,
5537+ _rv: v8::ReturnValue<v8::Value>,
5538+) {
5539+ let cell = args.get(0).to_rust_string_lossy(scope);
5540+ let reason = args.get(1).to_rust_string_lossy(scope);
5541+ let state = actor_runtime_state(scope);
5542+ state
5543+ .pending_puts
5544+ .lock()
5545+ .expect("pending puts lock poisoned")
5546+ .remove(&cell);
5547+ *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
5548+ error: format!("__CELLD_ACTOR_ABORT__:{reason}"),
5549+ actor_scope: Some(cell),
5550+ });
5551+ scope.terminate_execution();
5552+}
5553+
5554+fn op_process_exit(
5555+ scope: &mut v8::PinScope,
5556+ args: v8::FunctionCallbackArguments,
5557+ _rv: v8::ReturnValue<v8::Value>,
5558+) {
5559+ let code = args.get(0).integer_value(scope).unwrap_or(0);
5560+ let actor_scope = args.get(1).to_rust_string_lossy(scope);
5561+ let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope);
5562+ let state = actor_runtime_state(scope);
5563+ if let Some(actor_scope) = actor_scope.as_deref() {
5564+ state
5565+ .pending_puts
5566+ .lock()
5567+ .expect("pending puts lock poisoned")
5568+ .remove(actor_scope);
5569+ } else {
5570+ state.worker_exit_requested.store(true, Ordering::Relaxed);
5571+ }
5572+ *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
5573+ error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."),
5574+ actor_scope,
5575+ });
5576+ scope.terminate_execution();
5577+}
5578+
5579+fn op_log(
5580+ scope: &mut v8::PinScope,
5581+ args: v8::FunctionCallbackArguments,
5582+ _rv: v8::ReturnValue<v8::Value>,
5583+) {
5584+ let msg: Vec<String> = (0..args.length())
5585+ .map(|i| args.get(i).to_rust_string_lossy(scope))
5586+ .collect();
5587+ tracing::info!(target: "cell_console", "{}", msg.join(" "));
5588+}
5589+fn op_heap_limit_excessively_exceeded(
5590+ scope: &mut v8::PinScope,
5591+ _args: v8::FunctionCallbackArguments,
5592+ mut rv: v8::ReturnValue<v8::Value>,
5593+) {
5594+ let exceeded = scope
5595+ .get_slot::<Arc<HeapLimitState>>()
5596+ .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed));
5597+ rv.set(v8::Boolean::new(scope, exceeded).into());
5598+}
5599+#[cfg(all(test, celld_internal_tests))]
5600+fn op_test_set_heap_limit_excessively_exceeded(
5601+ scope: &mut v8::PinScope,
5602+ args: v8::FunctionCallbackArguments,
5603+ _rv: v8::ReturnValue<v8::Value>,
5604+) {
5605+ if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
5606+ state
5607+ .excessively_exceeded
5608+ .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
5609+ }
5610+}
5611+#[cfg(all(test, celld_internal_tests))]
5612+fn op_test_gc(
5613+ scope: &mut v8::PinScope,
5614+ _args: v8::FunctionCallbackArguments,
5615+ _rv: v8::ReturnValue<v8::Value>,
5616+) {
5617+ scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full);
5618+}
5619+/// `ctx.storage.sql.exec(query, ...binds)` — args: scope, query, binds(JSON).
5620+/// Returns a JSON `{columns, rows, rowsWritten}` (or `{error}`).
5621+fn op_sql_exec(
5622+ scope: &mut v8::PinScope,
5623+ args: v8::FunctionCallbackArguments,
5624+ mut rv: v8::ReturnValue<v8::Value>,
5625+) {
5626+ let sc = args.get(0).to_rust_string_lossy(scope);
5627+ let query = args.get(1).to_rust_string_lossy(scope);
5628+ let binds: Vec<serde_json::Value> =
5629+ serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)).unwrap_or_default();
5630+ let out = match storage::sql_exec(&sc, &query, &binds) {
5631+ Ok((columns, rows, rows_written)) => serde_json::json!({
5632+ "columns": columns, "rows": rows, "rowsWritten": rows_written,
5633+ }),
5634+ Err(e) => serde_json::json!({ "error": e }),
5635+ };
5636+ rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5637+}
5638+fn op_sql_ingest(
5639+ scope: &mut v8::PinScope,
5640+ args: v8::FunctionCallbackArguments,
5641+ mut rv: v8::ReturnValue<v8::Value>,
5642+) {
5643+ let cell = args.get(0).to_rust_string_lossy(scope);
5644+ let input = args.get(1).to_rust_string_lossy(scope);
5645+ let out = match storage::sql_ingest(&cell, &input) {
5646+ Ok((remainder, rows_written, statement_count)) => serde_json::json!({
5647+ "remainder": remainder,
5648+ "rowsWritten": rows_written,
5649+ "statementCount": statement_count,
5650+ }),
5651+ Err(error) => serde_json::json!({ "error": error }),
5652+ };
5653+ rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5654+}
5655+fn op_sql_cursor_start(
5656+ scope: &mut v8::PinScope,
5657+ args: v8::FunctionCallbackArguments,
5658+ mut rv: v8::ReturnValue<v8::Value>,
5659+) {
5660+ let cell = args.get(0).to_rust_string_lossy(scope);
5661+ let query = args.get(1).to_rust_string_lossy(scope);
5662+ let binds: Vec<serde_json::Value> =
5663+ serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)).unwrap_or_default();
5664+ let out = match storage::sql_cursor_start(&cell, &query, &binds) {
5665+ Ok((cursor, columns, row, rows_written, reused_cached_query)) => serde_json::json!({
5666+ "native": true,
5667+ "cursorId": cursor,
5668+ "columns": columns,
5669+ "row": row,
5670+ "rowsWritten": rows_written,
5671+ "reusedCachedQuery": reused_cached_query,
5672+ }),
5673+ Err(error) => serde_json::json!({ "error": error }),
5674+ };
5675+ rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5676+}
5677+fn op_sql_cursor_next(
5678+ scope: &mut v8::PinScope,
5679+ args: v8::FunctionCallbackArguments,
5680+ mut rv: v8::ReturnValue<v8::Value>,
5681+) {
5682+ let cursor = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
5683+ let out = match storage::sql_cursor_next(cursor) {
5684+ Ok((row, rows_written)) => serde_json::json!({
5685+ "row": row,
5686+ "rowsWritten": rows_written,
5687+ }),
5688+ Err(error) => serde_json::json!({ "error": error }),
5689+ };
5690+ rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5691+}
5692+fn op_sql_cursor_close(
5693+ scope: &mut v8::PinScope,
5694+ args: v8::FunctionCallbackArguments,
5695+ _rv: v8::ReturnValue<v8::Value>,
5696+) {
5697+ let cursor = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
5698+ storage::sql_cursor_close(cursor);
5699+}
5700+fn op_sql_database_size(
5701+ scope: &mut v8::PinScope,
5702+ args: v8::FunctionCallbackArguments,
5703+ mut rv: v8::ReturnValue<v8::Value>,
5704+) {
5705+ let cell = args.get(0).to_rust_string_lossy(scope);
5706+ match storage::sql_database_size(&cell) {
5707+ Ok(bytes) => rv.set(v8::Number::new(scope, bytes as f64).into()),
5708+ Err(error) => throw_storage_error(scope, "sql.databaseSize", error),
5709+ }
5710+}
5711+#[cfg(all(test, celld_internal_tests))]
5712+fn op_sql_set_max_page_count_for_test(
5713+ scope: &mut v8::PinScope,
5714+ args: v8::FunctionCallbackArguments,
5715+ _rv: v8::ReturnValue<v8::Value>,
5716+) {
5717+ let cell = args.get(0).to_rust_string_lossy(scope);
5718+ let pages = args.get(1).uint32_value(scope).unwrap_or(0);
5719+ if let Err(error) = storage::set_max_page_count_for_test(&cell, pages) {
5720+ throw_storage_error(scope, "sql.setMaxPageCountForTest", error);
5721+ }
5722+}
5723+#[cfg(all(test, celld_internal_tests))]
5724+fn op_sql_set_write_fault_for_test(
5725+ scope: &mut v8::PinScope,
5726+ args: v8::FunctionCallbackArguments,
5727+ _rv: v8::ReturnValue<v8::Value>,
5728+) {
5729+ storage::set_write_fault_for_test(args.get(0).boolean_value(scope));
5730+}
5731+#[cfg(all(test, celld_internal_tests))]
5732+fn op_sql_set_cache_size_for_test(
5733+ scope: &mut v8::PinScope,
5734+ args: v8::FunctionCallbackArguments,
5735+ _rv: v8::ReturnValue<v8::Value>,
5736+) {
5737+ let cell = args.get(0).to_rust_string_lossy(scope);
5738+ let pages = args.get(1).int32_value(scope).unwrap_or(0);
5739+ if let Err(error) = storage::set_cache_size_for_test(&cell, pages) {
5740+ throw_storage_error(scope, "sql.setCacheSizeForTest", error);
5741+ }
5742+}
5743+#[cfg(all(test, celld_internal_tests))]
5744+fn op_sql_set_interrupt_fault_for_test(
5745+ scope: &mut v8::PinScope,
5746+ args: v8::FunctionCallbackArguments,
5747+ _rv: v8::ReturnValue<v8::Value>,
5748+) {
5749+ let cell = args.get(0).to_rust_string_lossy(scope);
5750+ let enabled = args.get(1).boolean_value(scope);
5751+ if let Err(error) = storage::set_interrupt_fault_for_test(&cell, enabled) {
5752+ throw_storage_error(scope, "sql.setInterruptFaultForTest", error);
5753+ }
5754+}
5755+#[cfg(all(test, celld_internal_tests))]
5756+fn op_sql_register_nomem_function_for_test(
5757+ scope: &mut v8::PinScope,
5758+ args: v8::FunctionCallbackArguments,
5759+ _rv: v8::ReturnValue<v8::Value>,
5760+) {
5761+ let cell = args.get(0).to_rust_string_lossy(scope);
5762+ if let Err(error) = storage::register_nomem_function_for_test(&cell) {
5763+ throw_storage_error(scope, "sql.registerNomemFunctionForTest", error);
5764+ }
5765+}
5766+fn op_storage_transaction_control(
5767+ scope: &mut v8::PinScope,
5768+ args: v8::FunctionCallbackArguments,
5769+ _rv: v8::ReturnValue<v8::Value>,
5770+) {
5771+ let cell = args.get(0).to_rust_string_lossy(scope);
5772+ let action = args.get(1).to_rust_string_lossy(scope);
5773+ let nested = args.get(2).boolean_value(scope);
5774+ let savepoint = args.get(3).to_rust_string_lossy(scope);
5775+ match storage::transaction_control(&cell, &action, nested, &savepoint) {
5776+ Err(error) => throw_storage_error(scope, "transaction", error),
5777+ // An outermost commit published a dirty alarm: register its
5778+ // wake-entry PUT against the cell's output gate.
5779+ Ok(Some(at)) if at >= 0 => spawn_arm_gate(&cell, at),
5780+ Ok(_) => {}
5781+ }
5782+}
5783+fn op_storage_delete(
5784+ scope: &mut v8::PinScope,
5785+ args: v8::FunctionCallbackArguments,
5786+ mut rv: v8::ReturnValue<v8::Value>,
5787+) {
5788+ let s = args.get(0).to_rust_string_lossy(scope);
5789+ let k = args.get(1).to_rust_string_lossy(scope);
5790+ match storage::delete(&s, &k) {
5791+ Ok(deleted) => rv.set(v8::Boolean::new(scope, deleted).into()),
5792+ Err(error) => throw_storage_error(scope, "delete", error),
5793+ }
5794+}
5795+fn op_storage_delete_many(
5796+ scope: &mut v8::PinScope,
5797+ args: v8::FunctionCallbackArguments,
5798+ mut rv: v8::ReturnValue<v8::Value>,
5799+) {
5800+ let cell = args.get(0).to_rust_string_lossy(scope);
5801+ let keys = match storage_string_array(scope, args.get(1)) {
5802+ Ok(keys) => keys,
5803+ Err(error) => {
5804+ throw_storage_error(scope, "delete", error);
5805+ return;
5806+ }
5807+ };
5808+ match storage::delete_many(&cell, &keys) {
5809+ Ok(deleted) => rv.set(v8::Number::new(scope, deleted as f64).into()),
5810+ Err(error) => throw_storage_error(scope, "delete", error),
5811+ }
5812+}
5813+
5814+#[derive(Default, serde::Deserialize)]
5815+#[serde(default, rename_all = "camelCase")]
5816+struct StorageListOptions {
5817+ start: Option<String>,
5818+ end: Option<String>,
5819+ start_after: Option<String>,
5820+ prefix: Option<String>,
5821+ limit: Option<usize>,
5822+ reverse: bool,
5823+}
5824+
5825+fn op_storage_list(
5826+ scope: &mut v8::PinScope,
5827+ args: v8::FunctionCallbackArguments,
5828+ mut rv: v8::ReturnValue<v8::Value>,
5829+) {
5830+ let cell = args.get(0).to_rust_string_lossy(scope);
5831+ let options = match serde_json::from_str::<StorageListOptions>(
5832+ &args.get(1).to_rust_string_lossy(scope),
5833+ ) {
5834+ Ok(options) => options,
5835+ Err(error) => {
5836+ throw_storage_error(scope, "list", error);
5837+ return;
5838+ }
5839+ };
5840+ match storage::list_stored_with_options(
5841+ &cell,
5842+ options.start.as_deref(),
5843+ options.end.as_deref(),
5844+ options.start_after.as_deref(),
5845+ options.prefix.as_deref(),
5846+ options.limit,
5847+ options.reverse,
5848+ ) {
5849+ Ok(entries) => {
5850+ let sentinel = args.get(2);
5851+ if let Some((map, tagged)) = storage_entries_map(scope, entries, sentinel) {
5852+ rv.set(if tagged {
5853+ wrap_stored(scope, sentinel, map.into())
5854+ } else {
5855+ map.into()
5856+ });
5857+ }
5858+ }
5859+ Err(error) => throw_storage_error(scope, "list", error),
5860+ }
5861+}
5862+
5863+fn op_storage_sync_list_start(
5864+ scope: &mut v8::PinScope,
5865+ args: v8::FunctionCallbackArguments,
5866+ mut rv: v8::ReturnValue<v8::Value>,
5867+) {
5868+ let cell = args.get(0).to_rust_string_lossy(scope);
5869+ let options = match serde_json::from_str::<StorageListOptions>(
5870+ &args.get(1).to_rust_string_lossy(scope),
5871+ ) {
5872+ Ok(options) => options,
5873+ Err(error) => {
5874+ throw_storage_error(scope, "kv.list", error);
5875+ return;
5876+ }
5877+ };
5878+ match storage::sync_list_start(
5879+ &cell,
5880+ options.start.as_deref(),
5881+ options.end.as_deref(),
5882+ options.start_after.as_deref(),
5883+ options.prefix.as_deref(),
5884+ options.limit,
5885+ options.reverse,
5886+ ) {
5887+ Ok(cursor) => rv.set(v8::Number::new(scope, cursor as f64).into()),
5888+ Err(error) => throw_storage_error(scope, "kv.list", error),
5889+ }
5890+}
5891+
5892+fn op_storage_sync_list_next(
5893+ scope: &mut v8::PinScope,
5894+ args: v8::FunctionCallbackArguments,
5895+ mut rv: v8::ReturnValue<v8::Value>,
5896+) {
5897+ let cursor = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
5898+ match storage::sync_list_next(cursor) {
5899+ Ok(Some((key, value))) => {
5900+ let Some((decoded, _)) = deserialize_stored(scope, value, args.get(1)) else {
5901+ throw_storage_error(
5902+ scope,
5903+ "kv.list",
5904+ format!("deserialization failed for key {key}"),
5905+ );
5906+ return;
5907+ };
5908+ let pair = v8::Array::new(scope, 2);
5909+ let key = v8::String::new(scope, &key).unwrap();
5910+ pair.set_index(scope, 0, key.into());
5911+ pair.set_index(scope, 1, decoded);
5912+ rv.set(pair.into());
5913+ }
5914+ Ok(None) => rv.set(v8::null(scope).into()),
5915+ Err(error) => throw_storage_error(scope, "kv.list", error),
5916+ }
5917+}
5918+
5919+struct StorageValueDelegate;
5920+
5921+impl v8::ValueSerializerImpl for StorageValueDelegate {
5922+ fn throw_data_clone_error(&self, scope: &mut v8::PinScope, message: v8::Local<v8::String>) {
5923+ let exception = v8::Exception::type_error(scope, message);
5924+ scope.throw_exception(exception);
5925+ }
5926+}
5927+
5928+impl v8::ValueDeserializerImpl for StorageValueDelegate {}
5929+
5930+fn serialize_storage_value(
5931+ scope: &mut v8::PinScope,
5932+ value: v8::Local<v8::Value>,
5933+) -> Option<Vec<u8>> {
5934+ let context = scope.get_current_context();
5935+ let serializer = v8::ValueSerializer::new(scope, Box::new(StorageValueDelegate));
5936+ serializer.write_header();
5937+ if !serializer.write_value(context, value).unwrap_or(false) {
5938+ return None;
5939+ }
5940+ let mut bytes = serializer.release();
5941+ // Workerd pins persisted actor values to V8 wire version 15 so rolling
5942+ // upgrades remain readable by older processes. V8 150 writes version 16;
5943+ // for Cells' supported (sub-4GiB) ArrayBuffers its varint encoding is
5944+ // byte-compatible, so retain the Workerd on-disk version tag.
5945+ if bytes.starts_with(&[0xff, 0x10]) {
5946+ bytes[1] = 0x0f;
5947+ }
5948+ Some(bytes)
5949+}
5950+
5951+fn deserialize_storage_value<'s>(
5952+ scope: &mut v8::PinScope<'s, '_>,
5953+ value: storage::StoredValue,
5954+) -> Option<v8::Local<'s, v8::Value>> {
5955+ match value {
5956+ storage::StoredValue::LegacyJson(json) => {
5957+ let json = v8::String::new(scope, &json)?;
5958+ v8::json::parse(scope, json)
5959+ }
5960+ storage::StoredValue::V8(bytes) => {
5961+ let context = scope.get_current_context();
5962+ let deserializer =
5963+ v8::ValueDeserializer::new(scope, Box::new(StorageValueDelegate), &bytes);
5964+ deserializer.set_supports_legacy_wire_format(true);
5965+ if !deserializer.read_header(context).unwrap_or(false) {
5966+ return None;
5967+ }
5968+ deserializer.read_value(context)
5969+ }
5970+ }
5971+}
5972+
5973+/// First byte of a stored-stub row: a durable stub marker tree follows
5974+/// as an ordinary V8 clone. Plain rows keep V8's own 0xff prefix, so
5975+/// the tag branch never runs for them.
5976+const STORED_STUB_TAG: u8 = 0x01;
5977+
5978+fn wrap_stored<'s>(
5979+ scope: &mut v8::PinScope<'s, '_>,
5980+ sentinel: v8::Local<v8::Value>,
5981+ value: v8::Local<v8::Value>,
5982+) -> v8::Local<'s, v8::Value> {
5983+ let pair = v8::Array::new(scope, 2);
5984+ pair.set_index(scope, 0, sentinel);
5985+ pair.set_index(scope, 1, value);
5986+ pair.into()
5987+}
5988+
5989+/// Decode one stored row for JS. A stub-tagged row comes back as
5990+/// `[sentinel, tree]` (plus `true`), which only the storage wrapper —
5991+/// holder of the closure-private sentinel — turns back into live stubs.
5992+fn deserialize_stored<'s>(
5993+ scope: &mut v8::PinScope<'s, '_>,
5994+ value: storage::StoredValue,
5995+ sentinel: v8::Local<v8::Value>,
5996+) -> Option<(v8::Local<'s, v8::Value>, bool)> {
5997+ match value {
5998+ storage::StoredValue::V8(bytes) if bytes.first() == Some(&STORED_STUB_TAG) => {
5999+ let tree =
6000+ deserialize_storage_value(scope, storage::StoredValue::V8(bytes[1..].to_vec()))?;
6001+ Some((wrap_stored(scope, sentinel, tree), true))
6002+ }
6003+ value => deserialize_storage_value(scope, value).map(|value| (value, false)),
6004+ }
6005+}
6006+
6007+/// `__sc_encode(value)` -> Uint8Array: V8 structured clone, sharing the
6008+/// storage serializer (same delegate, same pinned wire version). The RPC
6009+/// marshalling seam — a failed clone leaves the delegate's throw pending.
6010+fn op_sc_encode(
6011+ scope: &mut v8::PinScope,
6012+ args: v8::FunctionCallbackArguments,
6013+ mut rv: v8::ReturnValue<v8::Value>,
6014+) {
6015+ if let Some(bytes) = serialize_storage_value(scope, args.get(0)) {
6016+ rv.set(bytes_value(scope, bytes));
6017+ }
6018+}
6019+
6020+/// `__sc_decode(bytes)` -> value: inverse of `__sc_encode`.
6021+fn op_sc_decode(
6022+ scope: &mut v8::PinScope,
6023+ args: v8::FunctionCallbackArguments,
6024+ mut rv: v8::ReturnValue<v8::Value>,
6025+) {
6026+ let Some(bytes) = view_bytes(args.get(0)) else {
6027+ let message = v8::String::new(scope, "__sc_decode expects bytes").unwrap();
6028+ let exception = v8::Exception::type_error(scope, message);
6029+ scope.throw_exception(exception);
6030+ return;
6031+ };
6032+ match deserialize_storage_value(scope, storage::StoredValue::V8(bytes)) {
6033+ Some(value) => rv.set(value),
6034+ None => throw_storage_error(scope, "rpc", "corrupt clone payload"),
6035+ }
6036+}
6037+
6038+fn storage_string_array(
6039+ scope: &mut v8::PinScope,
6040+ value: v8::Local<v8::Value>,
6041+) -> std::result::Result<Vec<String>, &'static str> {
6042+ let array = v8::Local::<v8::Array>::try_from(value).map_err(|_| "keys must be an array")?;
6043+ let mut keys = Vec::with_capacity(array.length() as usize);
6044+ for index in 0..array.length() {
6045+ let value = array.get_index(scope, index).ok_or("missing key")?;
6046+ keys.push(value.to_rust_string_lossy(scope));
6047+ }
6048+ Ok(keys)
6049+}
6050+
6051+/// The `bool` reports whether any entry was a stored-stub row, so the
6052+/// caller wraps the whole map only then — plain maps cross unwrapped and
6053+/// the JS side never walks them.
6054+fn storage_entries_map<'s>(
6055+ scope: &mut v8::PinScope<'s, '_>,
6056+ entries: Vec<(String, storage::StoredValue)>,
6057+ sentinel: v8::Local<v8::Value>,
6058+) -> Option<(v8::Local<'s, v8::Map>, bool)> {
6059+ let map = v8::Map::new(scope);
6060+ let mut any_tagged = false;
6061+ for (key, value) in entries {
6062+ let key = v8::String::new(scope, &key)?;
6063+ let (value, tagged) = deserialize_stored(scope, value, sentinel)?;
6064+ any_tagged |= tagged;
6065+ map.set(scope, key.into(), value)?;
6066+ }
6067+ Some((map, any_tagged))
6068+}
6069+
6070+fn throw_storage_error(scope: &mut v8::PinScope, operation: &str, error: impl std::fmt::Display) {
6071+ let message = v8::String::new(scope, &format!("storage.{operation}: {error}")).unwrap();
6072+ let exception = v8::Exception::error(scope, message);
6073+ scope.throw_exception(exception);
6074+}
6075+fn op_storage_delete_all(
6076+ scope: &mut v8::PinScope,
6077+ args: v8::FunctionCallbackArguments,
6078+ _rv: v8::ReturnValue<v8::Value>,
6079+) {
6080+ let cell = args.get(0).to_rust_string_lossy(scope);
6081+ let delete_alarm = args.get(1).boolean_value(scope);
6082+ if let Err(error) = storage::delete_all_with_alarm(&cell, delete_alarm) {
6083+ let message = v8::String::new(scope, &format!("deleteAll: {error}")).unwrap();
6084+ let exception = v8::Exception::error(scope, message);
6085+ scope.throw_exception(exception);
6086+ }
6087+}
6088+
6089+/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href}
6090+/// Backed by the WHATWG-conformant `url` crate.
6091+fn op_url_parse(
6092+ scope: &mut v8::PinScope,
6093+ args: v8::FunctionCallbackArguments,
6094+ mut rv: v8::ReturnValue<v8::Value>,
6095+) {
6096+ let input = args.get(0).to_rust_string_lossy(scope);
6097+ let base = args.get(1);
6098+ let parsed = if base.is_undefined() {
6099+ url::Url::parse(&input)
6100+ } else {
6101+ url::Url::options()
6102+ .base_url(
6103+ url::Url::parse(&base.to_rust_string_lossy(scope))
6104+ .ok()
6105+ .as_ref(),
6106+ )
6107+ .parse(&input)
6108+ };
6109+ let u = match parsed {
6110+ Ok(u) => u,
6111+ Err(e) => {
6112+ let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap();
6113+ let exc = v8::Exception::type_error(scope, msg);
6114+ scope.throw_exception(exc);
6115+ return;
6116+ }
6117+ };
6118+ let o = v8::Object::new(scope);
6119+ let set = |k: &str, v: &str| {
6120+ let key = v8::String::new(scope, k).unwrap();
6121+ let val = v8::String::new(scope, v).unwrap();
6122+ o.set(scope, key.into(), val.into());
6123+ };
6124+ set("protocol", u.scheme());
6125+ set("username", u.username());
6126+ set("password", u.password().unwrap_or(""));
6127+ set("host", u.host_str().unwrap_or(""));
6128+ set("port", &u.port().map(|p| p.to_string()).unwrap_or_default());
6129+ set("pathname", u.path());
6130+ set("search", u.query().unwrap_or(""));
6131+ set("hash", u.fragment().unwrap_or(""));
6132+ set("href", u.as_str());
6133+ rv.set(o.into());
6134+}
6135+
6136+// URLPattern host seam, split like Deno's: pattern parsing and match-input
6137+// canonicalization run in Rust via the `urlpattern` crate; per-match regex
6138+// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the
6139+// boundary — both ops run at construct/match-canonicalize time only.
6140+
6141+/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a
6142+/// pattern string or an init object of string components. Returns
6143+/// per-component `{ patternString, regexpString, groupNameList }` plus
6144+/// `hasRegexpGroups`. Throws TypeError on an invalid pattern.
6145+fn op_urlpattern_parse(
6146+ scope: &mut v8::PinScope,
6147+ args: v8::FunctionCallbackArguments,
6148+ mut rv: v8::ReturnValue<v8::Value>,
6149+) {
6150+ use urlpattern::quirks;
6151+ let input = args.get(0).to_rust_string_lossy(scope);
6152+ let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
6153+ let base = args.get(1);
6154+ let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
6155+ let options = urlpattern::UrlPatternOptions {
6156+ ignore_case: args.get(2).boolean_value(scope),
6157+ };
6158+ let pattern = quirks::process_construct_pattern_input(input, base.as_deref())
6159+ .and_then(|init| quirks::parse_pattern(init, options));
6160+ let p = match pattern {
6161+ Ok(p) => p,
6162+ Err(e) => {
6163+ let msg = v8::String::new(scope, &e.to_string()).unwrap();
6164+ let exc = v8::Exception::type_error(scope, msg);
6165+ scope.throw_exception(exc);
6166+ return;
6167+ }
6168+ };
6169+ let component = |c: &quirks::UrlPatternComponent| {
6170+ serde_json::json!({
6171+ "patternString": c.pattern_string,
6172+ "regexpString": c.regexp_string,
6173+ "groupNameList": c.group_name_list,
6174+ })
6175+ };
6176+ let out = serde_json::json!({
6177+ "protocol": component(&p.protocol),
6178+ "username": component(&p.username),
6179+ "password": component(&p.password),
6180+ "hostname": component(&p.hostname),
6181+ "port": component(&p.port),
6182+ "pathname": component(&p.pathname),
6183+ "search": component(&p.search),
6184+ "hash": component(&p.hash),
6185+ "hasRegexpGroups": p.has_regexp_groups,
6186+ });
6187+ rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
6188+}
6189+
6190+/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in
6191+/// component order (protocol..hash), or `null` when the input does not parse
6192+/// as a URL. Throws TypeError for an init combined with a baseURL argument.
6193+fn op_urlpattern_match_input(
6194+ scope: &mut v8::PinScope,
6195+ args: v8::FunctionCallbackArguments,
6196+ mut rv: v8::ReturnValue<v8::Value>,
6197+) {
6198+ use urlpattern::quirks;
6199+ let input = args.get(0).to_rust_string_lossy(scope);
6200+ let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
6201+ let base = args.get(1);
6202+ let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
6203+ let null = v8::null(scope).into();
6204+ let m = match quirks::process_match_input(input, base.as_deref()) {
6205+ Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) {
6206+ Some(m) => m,
6207+ None => return rv.set(null),
6208+ },
6209+ Ok(None) => return rv.set(null),
6210+ Err(e) => {
6211+ let msg = v8::String::new(scope, &e.to_string()).unwrap();
6212+ let exc = v8::Exception::type_error(scope, msg);
6213+ scope.throw_exception(exc);
6214+ return;
6215+ }
6216+ };
6217+ let out = serde_json::json!([
6218+ m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash,
6219+ ]);
6220+ rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
6221+}
6222+
6223+fn op_atob(
6224+ scope: &mut v8::PinScope,
6225+ args: v8::FunctionCallbackArguments,
6226+ mut rv: v8::ReturnValue<v8::Value>,
6227+) {
6228+ use base64::Engine;
6229+ let input = args.get(0).to_rust_string_lossy(scope);
6230+ let cleaned: String = input.chars().filter(|c| !c.is_whitespace()).collect();
6231+ match base64::engine::general_purpose::STANDARD.decode(cleaned) {
6232+ Ok(bytes) => {
6233+ // atob returns a binary string (latin1)
6234+ let s: String = bytes.iter().map(|&b| b as char).collect();
6235+ rv.set(v8::String::new(scope, &s).unwrap().into());
6236+ }
6237+ Err(_) => {
6238+ let msg = v8::String::new(scope, "Invalid base64").unwrap();
6239+ let exc = v8::Exception::error(scope, msg);
6240+ scope.throw_exception(exc);
6241+ }
6242+ }
6243+}
6244+
6245+// node:util introspection seam: V8-level queries that JS cannot perform,
6246+// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy
6247+// node:async_hooks prelude calls these. The value is V8's
6248+// continuation-preserved embedder data — the primitive Workerd's
6249+// AsyncContextFrame rides — which V8 itself captures and restores
6250+// around every promise reaction. No promise hooks are installed, and an
6251+// isolate that never touches AsyncLocalStorage never sets the value, so
6252+// a bundle that does not import async_hooks pays nothing per promise.
6253+
6254+fn op_als_get(
6255+ scope: &mut v8::PinScope,
6256+ _args: v8::FunctionCallbackArguments,
6257+ mut rv: v8::ReturnValue<v8::Value>,
6258+) {
6259+ rv.set(scope.get_continuation_preserved_embedder_data());
6260+}
6261+
6262+fn op_als_set(
6263+ scope: &mut v8::PinScope,
6264+ args: v8::FunctionCallbackArguments,
6265+ _rv: v8::ReturnValue<v8::Value>,
6266+) {
6267+ scope.set_continuation_preserved_embedder_data(args.get(0));
6268+}
6269+
6270+// node:util prelude calls these; registration is the sole per-isolate cost.
6271+
6272+/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js.
6273+fn op_util_type_flags(
6274+ _scope: &mut v8::PinScope,
6275+ args: v8::FunctionCallbackArguments,
6276+ mut rv: v8::ReturnValue<v8::Value>,
6277+) {
6278+ let v = args.get(0);
6279+ let checks: [bool; 27] = [
6280+ v.is_external(),
6281+ v.is_date(),
6282+ v.is_arguments_object(),
6283+ v.is_big_int_object(),
6284+ v.is_boolean_object(),
6285+ v.is_number_object(),
6286+ v.is_string_object(),
6287+ v.is_symbol_object(),
6288+ v.is_native_error(),
6289+ v.is_reg_exp(),
6290+ v.is_async_function(),
6291+ v.is_generator_function(),
6292+ v.is_generator_object(),
6293+ v.is_promise(),
6294+ v.is_map(),
6295+ v.is_set(),
6296+ v.is_map_iterator(),
6297+ v.is_set_iterator(),
6298+ v.is_weak_map(),
6299+ v.is_weak_set(),
6300+ v.is_array_buffer(),
6301+ v.is_data_view(),
6302+ v.is_shared_array_buffer(),
6303+ v.is_proxy(),
6304+ v.is_module_namespace_object(),
6305+ v.is_typed_array(),
6306+ v.is_array_buffer_view(),
6307+ ];
6308+ let mut flags: u32 = 0;
6309+ for (i, hit) in checks.iter().enumerate() {
6310+ if *hit {
6311+ flags |= 1 << i;
6312+ }
6313+ }
6314+ rv.set_uint32(flags);
6315+}
6316+
6317+fn op_util_constructor_name(
6318+ _scope: &mut v8::PinScope,
6319+ args: v8::FunctionCallbackArguments,
6320+ mut rv: v8::ReturnValue<v8::Value>,
6321+) {
6322+ let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
6323+ return; // undefined
6324+ };
6325+ rv.set(obj.get_constructor_name().into());
6326+}
6327+
6328+/// `[target, handler]` for a proxy, undefined otherwise.
6329+fn op_util_proxy_details(
6330+ scope: &mut v8::PinScope,
6331+ args: v8::FunctionCallbackArguments,
6332+ mut rv: v8::ReturnValue<v8::Value>,
6333+) {
6334+ let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else {
6335+ return;
6336+ };
6337+ let target = proxy.get_target(scope);
6338+ let handler = proxy.get_handler(scope);
6339+ rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into());
6340+}
6341+
6342+/// `[state]` for a pending promise, `[state, result]` otherwise,
6343+/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected.
6344+fn op_util_promise_details(
6345+ scope: &mut v8::PinScope,
6346+ args: v8::FunctionCallbackArguments,
6347+ mut rv: v8::ReturnValue<v8::Value>,
6348+) {
6349+ let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else {
6350+ return;
6351+ };
6352+ let state = match promise.state() {
6353+ v8::PromiseState::Pending => 0,
6354+ v8::PromiseState::Fulfilled => 1,
6355+ v8::PromiseState::Rejected => 2,
6356+ };
6357+ let pending = state == 0;
6358+ let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into();
6359+ let elements = if pending {
6360+ vec![state]
6361+ } else {
6362+ vec![state, promise.result(scope)]
6363+ };
6364+ rv.set(v8::Array::new_with_elements(scope, &elements).into());
6365+}
6366+
6367+/// `[entries, isKeyValue]` for collections and their iterators (V8's
6368+/// PreviewEntries), undefined when V8 has no preview.
6369+fn op_util_preview_entries(
6370+ scope: &mut v8::PinScope,
6371+ args: v8::FunctionCallbackArguments,
6372+ mut rv: v8::ReturnValue<v8::Value>,
6373+) {
6374+ let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
6375+ return;
6376+ };
6377+ let (entries, is_key_value) = obj.preview_entries(scope);
6378+ let Some(entries) = entries else { return };
6379+ let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into();
6380+ rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into());
6381+}
6382+
6383+fn op_alarm_set(
6384+ scope: &mut v8::PinScope,
6385+ args: v8::FunctionCallbackArguments,
6386+ _rv: v8::ReturnValue<v8::Value>,
6387+) {
6388+ let s = args.get(0).to_rust_string_lossy(scope);
6389+ let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64;
6390+ match storage::set_alarm(&s, at) {
6391+ Err(error) => throw_storage_error(scope, "setAlarm", error),
6392+ // Committed immediately: register the wake-entry PUT against the
6393+ // cell's output gate. Inside an explicit transaction (`Ok(None)`)
6394+ // the gate registers at that transaction's commit instead.
6395+ Ok(Some(committed)) if committed >= 0 => spawn_arm_gate(&s, committed),
6396+ Ok(_) => {}
6397+ }
6398+}
6399+fn op_alarm_get(
6400+ scope: &mut v8::PinScope,
6401+ args: v8::FunctionCallbackArguments,
6402+ mut rv: v8::ReturnValue<v8::Value>,
6403+) {
6404+ let s = args.get(0).to_rust_string_lossy(scope);
6405+ match storage::get_alarm(&s) {
6406+ Some(at) => rv.set(v8::Number::new(scope, at as f64).into()),
6407+ None => rv.set(v8::null(scope).into()),
6408+ }
6409+}
6410+fn op_alarm_delete(
6411+ scope: &mut v8::PinScope,
6412+ args: v8::FunctionCallbackArguments,
6413+ _rv: v8::ReturnValue<v8::Value>,
6414+) {
6415+ let s = args.get(0).to_rust_string_lossy(scope);
6416+ if let Err(error) = storage::delete_alarm(&s) {
6417+ throw_storage_error(scope, "deleteAlarm", error);
6418+ }
6419+}
6420+
6421+fn op_btoa(
6422+ scope: &mut v8::PinScope,
6423+ args: v8::FunctionCallbackArguments,
6424+ mut rv: v8::ReturnValue<v8::Value>,
6425+) {
6426+ use base64::Engine;
6427+ let input = args.get(0).to_rust_string_lossy(scope);
6428+ let bytes: Vec<u8> = input.chars().map(|c| c as u8).collect();
6429+ let s = base64::engine::general_purpose::STANDARD.encode(bytes);
6430+ rv.set(v8::String::new(scope, &s).unwrap().into());
6431+}
6432+
6433+// ---- WHATWG legacy text decoders (encoding_rs) ----
6434+//
6435+// TextDecoder's utf-8/utf-16 hot path stays pure JS in
6436+// src/js/text_encoding.js; these ops back every other WHATWG label
6437+// (windows-1252, Big5, GBK/GB18030, ISO-2022-JP, x-user-defined, …).
6438+// Streaming decoders live in a thread-local table keyed by id; JS frees
6439+// one on the final decode (last=true), on a fatal error (encoding_rs
6440+// poisons an errored decoder), or via FinalizationRegistry when a
6441+// mid-stream decoder is abandoned. Ids are never reused, so a late
6442+// finalizer free of an already-closed id is a no-op.
6443+
6444+thread_local! {
6445+ static TEXT_DECODERS: std::cell::RefCell<
6446+ std::collections::HashMap<u64, encoding_rs::Decoder>> =
6447+ Default::default();
6448+ static TEXT_DECODER_NEXT: std::cell::Cell<u64> =
6449+ const { std::cell::Cell::new(1) };
6450+}
6451+
6452+/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined
6453+/// for unknown labels and the replacement encoding (RangeError in JS).
6454+fn op_text_decoder_label(
6455+ scope: &mut v8::PinScope,
6456+ args: v8::FunctionCallbackArguments,
6457+ mut rv: v8::ReturnValue<v8::Value>,
6458+) {
6459+ let label = args.get(0).to_rust_string_lossy(scope);
6460+ if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) {
6461+ let name = enc.name().to_ascii_lowercase();
6462+ rv.set(v8::String::new(scope, &name).unwrap().into());
6463+ }
6464+}
6465+
6466+/// `$$textDecoderNew(name, ignoreBOM)` -> id.
6467+fn op_text_decoder_new(
6468+ scope: &mut v8::PinScope,
6469+ args: v8::FunctionCallbackArguments,
6470+ mut rv: v8::ReturnValue<v8::Value>,
6471+) {
6472+ let name = args.get(0).to_rust_string_lossy(scope);
6473+ let ignore_bom = args.get(1).boolean_value(scope);
6474+ let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
6475+ let dec = if ignore_bom {
6476+ enc.new_decoder_without_bom_handling()
6477+ } else {
6478+ enc.new_decoder_with_bom_removal()
6479+ };
6480+ let id = TEXT_DECODER_NEXT.with(|next| {
6481+ let id = next.get();
6482+ next.set(id + 1);
6483+ id
6484+ });
6485+ TEXT_DECODERS.with(|table| table.borrow_mut().insert(id, dec));
6486+ rv.set(v8::Number::new(scope, id as f64).into());
6487+}
6488+
6489+/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the
6490+/// decoder when `last` is true or on a fatal malformed sequence
6491+/// (TypeError).
6492+fn op_text_decoder_decode(
6493+ scope: &mut v8::PinScope,
6494+ args: v8::FunctionCallbackArguments,
6495+ mut rv: v8::ReturnValue<v8::Value>,
6496+) {
6497+ let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
6498+ let bytes = view_bytes(args.get(1)).unwrap_or_default();
6499+ let fatal = args.get(2).boolean_value(scope);
6500+ let last = args.get(3).boolean_value(scope);
6501+ // Per spec an empty streaming chunk is a no-op, but encoding_rs
6502+ // 0.8 flushes a pending multibyte lead when fed an empty non-last
6503+ // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead
6504+ // of あ). Skip the decoder entirely.
6505+ if bytes.is_empty() && !last {
6506+ rv.set(v8::String::empty(scope).into());
6507+ return;
6508+ }
6509+ let mut dec = TEXT_DECODERS
6510+ .with(|table| table.borrow_mut().remove(&id))
6511+ .expect("JS holds the only live id");
6512+ let mut out = String::new();
6513+ let ok = if fatal {
6514+ let cap = dec
6515+ .max_utf8_buffer_length_without_replacement(bytes.len())
6516+ .unwrap();
6517+ out.reserve(cap);
6518+ matches!(
6519+ dec.decode_to_string_without_replacement(&bytes, &mut out, last),
6520+ (encoding_rs::DecoderResult::InputEmpty, _),
6521+ )
6522+ } else {
6523+ let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap();
6524+ out.reserve(cap);
6525+ let _ = dec.decode_to_string(&bytes, &mut out, last);
6526+ true
6527+ };
6528+ if !ok {
6529+ let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap();
6530+ let exc = v8::Exception::type_error(scope, msg);
6531+ scope.throw_exception(exc);
6532+ return;
6533+ }
6534+ if !last {
6535+ TEXT_DECODERS.with(|table| table.borrow_mut().insert(id, dec));
6536+ }
6537+ rv.set(v8::String::new(scope, &out).unwrap().into());
6538+}
6539+
6540+/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder
6541+/// abandoned mid-stream.
6542+fn op_text_decoder_free(
6543+ scope: &mut v8::PinScope,
6544+ args: v8::FunctionCallbackArguments,
6545+ _rv: v8::ReturnValue<v8::Value>,
6546+) {
6547+ let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
6548+ TEXT_DECODERS.with(|table| table.borrow_mut().remove(&id));
6549+}
6550+
6551+// ---- the JS harness: Web API + the DO object model ----
6552+
6553+/// Per-process compiled-bytecode cache for the fixed bootstrap scripts.
6554+/// Every cell wake pays a fresh isolate, and without this each one re-parses
6555+/// and re-compiles the same ~23k lines of prelude + harness — the single
6556+/// largest slice of hibernated-wake latency. The first isolate compiles
6557+/// eagerly and publishes the cache; every later isolate consumes it and only
6558+/// executes.
6559+type BootstrapCache = std::collections::HashMap<&'static str, std::sync::Arc<Vec<u8>>>;
6560+
6561+fn bootstrap_code_cache() -> &'static std::sync::Mutex<BootstrapCache> {
6562+ static CACHE: std::sync::OnceLock<std::sync::Mutex<BootstrapCache>> =
6563+ std::sync::OnceLock::new();
6564+ CACHE.get_or_init(Default::default)
6565+}
6566+
6567+fn run_bootstrap_script(scope: &mut v8::PinScope, name: &'static str, src: &str) -> Result<()> {
6568+ use v8::script_compiler::CompileOptions;
6569+ use v8::script_compiler::NoCacheReason;
6570+ let code = v8::String::new(scope, src).unwrap();
6571+ let cached = bootstrap_code_cache().lock().unwrap().get(name).cloned();
6572+ let unbound = match cached {
6573+ // `CachedData` borrows `bytes`; the Arc binding outlives the Source.
6574+ Some(bytes) => {
6575+ let data = v8::script_compiler::CachedData::new(&bytes);
6576+ let mut source = v8::script_compiler::Source::new_with_cached_data(code, None, data);
6577+ let unbound = v8::script_compiler::compile_unbound_script(
6578+ scope,
6579+ &mut source,
6580+ CompileOptions::ConsumeCodeCache,
6581+ NoCacheReason::NoReason,
6582+ )
6583+ .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
6584+ debug_assert!(
6585+ !source.get_cached_data().is_some_and(|data| data.rejected()),
6586+ "code cache rejected for {name}"
6587+ );
6588+ unbound
6589+ }
6590+ None => {
6591+ let mut source = v8::script_compiler::Source::new(code, None);
6592+ // Eager: a lazily-compiled cache would push function-body compile
6593+ // cost back into every consumer's first request.
6594+ let unbound = v8::script_compiler::compile_unbound_script(
6595+ scope,
6596+ &mut source,
6597+ CompileOptions::EagerCompile,
6598+ NoCacheReason::NoReason,
6599+ )
6600+ .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
6601+ if let Some(data) = unbound.create_code_cache() {
6602+ bootstrap_code_cache()
6603+ .lock()
6604+ .unwrap()
6605+ .insert(name, std::sync::Arc::new(data.to_vec()));
6606+ }
6607+ unbound
6608+ }
6609+ };
6610+ unbound
6611+ .bind_to_current_context(scope)
6612+ .run(scope)
6613+ .ok_or_else(|| anyhow!("bootstrap run {name}"))?;
6614+ Ok(())
6615+}
6616+
6617+/// WPT-conformant Web APIs: TextEncoder, URL/URLSearchParams, atob/btoa, and
6618+/// Headers. Run once per isolate before the Cells/Cloudflare-specific harness.
6619+fn install_prelude(scope: &mut v8::PinScope) -> Result<()> {
6620+ const PRELUDE: &[(&str, &str)] = &[
6621+ ("text_encoding.js", include_str!("js/text_encoding.js")),
6622+ (
6623+ "url_search_params.js",
6624+ include_str!("js/url_search_params.js"),
6625+ ),
6626+ ("url.js", include_str!("js/url.js")),
6627+ ("atob_btoa.js", include_str!("js/atob_btoa.js")),
6628+ ("headers.js", include_str!("js/headers.js")),
6629+ ("streams.js", include_str!("js/streams.js")),
6630+ ("writable_stream.js", include_str!("js/writable_stream.js")),
6631+ (
6632+ "text_encoding_streams.js",
6633+ include_str!("js/text_encoding_streams.js"),
6634+ ),
6635+ ];
6636+ for (name, src) in PRELUDE {
6637+ run_bootstrap_script(scope, name, src)?;
6638+ }
6639+ Ok(())
6640+}
6641+
6642+fn install_harness(scope: &mut v8::PinScope) -> Result<()> {
6643+ run_bootstrap_script(scope, "harness.js", include_str!("js/harness.js"))?;
6644+ run_bootstrap_script(scope, "crypto.js", include_str!("js/crypto.js"))
6645+}
6646+
6647+fn register_class(scope: &mut v8::PinScope, name: &str, cls: v8::Local<v8::Value>) -> Result<()> {
6648+ let ctx = scope.get_current_context();
6649+ let global = ctx.global(scope);
6650+ let ck = v8::String::new(scope, "__cell").unwrap();
6651+ let cell = global
6652+ .get(scope, ck.into())
6653+ .unwrap()
6654+ .to_object(scope)
6655+ .unwrap();
6656+ let clk = v8::String::new(scope, "classes").unwrap();
6657+ let classes = cell
6658+ .get(scope, clk.into())
6659+ .unwrap()
6660+ .to_object(scope)
6661+ .unwrap();
6662+ let nk = v8::String::new(scope, name).unwrap();
6663+ classes.set(scope, nk.into(), cls);
6664+ Ok(())
6665+}
6666+
6667+/// Populate `cloudflare:workers` `exports` with the worker module's own exports:
6668+/// a Durable Object class is exposed as its namespace (idFromName/get/RPC), any
6669+/// other export by value. `default` is omitted (it is the fetch entrypoint, not
6670+/// an importable export). Mirrors Workerd's `import { exports }` surface.
6671+fn populate_cf_exports(
6672+ scope: &mut v8::PinScope,
6673+ ns: v8::Local<v8::Object>,
6674+ do_classes: &[String],
6675+) -> Result<()> {
6676+ let context = scope.get_current_context();
6677+ let global = context.global(scope);
6678+ let cf = global
6679+ .get(scope, v8::String::new(scope, "__cf").unwrap().into())
6680+ .and_then(|value| value.to_object(scope))
6681+ .ok_or_else(|| anyhow!("missing __cf runtime state"))?;
6682+ let exports = cf
6683+ .get(scope, v8::String::new(scope, "exports").unwrap().into())
6684+ .and_then(|value| value.to_object(scope))
6685+ .ok_or_else(|| anyhow!("missing __cf.exports"))?;
6686+ let cell = global
6687+ .get(scope, v8::String::new(scope, "__cell").unwrap().into())
6688+ .and_then(|value| value.to_object(scope))
6689+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
6690+ let make_ns: v8::Local<v8::Function> = cell
6691+ .get(
6692+ scope,
6693+ v8::String::new(scope, "makeNamespace").unwrap().into(),
6694+ )
6695+ .and_then(|value| value.try_into().ok())
6696+ .ok_or_else(|| anyhow!("missing __cell.makeNamespace"))?;
6697+ let do_set: std::collections::HashSet<&str> = do_classes.iter().map(String::as_str).collect();
6698+ let names = ns
6699+ .get_own_property_names(scope, Default::default())
6700+ .ok_or_else(|| anyhow!("no module export names"))?;
6701+ for index in 0..names.length() {
6702+ let name_value = names.get_index(scope, index).unwrap();
6703+ let name = name_value.to_rust_string_lossy(scope);
6704+ if name == "default" {
6705+ continue;
6706+ }
6707+ let export_value = if do_set.contains(name.as_str()) {
6708+ let arg = v8::String::new(scope, &name).unwrap().into();
6709+ make_ns
6710+ .call(scope, cell.into(), &[arg])
6711+ .ok_or_else(|| anyhow!("makeNamespace({name}) failed"))?
6712+ } else {
6713+ ns.get(scope, name_value)
6714+ .ok_or_else(|| anyhow!("export {name}"))?
6715+ };
6716+ let key = v8::String::new(scope, &name).unwrap();
6717+ exports.set(scope, key.into(), export_value);
6718+ }
6719+ Ok(())
6720+}
6721+
6722+fn inject_namespace_keys(
6723+ scope: &mut v8::PinScope,
6724+ script_name: &str,
6725+ do_classes: &[String],
6726+) -> Result<()> {
6727+ let context = scope.get_current_context();
6728+ let global = context.global(scope);
6729+ let cell_key = v8::String::new(scope, "__cell").unwrap();
6730+ let cell = global
6731+ .get(scope, cell_key.into())
6732+ .and_then(|value| value.to_object(scope))
6733+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
6734+ let keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
6735+ let keys = cell
6736+ .get(scope, keys_key.into())
6737+ .and_then(|value| value.to_object(scope))
6738+ .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
6739+ let script_key = v8::String::new(scope, "script").unwrap();
6740+ let script_value = v8::String::new(scope, script_name).unwrap();
6741+ cell.set(scope, script_key.into(), script_value.into());
6742+ for class_name in do_classes {
6743+ let class_key = v8::String::new(scope, class_name).unwrap();
6744+ let namespace_key = format!("cells:v1:{}:{script_name}:{class_name}", script_name.len(),);
6745+ let namespace_key = v8::String::new(scope, &namespace_key).unwrap();
6746+ if !keys
6747+ .set(scope, class_key.into(), namespace_key.into())
6748+ .unwrap_or(false)
6749+ {
6750+ anyhow::bail!("could not register namespace key for {class_name}");
6751+ }
6752+ }
6753+ Ok(())
6754+}
6755+
6756+/// `globalThis.Cloudflare.compatibilityFlags`. Only flags Cells actually
6757+/// honours are listed; a flag Cells does not model is absent (falsy) rather
6758+/// than reported as enabled.
6759+///
6760+/// Built through the V8 object API rather than by compiling a snippet: this
6761+/// runs on every isolate load, and a separate `Script::compile` there cost
6762+/// ~100us per worker.
6763+fn inject_compatibility_flags(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
6764+ let context = scope.get_current_context();
6765+ let global = context.global(scope);
6766+ let flags = v8::Object::new(scope);
6767+ let set_flag = |scope: &mut v8::PinScope, name: &str, value: bool| {
6768+ let key = v8::String::new(scope, name).unwrap();
6769+ let value = v8::Boolean::new(scope, value);
6770+ flags.set(scope, key.into(), value.into());
6771+ };
6772+ set_flag(scope, "upper_case_all_http_methods", true);
6773+ // Cells' async stream/pipe methods return rejected promises
6774+ // rather than throwing synchronously, which is exactly the
6775+ // behavior this flag names.
6776+ set_flag(scope, "capture_async_api_throws", true);
6777+ set_flag(
6778+ scope,
6779+ "delete_all_deletes_alarm",
6780+ compat.delete_all_deletes_alarm,
6781+ );
6782+ set_flag(scope, "js_rpc", compat.js_rpc);
6783+ set_flag(
6784+ scope,
6785+ "fetcher_no_get_put_delete",
6786+ !compat.fetcher_get_put_delete,
6787+ );
6788+ let cloudflare = v8::Object::new(scope);
6789+ let key = v8::String::new(scope, "compatibilityFlags").unwrap();
6790+ cloudflare.set(scope, key.into(), flags.into());
6791+ let key = v8::String::new(scope, "Cloudflare").unwrap();
6792+ global.set(scope, key.into(), cloudflare.into());
6793+ Ok(())
6794+}
6795+
6796+fn build_env(scope: &mut v8::PinScope, config: &WorkerConfig) -> Result<()> {
6797+ let script_name = config.script_name.as_str();
6798+ let bindings = config.bindings.as_slice();
6799+ let r2_bindings = config.r2_bindings.as_slice();
6800+ let ai_binding = config.ai_binding.as_deref();
6801+ let vars = config.vars.as_slice();
6802+ let services = config.services.as_slice();
6803+ let asset_binding = config.asset_binding.as_deref();
6804+ // call the harness: for each binding, env[bindingName] = makeNamespace(className)
6805+ let src = {
6806+ let mut lines = String::from("(() => { const e = __cell.env;\n");
6807+ for (bname, cname) in bindings {
6808+ lines.push_str(&format!(
6809+ "e[{:?}] = __cell.makeNamespace({:?});\n",
6810+ bname, cname
6811+ ));
6812+ }
6813+ for name in r2_bindings {
6814+ lines.push_str(&format!("e[{:?}] = __makeR2Bucket({:?});\n", name, name));
6815+ }
6816+ if let (Some(name), Ok(url)) = (ai_binding, std::env::var("CELLD_AI_URL")) {
6817+ lines.push_str(&format!("e[{:?}] = __makeAiBinding({:?});\n", name, url));
6818+ }
6819+ for (binding, script, entrypoint) in services {
6820+ let entrypoint = match entrypoint {
6821+ Some(name) => format!("{name:?}"),
6822+ None => "null".to_string(),
6823+ };
6824+ lines.push_str(&format!(
6825+ "e[{:?}] = __makeServiceBinding({:?}, {});\n",
6826+ binding, script, entrypoint
6827+ ));
6828+ }
6829+ for (name, value) in vars {
6830+ lines.push_str(&format!("e[{:?}] = {:?};\n", name, value));
6831+ }
6832+ if let Some(name) = asset_binding {
6833+ lines.push_str(&format!(
6834+ "e[{:?}] = __makeAssetsBinding({:?});\n",
6835+ name, script_name
6836+ ));
6837+ }
6838+ if let Some(name) = config.loader_binding.as_deref() {
6839+ lines.push_str(&format!("e[{:?}] = __makeLoader();\n", name));
6840+ }
6841+ // A loaded worker's caller-supplied `env` (plain JSON values only in
6842+ // the walking skeleton) merges last, over the declared bindings.
6843+ if let Some(env) = config.loader_env.as_deref() {
6844+ lines.push_str(&format!("Object.assign(e, {});\n", env));
6845+ }
6846+ lines.push_str("})();");
6847+ lines
6848+ };
6849+ let code = v8::String::new(scope, &src).unwrap();
6850+ let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("env compile"))?;
6851+ s.run(scope).ok_or_else(|| anyhow!("env run"))?;
6852+ Ok(())
6853+}
6854+
6855+/// Record every exported class deriving from `WorkerEntrypoint` in
6856+/// `__cell.entrypoints`, so a service binding with `entrypoint = "Name"` can
6857+/// resolve it, and every export deriving from `DurableObject` in
6858+/// `__cell.doExports`, so misrouting a DO class as a stateless entrypoint is
6859+/// reported as such (Workerd getExportedHandler()). Runs once per load; the
6860+/// check is a prototype walk, not a call into user code.
6861+fn register_entrypoints(scope: &mut v8::PinScope, ns: v8::Local<v8::Object>) -> Result<()> {
6862+ let context = scope.get_current_context();
6863+ let global = context.global(scope);
6864+ let cell_key = v8::String::new(scope, "__cell").unwrap();
6865+ let cell = global
6866+ .get(scope, cell_key.into())
6867+ .and_then(|value| value.to_object(scope))
6868+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
6869+ let key = v8::String::new(scope, "entrypoints").unwrap();
6870+ let entrypoints = cell
6871+ .get(scope, key.into())
6872+ .and_then(|value| value.to_object(scope))
6873+ .ok_or_else(|| anyhow!("missing entrypoint registry"))?;
6874+ let key = v8::String::new(scope, "objectEntrypoints").unwrap();
6875+ let object_entrypoints = cell
6876+ .get(scope, key.into())
6877+ .and_then(|value| value.to_object(scope))
6878+ .ok_or_else(|| anyhow!("missing object-entrypoint registry"))?;
6879+ let key = v8::String::new(scope, "doExports").unwrap();
6880+ let do_exports = cell
6881+ .get(scope, key.into())
6882+ .and_then(|value| value.to_object(scope))
6883+ .ok_or_else(|| anyhow!("missing doExports registry"))?;
6884+ let cf_key = v8::String::new(scope, "__cf").unwrap();
6885+ let cf = global
6886+ .get(scope, cf_key.into())
6887+ .and_then(|value| value.to_object(scope))
6888+ .ok_or_else(|| anyhow!("missing __cf"))?;
6889+ let key = v8::String::new(scope, "WorkerEntrypoint").unwrap();
6890+ let entrypoint_base = cf
6891+ .get(scope, key.into())
6892+ .ok_or_else(|| anyhow!("missing WorkerEntrypoint base"))?;
6893+ let key = v8::String::new(scope, "DurableObject").unwrap();
6894+ let durable_base = cf
6895+ .get(scope, key.into())
6896+ .ok_or_else(|| anyhow!("missing DurableObject base"))?;
6897+ let Some(names) = ns.get_own_property_names(scope, Default::default()) else {
6898+ return Ok(());
6899+ };
6900+ let yes = v8::Boolean::new(scope, true);
6901+ for index in 0..names.length() {
6902+ let Some(name) = names.get_index(scope, index) else {
6903+ continue;
6904+ };
6905+ let Some(value) = ns.get(scope, name) else {
6906+ continue;
6907+ };
6908+ if !value.is_function() {
6909+ // A plain-object export is Workerd's non-class entrypoint; its
6910+ // handler functions dispatch as fn(arg, env, ctx).
6911+ if value.is_object() {
6912+ object_entrypoints.set(scope, name, value);
6913+ }
6914+ continue;
6915+ }
6916+ // Walk the prototype chain rather than calling anything.
6917+ let mut proto = value.to_object(scope).and_then(|o| o.get_prototype(scope));
6918+ while let Some(current) = proto {
6919+ if current == entrypoint_base {
6920+ entrypoints.set(scope, name, value);
6921+ break;
6922+ }
6923+ if current == durable_base {
6924+ do_exports.set(scope, name, yes.into());
6925+ break;
6926+ }
6927+ proto = current
6928+ .to_object(scope)
6929+ .and_then(|o| o.get_prototype(scope));
6930+ }
6931+ }
6932+ Ok(())
6933+}
6934+
6935+/// Mark which cell scopes are local to this node and record the node id. Every
6936+/// other scope routes cross-node via `__do_call`.
6937+fn inject_routing(scope: &mut v8::PinScope, owned: &[String], node: &str) -> Result<()> {
6938+ let mut src = format!("(() => {{ __cell.node = {node:?};\n");
6939+ for s in owned {
6940+ src.push_str(&format!("__cell.owned[{s:?}] = true;\n"));
6941+ }
6942+ src.push_str("})();");
6943+ let code = v8::String::new(scope, &src).unwrap();
6944+ let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("routing compile"))?;
6945+ s.run(scope).ok_or_else(|| anyhow!("routing run"))?;
6946+ Ok(())
6947+}
6948+
6949+fn inject_storage_compatibility(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
6950+ let source = format!(
6951+ "__cell.deleteAllDeletesAlarm = {};\n\
6952+ __cell.compat.jsRpc = {};\n\
6953+ __cell.compat.fetcherGetPutDelete = {};\n\
6954+ __cell.compat.websocketStandardBinaryType = {};",
6955+ compat.delete_all_deletes_alarm,
6956+ compat.js_rpc,
6957+ compat.fetcher_get_put_delete,
6958+ compat.websocket_standard_binary_type,
6959+ );
6960+ let code = v8::String::new(scope, &source).unwrap();
6961+ let script =
6962+ v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compatibility compile"))?;
6963+ script
6964+ .run(scope)
6965+ .ok_or_else(|| anyhow!("compatibility run"))?;
6966+ Ok(())
6967+}
6968+
6969+fn harness_env<'s>(scope: &mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>> {
6970+ let ctx = scope.get_current_context();
6971+ let global = ctx.global(scope);
6972+ let ck = v8::String::new(scope, "__cell").unwrap();
6973+ let cell = global
6974+ .get(scope, ck.into())
6975+ .unwrap()
6976+ .to_object(scope)
6977+ .unwrap();
6978+ let ek = v8::String::new(scope, "env").unwrap();
6979+ Ok(cell.get(scope, ek.into()).unwrap())
6980+}
6981+
6982+fn begin_event_context<'s>(scope: &mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>> {
6983+ let global = scope.get_current_context().global(scope);
6984+ let key = v8::String::new(scope, "__beginEvent").unwrap();
6985+ let function: v8::Local<v8::Function> = global
6986+ .get(scope, key.into())
6987+ .ok_or_else(|| anyhow!("no __beginEvent"))?
6988+ .try_into()
6989+ .map_err(|_| anyhow!("__beginEvent is not a function"))?;
6990+ let recv = v8::undefined(scope).into();
6991+ function
6992+ .call(scope, recv, &[])
6993+ .ok_or_else(|| anyhow!("__beginEvent threw"))
6994+}
6995+
6996+fn end_event_context<'s>(
6997+ scope: &mut v8::PinScope<'s, '_>,
6998+) -> Result<Option<v8::Local<'s, v8::Promise>>> {
6999+ let global = scope.get_current_context().global(scope);
7000+ let key = v8::String::new(scope, "__endEvent").unwrap();
7001+ let function: v8::Local<v8::Function> = global
7002+ .get(scope, key.into())
7003+ .ok_or_else(|| anyhow!("no __endEvent"))?
7004+ .try_into()
7005+ .map_err(|_| anyhow!("__endEvent is not a function"))?;
7006+ let recv = v8::undefined(scope).into();
7007+ let value = function
7008+ .call(scope, recv, &[])
7009+ .ok_or_else(|| anyhow!("__endEvent threw"))?;
7010+ if value.is_null_or_undefined() {
7011+ Ok(None)
7012+ } else {
7013+ Ok(Some(value.try_into().map_err(|_| {
7014+ anyhow!("__endEvent did not return a promise")
7015+ })?))
7016+ }
7017+}
7018+
7019+// ---- module compilation + request/response marshalling ----
7020+
7021+fn compile_module<'s>(
7022+ scope: &mut v8::PinScope<'s, '_>,
7023+ name: &str,
7024+ src: &str,
7025+) -> Option<v8::Local<'s, v8::Module>> {
7026+ let name = v8::String::new(scope, name)?;
7027+ let source = v8::String::new(scope, src)?;
7028+ let origin = v8::ScriptOrigin::new(
7029+ scope,
7030+ name.into(),
7031+ 0,
7032+ 0,
7033+ false,
7034+ 0,
7035+ None,
7036+ false,
7037+ false,
7038+ true,
7039+ None,
7040+ );
7041+ let mut src = v8::script_compiler::Source::new(source, Some(&origin));
7042+ v8::script_compiler::compile_module(scope, &mut src)
7043+}
7044+
7045+thread_local! {
7046+ // specifier -> pre-compiled stub module, consulted by `resolve_external`
7047+ // while V8 statically links a real worker bundle's imports.
7048+ static MODREG: RefCell<HashMap<String, v8::Global<v8::Module>>> =
7049+ RefCell::new(HashMap::new());
7050+}
7051+
7052+/// Scan a bundle for its external (`cloudflare:*` / `node:*`) imports and the
7053+/// named/default bindings pulled from each. V8 static-links these, so a stub
7054+/// must provide exactly these names; namespace imports (`* as x`) need none.
7055+/// Is `spec` an external builtin (`node:*`, `cloudflare:*`, or a bare node
7056+/// builtin)? esbuild bundles every npm dep inline and leaves only builtins
7057+/// external, so a remaining bare specifier is a node builtin.
7058+fn is_external(spec: &str) -> bool {
7059+ const BARE: &[&str] = &[
7060+ "path",
7061+ "os",
7062+ "fs",
7063+ "fs/promises",
7064+ "crypto",
7065+ "stream",
7066+ "util",
7067+ "util/types",
7068+ "assert",
7069+ "module",
7070+ "process",
7071+ "tty",
7072+ "url",
7073+ "v8",
7074+ "constants",
7075+ "buffer",
7076+ "events",
7077+ "zlib",
7078+ "child_process",
7079+ "http",
7080+ "https",
7081+ "http2",
7082+ "net",
7083+ "tls",
7084+ "dns",
7085+ "readline",
7086+ "string_decoder",
7087+ "querystring",
7088+ "async_hooks",
7089+ "perf_hooks",
7090+ "worker_threads",
7091+ "vm",
7092+ "diagnostics_channel",
7093+ "timers",
7094+ "inspector",
7095+ "dgram",
7096+ "cluster",
7097+ "punycode",
7098+ "sqlite",
7099+ ];
7100+ if spec.starts_with("node:") || spec.starts_with("cloudflare:") {
7101+ return true;
7102+ }
7103+ // bare builtin, or a builtin submodule like `stream/promises`
7104+ BARE.contains(&spec) || BARE.contains(&spec.split('/').next().unwrap_or(""))
7105+}
7106+
7107+fn scan_external_imports(
7108+ src: &str,
7109+) -> std::collections::BTreeMap<String, std::collections::BTreeSet<String>> {
7110+ let re = regex::Regex::new(r#"import\s+([^;]*?)\s*from\s*["']([^"']+)["']"#).unwrap();
7111+ let braces = regex::Regex::new(r"\{([^}]*)\}").unwrap();
7112+ let mut map: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
7113+ Default::default();
7114+ for cap in re.captures_iter(src) {
7115+ if !is_external(&cap[2]) {
7116+ continue;
7117+ }
7118+ let clause = cap[1].trim();
7119+ let set = map.entry(cap[2].to_string()).or_default();
7120+ if let Some(b) = braces.captures(clause) {
7121+ for part in b[1].split(',') {
7122+ let name = part.split_whitespace().next().unwrap_or("");
7123+ // A commented-out binding inside the braces is not a name.
7124+ if !name.is_empty() && !name.starts_with("//") {
7125+ set.insert(name.to_string());
7126+ }
7127+ }
7128+ }
7129+ let head = clause
7130+ .split(['{', '*'])
7131+ .next()
7132+ .unwrap_or("")
7133+ .trim()
7134+ .trim_end_matches(',')
7135+ .trim();
7136+ if !head.is_empty() {
7137+ set.insert("default".into());
7138+ } // default import
7139+ // `import * as x` consumes the whole namespace; the stub must then
7140+ // export the module's full surface, not just the scanned names.
7141+ if clause.contains('*') {
7142+ set.insert("*".into());
7143+ }
7144+ }
7145+ map
7146+}
7147+
7148+/// A stub ES module for `spec`. `cloudflare:workers` binds the real DO base
7149+/// class from the harness; every other builtin routes to a pass-through proxy
7150+/// so evaluation never crashes on an unsupported node/cf API.
7151+/// A module Cells really implements in JS. Its source is injected into the
7152+/// generated stub module, and `register_stubs` only builds stubs for
7153+/// specifiers a bundle actually imports — so an isolate that never imports it
7154+/// pays nothing at load. `global` is what the source defines and doubles as
7155+/// the redefinition guard when a bundle imports several aliases.
7156+struct LazyModule {
7157+ specs: &'static [&'static str],
7158+ global: &'static str,
7159+ source: &'static str,
7160+}
7161+
7162+const LAZY_MODULES: &[LazyModule] = &[
7163+ LazyModule {
7164+ specs: &["assert", "node:assert"],
7165+ global: "__assertModule",
7166+ source: include_str!("js/node_assert.js"),
7167+ },
7168+ LazyModule {
7169+ specs: &["assert/strict", "node:assert/strict"],
7170+ global: "__assertStrictModule",
7171+ source: include_str!("js/node_assert.js"),
7172+ },
7173+ LazyModule {
7174+ specs: &["timers/promises", "node:timers/promises"],
7175+ global: "__timersPromises",
7176+ source: include_str!("js/node_timers.js"),
7177+ },
7178+ LazyModule {
7179+ specs: &["test", "node:test", "node:test/reporters"],
7180+ global: "__nodeTest",
7181+ source: include_str!("js/node_test.js"),
7182+ },
7183+ LazyModule {
7184+ specs: &["util", "node:util"],
7185+ global: "__utilModule",
7186+ source: include_str!("js/node_util.js"),
7187+ },
7188+ // Same source, different namespace: node:util/types has the type
7189+ // predicates as its named exports. The shared source defines both
7190+ // globals, so either entry's guard covers the other.
7191+ LazyModule {
7192+ specs: &["util/types", "node:util/types"],
7193+ global: "__utilTypesModule",
7194+ source: include_str!("js/node_util.js"),
7195+ },
7196+ LazyModule {
7197+ specs: &["events", "node:events"],
7198+ global: "__eventsModule",
7199+ source: include_str!("js/node_events.js"),
7200+ },
7201+ LazyModule {
7202+ specs: &["path", "node:path", "path/posix", "node:path/posix"],
7203+ global: "__pathModule",
7204+ source: include_str!("js/node_path.js"),
7205+ },
7206+ // Same source; either entry's guard covers the other.
7207+ LazyModule {
7208+ specs: &["path/win32", "node:path/win32"],
7209+ global: "__pathWin32Module",
7210+ source: include_str!("js/node_path.js"),
7211+ },
7212+ // Shares its source with the `Buffer` LAZY_GLOBALS entry; the script
7213+ // is self-guarded, so whichever seam runs first wins and the other
7214+ // reuses the same classes.
7215+ LazyModule {
7216+ specs: &["buffer", "node:buffer"],
7217+ global: "__buffer",
7218+ source: include_str!("js/node_buffer.js"),
7219+ },
7220+ LazyModule {
7221+ specs: &["crypto", "node:crypto"],
7222+ global: "__cryptoModule",
7223+ source: include_str!("js/node_crypto.js"),
7224+ },
7225+ LazyModule {
7226+ specs: &["async_hooks", "node:async_hooks"],
7227+ global: "__asyncHooksModule",
7228+ source: include_str!("js/node_async_hooks.js"),
7229+ },
7230+ // One source defines the whole stream family; whichever entry runs
7231+ // first, its guard covers the others.
7232+ LazyModule {
7233+ specs: &["stream", "node:stream"],
7234+ global: "__streamModule",
7235+ source: include_str!("js/node_stream.js"),
7236+ },
7237+ LazyModule {
7238+ specs: &["stream/promises", "node:stream/promises"],
7239+ global: "__streamPromises",
7240+ source: include_str!("js/node_stream.js"),
7241+ },
7242+ LazyModule {
7243+ specs: &["stream/web", "node:stream/web"],
7244+ global: "__streamWeb",
7245+ source: include_str!("js/node_stream.js"),
7246+ },
7247+ LazyModule {
7248+ specs: &["stream/consumers", "node:stream/consumers"],
7249+ global: "__streamConsumers",
7250+ source: include_str!("js/node_stream.js"),
7251+ },
7252+];
7253+
7254+/// A global whose definition only compiles when something reads the name.
7255+/// One script may define several names; touching any of them installs them
7256+/// all. A bundle that names none pays only the `SetLazyDataProperty` calls
7257+/// at boot, so this is where a new global belongs unless the prelude has to
7258+/// see it.
7259+struct LazyGlobal {
7260+ names: &'static [&'static str],
7261+ source: &'static str,
7262+}
7263+
7264+const LAZY_GLOBALS: &[LazyGlobal] = &[
7265+ LazyGlobal {
7266+ names: &["IdentityTransformStream", "FixedLengthStream"],
7267+ source: include_str!("js/identity_transform_stream.js"),
7268+ },
7269+ LazyGlobal {
7270+ names: &["CompressionStream", "DecompressionStream"],
7271+ source: include_str!("js/compression_streams.js"),
7272+ },
7273+ LazyGlobal {
7274+ names: &[
7275+ "ReadableByteStreamController",
7276+ "ReadableStreamBYOBReader",
7277+ "ReadableStreamBYOBRequest",
7278+ ],
7279+ source: include_str!("js/byte_streams.js"),
7280+ },
7281+ LazyGlobal {
7282+ names: &["Buffer"],
7283+ source: include_str!("js/node_buffer.js"),
7284+ },
7285+ LazyGlobal {
7286+ names: &["setImmediate", "clearImmediate"],
7287+ source: include_str!("js/set_immediate.js"),
7288+ },
7289+ LazyGlobal {
7290+ names: &["URLPattern"],
7291+ source: include_str!("js/url_pattern.js"),
7292+ },
7293+];
7294+
7295+/// Runs once per group, the first time one of its names is read. V8 then
7296+/// replaces the accessor with the returned value, so the script never
7297+/// compiles twice.
7298+fn lazy_global_getter(
7299+ scope: &mut v8::PinScope,
7300+ name: v8::Local<v8::Name>,
7301+ args: v8::PropertyCallbackArguments,
7302+ mut rv: v8::ReturnValue<v8::Value>,
7303+) {
7304+ let index = args.data().integer_value(scope).unwrap();
7305+ let group = &LAZY_GLOBALS[index as usize];
7306+ let code = v8::String::new(scope, group.source).unwrap();
7307+ let script = v8::Script::compile(scope, code, None).unwrap();
7308+ let exports = script.run(scope).unwrap();
7309+ let exports: v8::Local<v8::Object> = exports.try_into().unwrap();
7310+ // The group's other names are still lazy; define them now or reading one
7311+ // would compile the same script again. Not this one — V8 asserts the
7312+ // property is still an accessor when the getter returns.
7313+ let global = scope.get_current_context().global(scope);
7314+ for other in group.names {
7315+ let key = v8::String::new(scope, other).unwrap();
7316+ if name.strict_equals(key.into()) {
7317+ continue;
7318+ }
7319+ let value = exports.get(scope, key.into()).unwrap();
7320+ global.create_data_property(scope, key.into(), value);
7321+ }
7322+ rv.set(exports.get(scope, name.into()).unwrap());
7323+}
7324+
7325+fn install_lazy_globals(scope: &mut v8::PinScope) -> Result<()> {
7326+ let global = scope.get_current_context().global(scope);
7327+ for (i, group) in LAZY_GLOBALS.iter().enumerate() {
7328+ let data = v8::Integer::new(scope, i as i32);
7329+ for name in group.names {
7330+ let key = v8::String::new(scope, name).unwrap();
7331+ global.set_lazy_data_property_with_data(
7332+ scope,
7333+ key.into(),
7334+ lazy_global_getter,
7335+ data.into(),
7336+ v8::PropertyAttribute::NONE,
7337+ v8::SideEffectType::HasSideEffect,
7338+ v8::SideEffectType::HasSideEffect,
7339+ );
7340+ }
7341+ }
7342+ Ok(())
7343+}
7344+
7345+/// Globals already installed by the src/js/harness for partially supported
7346+/// builtins. These cost every isolate, so new modules belong in
7347+/// `LAZY_MODULES` instead.
7348+fn eager_module_global(spec: &str) -> Option<&'static str> {
7349+ Some(match spec {
7350+ "fs" | "node:fs" | "fs/promises" | "node:fs/promises" => "globalThis.__fs",
7351+ "zlib" | "node:zlib" => "globalThis.__zlibModule",
7352+ _ => return None,
7353+ })
7354+}
7355+
7356+fn stub_source(spec: &str, names: &std::collections::BTreeSet<String>) -> String {
7357+ let cf = spec == "cloudflare:workers";
7358+ let lazy = LAZY_MODULES.iter().find(|m| m.specs.contains(&spec));
7359+ let eager = eager_module_global(spec);
7360+ let base = if cf {
7361+ "globalThis.__cf".to_string()
7362+ } else if let Some(m) = lazy {
7363+ format!("globalThis.{}", m.global)
7364+ } else if let Some(global) = eager {
7365+ global.to_string()
7366+ } else {
7367+ "globalThis.__nodeStub".to_string()
7368+ };
7369+ let real = cf || lazy.is_some() || eager.is_some();
7370+ let mut out = String::new();
7371+ if let Some(m) = lazy {
7372+ out.push_str(&format!("if (!globalThis.{}) {{\n", m.global));
7373+ out.push_str(m.source);
7374+ out.push_str("}\n");
7375+ }
7376+ for n in names {
7377+ if n == "*" {
7378+ continue; // namespace imports take the full-surface path
7379+ } else if n == "default" {
7380+ out.push_str(&format!("export default {base};\n"));
7381+ } else if cf
7382+ && matches!(
7383+ n.as_str(),
7384+ "DurableObject" | "RpcTarget" | "WorkerEntrypoint" | "env" | "exports"
7385+ )
7386+ {
7387+ out.push_str(&format!("export const {n} = globalThis.__cf.{n};\n"));
7388+ } else if real {
7389+ out.push_str(&format!("export const {n} = {base}.{n};\n"));
7390+ } else {
7391+ out.push_str(&format!("export const {n} = globalThis.__nodeStub;\n"));
7392+ }
7393+ }
7394+ out
7395+}
7396+
7397+/// Compile one stub module per external specifier into MODREG. Run before
7398+/// instantiating a real bundle; `resolve_external` then serves them.
7399+fn register_stubs(scope: &mut v8::PinScope, src: &str, text: &[(String, String)]) {
7400+ MODREG.with(|r| r.borrow_mut().clear());
7401+ let reg = |spec: String, source: String, scope: &mut v8::PinScope| {
7402+ if let Some(m) = compile_module(scope, &spec, &source) {
7403+ MODREG.with(|r| r.borrow_mut().insert(spec, v8::Global::new(scope, m)));
7404+ } else {
7405+ tracing::warn!(%spec, "module stub failed to compile");
7406+ }
7407+ };
7408+ for (spec, names) in scan_external_imports(src) {
7409+ // `import * as x` binds the whole namespace, so the stub's exports
7410+ // must be the module's full surface — probed from the backing
7411+ // object, like dynamic import() — not just the scanned names.
7412+ let s = if names.contains("*") {
7413+ full_surface_source(scope, &spec, &names).unwrap_or_else(|| stub_source(&spec, &names))
7414+ } else {
7415+ stub_source(&spec, &names)
7416+ };
7417+ reg(spec, s, scope);
7418+ }
7419+ // sibling text modules (wrangler Text rule: `import md from './x.md'`)
7420+ for (spec, content) in text {
7421+ let s = format!(
7422+ "export default {};",
7423+ serde_json::to_string(content).unwrap()
7424+ );
7425+ reg(spec.clone(), s, scope);
7426+ }
7427+ tracing::debug!(
7428+ mods = MODREG.with(|r| r.borrow().len()),
7429+ "registered import stubs + text modules"
7430+ );
7431+}
7432+
7433+/// Register a loaded worker's sibling JS modules (Worker Loader multi-module
7434+/// bundles), in addition to the builtins `register_stubs` already added for the
7435+/// main module. Each module is registered under its own name and `./name` so
7436+/// both bare and relative sibling imports resolve; the whole graph links when
7437+/// the main module instantiates. Any builtin a sibling imports (and the main
7438+/// module did not) is stubbed too.
7439+fn register_loader_modules(scope: &mut v8::PinScope, modules: &[(String, String)]) {
7440+ for (_name, source) in modules {
7441+ for (spec, names) in scan_external_imports(source) {
7442+ if MODREG.with(|r| r.borrow().contains_key(&spec)) {
7443+ continue;
7444+ }
7445+ let s = if names.contains("*") {
7446+ full_surface_source(scope, &spec, &names)
7447+ .unwrap_or_else(|| stub_source(&spec, &names))
7448+ } else {
7449+ stub_source(&spec, &names)
7450+ };
7451+ if let Some(m) = compile_module(scope, &spec, &s) {
7452+ MODREG.with(|r| r.borrow_mut().insert(spec, v8::Global::new(scope, m)));
7453+ }
7454+ }
7455+ }
7456+ for (name, source) in modules {
7457+ let Some(m) = compile_module(scope, name, source) else {
7458+ tracing::warn!(%name, "loader module failed to compile");
7459+ continue;
7460+ };
7461+ let g = v8::Global::new(scope, m);
7462+ MODREG.with(|r| {
7463+ let mut reg = r.borrow_mut();
7464+ reg.insert(name.clone(), g.clone());
7465+ reg.insert(format!("./{name}"), g);
7466+ });
7467+ }
7468+}
7469+
7470+/// Module resolve callback: serve a registered stub for `cloudflare:*`/`node:*`.
7471+/// celld bundles are single-file, so anything else is genuinely unresolvable.
7472+fn resolve_external<'s>(
7473+ context: v8::Local<'s, v8::Context>,
7474+ specifier: v8::Local<'s, v8::String>,
7475+ _a: v8::Local<'s, v8::FixedArray>,
7476+ _r: v8::Local<'s, v8::Module>,
7477+) -> Option<v8::Local<'s, v8::Module>> {
7478+ v8::callback_scope!(unsafe scope, context);
7479+ let spec = specifier.to_rust_string_lossy(scope);
7480+ let m = MODREG.with(|r| r.borrow().get(&spec).map(|g| v8::Local::new(scope, g)));
7481+ if m.is_none() {
7482+ tracing::warn!(%spec, "resolve: no stub for specifier");
7483+ }
7484+ m
7485+}
7486+
7487+/// The (guarded setup script, backing-object expression) pair for a builtin
7488+/// specifier, or None if `spec` is not one. The setup materializes a lazy
7489+/// module's source at most once; the expression then names its global.
7490+fn builtin_source(spec: &str) -> Option<(String, String)> {
7491+ if spec == "cloudflare:workers" {
7492+ return Some((String::new(), "globalThis.__cf".into()));
7493+ }
7494+ if let Some(m) = LAZY_MODULES.iter().find(|m| m.specs.contains(&spec)) {
7495+ return Some((
7496+ format!("if (!globalThis.{}) {{\n{}}}\n", m.global, m.source),
7497+ format!("globalThis.{}", m.global),
7498+ ));
7499+ }
7500+ if let Some(global) = eager_module_global(spec) {
7501+ return Some((String::new(), global.to_string()));
7502+ }
7503+ is_external(spec).then(|| (String::new(), "globalThis.__nodeStub".to_string()))
7504+}
7505+
7506+/// Full-surface module source for a builtin: run the (guarded) setup, probe
7507+/// the backing object's enumerable keys, and re-export each one. Serves both
7508+/// `import * as x` stubs and dynamic import(). `extra` adds statically
7509+/// scanned names the probe may have missed, so mixed named + namespace
7510+/// imports still link. String export names sidestep identifier restrictions.
7511+fn full_surface_source(
7512+ scope: &mut v8::PinScope,
7513+ spec: &str,
7514+ extra: &std::collections::BTreeSet<String>,
7515+) -> Option<String> {
7516+ let (setup, expr) = builtin_source(spec)?;
7517+ let probe = format!("{setup}JSON.stringify(Object.keys(Object({expr})))");
7518+ let code = v8::String::new(scope, &probe)?;
7519+ let script = v8::Script::compile(scope, code, None)?;
7520+ let keys = script.run(scope)?.to_rust_string_lossy(scope);
7521+ let mut names: Vec<String> = serde_json::from_str(&keys).unwrap_or_default();
7522+ for name in extra {
7523+ if name != "*" && !names.contains(name) {
7524+ names.push(name.clone());
7525+ }
7526+ }
7527+ let mut src = format!("const __b = {expr};\nexport default __b;\n");
7528+ for (i, name) in names.iter().enumerate() {
7529+ if name == "default" {
7530+ continue;
7531+ }
7532+ let name = serde_json::to_string(name).unwrap();
7533+ src.push_str(&format!(
7534+ "const __e{i} = __b[{name}]; export {{ __e{i} as {name} }};\n"
7535+ ));
7536+ }
7537+ Some(src)
7538+}
7539+
7540+/// `process.getBuiltinModule(id)`: the builtin's backing object, or
7541+/// undefined for anything that is not a node builtin.
7542+fn op_builtin_module(
7543+ scope: &mut v8::PinScope,
7544+ args: v8::FunctionCallbackArguments,
7545+ mut rv: v8::ReturnValue<v8::Value>,
7546+) {
7547+ let spec = args.get(0).to_rust_string_lossy(scope);
7548+ if spec.starts_with("cloudflare:") {
7549+ return; // not a node builtin
7550+ }
7551+ let Some((setup, expr)) = builtin_source(&spec) else {
7552+ return;
7553+ };
7554+ let code = v8::String::new(scope, &format!("{setup}{expr}")).unwrap();
7555+ if let Some(script) = v8::Script::compile(scope, code, None) {
7556+ if let Some(value) = script.run(scope) {
7557+ rv.set(value);
7558+ }
7559+ }
7560+}
7561+
7562+/// Evaluate (once per isolate) a full-namespace module for a builtin
7563+/// specifier. Unlike the static stubs, whose exports are the statically
7564+/// scanned import names, this re-exports every enumerable key of the
7565+/// backing object — a dynamic import's consumer can reach for any of them.
7566+/// Cached in MODREG under a `dyn:` key so later import() calls are a
7567+/// table lookup.
7568+fn dynamic_namespace<'s>(
7569+ scope: &mut v8::PinScope<'s, '_>,
7570+ spec: &str,
7571+) -> Result<v8::Local<'s, v8::Value>> {
7572+ let key = format!("dyn:{spec}");
7573+ let cached = MODREG.with(|r| r.borrow().get(&key).map(|g| v8::Local::new(scope, g)));
7574+ if let Some(module) = cached {
7575+ return Ok(module.get_module_namespace());
7576+ }
7577+ let src = full_surface_source(scope, spec, &Default::default())
7578+ .ok_or_else(|| anyhow!("dynamic import of \"{spec}\" is not supported"))?;
7579+ let module = compile_module(scope, spec, &src)
7580+ .ok_or_else(|| anyhow!("dynamic module for {spec} did not compile"))?;
7581+ module
7582+ .instantiate_module(scope, resolve_external)
7583+ .ok_or_else(|| anyhow!("dynamic module for {spec} did not link"))?;
7584+ module
7585+ .evaluate(scope)
7586+ .ok_or_else(|| anyhow!("dynamic module for {spec} threw"))?;
7587+ if module.get_status() != v8::ModuleStatus::Evaluated {
7588+ return Err(anyhow!("dynamic module for {spec} failed to evaluate"));
7589+ }
7590+ MODREG.with(|r| r.borrow_mut().insert(key, v8::Global::new(scope, module)));
7591+ Ok(module.get_module_namespace())
7592+}
7593+
7594+/// Dynamic `import()` host hook. Builtin specifiers resolve through the same
7595+/// table static imports use; anything else rejects — celld bundles are
7596+/// single-file, so there is nothing else to load.
7597+fn host_import_module_dynamically<'s>(
7598+ scope: &mut v8::PinScope<'s, '_>,
7599+ _host_defined_options: v8::Local<'s, v8::Data>,
7600+ _resource_name: v8::Local<'s, v8::Value>,
7601+ specifier: v8::Local<'s, v8::String>,
7602+ _import_attributes: v8::Local<'s, v8::FixedArray>,
7603+) -> Option<v8::Local<'s, v8::Promise>> {
7604+ let resolver = v8::PromiseResolver::new(scope)?;
7605+ let promise = resolver.get_promise(scope);
7606+ let spec = specifier.to_rust_string_lossy(scope);
7607+ let tc = std::pin::pin!(v8::TryCatch::new(scope));
7608+ let tc = &mut tc.init();
7609+ match dynamic_namespace(tc, &spec) {
7610+ Ok(namespace) => {
7611+ resolver.resolve(tc, namespace);
7612+ }
7613+ Err(error) => {
7614+ let caught = tc.exception();
7615+ tc.reset();
7616+ let exception = caught.unwrap_or_else(|| {
7617+ let message = v8::String::new(tc, &error.to_string()).unwrap();
7618+ v8::Exception::error(tc, message)
7619+ });
7620+ resolver.reject(tc, exception);
7621+ }
7622+ }
7623+ Some(promise)
7624+}
7625+
7626+/// Like `make_request`, but marks the request as incoming. Its signal is
7627+/// registered only if the handler actually suspends, preserving the
7628+/// synchronous request path.
7629+fn make_incoming_request<'s>(
7630+ tc: &mut v8::PinScope<'s, '_>,
7631+ url: &str,
7632+ method: &str,
7633+ body: &[u8],
7634+ headers: &[(String, String)],
7635+) -> Result<v8::Local<'s, v8::Value>> {
7636+ let global = tc.get_current_context().global(tc);
7637+ let key = v8::String::new(tc, "__makeIncomingRequest").unwrap();
7638+ let f: v8::Local<v8::Function> = global
7639+ .get(tc, key.into())
7640+ .ok_or_else(|| anyhow!("no __makeIncomingRequest"))?
7641+ .try_into()
7642+ .map_err(|_| anyhow!("not fn"))?;
7643+ let url = v8::String::new(tc, url).unwrap();
7644+ let method = v8::String::new(tc, method).unwrap();
7645+ let body = bytes_value(tc, body.to_vec());
7646+ let headers = v8::String::new(
7647+ tc,
7648+ &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()),
7649+ )
7650+ .unwrap();
7651+ let recv = v8::undefined(tc).into();
7652+ f.call(tc, recv, &[url.into(), method.into(), body, headers.into()])
7653+ .ok_or_else(|| anyhow!("__makeIncomingRequest threw"))
7654+}
7655+
7656+fn register_incoming_request(
7657+ tc: &mut v8::PinScope,
7658+ request_id: RequestId,
7659+ request: v8::Local<v8::Value>,
7660+) -> Result<()> {
7661+ let global = tc.get_current_context().global(tc);
7662+ let key = v8::String::new(tc, "__registerIncomingRequest").unwrap();
7663+ let function: v8::Local<v8::Function> = global
7664+ .get(tc, key.into())
7665+ .ok_or_else(|| anyhow!("no __registerIncomingRequest"))?
7666+ .try_into()
7667+ .map_err(|_| anyhow!("__registerIncomingRequest is not a function"))?;
7668+ let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
7669+ let recv = v8::undefined(tc).into();
7670+ function
7671+ .call(tc, recv, &[id.into(), request])
7672+ .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?;
7673+ Ok(())
7674+}
7675+
7676+fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) {
7677+ let global = tc.get_current_context().global(tc);
7678+ let key = v8::String::new(tc, "__finishIncomingRequest").unwrap();
7679+ let Some(value) = global.get(tc, key.into()) else {
7680+ return;
7681+ };
7682+ let Ok(function) = value.try_cast::<v8::Function>() else {
7683+ return;
7684+ };
7685+ let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
7686+ let recv = v8::undefined(tc).into();
7687+ let _ = function.call(tc, recv, &[id.into()]);
7688+}
7689+
7690+fn make_request<'s>(
7691+ tc: &mut v8::PinScope<'s, '_>,
7692+ url: &str,
7693+ method: &str,
7694+ body: &[u8],
7695+ headers: &[(String, String)],
7696+) -> Result<v8::Local<'s, v8::Value>> {
7697+ let g = tc.get_current_context().global(tc);
7698+ let k = v8::String::new(tc, "__makeRequest").unwrap();
7699+ let f: v8::Local<v8::Function> = g.get(tc, k.into()).unwrap().try_into().unwrap();
7700+ let u = v8::String::new(tc, url).unwrap();
7701+ let m = v8::String::new(tc, method).unwrap();
7702+ let b = bytes_value(tc, body.to_vec());
7703+ let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap();
7704+ let recv = v8::undefined(tc).into();
7705+ f.call(tc, recv, &[u.into(), m.into(), b, h.into()])
7706+ .ok_or_else(|| anyhow!("makeRequest threw"))
7707+}
7708+
7709+fn read_response(
7710+ scope: &mut v8::PinScope,
7711+ ret: v8::Local<v8::Value>,
7712+ cell_rx: Option<&std::sync::mpsc::Receiver<CellJob>>,
7713+) -> Result<HttpResponse> {
7714+ let ctx = scope.get_current_context();
7715+ let global = ctx.global(scope);
7716+ let key = v8::String::new(scope, "__readResponse").unwrap();
7717+ let f: v8::Local<v8::Function> = global
7718+ .get(scope, key.into())
7719+ .ok_or_else(|| anyhow!("no __readResponse"))?
7720+ .try_into()
7721+ .map_err(|_| anyhow!("not fn"))?;
7722+ let recv = v8::undefined(scope).into();
7723+ let out = f
7724+ .call(scope, recv, &[ret])
7725+ .ok_or_else(|| anyhow!("readResponse threw"))?;
7726+ let out = if let Ok(promise) = out.try_cast::<v8::Promise>() {
7727+ run_loop(scope, promise, cell_rx)?
7728+ } else {
7729+ out
7730+ };
7731+ let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?;
7732+ let sk = v8::String::new(scope, "status").unwrap();
7733+ let bk = v8::String::new(scope, "bodyBytes").unwrap();
7734+ let tk = v8::String::new(scope, "bodyStreamId").unwrap();
7735+ let hk = v8::String::new(scope, "headersJson").unwrap();
7736+ let wk = v8::String::new(scope, "wsTargetJson").unwrap();
7737+ let status = out
7738+ .get(scope, sk.into())
7739+ .and_then(|v| v.uint32_value(scope))
7740+ .unwrap_or(200) as u16;
7741+ // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON
7742+ // number array (which was ~4x the bytes to serialize + parse per response).
7743+ let body = out
7744+ .get(scope, bk.into())
7745+ .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok())
7746+ .map(|view| {
7747+ let mut buf = vec![0u8; view.byte_length()];
7748+ view.copy_contents(&mut buf);
7749+ buf
7750+ })
7751+ .unwrap_or_default();
7752+ let stream_id = out
7753+ .get(scope, tk.into())
7754+ .and_then(|value| value.integer_value(scope))
7755+ .unwrap_or(0)
7756+ .max(0) as u64;
7757+ let stream = if stream_id == 0 {
7758+ None
7759+ } else {
7760+ http_streams()
7761+ .lock()
7762+ .unwrap()
7763+ .remove(&stream_id)
7764+ .and_then(|stream| stream.source)
7765+ .map(http_chunk_stream)
7766+ };
7767+ if stream_id != 0 && stream.is_none() {
7768+ return Err(anyhow!(
7769+ "response stream {stream_id} is no longer available"
7770+ ));
7771+ }
7772+ let headers = out
7773+ .get(scope, hk.into())
7774+ .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok())
7775+ .unwrap_or_default();
7776+ let ws_json = out
7777+ .get(scope, wk.into())
7778+ .map(|v| v.to_rust_string_lossy(scope))
7779+ .unwrap_or_else(|| "null".into());
7780+ let ws = serde_json::from_str(&ws_json).ok();
7781+ if status == 101 {
7782+ tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response");
7783+ }
7784+ Ok(HttpResponse {
7785+ status,
7786+ body,
7787+ stream,
7788+ headers,
7789+ ws,
7790+ write_position: None,
7791+ })
7792+}
7793+
7794+#[cfg(all(test, celld_internal_tests))]
7795+fn init_engine_for_tests() {
7796+ static INIT: std::sync::Once = std::sync::Once::new();
7797+ INIT.call_once(|| {
7798+ v8::V8::set_flags_from_string("--expose-gc");
7799+ Engine::init();
7800+ });
7801+}
7802+
7803+/// Externally injected Web-platform tests.
7804+#[cfg(all(test, celld_internal_tests))]
7805+mod conformance_runtime_tests {
7806+ include!(env!("CELLD_CONFORMANCE_JS_RUNTIME_TESTS"));
7807+}
7808+
7809+#[cfg(all(test, celld_internal_tests))]
7810+mod conformance_web_platform_tests {
7811+ include!(env!("CELLD_CONFORMANCE_WEB_PLATFORM_TESTS"));
7812+}
addedcrates/celld/js/atob_btoa.js+42−0View file
@@ -1,0 +1,42 @@
1+// atob / btoa.
2+// Own IIFE: captures the host ops it needs, attaches to
3+// globalThis, exits. The $$-prefixed host ops stay defined
4+// for the life of the isolate — non-enumerable (see the ops
5+// macro in js.rs), not removed. DOMException is installed
6+// later, by harness.js, and is only referenced at call time.
7+(function () {
8+ const _atob = $$atob;
9+ const _btoa = $$btoa;
10+
11+ // WHATWG infra: atob strips ASCII whitespace
12+ // (U+0009 TAB, U+000A LF, U+000C FF, U+000D CR,
13+ // U+0020 SPACE) from input before decoding, and
14+ // throws DOMException("InvalidCharacterError") on
15+ // bad input (not a plain Error). The Rust op does
16+ // neither — preprocess and re-wrap here.
17+ globalThis.atob = (s) => {
18+ s = String(s).replace(/[\t\n\f\r ]/g, "");
19+ try {
20+ return _atob(s);
21+ } catch (e) {
22+ throw new DOMException(
23+ e && e.message
24+ ? String(e.message)
25+ : "atob: invalid base64",
26+ "InvalidCharacterError",
27+ );
28+ }
29+ };
30+ globalThis.btoa = (s) => {
31+ s = String(s);
32+ for (let i = 0; i < s.length; i++) {
33+ if (s.charCodeAt(i) > 0xff) {
34+ throw new DOMException(
35+ "String contains a code point > U+00FF",
36+ "InvalidCharacterError",
37+ );
38+ }
39+ }
40+ return _btoa(s);
41+ };
42+})();
addedcrates/celld/js/byte_streams.js+693−0View file
@@ -1,0 +1,693 @@
1+// Readable byte streams (WHATWG subset): ReadableByteStreamController,
2+// ReadableStreamBYOBReader, ReadableStreamBYOBRequest.
3+//
4+// Compiled on first access (see LAZY_GLOBALS); streams.js names the
5+// ReadableByteStreamController global when a source declares
6+// `type: 'bytes'`, so a bundle with no byte streams never pays for this
7+// file. All state lives on the controller; the stream keeps only a
8+// `_byteCtl` backref plus instance overrides for `getReader` and
9+// `_cancel`, so default-stream paths are untouched.
10+//
11+// Three deliberate Workerd deviations from current spec text: a read on
12+// a default reader drains the whole byte queue as one coalesced chunk,
13+// a source with no start() is started synchronously (mirroring the
14+// writable's sink handling), and close() settles parked BYOB reads (see
15+// _closeCommit) instead of leaving them for respond(0).
16+(() => {
17+
18+const _brand = Symbol('ReadableByteStreamController');
19+const INVALIDATED =
20+ 'This ReadableStreamBYOBRequest has been invalidated.';
21+const RELEASED =
22+ 'This ReadableStream reader has been released.';
23+
24+// Same shape streams.js returns from reads: shadow `then` so a user
25+// override of Object.prototype.then cannot intercept the result.
26+function _readResult(value, done) {
27+ const r = { value, done };
28+ Object.defineProperty(r, 'then', {
29+ value: undefined,
30+ enumerable: false,
31+ writable: true,
32+ configurable: true,
33+ });
34+ return r;
35+}
36+
37+class ReadableStreamBYOBRequest {
38+ constructor(brand, controller, view) {
39+ if (brand !== _brand)
40+ throw new TypeError(
41+ 'ReadableStreamBYOBRequest cannot be constructed directly');
42+ this._c = controller;
43+ this._view = view;
44+ }
45+ get view() { return this._view; }
46+ respond(bytesWritten) {
47+ if (this._c === null) throw new TypeError(INVALIDATED);
48+ const n = Number(bytesWritten);
49+ if (!Number.isInteger(n) || n < 0)
50+ throw new TypeError('invalid bytesWritten');
51+ this._c._respond(n);
52+ }
53+ respondWithNewView(view) {
54+ if (this._c === null) throw new TypeError(INVALIDATED);
55+ if (!ArrayBuffer.isView(view))
56+ throw new TypeError('view must be an ArrayBufferView');
57+ this._c._respondWithNewView(view);
58+ }
59+}
60+
61+class ReadableByteStreamController {
62+ _stream;
63+ // Byte queue: {buffer, byteOffset, byteLength} slices.
64+ _queue = [];
65+ _queueTotalSize = 0;
66+ _closeRequested = false;
67+ // Pull-into descriptors. `readerType` is 'byob' (req carries the
68+ // read's resolve/reject) or 'default' (an autoAllocate read whose
69+ // request sits in the stream's _readRequests).
70+ _pendingPullIntos = [];
71+ _byobRequest = null;
72+ _autoAlloc;
73+ _hwm = 0;
74+ _source;
75+ _pullFn;
76+ _cancelFn;
77+ _started = false;
78+ _pulling = false;
79+ _pullAgain = false;
80+
81+ constructor(brand, stream) {
82+ if (brand !== _brand)
83+ throw new TypeError(
84+ 'ReadableByteStreamController cannot be constructed directly');
85+ this._stream = stream;
86+ }
87+
88+ // Wires a `type: 'bytes'` stream: called by the ReadableStream
89+ // constructor, which returns immediately after (so none of the
90+ // default controller/pull machinery is set up). `hwm` is undefined
91+ // when the strategy did not provide one; byte streams default to 0.
92+ static _setup(stream, src, hwm) {
93+ const startFn = src.start;
94+ const pullFn = src.pull;
95+ const cancelFn = src.cancel;
96+ for (const [name, fn] of [['start', startFn], ['pull', pullFn],
97+ ['cancel', cancelFn]])
98+ if (fn !== undefined && typeof fn !== 'function')
99+ throw new TypeError(`${name} must be a function`);
100+ let auto = src.autoAllocateChunkSize;
101+ if (auto !== undefined) {
102+ auto = Number(auto);
103+ if (!Number.isInteger(auto) || auto <= 0)
104+ throw new TypeError(
105+ 'autoAllocateChunkSize must be a positive integer');
106+ }
107+ const c = new ReadableByteStreamController(_brand, stream);
108+ c._source = src;
109+ c._pullFn = pullFn;
110+ c._cancelFn = cancelFn;
111+ c._autoAlloc = auto;
112+ c._hwm = hwm === undefined ? 0 : hwm;
113+ stream._byteCtl = c;
114+ stream._controller = c;
115+ // Instance overrides so shared prototype paths stay unbranched.
116+ Object.defineProperties(stream, {
117+ getReader: { value: byteGetReader, writable: true,
118+ configurable: true },
119+ _cancel: { value: byteCancel, writable: true,
120+ configurable: true },
121+ });
122+ if (startFn) {
123+ let result;
124+ try { result = startFn.call(src, c); }
125+ catch (e) { result = Promise.reject(e); }
126+ Promise.resolve(result).then(
127+ () => { c._started = true; c._pull(); },
128+ (e) => c.error(e));
129+ } else {
130+ // Workerd starts a source with no start() synchronously.
131+ c._started = true;
132+ c._pull();
133+ }
134+ }
135+
136+ get byobRequest() {
137+ if (this._byobRequest === null &&
138+ this._pendingPullIntos.length > 0) {
139+ const d = this._pendingPullIntos[0];
140+ const view = new Uint8Array(d.buffer,
141+ d.byteOffset + d.bytesFilled, d.byteLength - d.bytesFilled);
142+ this._byobRequest =
143+ new ReadableStreamBYOBRequest(_brand, this, view);
144+ }
145+ return this._byobRequest;
146+ }
147+
148+ get desiredSize() {
149+ const s = this._stream;
150+ if (s._errored) return null;
151+ if (s._closed || this._closeRequested) return 0;
152+ return this._hwm - this._queueTotalSize;
153+ }
154+
155+ enqueue(chunk) {
156+ const s = this._stream;
157+ if (!ArrayBuffer.isView(chunk) || chunk.byteLength === 0 ||
158+ chunk.buffer.byteLength === 0)
159+ throw new TypeError(
160+ 'chunk must be a non-empty ArrayBufferView');
161+ if (this._closeRequested || s._closed || s._errored)
162+ throw new TypeError('Cannot enqueue a closed/errored stream');
163+ const { byteOffset, byteLength } = chunk;
164+ const buffer = chunk.buffer.transfer();
165+ const first = this._pendingPullIntos[0];
166+ if (first) {
167+ this._invalidate();
168+ if (first.readerType === 'default') {
169+ // A pending autoAllocate descriptor is dropped; salvage any
170+ // bytes it already holds ahead of the new chunk.
171+ this._pendingPullIntos.shift();
172+ if (first.bytesFilled > 0) {
173+ this._queue.push({ buffer: first.buffer,
174+ byteOffset: first.byteOffset,
175+ byteLength: first.bytesFilled });
176+ this._queueTotalSize += first.bytesFilled;
177+ }
178+ }
179+ }
180+ const reader = s._reader;
181+ if (reader instanceof ReadableStreamDefaultReader) {
182+ while (s._readRequests.length > 0 && this._queueTotalSize > 0)
183+ s._readRequests.shift()
184+ .resolve(_readResult(this._drain(), false));
185+ if (s._readRequests.length > 0) {
186+ s._readRequests.shift().resolve(_readResult(
187+ new Uint8Array(buffer, byteOffset, byteLength), false));
188+ } else {
189+ this._queue.push({ buffer, byteOffset, byteLength });
190+ this._queueTotalSize += byteLength;
191+ }
192+ } else {
193+ this._queue.push({ buffer, byteOffset, byteLength });
194+ this._queueTotalSize += byteLength;
195+ if (reader) this._process();
196+ }
197+ this._pull();
198+ }
199+
200+ close() {
201+ const s = this._stream;
202+ if (this._closeRequested || s._closed || s._errored)
203+ throw new TypeError('Cannot close a closed/errored stream');
204+ if (this._queueTotalSize > 0) {
205+ this._closeRequested = true;
206+ return;
207+ }
208+ const d = this._pendingPullIntos[0];
209+ if (d && d.bytesFilled % d.elementSize !== 0) {
210+ const e = new TypeError('Insufficient bytes to fill elements');
211+ this.error(e);
212+ throw e;
213+ }
214+ this._closeCommit();
215+ }
216+
217+ // Workerd settles parked BYOB reads when the stream closes: a
218+ // partially filled (min/readAtLeast) descriptor commits what it got
219+ // with done still false, an empty one hands its buffer back as a
220+ // zero-length done view. (Spec would leave them for respond(0);
221+ // a respond after this sees no request and is a no-op.)
222+ _closeCommit() {
223+ const pending = this._pendingPullIntos;
224+ this._pendingPullIntos = [];
225+ this._invalidate();
226+ this._stream._finishClose();
227+ for (const d of pending)
228+ if (d.req) d.req.resolve(_readResult(
229+ new d.ctor(d.buffer, d.byteOffset,
230+ d.bytesFilled / d.elementSize),
231+ d.bytesFilled === 0));
232+ }
233+
234+ error(e) {
235+ const s = this._stream;
236+ if (s._closed || s._errored) return;
237+ this._queue = [];
238+ this._queueTotalSize = 0;
239+ const pending = this._pendingPullIntos;
240+ this._pendingPullIntos = [];
241+ this._invalidate();
242+ s._error = e;
243+ s._errored = true;
244+ // Reject closed first (spec order), then reads.
245+ s._rejectClosed(e);
246+ for (const r of s._readRequests) r.reject(e);
247+ s._readRequests = [];
248+ for (const d of pending) if (d.req) d.req.reject(e);
249+ }
250+
251+ _invalidate() {
252+ const r = this._byobRequest;
253+ if (r === null) return;
254+ r._c = null;
255+ r._view = null;
256+ this._byobRequest = null;
257+ }
258+
259+ // Workerd: a default-reader read drains the whole byte queue as one
260+ // chunk (a single entry is handed back without a copy).
261+ _drain() {
262+ const q = this._queue;
263+ let out;
264+ if (q.length === 1) {
265+ const d = q[0];
266+ out = new Uint8Array(d.buffer, d.byteOffset, d.byteLength);
267+ } else {
268+ out = new Uint8Array(this._queueTotalSize);
269+ let off = 0;
270+ for (const d of q) {
271+ out.set(
272+ new Uint8Array(d.buffer, d.byteOffset, d.byteLength), off);
273+ off += d.byteLength;
274+ }
275+ }
276+ this._queue = [];
277+ this._queueTotalSize = 0;
278+ this._handleDrain();
279+ return out;
280+ }
281+
282+ _handleDrain() {
283+ if (this._queueTotalSize === 0 && this._closeRequested)
284+ this._closeCommit();
285+ }
286+
287+ // FillPullIntoDescriptorFromQueue: copies up to the descriptor's
288+ // capacity, committing only element-aligned bytes once minFill is
289+ // reachable. Returns whether the descriptor is ready to commit.
290+ _fill(d) {
291+ const max = Math.min(this._queueTotalSize,
292+ d.byteLength - d.bytesFilled);
293+ const maxFilled = d.bytesFilled + max;
294+ const aligned = maxFilled - (maxFilled % d.elementSize);
295+ let remaining = max;
296+ let ready = false;
297+ if (aligned >= d.minFill) {
298+ remaining = aligned - d.bytesFilled;
299+ ready = true;
300+ }
301+ const dest = new Uint8Array(d.buffer);
302+ while (remaining > 0) {
303+ const head = this._queue[0];
304+ const n = Math.min(remaining, head.byteLength);
305+ dest.set(new Uint8Array(head.buffer, head.byteOffset, n),
306+ d.byteOffset + d.bytesFilled);
307+ if (n === head.byteLength) this._queue.shift();
308+ else { head.byteOffset += n; head.byteLength -= n; }
309+ this._queueTotalSize -= n;
310+ d.bytesFilled += n;
311+ remaining -= n;
312+ }
313+ return ready;
314+ }
315+
316+ _commit(d, done) {
317+ const view = new d.ctor(d.buffer, d.byteOffset,
318+ d.bytesFilled / d.elementSize);
319+ if (d.readerType === 'default') {
320+ const r = this._stream._readRequests.shift();
321+ if (r) r.resolve(_readResult(view, done));
322+ } else {
323+ d.req.resolve(_readResult(view, done));
324+ }
325+ }
326+
327+ _process() {
328+ while (this._pendingPullIntos.length > 0 &&
329+ this._queueTotalSize > 0) {
330+ const d = this._pendingPullIntos[0];
331+ if (!this._fill(d)) return;
332+ this._pendingPullIntos.shift();
333+ this._commit(d, false);
334+ }
335+ }
336+
337+ _pullInto(view, min) {
338+ const s = this._stream;
339+ const elementSize = view.BYTES_PER_ELEMENT ?? 1; // DataView: 1
340+ const d = {
341+ buffer: null,
342+ bufferLen: 0,
343+ byteOffset: view.byteOffset,
344+ byteLength: view.byteLength,
345+ bytesFilled: 0,
346+ elementSize,
347+ minFill: min * elementSize,
348+ ctor: view.constructor,
349+ readerType: 'byob',
350+ req: null,
351+ };
352+ try { d.buffer = view.buffer.transfer(); }
353+ catch (e) { return Promise.reject(e); }
354+ d.bufferLen = d.buffer.byteLength;
355+ if (this._pendingPullIntos.length > 0)
356+ return new Promise((resolve, reject) => {
357+ d.req = { resolve, reject };
358+ this._pendingPullIntos.push(d);
359+ });
360+ if (s._closed)
361+ return Promise.resolve(_readResult(
362+ new d.ctor(d.buffer, d.byteOffset, 0), true));
363+ if (this._queueTotalSize > 0) {
364+ if (this._fill(d)) {
365+ const filled = new d.ctor(d.buffer, d.byteOffset,
366+ d.bytesFilled / elementSize);
367+ this._handleDrain();
368+ return Promise.resolve(_readResult(filled, false));
369+ }
370+ if (this._closeRequested) {
371+ const e = new TypeError('Insufficient bytes to fill elements');
372+ this.error(e);
373+ return Promise.reject(e);
374+ }
375+ }
376+ const p = new Promise((resolve, reject) => {
377+ d.req = { resolve, reject };
378+ this._pendingPullIntos.push(d);
379+ });
380+ this._pull();
381+ return p;
382+ }
383+
384+ _respond(n) {
385+ const s = this._stream;
386+ const d = this._pendingPullIntos[0];
387+ if (s._closed) {
388+ if (n !== 0)
389+ throw new TypeError(
390+ 'bytesWritten must be zero on a closed stream');
391+ } else {
392+ if (n === 0)
393+ throw new TypeError('bytesWritten must be non-zero');
394+ if (d.bytesFilled + n > d.byteLength)
395+ throw new RangeError('bytesWritten exceeds the view');
396+ }
397+ this._respondInternal(d, n);
398+ }
399+
400+ _respondWithNewView(view) {
401+ const s = this._stream;
402+ const d = this._pendingPullIntos[0];
403+ if (!(view.buffer instanceof ArrayBuffer))
404+ throw new TypeError(
405+ 'view must be over a detachable ArrayBuffer');
406+ if (s._closed) {
407+ if (view.byteLength !== 0)
408+ throw new TypeError(
409+ 'view must be zero-length on a closed stream');
410+ } else if (view.byteLength === 0) {
411+ throw new TypeError('view must be non-zero-length');
412+ }
413+ if (d.byteOffset + d.bytesFilled !== view.byteOffset)
414+ throw new RangeError(
415+ 'view byteOffset does not match the request');
416+ if (d.bufferLen !== view.buffer.byteLength)
417+ throw new RangeError('view buffer does not match the request');
418+ if (d.bytesFilled + view.byteLength > d.byteLength)
419+ throw new RangeError('view is larger than the request');
420+ const n = view.byteLength;
421+ d.buffer = view.buffer.transfer();
422+ this._respondInternal(d, n);
423+ }
424+
425+ _respondInternal(d, n) {
426+ this._invalidate();
427+ if (this._stream._closed) {
428+ // respond(0) after close: every pending descriptor commits as
429+ // done with a zero-length view over its (filled) buffer.
430+ while (this._pendingPullIntos.length > 0)
431+ this._commit(this._pendingPullIntos.shift(), true);
432+ return;
433+ }
434+ d.bytesFilled += n;
435+ if (d.bytesFilled < d.minFill) { this._pull(); return; }
436+ this._pendingPullIntos.shift();
437+ const remainder = d.bytesFilled % d.elementSize;
438+ if (remainder > 0) {
439+ // Unaligned tail goes back on the queue for the next read.
440+ const end = d.byteOffset + d.bytesFilled;
441+ this._queue.push({
442+ buffer: d.buffer.slice(end - remainder, end),
443+ byteOffset: 0,
444+ byteLength: remainder,
445+ });
446+ this._queueTotalSize += remainder;
447+ d.bytesFilled -= remainder;
448+ }
449+ this._commit(d, false);
450+ this._process();
451+ this._pull();
452+ }
453+
454+ _shouldPull() {
455+ const s = this._stream;
456+ if (!this._started || !this._pullFn || s._closed || s._errored ||
457+ this._closeRequested)
458+ return false;
459+ if (s._readRequests.length > 0) return true;
460+ if (this._pendingPullIntos.length > 0) return true;
461+ return this._hwm - this._queueTotalSize > 0;
462+ }
463+
464+ _pull() {
465+ if (!this._shouldPull()) return;
466+ if (this._pulling) {
467+ this._pullAgain = true;
468+ return;
469+ }
470+ this._pulling = true;
471+ let result;
472+ try { result = this._pullFn.call(this._source, this); }
473+ catch (e) {
474+ this._pulling = false;
475+ this.error(e);
476+ return;
477+ }
478+ Promise.resolve(result).then(
479+ () => {
480+ this._pulling = false;
481+ if (this._pullAgain) {
482+ this._pullAgain = false;
483+ this._pull();
484+ }
485+ },
486+ (e) => {
487+ this._pulling = false;
488+ this.error(e);
489+ });
490+ }
491+}
492+
493+// Default reader over a byte stream. Subclassing keeps the shared
494+// ReadableStreamDefaultReader.read() free of byte-stream branches;
495+// releaseLock/cancel/closed are inherited (release nulls _reader,
496+// which is this class's released signal).
497+class ByteDefaultReader extends ReadableStreamDefaultReader {
498+ constructor(stream) {
499+ super(stream);
500+ this._s = stream;
501+ }
502+ read() {
503+ const s = this._s;
504+ if (s._reader !== this)
505+ return Promise.reject(new TypeError(RELEASED));
506+ s._disturbed = true;
507+ if (s._errored) return Promise.reject(s._error);
508+ const c = s._byteCtl;
509+ if (c._queueTotalSize > 0)
510+ return Promise.resolve(_readResult(c._drain(), false));
511+ if (s._closed)
512+ return Promise.resolve(_readResult(undefined, true));
513+ const p = new Promise((resolve, reject) =>
514+ s._readRequests.push({ resolve, reject }));
515+ const auto = c._autoAlloc;
516+ if (auto !== undefined)
517+ c._pendingPullIntos.push({
518+ buffer: new ArrayBuffer(auto),
519+ bufferLen: auto,
520+ byteOffset: 0,
521+ byteLength: auto,
522+ bytesFilled: 0,
523+ elementSize: 1,
524+ minFill: 1,
525+ ctor: Uint8Array,
526+ readerType: 'default',
527+ req: null,
528+ });
529+ c._pull();
530+ return p;
531+ }
532+}
533+
534+class ReadableStreamBYOBReader {
535+ _released = false;
536+
537+ // Accepts byte streams (`_byteCtl`) and internal streams (`_ictl`:
538+ // IdentityTransformStream readables and materialized body streams),
539+ // both of which implement the `_pullInto` protocol.
540+ constructor(stream) {
541+ const c = stream instanceof ReadableStream
542+ ? (stream._byteCtl ?? stream._ictl) : undefined;
543+ if (c === undefined)
544+ throw new TypeError(
545+ 'ReadableStreamBYOBReader requires a byte ReadableStream');
546+ if (stream._locked)
547+ throw new TypeError('ReadableStream is locked');
548+ this._s = stream;
549+ this._c = c;
550+ stream._locked = true;
551+ stream._reader = this;
552+ }
553+
554+ read(view, options) {
555+ if (this._released)
556+ return Promise.reject(new TypeError(RELEASED));
557+ if (!ArrayBuffer.isView(view) || view.byteLength === 0 ||
558+ view.buffer.byteLength === 0)
559+ return Promise.reject(new TypeError(
560+ 'read() requires a non-empty ArrayBufferView'));
561+ let min = 1;
562+ if (options !== undefined && options !== null &&
563+ options.min !== undefined) {
564+ min = Number(options.min);
565+ const elements = view.length ?? view.byteLength; // DataView
566+ if (!Number.isInteger(min) || min < 1 || min > elements)
567+ return Promise.reject(new TypeError('invalid min'));
568+ }
569+ const s = this._s;
570+ s._disturbed = true;
571+ if (s._errored) return Promise.reject(s._error);
572+ return this._c._pullInto(view, min);
573+ }
574+
575+ // Workerd extension: resolve only once at least `min` bytes are in
576+ // `view` (or the stream ends first — then with what arrived).
577+ readAtLeast(min, view) {
578+ return this.read(view, { min });
579+ }
580+
581+ // Internal `_ictl` for the harness's materialized body streams,
582+ // created on the first byob getReader() so the eager harness carries
583+ // none of this machinery.
584+ static _buffered(st) {
585+ return new BufferedInternalController(st);
586+ }
587+
588+ cancel(reason) {
589+ if (this._released)
590+ return Promise.reject(new TypeError(RELEASED));
591+ return this._s._cancel(reason);
592+ }
593+
594+ get closed() {
595+ if (this._released)
596+ return Promise.reject(new TypeError(RELEASED));
597+ return this._s._closedPromise;
598+ }
599+
600+ releaseLock() {
601+ if (this._released) return;
602+ const s = this._s;
603+ const c = this._c;
604+ const err = new TypeError(RELEASED);
605+ for (const d of c._pendingPullIntos)
606+ if (d.req) d.req.reject(err);
607+ c._pendingPullIntos = [];
608+ c._invalidate();
609+ s._locked = false;
610+ s._reader = null;
611+ this._released = true;
612+ }
613+}
614+
615+// Internal controller over an already-materialized body: BYOB reads
616+// fill from the remaining bytes of the shared {bytes, off} cursor and
617+// never park. Fewer bytes than asked (or than `min`) means the body is
618+// ending; done flips only on the empty read after it, like Workerd's
619+// internal sources.
620+class BufferedInternalController {
621+ _pendingPullIntos = []; // for releaseLock; never populated
622+
623+ constructor(st) { this._st = st; }
624+
625+ _invalidate() {}
626+
627+ _pullInto(view, _min) {
628+ let buffer;
629+ try { buffer = view.buffer.transfer(); }
630+ catch (e) { return Promise.reject(e); }
631+ const st = this._st;
632+ const elementSize = view.BYTES_PER_ELEMENT ?? 1;
633+ let n = Math.min(st.bytes.byteLength - st.off, view.byteLength);
634+ n -= n % elementSize;
635+ if (n > 0) {
636+ new Uint8Array(buffer, view.byteOffset, n)
637+ .set(st.bytes.subarray(st.off, st.off + n));
638+ st.off += n;
639+ }
640+ return Promise.resolve(_readResult(
641+ new view.constructor(buffer, view.byteOffset, n / elementSize),
642+ n === 0));
643+ }
644+}
645+
646+// Installed per byte-stream instance by _setup.
647+function byteGetReader(options) {
648+ if (options !== undefined && options !== null &&
649+ options.mode !== undefined) {
650+ if (String(options.mode) !== 'byob')
651+ throw new TypeError(`Invalid reader mode '${options.mode}'`);
652+ return new ReadableStreamBYOBReader(this);
653+ }
654+ return new ByteDefaultReader(this);
655+}
656+
657+function byteCancel(reason) {
658+ const c = this._byteCtl;
659+ if (this._closed) return Promise.resolve();
660+ if (this._errored) return Promise.reject(this._error);
661+ this._disturbed = true;
662+ c._queue = [];
663+ c._queueTotalSize = 0;
664+ const pending = c._pendingPullIntos;
665+ c._pendingPullIntos = [];
666+ c._invalidate();
667+ // Spec: cancel resolves pending BYOB reads with no value.
668+ for (const d of pending)
669+ if (d.req) d.req.resolve(_readResult(undefined, true));
670+ this._finishClose();
671+ if (!c._cancelFn) return Promise.resolve();
672+ let result;
673+ try { result = c._cancelFn.call(c._source, reason); }
674+ catch (e) { return Promise.reject(e); }
675+ return Promise.resolve(result).then(() => undefined);
676+}
677+
678+// Web IDL toStringTag.
679+for (const [cls, name] of [
680+ [ReadableByteStreamController, 'ReadableByteStreamController'],
681+ [ReadableStreamBYOBReader, 'ReadableStreamBYOBReader'],
682+ [ReadableStreamBYOBRequest, 'ReadableStreamBYOBRequest'],
683+]) {
684+ Object.defineProperty(cls.prototype, Symbol.toStringTag,
685+ { value: name, configurable: true });
686+}
687+
688+return {
689+ ReadableByteStreamController,
690+ ReadableStreamBYOBReader,
691+ ReadableStreamBYOBRequest,
692+};
693+})()
addedcrates/celld/js/compression_streams.js+73−0View file
@@ -1,0 +1,73 @@
1+// CompressionStream / DecompressionStream — WHATWG Compression Streams,
2+// each a TransformStream over one stateful native zlib stream
3+// (__zlib_stream_new / push / end / drop). Output streams chunk by chunk
4+// as input is written; the terminal block arrives from flush() when the
5+// writable side closes. A cancelled or aborted stream drops its native
6+// state instead of leaking it.
7+//
8+// Compiled on first access (see LAZY_GLOBALS); a bundle that never names
9+// either global never pays for this file.
10+(() => {
11+
12+// Per spec the chunk must be a BufferSource; anything else is a
13+// TypeError, which errors both sides of the transform.
14+function bytes(chunk) {
15+ if (ArrayBuffer.isView(chunk))
16+ return new Uint8Array(chunk.buffer, chunk.byteOffset,
17+ chunk.byteLength);
18+ if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
19+ throw new TypeError(
20+ 'The provided value is not of type (ArrayBuffer or ' +
21+ 'ArrayBufferView).');
22+}
23+
24+function make(format, decompress) {
25+ format = String(format);
26+ if (format !== 'gzip' && format !== 'deflate' &&
27+ format !== 'deflate-raw')
28+ throw new TypeError(
29+ `Unsupported compression format: '${format}'`);
30+ const id = __zlib_stream_new(format, decompress);
31+ const ts = new TransformStream({
32+ transform(chunk, controller) {
33+ const out = __zlib_stream_push(id, bytes(chunk));
34+ if (out.byteLength) controller.enqueue(out);
35+ },
36+ flush(controller) {
37+ const out = __zlib_stream_end(id);
38+ if (out.byteLength) controller.enqueue(out);
39+ },
40+ cancel() { __zlib_stream_drop(id); },
41+ });
42+ // Workerd's compression streams are internal streams: a
43+ // pending read() rejects with the cancel reason instead
44+ // of resolving {done: true}.
45+ ts.readable._cancelRejectsReads = true;
46+ return ts;
47+}
48+
49+class CompressionStream {
50+ constructor(format) {
51+ const ts = make(format, false);
52+ this.readable = ts.readable;
53+ this.writable = ts.writable;
54+ }
55+}
56+
57+class DecompressionStream {
58+ constructor(format) {
59+ const ts = make(format, true);
60+ this.readable = ts.readable;
61+ this.writable = ts.writable;
62+ }
63+}
64+
65+for (const [cls, name] of [
66+ [CompressionStream, 'CompressionStream'],
67+ [DecompressionStream, 'DecompressionStream'],
68+])
69+ Object.defineProperty(cls.prototype, Symbol.toStringTag,
70+ { value: name, configurable: true });
71+
72+return { CompressionStream, DecompressionStream };
73+})()
addedcrates/celld/js/crypto.js+317−0View file
@@ -1,0 +1,317 @@
1+// Web Crypto implementation for the embedded runtime.
2+//
3+// The common WebCrypto paths use typed-array host ops.
4+// Cells keeps a second, JSON-shaped op for Workers-compatible algorithms that
5+// require structured arguments (RSA-OAEP, ECDSA, and Ed25519).
6+(function () {
7+ const _randomValues = $$randomValues;
8+ const _digest = $$digest;
9+ const _hmacSign = $$hmacSign;
10+ const _hmacVerify = $$hmacVerify;
11+ const _aesEncrypt = $$aesEncrypt;
12+ const _aesDecrypt = $$aesDecrypt;
13+
14+ const _DIGEST_ALGS = new Set([
15+ "SHA-1", "SHA-256", "SHA-384", "SHA-512",
16+ ]);
17+ const _SECRET_KEY_ALGS = new Set(["HMAC", "AES-GCM", "AES-CBC"]);
18+
19+ function _toBuf(data) {
20+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
21+ if (ArrayBuffer.isView(data)) {
22+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
23+ }
24+ throw new TypeError("expected an ArrayBuffer or ArrayBufferView");
25+ }
26+
27+ function _algorithmName(algorithm) {
28+ return String(
29+ typeof algorithm === "string" ? algorithm : algorithm?.name || "",
30+ ).toUpperCase();
31+ }
32+
33+ function _hashName(hash) {
34+ return _algorithmName(
35+ typeof hash === "string" ? hash : hash?.name || "SHA-256",
36+ );
37+ }
38+
39+ function _notSupported(message) {
40+ return new DOMException(message, "NotSupportedError");
41+ }
42+
43+ function _operationError(message) {
44+ return new DOMException(message, "OperationError");
45+ }
46+
47+ class CryptoKey {
48+ constructor(type, algorithm, extractable, usages, material) {
49+ Object.defineProperties(this, {
50+ type: { value: type, enumerable: true },
51+ algorithm: { value: algorithm, enumerable: true },
52+ extractable: { value: Boolean(extractable), enumerable: true },
53+ usages: { value: Object.freeze(Array.from(usages || [])), enumerable: true },
54+ __celldMaterial: { value: material },
55+ });
56+ }
57+ get [Symbol.toStringTag]() { return "CryptoKey"; }
58+ }
59+
60+ function _makeKey(type, algorithm, extractable, usages, material) {
61+ return new CryptoKey(type, algorithm, extractable, usages, material);
62+ }
63+
64+ function _extra(operation, input) {
65+ return JSON.parse(__crypto_operation(operation, JSON.stringify(input)));
66+ }
67+
68+ class SubtleCrypto {
69+ get [Symbol.toStringTag]() { return "SubtleCrypto"; }
70+
71+ async digest(algorithm, data) {
72+ const name = _algorithmName(algorithm);
73+ if (!_DIGEST_ALGS.has(name)) {
74+ throw _notSupported("unsupported digest algorithm: " + name);
75+ }
76+ const out = _digest(name, _toBuf(data));
77+ return out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength);
78+ }
79+
80+ async importKey(format, keyData, algorithm, extractable, usages) {
81+ const name = _algorithmName(algorithm);
82+ if (format === "raw" && _SECRET_KEY_ALGS.has(name)) {
83+ const raw = _toBuf(keyData).slice();
84+ const normalized = name === "HMAC"
85+ ? { name, hash: { name: _hashName(algorithm?.hash) }, length: raw.byteLength * 8 }
86+ : { name, length: raw.byteLength * 8 };
87+ return _makeKey(
88+ "secret", normalized, extractable, usages, { bytes: raw },
89+ );
90+ }
91+ if (format === "pkcs8" && (name === "ED25519" || name === "ECDSA")) {
92+ return _makeKey(
93+ "private", algorithm, extractable, usages,
94+ { bytes: _toBuf(keyData).slice() },
95+ );
96+ }
97+ if (format === "jwk" && name === "RSA-OAEP") {
98+ return _makeKey(
99+ keyData?.d ? "private" : "public",
100+ algorithm,
101+ extractable,
102+ usages,
103+ { jwk: structuredClone(keyData) },
104+ );
105+ }
106+ throw _notSupported("unsupported key import");
107+ }
108+
109+ async exportKey(format, key) {
110+ if (format === "raw" && key?.__celldMaterial?.bytes) {
111+ if (!key.extractable) {
112+ throw new DOMException("key is not extractable", "InvalidAccessError");
113+ }
114+ const raw = key.__celldMaterial.bytes;
115+ return raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength);
116+ }
117+ if (format === "jwk" && key?.__celldMaterial?.jwk) {
118+ if (!key.extractable) {
119+ throw new DOMException("key is not extractable", "InvalidAccessError");
120+ }
121+ return structuredClone(key.__celldMaterial.jwk);
122+ }
123+ throw _notSupported("unsupported key export");
124+ }
125+
126+ async generateKey(algorithm, extractable, usages) {
127+ const name = _algorithmName(algorithm);
128+ if (_SECRET_KEY_ALGS.has(name)) {
129+ let byteLength;
130+ if (name === "HMAC") {
131+ const defaults = {
132+ "SHA-1": 20,
133+ "SHA-256": 32,
134+ "SHA-384": 48,
135+ "SHA-512": 64,
136+ };
137+ const hash = _hashName(algorithm?.hash);
138+ byteLength = algorithm?.length
139+ ? Number(algorithm.length) / 8
140+ : defaults[hash];
141+ if (!byteLength) throw _notSupported("unsupported HMAC hash: " + hash);
142+ const raw = new Uint8Array(byteLength);
143+ crypto.getRandomValues(raw);
144+ return _makeKey(
145+ "secret",
146+ { name, hash: { name: hash }, length: raw.byteLength * 8 },
147+ extractable,
148+ usages,
149+ { bytes: raw },
150+ );
151+ }
152+ byteLength = Number(algorithm?.length || 256) / 8;
153+ if (byteLength !== 16 && byteLength !== 32) {
154+ throw new DOMException("AES-GCM length must be 128 or 256", "OperationError");
155+ }
156+ const raw = new Uint8Array(byteLength);
157+ crypto.getRandomValues(raw);
158+ return _makeKey(
159+ "secret",
160+ { name, length: raw.byteLength * 8 },
161+ extractable,
162+ usages,
163+ { bytes: raw },
164+ );
165+ }
166+ if (name === "RSA-OAEP") {
167+ const pair = _extra("rsa-generate", {});
168+ return {
169+ publicKey: _makeKey(
170+ "public", algorithm, true,
171+ usages.filter((usage) => usage === "encrypt"),
172+ { jwk: pair.publicKey },
173+ ),
174+ privateKey: _makeKey(
175+ "private", algorithm, extractable,
176+ usages.filter((usage) => usage === "decrypt"),
177+ { jwk: pair.privateKey },
178+ ),
179+ };
180+ }
181+ throw _notSupported("unsupported key algorithm: " + name);
182+ }
183+
184+ async sign(algorithm, key, data) {
185+ const name = _algorithmName(algorithm || key?.algorithm);
186+ const bytes = _toBuf(data);
187+ if (name === "HMAC") {
188+ const hash = _hashName(key?.algorithm?.hash);
189+ const sig = _hmacSign(hash, key.__celldMaterial.bytes, bytes);
190+ if (!sig) throw _operationError("HMAC sign failed");
191+ return sig.buffer.slice(sig.byteOffset, sig.byteOffset + sig.byteLength);
192+ }
193+ const operation = name === "ED25519"
194+ ? "ed25519-sign"
195+ : name === "ECDSA"
196+ ? "p256-sign"
197+ : null;
198+ if (!operation) throw _notSupported("unsupported sign algorithm: " + name);
199+ const result = _extra(operation, {
200+ key: Array.from(key?.__celldMaterial?.bytes || []),
201+ data: Array.from(bytes),
202+ });
203+ return Uint8Array.from(result.bytes).buffer;
204+ }
205+
206+ async verify(algorithm, key, signature, data) {
207+ const name = _algorithmName(algorithm || key?.algorithm);
208+ if (name !== "HMAC") {
209+ throw _notSupported("unsupported verify algorithm: " + name);
210+ }
211+ return _hmacVerify(
212+ _hashName(key?.algorithm?.hash),
213+ key.__celldMaterial.bytes,
214+ _toBuf(signature),
215+ _toBuf(data),
216+ );
217+ }
218+
219+ async encrypt(algorithm, key, data) {
220+ const name = _algorithmName(algorithm);
221+ if (name !== "AES-GCM") {
222+ throw _notSupported("unsupported encrypt algorithm: " + name);
223+ }
224+ const out = _aesEncrypt(
225+ key.__celldMaterial.bytes,
226+ _toBuf(algorithm.iv),
227+ _toBuf(data),
228+ );
229+ if (!out) throw _operationError("AES-GCM encrypt failed");
230+ return out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength);
231+ }
232+
233+ async decrypt(algorithm, key, data) {
234+ const name = _algorithmName(algorithm);
235+ if (name === "AES-GCM") {
236+ const out = _aesDecrypt(
237+ key.__celldMaterial.bytes,
238+ _toBuf(algorithm.iv),
239+ _toBuf(data),
240+ );
241+ if (!out) throw _operationError("AES-GCM decrypt failed");
242+ return out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength);
243+ }
244+ if (name === "RSA-OAEP") {
245+ const result = _extra("rsa-oaep-decrypt", {
246+ jwk: key?.__celldMaterial?.jwk,
247+ data: Array.from(_toBuf(data)),
248+ });
249+ return Uint8Array.from(result.bytes).buffer;
250+ }
251+ throw _notSupported("unsupported decrypt algorithm: " + name);
252+ }
253+ }
254+
255+ const subtle = new SubtleCrypto();
256+ const crypto = {
257+ getRandomValues(array) {
258+ // Web IDL brand check, observable via node:crypto's webcrypto alias.
259+ if (this !== crypto) throw new TypeError("Illegal invocation");
260+ if (
261+ !(array instanceof Int8Array) &&
262+ !(array instanceof Uint8Array) &&
263+ !(array instanceof Uint8ClampedArray) &&
264+ !(array instanceof Int16Array) &&
265+ !(array instanceof Uint16Array) &&
266+ !(array instanceof Int32Array) &&
267+ !(array instanceof Uint32Array) &&
268+ !(array instanceof BigInt64Array) &&
269+ !(array instanceof BigUint64Array)
270+ ) {
271+ throw new DOMException(
272+ "Argument is not an integer-typed array",
273+ "TypeMismatchError",
274+ );
275+ }
276+ if (array.byteLength > 65536) {
277+ throw new DOMException(
278+ "getRandomValues byteLength must be at most 65536",
279+ "QuotaExceededError",
280+ );
281+ }
282+ _randomValues(array);
283+ return array;
284+ },
285+
286+ randomUUID() {
287+ const bytes = new Uint8Array(16);
288+ _randomValues(bytes);
289+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
290+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
291+ const h = (index) => bytes[index].toString(16).padStart(2, "0");
292+ return h(0) + h(1) + h(2) + h(3) + "-" +
293+ h(4) + h(5) + "-" + h(6) + h(7) + "-" +
294+ h(8) + h(9) + "-" + h(10) + h(11) +
295+ h(12) + h(13) + h(14) + h(15);
296+ },
297+
298+ subtle,
299+ get [Symbol.toStringTag]() { return "Crypto"; },
300+ };
301+
302+ globalThis.CryptoKey = CryptoKey;
303+ globalThis.SubtleCrypto = SubtleCrypto;
304+ globalThis.crypto = crypto;
305+})();
306+
307+// Last harness script, so this sees every internal the others declared.
308+// Runtime plumbing must not show up in `for (const k in globalThis)`: a
309+// bundle walking the globals should find the Web platform and nothing
310+// else. Host ops are already non-enumerable; these are the JS-side ones.
311+for (const n of Object.getOwnPropertyNames(globalThis))
312+ if (n.startsWith("__") || n.startsWith("$$"))
313+ // A top-level `function` declaration is non-configurable, so a
314+ // couple of harness helpers cannot be hidden. Harmless: a walker
315+ // sees a function either way.
316+ try { Object.defineProperty(globalThis, n, { enumerable: false }); }
317+ catch { /* non-configurable */ }
addedcrates/celld/js/harness.js+4479−0View file
@@ -1,0 +1,4479 @@
1+// The DO object model and the Cloudflare-compatible runtime surface, run
2+// once per isolate by `js.rs::install_harness` after the Web-API prelude.
3+// Lived as a 4,000-line raw string inside js.rs until 2026-07-29; it is a
4+// JavaScript program and belongs in a .js file, like the rest of src/js/.
5+function __bodyBytes(body) {
6+ if (body == null) return new Uint8Array();
7+ if (body && body.__celldBodyBytes instanceof Uint8Array)
8+ return body.__celldBodyBytes.slice();
9+ if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0));
10+ if (ArrayBuffer.isView(body))
11+ return new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice();
12+ return new TextEncoder().encode(String(body));
13+}
14+function __chunkBytes(chunk) {
15+ if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
16+ if (ArrayBuffer.isView(chunk))
17+ return new Uint8Array(
18+ chunk.buffer, chunk.byteOffset, chunk.byteLength);
19+ throw new TypeError(
20+ "Iterable bodies must produce ArrayBuffer or " +
21+ "ArrayBufferView chunks");
22+}
23+// Workerd's "gen" bodies: async iterables become a body stream;
24+// sync iterables of buffers/views concatenate eagerly. Called only
25+// for object bodies that are not streams or Blobs — an object with
26+// a custom toString/@@toPrimitive stringifies instead, unless it is
27+// an array or async-iterable (Workerd's precedence). Returns null
28+// for the string-coercion path.
29+function __iterableBody(body) {
30+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))
31+ return null;
32+ const asyncIter = body[Symbol.asyncIterator];
33+ if (typeof asyncIter === "function") {
34+ const iterator = asyncIter.call(body);
35+ return new ReadableStream({
36+ async pull(controller) {
37+ const result = await iterator.next();
38+ if (result.done) { controller.close(); return; }
39+ controller.enqueue(__chunkBytes(result.value));
40+ },
41+ cancel(reason) {
42+ if (typeof iterator.return === "function")
43+ iterator.return(reason);
44+ },
45+ }, { highWaterMark: 0 });
46+ }
47+ if (!Array.isArray(body) &&
48+ (body.toString !== Object.prototype.toString ||
49+ body[Symbol.toPrimitive] !== undefined))
50+ return null;
51+ if (typeof body[Symbol.iterator] !== "function") return null;
52+ const chunks = [];
53+ let length = 0;
54+ for (const chunk of body) {
55+ if (!(chunk instanceof ArrayBuffer) && !ArrayBuffer.isView(chunk))
56+ return null;
57+ const view = __chunkBytes(chunk);
58+ chunks.push(view);
59+ length += view.byteLength;
60+ }
61+ const bytes = new Uint8Array(length);
62+ let offset = 0;
63+ for (const view of chunks) {
64+ bytes.set(view, offset);
65+ offset += view.byteLength;
66+ }
67+ return bytes;
68+}
69+// Drain a Request/Response body stream, caching the result on the
70+// instance so later consumers see the materialized bytes.
71+async function __drainBody(target) {
72+ const chunks = [];
73+ let length = 0;
74+ const reader = target.body.getReader();
75+ for (;;) {
76+ const result = await reader.read();
77+ if (result.done) break;
78+ chunks.push(result.value);
79+ length += result.value.byteLength;
80+ }
81+ const bytes = new Uint8Array(length);
82+ let offset = 0;
83+ for (const chunk of chunks) {
84+ bytes.set(chunk, offset);
85+ offset += chunk.byteLength;
86+ }
87+ target._bodyBytes = bytes;
88+ target._body = new TextDecoder().decode(bytes);
89+ return bytes;
90+}
91+class CelldBodyStream extends ReadableStream {
92+ constructor(body) {
93+ const bytes = __bodyBytes(body);
94+ const st = { bytes, off: 0 };
95+ super({
96+ pull(controller) {
97+ if (st.off >= st.bytes.byteLength) {
98+ controller.close();
99+ return;
100+ }
101+ const end = Math.min(st.off + 64 * 1024, st.bytes.byteLength);
102+ controller.enqueue(st.bytes.subarray(st.off, end));
103+ st.off = end;
104+ },
105+ }, { highWaterMark: 0 });
106+ this._st = st;
107+ this.__celldBodyBytes = bytes;
108+ // Known length, so re-using this stream as a subrequest body
109+ // still advertises Content-Length.
110+ this._expectedLength = bytes.byteLength;
111+ }
112+ get __celldBodyText() { return new TextDecoder().decode(this.__celldBodyBytes); }
113+ // Workerd body streams are internal streams, so BYOB readers
114+ // work on them. Naming ReadableStreamBYOBReader compiles the
115+ // lazy byte-stream prelude; a worker that never asks for byob
116+ // mode never pays for it.
117+ getReader(options) {
118+ if (options !== undefined && options !== null &&
119+ options.mode !== undefined) {
120+ if (String(options.mode) !== "byob")
121+ throw new TypeError(`Invalid reader mode '${options.mode}'`);
122+ if (this._ictl === undefined)
123+ this._ictl = ReadableStreamBYOBReader._buffered(this._st);
124+ return new ReadableStreamBYOBReader(this);
125+ }
126+ return super.getReader(options);
127+ }
128+ // Cancelling a body stream poisons later consumption: text()
129+ // and friends reject, as they would over a real socket.
130+ _cancel(reason) {
131+ this._cancelled = true;
132+ return super._cancel(reason);
133+ }
134+}
135+class CelldHttpBodyStream extends ReadableStream {
136+ constructor(streamId) {
137+ const id = Number(streamId);
138+ super({
139+ async pull(controller) {
140+ const chunk = JSON.parse(await __http_stream_read(id));
141+ if (chunk.done) controller.close();
142+ else controller.enqueue(Uint8Array.from(chunk.bytes || []));
143+ },
144+ cancel() { __http_stream_cancel(id); },
145+ }, { highWaterMark: 0 });
146+ this.__celldStreamId = id;
147+ }
148+ tee() {
149+ if (this.locked) throw new TypeError("ReadableStream is locked");
150+ this._locked = true;
151+ this._disturbed = true;
152+ const [left, right] = JSON.parse(
153+ __http_stream_tee(this.__celldStreamId),
154+ );
155+ return [
156+ new CelldHttpBodyStream(left),
157+ new CelldHttpBodyStream(right),
158+ ];
159+ }
160+}
161+globalThis.Response = class Response {
162+ constructor(body, init = {}) {
163+ // Streaming/iterable detection runs only for object bodies, so
164+ // the common string path skips every instanceof below.
165+ let stream = null;
166+ let blob = null;
167+ if (body !== null && typeof body === "object") {
168+ if (body instanceof ReadableStream) stream = body;
169+ else if (globalThis.Blob && body instanceof Blob) blob = body;
170+ else {
171+ const iterable = __iterableBody(body);
172+ if (iterable instanceof ReadableStream) stream = iterable;
173+ else if (iterable !== null) body = iterable;
174+ }
175+ }
176+ this._bodyBytes = stream !== null
177+ ? null
178+ : blob ? blob._bytes.slice() : __bodyBytes(body);
179+ this._body = stream !== null
180+ ? null
181+ : new TextDecoder().decode(this._bodyBytes);
182+ // Hono rebuilds a response after middleware with
183+ // `new Response(response.body, response)`; the held stream (or a
184+ // fresh CelldBodyStream) preserves the payload across that
185+ // standard clone shape.
186+ this.body = body == null
187+ ? null
188+ : stream !== null
189+ ? stream
190+ : new CelldBodyStream(this._bodyBytes);
191+ this.status = init.status === undefined ? 200 : Number(init.status);
192+ this.statusText = init.statusText === undefined ? "" : String(init.statusText);
193+ this.headers = new Headers(init.headers);
194+ if (blob && blob.type && !this.headers.has("content-type"))
195+ this.headers.set("content-type", blob.type);
196+ this.webSocket = init.webSocket;
197+ this._wsTarget = init.__wsTarget || init._wsTarget || null;
198+ this.ok = this.status >= 200 && this.status <= 299;
199+ this.redirected = false;
200+ this.type = "default";
201+ this.url = "";
202+ this.bodyUsed = false;
203+ if (init.cf !== undefined) this.cf = init.cf;
204+ }
205+ static json(data, init = {}) {
206+ const headers = new Headers(init.headers || {});
207+ if (!headers.has("content-type"))
208+ headers.set("content-type", "application/json");
209+ return new Response(JSON.stringify(data), { ...init, headers });
210+ }
211+ async _consume() {
212+ if (this._bodyBytes !== null) {
213+ if (this.body !== null && this.body._cancelled)
214+ throw new TypeError(
215+ "Body has already been used. It can only be used once. " +
216+ "Use tee() first if you need to read it multiple times.");
217+ return this._bodyBytes;
218+ }
219+ return __drainBody(this);
220+ }
221+ async text() {
222+ this.bodyUsed = true;
223+ return new TextDecoder().decode(await this._consume());
224+ }
225+ async json() { return JSON.parse(await this.text()); }
226+ async formData() {
227+ return __parseFormData(
228+ await this.text(), this.headers.get('content-type'));
229+ }
230+ async arrayBuffer() {
231+ this.bodyUsed = true;
232+ return (await this._consume()).slice().buffer;
233+ }
234+ async blob() {
235+ return new Blob([await this.arrayBuffer()],
236+ { type: this.headers.get("content-type") || "" });
237+ }
238+ clone() {
239+ if (this.bodyUsed) throw new TypeError("Body has already been consumed");
240+ if (this._bodyBytes === null)
241+ throw new TypeError("Cannot clone a streaming response before consumption");
242+ return new Response(this._bodyBytes, {
243+ status: this.status, statusText: this.statusText, headers: this.headers,
244+ webSocket: this.webSocket, __wsTarget: this._wsTarget, cf: this.cf,
245+ });
246+ }
247+};
248+// Hoisted: this would otherwise allocate an array and scan it on
249+// every Request construction, which is the HTTP hot path.
250+const __HTTP_METHODS = new Set(
251+ ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]);
252+globalThis.Request = class Request {
253+ constructor(input, init = {}) {
254+ const prior = input instanceof Request ? input : null;
255+ const suppliedSignal = init.signal !== undefined;
256+ // The cache option needs the cache_option_enabled compat flag,
257+ // which Cells does not implement (Workerd's cache-disabled path).
258+ if (init.cache !== undefined)
259+ throw new Error("The 'cache' field on 'RequestInitializerDict' " +
260+ "is not implemented.");
261+ this.url = prior ? prior.url : String(input);
262+ {
263+ // Workers upper-cases every method (the
264+ // upper_case_all_http_methods flag) but rejects anything outside
265+ // the known set, reporting the original casing.
266+ const raw = String(init.method === undefined
267+ ? (prior ? prior.method : "GET") : init.method);
268+ const upper = raw.toUpperCase();
269+ if (!__HTTP_METHODS.has(upper))
270+ throw new TypeError(`Invalid HTTP method string: ${raw}`);
271+ this.method = upper;
272+ }
273+ const hasBody =
274+ Object.prototype.hasOwnProperty.call(init, "body");
275+ let body = hasBody ? init.body : null;
276+ let stream = null;
277+ let blob = null;
278+ if (hasBody && body !== null && typeof body === "object") {
279+ if (body instanceof ReadableStream) stream = body;
280+ else if (globalThis.Blob && body instanceof Blob) blob = body;
281+ else {
282+ const iterable = __iterableBody(body);
283+ if (iterable instanceof ReadableStream) stream = iterable;
284+ else if (iterable !== null) body = iterable;
285+ }
286+ }
287+ if (!hasBody && prior && prior._bodyBytes === null) {
288+ // Adopt the prior request's stream; per spec the prior body
289+ // is disturbed by the new request.
290+ stream = prior.body;
291+ prior.bodyUsed = true;
292+ }
293+ this._bodyBytes = stream !== null
294+ ? null
295+ : hasBody
296+ ? (blob ? blob._bytes.slice() : __bodyBytes(body))
297+ : (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);
304+ this.bodyUsed = false;
305+ this.body = stream !== null
306+ ? stream
307+ : ["GET", "HEAD"].includes(this.method)
308+ ? null : new CelldBodyStream(this._bodyBytes);
309+ this.redirect = init.redirect || (prior ? prior.redirect : "follow");
310+ const cf = init.cf === undefined
311+ ? (prior ? prior.cf : undefined) : init.cf;
312+ if (cf !== undefined) this.cf = cf;
313+ this.signal = suppliedSignal
314+ ? init.signal
315+ : (prior ? prior.signal : new AbortController().signal);
316+ this._signalForSubrequests = init.__celldIncomingSignal
317+ ? null
318+ : suppliedSignal
319+ ? this.signal
320+ : (prior ? prior._signalForSubrequests : null);
321+ }
322+ async _consume() {
323+ if (this._bodyBytes !== null) return this._bodyBytes;
324+ return __drainBody(this);
325+ }
326+ async text() {
327+ this.bodyUsed = true;
328+ if (this._body !== null) return this._body;
329+ await this._consume();
330+ return this._body;
331+ }
332+ async json() { return JSON.parse(await this.text()); }
333+ async formData() {
334+ return __parseFormData(
335+ await this.text(), this.headers.get('content-type'));
336+ }
337+ async arrayBuffer() {
338+ this.bodyUsed = true;
339+ return (await this._consume()).slice().buffer;
340+ }
341+ async blob() {
342+ return new Blob([await this.arrayBuffer()],
343+ { type: this.headers.get("content-type") || "" });
344+ }
345+ clone() {
346+ if (this.bodyUsed) throw new TypeError("Body has already been consumed");
347+ if (this._bodyBytes === null) {
348+ // Streaming body: tee, keep one branch, clone the other.
349+ const [left, right] = this.body.tee();
350+ this.body = left;
351+ return new Request(this, { body: right });
352+ }
353+ return new Request(this);
354+ }
355+};
356+globalThis.__makeRequest = (
357+ url, method, body, headersJson = "[]", signal = undefined,
358+ incomingSignal = false,
359+) => new Request(url, {
360+ method, body, headers: JSON.parse(headersJson), signal,
361+ __celldIncomingSignal: incomingSignal,
362+});
363+const __fmt = (a) => a.map((x) => {
364+ if (typeof x === "string") return x;
365+ if (x instanceof Error) return x.stack || (x.name + ": " + x.message);
366+ try { return JSON.stringify(x); } catch { return String(x); }
367+}).join(" ");
368+globalThis.console = {
369+ log: (...a) => __log(__fmt(a)), info: (...a) => __log(__fmt(a)),
370+ error: (...a) => __log("ERROR " + __fmt(a)), warn: (...a) => __log("WARN " + __fmt(a)),
371+ debug() {}, trace() {}, group() {}, groupEnd() {}, table() {},
372+};
373+
374+// async-op shims: outbound fetch + timers, driven by the host event loop.
375+globalThis.fetch = async (input, init) => {
376+ const req = new Request(input, init);
377+ // `fetch(url, { headers: { Upgrade: "websocket" } })` is the other way
378+ // Cloudflare opens an outbound socket, and the one most examples use.
379+ if ((req.headers.get("upgrade") ?? "").toLowerCase() === "websocket") {
380+ return await __fetchWebSocketUpgrade(req);
381+ }
382+ const bytes = ["GET", "HEAD"].includes(req.method)
383+ ? null : await req._consume();
384+ const body = bytes === null
385+ ? undefined : JSON.stringify(Array.from(bytes));
386+ const r = JSON.parse(await __op_fetch(
387+ req.method, req.url, body, JSON.stringify(Array.from(req.headers)), req.redirect,
388+ ));
389+ const response = new Response(
390+ new CelldHttpBodyStream(r.streamId),
391+ { status: r.status, headers: r.headers },
392+ );
393+ response.url = req.url;
394+ return response;
395+};
396+globalThis.__fetchWebSocketUpgrade = async (req) => {
397+ const scope = __actorEventStack[__actorEventStack.length - 1] || "";
398+ const id = __ws_alloc();
399+ const socket = __makeSocket(id);
400+ socket._outbound = true;
401+ socket._polled = !scope;
402+ socket.url = req.url;
403+ socket.readyState = WebSocket.READY_STATE_CONNECTING;
404+ __sockets.set(id, socket);
405+ let raw;
406+ try {
407+ raw = JSON.parse(await __ws_upgrade(
408+ id,
409+ scope,
410+ req.url,
411+ JSON.stringify(Array.from(req.headers)),
412+ ));
413+ } catch (error) {
414+ __sockets.delete(id);
415+ throw error;
416+ }
417+ if (!raw.upgraded) {
418+ // The server answered without upgrading. That is an ordinary response,
419+ // not a connection error, and it is returned unchanged.
420+ __sockets.delete(id);
421+ const response = new Response(new Uint8Array(raw.body), {
422+ status: raw.status,
423+ headers: raw.headers,
424+ });
425+ response.url = req.url;
426+ return response;
427+ }
428+ socket.protocol = raw.protocol ?? "";
429+ const response = new Response(null, { status: 101 });
430+ response.webSocket = socket;
431+ response.url = req.url;
432+ return response;
433+};
434+globalThis.__makeAssetsBinding = (script) => ({
435+ async fetch(input, init) {
436+ const req = input instanceof Request ? new Request(input, init) : new Request(input, init);
437+ const r = JSON.parse(await __asset_fetch(
438+ script,
439+ req.method,
440+ req.url,
441+ JSON.stringify(Array.from(req.headers)),
442+ ));
443+ const response = new Response(
444+ new CelldHttpBodyStream(r.streamId),
445+ { status: r.status, headers: r.headers },
446+ );
447+ response.url = req.url;
448+ return response;
449+ },
450+});
451+// R2 is deliberately not implemented. The binding exists so a worker
452+// that declares r2_buckets still loads, but every method fails loudly
453+// instead of pretending to be a bucket.
454+globalThis.__makeR2Bucket = (name) => {
455+ const fail = (method) => () => {
456+ throw new Error(
457+ `R2 is not implemented in celld (binding ${name}, ` +
458+ `method ${method})`,
459+ );
460+ };
461+ const bucket = {};
462+ for (const method of ["head", "get", "put", "delete", "list",
463+ "createMultipartUpload", "resumeMultipartUpload"]) {
464+ bucket[method] = fail(method);
465+ }
466+ return bucket;
467+};
468+globalThis.__makeAiBinding = (url) => ({
469+ async run(model, input) {
470+ const response = await fetch(url, {
471+ method: "POST",
472+ headers: { "content-type": "application/json" },
473+ body: JSON.stringify({ model, input }),
474+ });
475+ if (!response.ok) throw new Error(`AI binding returned ${response.status}`);
476+ return response.json();
477+ },
478+});
479+const __timers = new Map();
480+globalThis.setTimeout = (cb, ms, ...a) => {
481+ const id = __timer_alloc();
482+ __timers.set(id, true);
483+ __op_timer(id, ms | 0).then(() => {
484+ if (!__timers.delete(id)) return;
485+ cb(...a);
486+ });
487+ return id;
488+};
489+globalThis.clearTimeout = (id) => {
490+ if (!__timers.delete(id)) return;
491+ __timer_cancel(id);
492+};
493+globalThis.setInterval = () => {
494+ throw new Error("setInterval is not implemented in celld");
495+};
496+globalThis.clearInterval = () => {};
497+
498+const __sqlCursorFinalizer = typeof FinalizationRegistry === "function"
499+ ? new FinalizationRegistry((cursorId) => __sql_cursor_close(cursorId))
500+ : null;
501+
502+// A `SqlStorageCursor` over one exec's result (Cloudflare DO SQL API).
503+class SqlCursor {
504+ constructor(res) {
505+ if (res.error) throw new Error("SQL error: " + res.error);
506+ this._decode = (value) => value && typeof value === "object" &&
507+ Array.isArray(value.__celld_bytes)
508+ ? Uint8Array.from(value.__celld_bytes).buffer
509+ : value;
510+ this.columns = res.columns;
511+ this.rowsWritten = Number(res.rowsWritten || 0);
512+ this.reusedCachedQueryForTest = Boolean(res.reusedCachedQuery);
513+ this._deferredError = null;
514+ if (res.native) {
515+ this._native = true;
516+ this._cursorId = Number(res.cursorId || 0);
517+ this._prefetched = res.row === null
518+ ? null
519+ : res.row.map(this._decode);
520+ this.rowsRead = this._prefetched === null ? 0 : 1;
521+ this._finalizerToken = null;
522+ if (this._cursorId && __sqlCursorFinalizer) {
523+ this._finalizerToken = {};
524+ __sqlCursorFinalizer.register(
525+ this, this._cursorId, this._finalizerToken,
526+ );
527+ }
528+ } else {
529+ this._native = false;
530+ this._rows = res.rows.map((row) => row.map(this._decode));
531+ this._rowCount = this._rows.length;
532+ this._index = 0;
533+ this.rowsRead = Math.min(1, this._rowCount);
534+ }
535+ }
536+ _obj(r) { const o = {}; for (let i = 0; i < this.columns.length; i++) o[this.columns[i]] = r[i]; return o; }
537+ _finishNative() {
538+ if (this._finalizerToken && __sqlCursorFinalizer)
539+ __sqlCursorFinalizer.unregister(this._finalizerToken);
540+ this._finalizerToken = null;
541+ this._cursorId = 0;
542+ }
543+ _advanceNative() {
544+ if (!this._cursorId) {
545+ this._prefetched = null;
546+ return;
547+ }
548+ const result = JSON.parse(__sql_cursor_next(this._cursorId));
549+ if (result.error) {
550+ this._deferredError = new Error("SQL error: " + result.error);
551+ this._prefetched = null;
552+ this._finishNative();
553+ return;
554+ }
555+ this.rowsWritten = Number(result.rowsWritten || this.rowsWritten);
556+ if (result.row === null) {
557+ this._prefetched = null;
558+ this._finishNative();
559+ } else {
560+ this._prefetched = result.row.map(this._decode);
561+ this.rowsRead++;
562+ }
563+ }
564+ _nextRaw() {
565+ if (this._native) {
566+ if (this._deferredError) {
567+ const error = this._deferredError;
568+ this._deferredError = null;
569+ throw error;
570+ }
571+ if (this._prefetched === null) return { done: true };
572+ const value = this._prefetched;
573+ this._advanceNative();
574+ return { done: false, value };
575+ }
576+ if (this._index >= this._rowCount) return { done: true };
577+ const index = this._index++;
578+ const value = this._rows[index];
579+ // Release consumed rows even if the cursor itself remains reachable.
580+ this._rows[index] = null;
581+ this.rowsRead = Math.min(this._index + 1, this._rowCount);
582+ return { done: false, value };
583+ }
584+ toArray() {
585+ const rows = [];
586+ while (true) {
587+ const result = this.next();
588+ if (result.done) return rows;
589+ rows.push(result.value);
590+ if (__heap_limit_excessively_exceeded())
591+ throw new Error("result set is too large to fit in memory");
592+ }
593+ }
594+ one() {
595+ const first = this.next();
596+ if (first.done)
597+ throw new Error("Expected exactly one result from SQL query, but got no results");
598+ if (!this.next().done)
599+ throw new Error("Expected exactly one result from SQL query, but got multiple results");
600+ return first.value;
601+ }
602+ *raw() {
603+ while (true) {
604+ const result = this._nextRaw();
605+ if (result.done) return;
606+ yield result.value;
607+ }
608+ }
609+ get columnNames() { return this.columns; }
610+ next() {
611+ const result = this._nextRaw();
612+ return result.done ? result : { done: false, value: this._obj(result.value) };
613+ }
614+ [Symbol.iterator]() { return this; }
615+}
616+class SqlStorage {
617+ constructor(scope) { this._scope = scope; }
618+ prepare(query) {
619+ const storage = this;
620+ const source = String(query);
621+ return (...binds) => storage.exec(source, ...binds);
622+ }
623+ exec(query, ...binds) {
624+ const encode = (value) => {
625+ if (value instanceof ArrayBuffer)
626+ return { __celld_bytes: Array.from(new Uint8Array(value)) };
627+ if (ArrayBuffer.isView(value))
628+ return { __celld_bytes: Array.from(
629+ new Uint8Array(value.buffer, value.byteOffset, value.byteLength),
630+ ) };
631+ return value;
632+ };
633+ return new SqlCursor(JSON.parse(__sql_cursor_start(
634+ this._scope, query, JSON.stringify(binds.map(encode)),
635+ )));
636+ }
637+ ingest(input) {
638+ const result = JSON.parse(__sql_ingest(this._scope, String(input)));
639+ if (result.error) throw new Error("SQL error: " + result.error);
640+ return result;
641+ }
642+ get databaseSize() { return __sql_database_size(this._scope); }
643+ setMaxPageCountForTest(pages) {
644+ if (typeof __sql_set_max_page_count_for_test !== "function")
645+ throw new Error("setMaxPageCountForTest is only available in tests");
646+ __sql_set_max_page_count_for_test(this._scope, Number(pages));
647+ }
648+ setWriteFaultForTest(enabled) {
649+ if (typeof __sql_set_write_fault_for_test !== "function")
650+ throw new Error("setWriteFaultForTest is only available in tests");
651+ __sql_set_write_fault_for_test(!!enabled);
652+ }
653+ setCacheSizeForTest(pages) {
654+ if (typeof __sql_set_cache_size_for_test !== "function")
655+ throw new Error("setCacheSizeForTest is only available in tests");
656+ __sql_set_cache_size_for_test(this._scope, Number(pages));
657+ }
658+ setInterruptFaultForTest(enabled) {
659+ if (typeof __sql_set_interrupt_fault_for_test !== "function")
660+ throw new Error(
661+ "setInterruptFaultForTest is only available in tests");
662+ __sql_set_interrupt_fault_for_test(this._scope, !!enabled);
663+ }
664+ registerNomemFunctionForTest() {
665+ if (typeof __sql_register_nomem_function_for_test !== "function")
666+ throw new Error(
667+ "registerNomemFunctionForTest is only available in tests");
668+ __sql_register_nomem_function_for_test(this._scope);
669+ }
670+}
671+function __readStoredValue(scope, key, read) {
672+ try {
673+ return read();
674+ } catch (error) {
675+ const message = String(error && error.message || error);
676+ if (!message.toLowerCase().includes("deserialize cloned data"))
677+ throw error;
678+ const contextual = new Error(
679+ "actor storage deserialization failed; actorId = " +
680+ scope + "; key = " + key + "; " + message,
681+ );
682+ contextual.cause = error;
683+ throw contextual;
684+ }
685+}
686+class SyncKvListIterator {
687+ constructor(root, generation, cursor) {
688+ this._root = root;
689+ this._generation = generation;
690+ this._cursor = cursor;
691+ }
692+ [Symbol.iterator]() { return this; }
693+ next() {
694+ if (this._generation !== this._root._syncKvListGeneration) {
695+ throw new Error(
696+ "kv.list() iterator was invalidated because a new call to kv.list() was started. " +
697+ "Only one kv.list() iterator can exist at a time.",
698+ );
699+ }
700+ const value =
701+ __storage_sync_list_next(this._cursor, __storedSentinel);
702+ if (value === null) return { done: true, value: undefined };
703+ value[1] = __unwrapStored(value[1]);
704+ return { done: false, value };
705+ }
706+}
707+class SyncKvStorage {
708+ constructor(storage) {
709+ this._storage = storage;
710+ this._root = storage._transactionRoot;
711+ }
712+ get(key) {
713+ key = String(key);
714+ return __unwrapStored(__readStoredValue(
715+ this._storage._scope, key,
716+ () => __storage_get(this._storage._scope, key,
717+ __storedSentinel),
718+ ));
719+ }
720+ put(key, value) {
721+ key = String(key);
722+ try {
723+ __storage_put(this._storage._scope, key, value);
724+ } catch (error) {
725+ __storage_put_serialized(this._storage._scope, key,
726+ __storedBytes(value, error));
727+ }
728+ }
729+ delete(key) {
730+ return __storage_delete(this._storage._scope, String(key));
731+ }
732+ list(options = {}) {
733+ const generation = ++this._root._syncKvListGeneration;
734+ const cursor = __storage_sync_list_start(
735+ this._storage._scope, JSON.stringify(options),
736+ );
737+ return new SyncKvListIterator(
738+ this._root, generation, cursor,
739+ );
740+ }
741+}
742+class DurableObjectStorage {
743+ constructor(
744+ scope,
745+ state = null,
746+ transactionRoot = null,
747+ transactionDepth = 0,
748+ transactionControl = null,
749+ ) {
750+ this._scope = scope;
751+ this._state = state;
752+ this.sql = new SqlStorage(scope);
753+ this._transactionRoot = transactionRoot || this;
754+ this._transactionDepth = transactionDepth;
755+ this._transactionControl = transactionControl;
756+ if (!transactionRoot) {
757+ this._transactionSerial = 0;
758+ this._transactionTail = Promise.resolve();
759+ this._syncKvListGeneration = 0;
760+ }
761+ this._kv = new SyncKvStorage(this);
762+ }
763+ get kv() { return this._kv; }
764+ _flushPendingPuts() {
765+ if (this._state && this._state._aborted) return false;
766+ __storage_flush_pending_puts(this._scope);
767+ return true;
768+ }
769+ async get(k) {
770+ await Promise.resolve();
771+ if (!this._flushPendingPuts()) return;
772+ const key = Array.isArray(k) ? JSON.stringify(k) : String(k);
773+ return __readStoredValue(this._scope, key, () => {
774+ if (Array.isArray(k))
775+ return __unwrapStoredMap(
776+ __storage_get_many(this._scope, k, __storedSentinel));
777+ return __unwrapStored(
778+ __storage_get(this._scope, k, __storedSentinel));
779+ });
780+ }
781+ async put(k, val) {
782+ if (typeof k === "string") {
783+ try {
784+ __storage_queue_put(this._scope, k, val);
785+ } catch (error) {
786+ __storage_queue_put_serialized(this._scope, k,
787+ __storedBytes(val, error));
788+ }
789+ await Promise.resolve();
790+ this._flushPendingPuts();
791+ return;
792+ }
793+ const source = k instanceof Map ? Array.from(k) : Object.entries(k);
794+ if (source.length === 0) return;
795+ const entries =
796+ source.map(([key, value]) => [String(key), value]);
797+ try {
798+ __storage_queue_put_many(this._scope, entries);
799+ } catch (error) {
800+ // A batch with a stub entry: encode every entry first (plain
801+ // entries keep their native clone bytes, stub entries take
802+ // the stored-stub envelope), then queue — so a genuinely
803+ // uncloneable entry still queues nothing, like the batch op,
804+ // which serializes fully before queueing.
805+ const encoded = entries.map(([key, value]) => {
806+ try {
807+ return [key, __sc_encode(value)];
808+ } catch (error_) {
809+ return [key, __storedBytes(value, error_)];
810+ }
811+ });
812+ for (const [key, bytes] of encoded)
813+ __storage_queue_put_serialized(this._scope, key, bytes);
814+ }
815+ await Promise.resolve();
816+ this._flushPendingPuts();
817+ }
818+ async delete(k) {
819+ await Promise.resolve();
820+ if (!this._flushPendingPuts()) return;
821+ if (Array.isArray(k)) {
822+ if (k.length === 0) return 0;
823+ return __storage_delete_many(this._scope, k);
824+ }
825+ return __storage_delete(this._scope, k);
826+ }
827+ async list(options = {}) {
828+ await Promise.resolve();
829+ if (!this._flushPendingPuts()) return new Map();
830+ return __unwrapStoredMap(__storage_list(
831+ this._scope, JSON.stringify(options), __storedSentinel));
832+ }
833+ async deleteAll() {
834+ await Promise.resolve();
835+ if (!this._flushPendingPuts()) return;
836+ __storage_delete_all(this._scope, __cell.deleteAllDeletesAlarm);
837+ }
838+ async sync() {
839+ await Promise.resolve();
840+ this._flushPendingPuts();
841+ }
842+ async setAlarm(t) {
843+ await Promise.resolve();
844+ if (!this._flushPendingPuts()) return;
845+ __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t));
846+ }
847+ async getAlarm() {
848+ await Promise.resolve();
849+ if (!this._flushPendingPuts()) return null;
850+ const v = __alarm_get(this._scope);
851+ return v === null ? null : v;
852+ }
853+ async deleteAlarm() {
854+ await Promise.resolve();
855+ if (!this._flushPendingPuts()) return;
856+ __alarm_delete(this._scope);
857+ }
858+ _transactionStart() {
859+ const root = this._transactionRoot;
860+ const savepoint = "cells_tx_" + (++root._transactionSerial);
861+ __storage_transaction_control(
862+ this._scope, "start", this._transactionDepth > 0, savepoint,
863+ );
864+ return savepoint;
865+ }
866+ _transactionCommit(savepoint) {
867+ __storage_transaction_control(
868+ this._scope, "commit", this._transactionDepth > 0, savepoint,
869+ );
870+ }
871+ _transactionRollback(savepoint, explicit = false) {
872+ __storage_transaction_control(
873+ this._scope,
874+ explicit ? "rollback_explicit" : "rollback",
875+ this._transactionDepth > 0,
876+ savepoint,
877+ );
878+ }
879+ _transactionView(transactionControl) {
880+ return new DurableObjectStorage(
881+ this._scope,
882+ this._state,
883+ this._transactionRoot,
884+ this._transactionDepth + 1,
885+ transactionControl,
886+ );
887+ }
888+ rollback() {
889+ const control = this._transactionControl;
890+ if (!control)
891+ throw new TypeError("rollback() must be called on a transaction");
892+ if (!control.rolledBack) {
893+ control.rollback();
894+ control.rolledBack = true;
895+ }
896+ }
897+ transactionSync(f) {
898+ const savepoint = this._transactionStart();
899+ const control = {
900+ rolledBack: false,
901+ rollback: () => this._transactionRollback(savepoint, true),
902+ };
903+ try {
904+ const value = f(this._transactionView(control));
905+ if (!control.rolledBack) this._transactionCommit(savepoint);
906+ return value;
907+ } catch (error) {
908+ if (!control.rolledBack) {
909+ try { this._transactionRollback(savepoint); } catch {}
910+ }
911+ throw error;
912+ }
913+ }
914+ async _runTransaction(f) {
915+ const savepoint = this._transactionStart();
916+ const control = {
917+ rolledBack: false,
918+ rollback: () => this._transactionRollback(savepoint, true),
919+ };
920+ try {
921+ const value = await f(this._transactionView(control));
922+ if (!control.rolledBack) this._transactionCommit(savepoint);
923+ return value;
924+ } catch (error) {
925+ if (!control.rolledBack) {
926+ try { this._transactionRollback(savepoint); } catch {}
927+ }
928+ throw error;
929+ }
930+ }
931+ async transaction(f) {
932+ if (this._transactionDepth > 0) return this._runTransaction(f);
933+ const root = this._transactionRoot;
934+ const previous = root._transactionTail;
935+ let release;
936+ root._transactionTail = new Promise((resolve) => { release = resolve; });
937+ await previous;
938+ try {
939+ return await this._runTransaction(f);
940+ } finally {
941+ release();
942+ }
943+ }
944+}
945+class DurableObjectId {
946+ constructor(className, value, name = undefined) {
947+ Object.defineProperties(this, {
948+ _className: { value: className },
949+ _value: { value },
950+ });
951+ this.name = name;
952+ this.jurisdiction = undefined;
953+ }
954+ toString() { return this._value; }
955+ equals(other) {
956+ return other instanceof DurableObjectId && other._value === this._value;
957+ }
958+ _scope() { return this._className + ":" + this._value; }
959+}
960+globalThis.DurableObjectRoutingError = class DurableObjectRoutingError
961+ extends Error {
962+ constructor(detail = {}) {
963+ super("The Durable Object owner is currently unreachable");
964+ this.name = "DurableObjectRoutingError";
965+ this.code = "owner_unreachable";
966+ this.retryable = true;
967+ if (typeof detail.scope === "string") this.scope = detail.scope;
968+ if (typeof detail.owner === "string") this.owner = detail.owner;
969+ }
970+};
971+const __durableObjectRoutingError = (error) => {
972+ const marker = "__CELLD_DO_ROUTING_ERROR__:";
973+ const message = String(error && error.message || error);
974+ const offset = message.indexOf(marker);
975+ if (offset < 0) return null;
976+ try {
977+ return new DurableObjectRoutingError(
978+ JSON.parse(message.slice(offset + marker.length)),
979+ );
980+ } catch {
981+ return new DurableObjectRoutingError();
982+ }
983+};
984+class DurableObjectState {
985+ constructor(scope) {
986+ this._scope = scope;
987+ this._aborted = false;
988+ this.storage = new DurableObjectStorage(scope, this);
989+ this._gate = Promise.resolve();
990+ this._blockDepth = 0;
991+ const separator = scope.indexOf(":");
992+ const className = separator < 0 ? scope : scope.slice(0, separator);
993+ const value = separator < 0 ? scope : scope.slice(separator + 1);
994+ this.id = new DurableObjectId(
995+ className, value, __cell.idNames[scope],
996+ );
997+ }
998+ // Workerd's DurableObjectState.exports (actor-state.h): the same
999+ // loopback surface as ctx.exports on stateless entrypoints.
1000+ get exports() { return __ctxExports(); }
1001+ blockConcurrencyWhile(f) {
1002+ if (typeof f !== "function")
1003+ throw new TypeError("blockConcurrencyWhile() requires a function");
1004+ if (this._blockDepth >= 64)
1005+ throw new Error(
1006+ "blockConcurrencyWhile() calls are nested too deeply.",
1007+ );
1008+ if (this._blockDepth > 0) return this._runConcurrencyBlock(f);
1009+ const next = this._gate.then(() => this._runConcurrencyBlock(f));
1010+ this._gate = next;
1011+ return next;
1012+ }
1013+ _runConcurrencyBlock(f) {
1014+ this._blockDepth++;
1015+ let result;
1016+ try {
1017+ result = f();
1018+ } catch (error) {
1019+ this._blockDepth--;
1020+ this._resetAfterConcurrencyFailure(error);
1021+ throw error;
1022+ }
1023+ const timerId = __timer_alloc();
1024+ let settled = false;
1025+ const timeout = __op_timer(
1026+ timerId,
1027+ 30_000,
1028+ ).then(() => {
1029+ if (!settled) {
1030+ throw new Error(
1031+ "A call to blockConcurrencyWhile() in a Durable Object waited for " +
1032+ "too long. The call was canceled and the Durable Object was reset.",
1033+ );
1034+ }
1035+ });
1036+ return Promise.race([Promise.resolve(result), timeout]).then(
1037+ (value) => {
1038+ settled = true;
1039+ __timer_cancel(timerId);
1040+ this._blockDepth--;
1041+ return value;
1042+ },
1043+ (error) => {
1044+ settled = true;
1045+ __timer_cancel(timerId);
1046+ this._blockDepth--;
1047+ this._resetAfterConcurrencyFailure(error);
1048+ throw error;
1049+ },
1050+ );
1051+ }
1052+ _resetAfterConcurrencyFailure(error) {
1053+ this._aborted = true;
1054+ __storage_cancel_pending_puts(this._scope);
1055+ const instance = __cell.instances[this._scope];
1056+ if (instance && instance.__celldState === this)
1057+ delete __cell.instances[this._scope];
1058+ // Under a stub-mediated caller (this scope is not the current
1059+ // event) the failure breaks the actor, as Workerd joins it
1060+ // into the on-abort promise; a direct event keeps reset-only
1061+ // semantics — its caller sees the rejection itself.
1062+ if (__actorEventStack[__actorEventStack.length - 1] !==
1063+ this._scope)
1064+ __actorBreak(this._scope, error);
1065+ }
1066+ abort(reason) {
1067+ this._aborted = true;
1068+ __storage_cancel_pending_puts(this._scope);
1069+ const instance = __cell.instances[this._scope];
1070+ if (instance && instance.__celldState === this)
1071+ delete __cell.instances[this._scope];
1072+ const message = reason instanceof Error
1073+ ? reason.message
1074+ : String(reason);
1075+ // Direct host-dispatched event on this actor: the uncatchable
1076+ // terminate_execution path. Under a same-isolate stub caller,
1077+ // termination would unwind the caller too, so break in JS.
1078+ if (__actorEventStack[__actorEventStack.length - 1] ===
1079+ this._scope) {
1080+ __actor_abort(this._scope, message);
1081+ return;
1082+ }
1083+ __actorBreak(this._scope,
1084+ reason instanceof Error ? reason : new Error(message));
1085+ }
1086+ _ready() { return this._gate; }
1087+ getWebSockets(tag) {
1088+ return JSON.parse(__ws_list(this._scope, tag)).map((row) => __socketFromRow(row));
1089+ }
1090+ acceptWebSocket(ws, tags = []) {
1091+ ws._target = { id: ws._id, scope: this._scope };
1092+ if (ws._peer) ws._peer._target = ws._target;
1093+ ws._hibernatable = true;
1094+ if (ws._peer) ws._peer._hibernatable = true;
1095+ ws._tags = Array.from(tags, String);
1096+ __ws_accept(ws._id, this._scope, JSON.stringify(ws._tags));
1097+ __sockets.set(ws._id, ws);
1098+ }
1099+ _socket(id) {
1100+ return __sockets.get(Number(id)) ||
1101+ this.getWebSockets().find((ws) => ws._id === id) ||
1102+ __wsStub(id);
1103+ }
1104+ waitUntil(promise) {
1105+ globalThis.__registerWaitUntil(promise);
1106+ }
1107+}
1108+function _instance(scope) {
1109+ let inst = __cell.instances[scope];
1110+ if (!inst) {
1111+ const className = scope.split(":")[0];
1112+ const cls = __cell.classes[className];
1113+ if (!cls) throw new Error("no DO class " + className);
1114+ const state = new DurableObjectState(scope);
1115+ inst = new cls(state, __cell.env);
1116+ Object.defineProperty(inst, "__celldState", { value: state });
1117+ // Workerd worker-rpc.c++ getTargetInfo(): RPC needs `extends
1118+ // DurableObject` unless the js_rpc compat flag is on. Decided
1119+ // once here; dispatch reads a boolean.
1120+ state._rpcOk = __cell.compat.jsRpc ||
1121+ __cell.doExports[className] === true;
1122+ __cell.instances[scope] = inst;
1123+ }
1124+ return inst;
1125+}
1126+async function _readyInstance(scope) {
1127+ const inst = _instance(scope);
1128+ await inst.__celldState._ready();
1129+ return inst;
1130+}
1131+const __actorEventStack = [];
1132+const __incomingRequestSignals = new Map();
1133+const __abortSignal = (signal, reason) => {
1134+ if (signal.aborted) return;
1135+ signal.aborted = true;
1136+ signal.reason = reason;
1137+ signal.dispatchEvent(new Event("abort"));
1138+};
1139+globalThis.__abortIncomingRequest = (requestId) => {
1140+ const signal = __incomingRequestSignals.get(String(requestId));
1141+ if (signal && !signal.aborted) {
1142+ __abortSignal(signal, new Error("The client has disconnected"));
1143+ return true;
1144+ }
1145+ return false;
1146+};
1147+globalThis.__registerIncomingRequest = (requestId, request) => {
1148+ __incomingRequestSignals.set(String(requestId), request.signal);
1149+};
1150+globalThis.__finishIncomingRequest = (requestId) => {
1151+ __incomingRequestSignals.delete(String(requestId));
1152+};
1153+globalThis.__endTerminatedActorEvent = (scope) => {
1154+ for (let index = __actorEventStack.length - 1; index >= 0; index--) {
1155+ if (__actorEventStack[index] === scope) {
1156+ __actorEventStack.splice(index, 1);
1157+ return;
1158+ }
1159+ }
1160+};
1161+// Race a pending dispatch against the caller's abort signal: on abort,
1162+// run `abandon` (which reaches the target's side) and reject with the
1163+// caller's reason. The dispatch keeps its settle handlers, so a late
1164+// settlement after abandonment cannot trip the unhandled-rejection
1165+// signal.
1166+const __raceCallerAbort = (dispatch, signal, abandon) =>
1167+ new Promise((resolve, reject) => {
1168+ let settled = false;
1169+ const onAbort = () => {
1170+ if (settled) return;
1171+ settled = true;
1172+ abandon();
1173+ reject(signal.reason);
1174+ };
1175+ signal.addEventListener("abort", onAbort, { once: true });
1176+ dispatch.then(
1177+ (value) => {
1178+ if (settled) return;
1179+ settled = true;
1180+ signal.removeEventListener("abort", onAbort);
1181+ resolve(value);
1182+ },
1183+ (error) => {
1184+ if (settled) return;
1185+ settled = true;
1186+ signal.removeEventListener("abort", onAbort);
1187+ reject(error);
1188+ },
1189+ );
1190+ });
1191+const __awaitCancellableDoCall = (operation, signal) => {
1192+ if (signal.aborted) {
1193+ __do_call_cancel(operation.__celldCancelId);
1194+ return Promise.reject(signal.reason);
1195+ }
1196+ return __raceCallerAbort(operation, signal,
1197+ () => __do_call_cancel(operation.__celldCancelId));
1198+};
1199+// Workerd semantics: a Response crossing a service binding is a fresh
1200+// fetch-shaped Response — immutable headers, default reason phrase,
1201+// the request URL, and a real body stream — never the callee's own
1202+// mutable object.
1203+const __STATUS_TEXT = {
1204+ 100: "Continue", 101: "Switching Protocols", 102: "Processing",
1205+ 103: "Early Hints", 200: "OK", 201: "Created", 202: "Accepted",
1206+ 203: "Non-Authoritative Information", 204: "No Content",
1207+ 205: "Reset Content", 206: "Partial Content", 207: "Multi-Status",
1208+ 208: "Already Reported", 226: "IM Used", 300: "Multiple Choices",
1209+ 301: "Moved Permanently", 302: "Found", 303: "See Other",
1210+ 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect",
1211+ 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized",
1212+ 402: "Payment Required", 403: "Forbidden", 404: "Not Found",
1213+ 405: "Method Not Allowed", 406: "Not Acceptable",
1214+ 407: "Proxy Authentication Required", 408: "Request Timeout",
1215+ 409: "Conflict", 410: "Gone", 411: "Length Required",
1216+ 412: "Precondition Failed", 413: "Payload Too Large",
1217+ 414: "URI Too Long", 415: "Unsupported Media Type",
1218+ 416: "Range Not Satisfiable", 417: "Expectation Failed",
1219+ 418: "I'm a teapot", 421: "Misdirected Request",
1220+ 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency",
1221+ 425: "Too Early", 426: "Upgrade Required",
1222+ 428: "Precondition Required", 429: "Too Many Requests",
1223+ 431: "Request Header Fields Too Large",
1224+ 451: "Unavailable For Legal Reasons", 500: "Internal Server Error",
1225+ 501: "Not Implemented", 502: "Bad Gateway",
1226+ 503: "Service Unavailable", 504: "Gateway Timeout",
1227+ 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates",
1228+ 507: "Insufficient Storage", 508: "Loop Detected",
1229+ 510: "Not Extended", 511: "Network Authentication Required",
1230+};
1231+const __wrapServiceResponse = (res, url) => {
1232+ const wrapped = new Response(
1233+ // Buffered bodies re-stream (an empty buffer still yields a
1234+ // stream, as over real HTTP); a streaming body passes through.
1235+ res._bodyBytes !== null ? res._bodyBytes : res.body,
1236+ {
1237+ status: res.status,
1238+ statusText:
1239+ res.statusText || __STATUS_TEXT[res.status] || "",
1240+ headers: res.headers,
1241+ webSocket: res.webSocket,
1242+ __wsTarget: res._wsTarget,
1243+ },
1244+ );
1245+ // The constructor copies headers, so mark the copy.
1246+ Object.defineProperty(wrapped.headers, "_immutable", { value: true });
1247+ wrapped.url = url;
1248+ // An upgraded pair whose both ends live in this isolate: link them
1249+ // directly — the host connection seam only reaches external
1250+ // clients. Frames the handler queued before linking flush first.
1251+ const client = wrapped.webSocket;
1252+ if (wrapped.status === 101 && client && client._peer) {
1253+ const server = client._peer;
1254+ client._loopback = server;
1255+ server._loopback = client;
1256+ for (const frame of server._pending.splice(0)) {
1257+ // "send-binary" joined this queue with outbound sockets; without a case
1258+ // of its own it fell through to the close branch and tore the pair down
1259+ // instead of delivering the frame.
1260+ if (frame[0] === "send")
1261+ queueMicrotask(() => client._dispatchMessage(frame[1]));
1262+ else if (frame[0] === "send-binary")
1263+ queueMicrotask(() => {
1264+ const data = frame[1];
1265+ client._dispatchMessage(
1266+ data instanceof ArrayBuffer ? data : data.buffer.slice(
1267+ data.byteOffset,
1268+ data.byteOffset + data.byteLength,
1269+ ),
1270+ );
1271+ });
1272+ else
1273+ queueMicrotask(
1274+ () => client._dispatchClose(frame[1], frame[2], true));
1275+ }
1276+ }
1277+ return wrapped;
1278+};
1279+// `[[services]]` binding: a Fetcher pointed at another Worker in this
1280+// process. No identity to resolve, so it goes straight to __svc_call.
1281+// Worker Loader (Code Mode): spawn a fresh isolate from supplied code and
1282+// invoke it. Walking skeleton — only `load(code)` and a default-entrypoint
1283+// `fetch()` are wired, mirroring the cross-isolate service-binding path below.
1284+globalThis.__makeLoader = () => {
1285+ // `get(name, …)` is memoized by name to one isolate; `load()` is anonymous.
1286+ // A stub holds a Promise<id> so `getCode` may be async and load lazily.
1287+ const byName = new Map();
1288+ const makeEntrypoint = (idPromise, entrypoint) => {
1289+ const target = {
1290+ async fetch(input, init) {
1291+ const id = await idPromise;
1292+ const req = new Request(input, init);
1293+ const headers = JSON.stringify(Array.from(req.headers));
1294+ const body_ = req._bodyBytes === null
1295+ ? await req._consume() : req._bodyBytes;
1296+ const r = JSON.parse(
1297+ await __loader_fetch(id, req.url, req.method, body_, headers));
1298+ const body = r.streamId !== undefined
1299+ ? new CelldHttpBodyStream(r.streamId)
1300+ : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []);
1301+ return __wrapServiceResponse(
1302+ new Response(body, { status: r.status, headers: r.headers }),
1303+ req.url);
1304+ },
1305+ };
1306+ // Both the default and named entrypoints expose RPC: property access is a
1307+ // callable pipeline node dispatched via __loader_rpc to that entrypoint in
1308+ // the loaded worker (default -> the "default" export, which
1309+ // register_entrypoints registers like any other). fetch stays on the
1310+ // target. Only single-method calls are supported for now.
1311+ const session = {
1312+ get: () => Promise.reject(new Error(
1313+ "Awaitable properties on loaded workers are not supported yet.")),
1314+ call: (path, args) => (async () => {
1315+ if (path.length !== 1)
1316+ throw new Error(
1317+ "Pipelined property paths on loaded workers are not supported " +
1318+ "yet.");
1319+ const id = await idPromise;
1320+ return __rpcDes(
1321+ await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false)));
1322+ })(),
1323+ };
1324+ return new Proxy(target, {
1325+ get: (base, prop) => {
1326+ if (prop === "then") return undefined;
1327+ if (Reflect.has(base, prop)) return Reflect.get(base, prop);
1328+ if (typeof prop !== "string") return undefined;
1329+ return __makeNode(session, [prop], null);
1330+ },
1331+ });
1332+ };
1333+ // Anonymous load() workers are evicted when their only stub is GC'd: the
1334+ // finalizer drops the worker's isolate so it does not leak. Named get()
1335+ // workers are retained by `byName` (memoized) and so are not registered.
1336+ const finalizer = typeof FinalizationRegistry === "function"
1337+ ? new FinalizationRegistry((id) => __loader_drop(id))
1338+ : null;
1339+ const makeStub = (idPromise, evictable) => {
1340+ // Explicit disposal evicts the worker deterministically; the finalizer is
1341+ // a GC backstop for anonymous stubs that are dropped without disposing.
1342+ // __loader_drop is idempotent, so the two paths cannot double-free.
1343+ const drop = () => { idPromise.then((id) => __loader_drop(id), () => {}); };
1344+ const stub = {
1345+ getEntrypoint(name = null, _options = {}) {
1346+ return makeEntrypoint(idPromise, name === null ? "default" : name);
1347+ },
1348+ dispose: drop,
1349+ };
1350+ if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop;
1351+ if (evictable && finalizer)
1352+ idPromise.then((id) => finalizer.register(stub, id), () => {});
1353+ return stub;
1354+ };
1355+ // getCode is deferred into a microtask so a throw (or async getCode)
1356+ // surfaces as a rejection when the worker is first used, not at get()/load().
1357+ const loadFrom = (getCode) =>
1358+ Promise.resolve().then(getCode).then((c) => __loader_load(JSON.stringify(c)));
1359+ return {
1360+ load(code) { return makeStub(loadFrom(() => code), true); },
1361+ get(name, getCode) {
1362+ let idPromise = byName.get(name);
1363+ if (idPromise === undefined) {
1364+ idPromise = loadFrom(getCode);
1365+ byName.set(name, idPromise);
1366+ }
1367+ return makeStub(idPromise, false);
1368+ },
1369+ };
1370+};
1371+
1372+globalThis.__makeServiceBinding = (script, entrypoint = null) => {
1373+ const target = {
1374+ async fetch(input, init) {
1375+ const req = new Request(input, init);
1376+ const signal = req._signalForSubrequests;
1377+ if (signal?.aborted) throw signal.reason;
1378+ // A stream body advertises its length the way the HTTP layer
1379+ // would: known length → Content-Length, unknown → chunked.
1380+ if (req._bodyBytes === null &&
1381+ !req.headers.has("content-length") &&
1382+ !req.headers.has("transfer-encoding")) {
1383+ const length = req.body._expectedLength;
1384+ if (length === undefined)
1385+ req.headers.set("transfer-encoding", "chunked");
1386+ else req.headers.set("content-length", String(length));
1387+ }
1388+ // Fast path: the target is this same script, so its handler lives in
1389+ // this isolate. Skip the op + pool-thread hop and call it directly,
1390+ // inside its own event so the target's waitUntil does not attach to
1391+ // the caller's. Cross-script targets still need their own isolate.
1392+ if (script === __cell.script && entrypoint !== null) {
1393+ // Mirror __dispatchTo: the target sees a fresh incoming signal,
1394+ // aborted with "The client has disconnected" when the caller
1395+ // abandons the call or cancels the response body; the caller's
1396+ // own signal races the dispatch so an abandoned call rejects
1397+ // immediately instead of pinning on a hung target.
1398+ const requestController = new AbortController();
1399+ const dispatch = __dispatchEntrypointFetch(
1400+ entrypoint,
1401+ new Request(req, {
1402+ signal: requestController.signal,
1403+ __celldIncomingSignal: true,
1404+ }));
1405+ const response = signal
1406+ ? await __raceCallerAbort(dispatch, signal, () =>
1407+ requestController.abort(
1408+ new Error("The client has disconnected")))
1409+ : await dispatch;
1410+ __attachResponseRequestCancellation(
1411+ response, requestController, true);
1412+ return __wrapServiceResponse(response, req.url);
1413+ }
1414+ if (entrypoint !== null)
1415+ throw new Error(
1416+ "Cross-script service bindings with an entrypoint do not " +
1417+ "support fetch() yet; only same-script targets do.");
1418+ if (script === __cell.script && typeof __cell.selfFetch === "function") {
1419+ if (__cell.svcDepth >= 8)
1420+ throw new Error(
1421+ "Service binding recursion limit exceeded (8)");
1422+ __cell.svcDepth = (__cell.svcDepth || 0) + 1;
1423+ const ctx = __beginEvent();
1424+ try {
1425+ return __wrapServiceResponse(
1426+ await __ctxRun(undefined,
1427+ () => __cell.selfFetch(req, __cell.env, ctx)),
1428+ req.url);
1429+ } finally {
1430+ __cell.svcDepth--;
1431+ __endEvent();
1432+ }
1433+ }
1434+ const headers = JSON.stringify(Array.from(req.headers));
1435+ // Cross-isolate calls carry exact bytes; a stream body is drained
1436+ // (and per spec disturbed) first.
1437+ const body_ = req._bodyBytes === null
1438+ ? await req._consume() : req._bodyBytes;
1439+ const r = JSON.parse(await (signal
1440+ ? __awaitCancellableDoCall(
1441+ __svc_call_cancellable(
1442+ script, req.url, req.method, body_, headers),
1443+ signal)
1444+ : __svc_call(
1445+ script, req.url, req.method, body_, headers)));
1446+ const body = r.streamId !== undefined
1447+ ? new CelldHttpBodyStream(r.streamId)
1448+ : r.body !== undefined
1449+ ? r.body
1450+ : Uint8Array.from(r.bodyBytes || []);
1451+ return __wrapServiceResponse(
1452+ new Response(body, { status: r.status, headers: r.headers }),
1453+ req.url);
1454+ },
1455+ // Workerd's test-visible Fetcher.scheduled(): invoke the target's
1456+ // scheduled handler and report the outcome.
1457+ async scheduled(options = {}) {
1458+ if (script !== __cell.script || entrypoint !== null ||
1459+ typeof __cell.selfScheduled !== "function")
1460+ throw new Error(
1461+ "scheduled() is only implemented for same-script service " +
1462+ "bindings whose target has a scheduled handler");
1463+ let noRetry = false;
1464+ const ctrl = {
1465+ scheduledTime: options.scheduledTime === undefined
1466+ ? Date.now() : Number(options.scheduledTime),
1467+ cron: options.cron === undefined ? "" : String(options.cron),
1468+ noRetry() { noRetry = true; },
1469+ };
1470+ const ctx = __beginEvent();
1471+ try {
1472+ await __cell.selfScheduled(ctrl, __cell.env, ctx);
1473+ return { outcome: "ok", noRetry };
1474+ } finally {
1475+ __endEvent();
1476+ }
1477+ },
1478+ };
1479+ if (entrypoint === null) return target;
1480+ // With `entrypoint = "Name"`, any property other than fetch is an
1481+ // awaitable/callable pipeline node rooted at that class: awaiting
1482+ // resolves the property remotely (a property-GET wire op), calling
1483+ // invokes it, and deeper access extends the path, resolved on the
1484+ // receiver side in one op. Same-script dispatch stays in this
1485+ // isolate, so stub-able values may cross. A property path rooted
1486+ // directly at the binding is context-free (ctx null): awaiting it
1487+ // starts a fresh session, as in Workerd.
1488+ const session =
1489+ __entrypointSession(entrypoint, script === __cell.script, script);
1490+ return new Proxy(target, {
1491+ getPrototypeOf: () => __cf.ServiceStub.prototype,
1492+ get: (base, prop) => {
1493+ if (prop === "then") return undefined; // a stub is not a thenable
1494+ if (Reflect.has(base, prop)) return Reflect.get(base, prop);
1495+ if (typeof prop !== "string") return undefined;
1496+ // Workerd's test hook: the named method as a callable handle,
1497+ // resolved — and refused — on the receiver side.
1498+ if (prop === "getRpcMethodForTestOnly")
1499+ return (name) => __makeNode(session, [String(name)], null);
1500+ return __makeNode(session, [prop], null);
1501+ }});
1502+};
1503+// RPC marshalling: V8 structured clone (Workerd js-rpc semantics), so
1504+// undefined, Date, Map, Set, BigInt, typed arrays, and cycles survive.
1505+// A value V8 cannot clone throws DataCloneError, as in Workerd.
1506+//
1507+// The envelope's first byte tags the payload. 0xff (the clone version
1508+// header) = plain clone, decoded as-is — the common case pays one
1509+// byte-compare and nothing else. 0x01 = clone of a lifted tree in
1510+// which RpcTarget instances, functions, and Durable Object stubs were
1511+// replaced by stub markers; the lift runs only after a plain clone
1512+// already threw, so plain-data calls never walk. 0x02 = a lifted
1513+// tree carrying only by-value host types (Blob/File, Headers,
1514+// Request/Response) and no capabilities — decoded like 0x01, but a
1515+// reply so tagged does not root its callee context. 0x00 = clone of
1516+// [error, ownProps] — a callee exception crossing as a real Error.
1517+const __dataCloneError = (error) => new DOMException(
1518+ String(error && error.message || error), "DataCloneError");
1519+const __tagged = (tag, sc) => {
1520+ const out = new Uint8Array(sc.length + 1);
1521+ out[0] = tag;
1522+ out.set(sc, 1);
1523+ return out;
1524+};
1525+// ---- request-context confinement -------------------------------
1526+// Workerd ties I/O objects to the IoContext of the event that made
1527+// them. Cells' equivalent: each dispatched event enters an
1528+// async-context frame (the same CPED the ALS rides, so it survives
1529+// awaits) carrying a context id. Stubs remember their owning
1530+// context and refuse to serialize elsewhere; pipeline nodes refuse
1531+// foreign awaits and calls — each with Workerd's exact error.
1532+let __nextCtxId = 1;
1533+const __ctxKey = Symbol("celld.ctx");
1534+const __ctxNow = () => {
1535+ const frame = __als_get();
1536+ return frame === undefined ? undefined : frame.get(__ctxKey);
1537+};
1538+// Run `fn` under context `id` (undefined = a fresh one). An async
1539+// fn started inside keeps the frame across its awaits. The prior
1540+// frame is cloned so user AsyncLocalStorage stores still flow into
1541+// same-isolate callees, as they did before contexts existed.
1542+const __ctxRun = (id, fn) => {
1543+ const prior = __als_get();
1544+ const frame = new Map(prior);
1545+ frame.set(__ctxKey, id ?? __nextCtxId++);
1546+ __als_set(frame);
1547+ try {
1548+ return fn();
1549+ } finally {
1550+ __als_set(prior);
1551+ }
1552+};
1553+const __ctxError = (kind) => new Error(
1554+ "Cannot perform I/O on behalf of a different request. I/O " +
1555+ "objects (such as streams, request/response bodies, and others) " +
1556+ "created in the context of one request handler cannot be " +
1557+ "accessed from a different request's handler. This is a " +
1558+ "limitation of Cloudflare Workers which allows us to improve " +
1559+ "overall performance. (I/O type: " + kind + ")");
1560+// ---- abortable request contexts --------------------------------
1561+// Workerd's ctx.abort(reason) on an entrypoint aborts the request's
1562+// IoContext: the in-flight call rejects with the reason, and stubs
1563+// the context holds are disposed (their disposal callbacks fire).
1564+// State is allocated only when a context first holds a stub handle
1565+// or aborts, so plain-data dispatch pays nothing; call paths gate
1566+// every abort lookup on `__abortedCtxs.size` (one field read).
1567+// Aborted ids stay recorded: a stub rooted in a dead context must
1568+// keep rejecting with the reason.
1569+const __abortedCtxs = new Map();
1570+// An actor-flavored abort reason: in-flight ops reject with the
1571+// wrapped reason, later ops with Workerd's post-abort message
1572+// (upstream TODO(bug): should propagate the reason, but doesn't).
1573+class __ActorAbort { constructor(reason) { this.reason = reason; } }
1574+const __postAbortError = (aborted) => aborted instanceof __ActorAbort
1575+ ? new Error("The execution context which hosts this callback " +
1576+ "is no longer running.")
1577+ : aborted;
1578+// ctx id -> Set of live stub handles (metas) the context holds.
1579+const __ctxStubs = new Map();
1580+// ctx id -> Set of reject callbacks for stub ops in flight against
1581+// that context. A hung callee never settles, so a context abort
1582+// must reject its pending callers directly.
1583+const __ctxPendingOps = new Map();
1584+const __opTrack = (ctx, reject) => {
1585+ let set = __ctxPendingOps.get(ctx);
1586+ if (set === undefined) __ctxPendingOps.set(ctx, set = new Set());
1587+ set.add(reject);
1588+ return () => {
1589+ set.delete(reject);
1590+ if (set.size === 0) __ctxPendingOps.delete(ctx);
1591+ };
1592+};
1593+const __ctxRegister = (meta) => {
1594+ if (meta.ctx === undefined) return;
1595+ let set = __ctxStubs.get(meta.ctx);
1596+ if (set === undefined) __ctxStubs.set(meta.ctx, set = new Set());
1597+ set.add(meta);
1598+};
1599+const __ctxUnregister = (meta) => {
1600+ const set = __ctxStubs.get(meta.ctx);
1601+ if (set === undefined) return;
1602+ set.delete(meta);
1603+ if (set.size === 0) __ctxStubs.delete(meta.ctx);
1604+};
1605+// Tear down a context: dispose every handle it still holds, so a
1606+// dup() leaked into it reaches the sender's disposal callback.
1607+const __ctxEnd = (id) => {
1608+ const set = __ctxStubs.get(id);
1609+ if (set === undefined) return;
1610+ __ctxStubs.delete(id);
1611+ for (const meta of set) __disposeStub(meta);
1612+};
1613+const __ctxAbort = (id, reason) => {
1614+ if (id === undefined || __abortedCtxs.has(id)) return;
1615+ const stored = reason === undefined
1616+ ? new Error("The execution context has been aborted.")
1617+ : reason;
1618+ __abortedCtxs.set(id, stored);
1619+ __ctxEnd(id);
1620+ const pending = __ctxPendingOps.get(id);
1621+ if (pending === undefined) return;
1622+ __ctxPendingOps.delete(id);
1623+ const live =
1624+ stored instanceof __ActorAbort ? stored.reason : stored;
1625+ for (const reject of pending) reject(live);
1626+};
1627+// The entrypoint ctx.abort. Instances are cached across calls, so
1628+// the construction-time ctx cannot pin a request id (Workerd
1629+// constructs per request); the current frame's id at abort() time
1630+// is the request being served, which matches Workerd observably.
1631+const __ctxAbortCurrent =
1632+ (reason) => __ctxAbort(__ctxNow(), reason);
1633+// ---- same-process RPC stubs ------------------------------------
1634+// A stub entry owns a local target; `refs` counts live handles
1635+// across dup()s. When the last handle is disposed the target's own
1636+// Symbol.dispose runs (async, matching Workerd's disposal callback).
1637+// Stubs cross same-isolate transports only (the DO owned fast path
1638+// and same-script entrypoint RPC); a marker revived elsewhere fails
1639+// loudly on use instead of aliasing an unrelated local entry.
1640+// `ctx` records the owning request context: the entry's for
1641+// running its target, the handle's for the serialize-elsewhere
1642+// check.
1643+const __stubEntries = new Map();
1644+const __stubMeta = new WeakMap();
1645+let __nextStubId = 1;
1646+const __stubIsolate = Math.random().toString(36).slice(2);
1647+const __newEntry = (target) => {
1648+ // `scope` records the actor event that minted the entry (top of
1649+ // the event stack at lift time), so an actor breakage can find
1650+ // and abort the contexts hosting its exported stubs.
1651+ const entry = {
1652+ id: __nextStubId++, target, refs: 1, ctx: __ctxNow(),
1653+ scope: __actorEventStack[__actorEventStack.length - 1],
1654+ };
1655+ __stubEntries.set(entry.id, entry);
1656+ return entry;
1657+};
1658+// Actors broken in JS: scope -> reason. Workerd's DO ctx.abort
1659+// rejects in-flight and future calls; when the abort fires under a
1660+// same-isolate stub caller, terminate_execution would unwind that
1661+// caller too (the routed dispatch re-enters the isolate), so the
1662+// breakage is recorded here instead: contexts hosting the actor's
1663+// exported stubs abort (in-flight ops reject with the reason,
1664+// later ops with the post-abort message) and RPC dispatch to the
1665+// scope rejects with the reason. Direct host-dispatched DO events
1666+// keep the uncatchable terminate_execution path.
1667+const __brokenActors = new Map();
1668+const __actorBreak = (scope, reason) => {
1669+ if (__brokenActors.has(scope)) return;
1670+ __brokenActors.set(scope, reason);
1671+ for (const entry of __stubEntries.values())
1672+ if (entry.scope === scope)
1673+ __ctxAbort(entry.ctx, new __ActorAbort(reason));
1674+};
1675+const __disposeStub = (meta) => {
1676+ if (meta.disposed) return;
1677+ meta.disposed = true;
1678+ __ctxUnregister(meta);
1679+ const entry = meta.entry;
1680+ if (--entry.refs > 0) return;
1681+ __stubEntries.delete(entry.id);
1682+ const disposer = entry.target?.[Symbol.dispose];
1683+ if (typeof disposer === "function")
1684+ Promise.resolve().then(() => disposer.call(entry.target));
1685+};
1686+const __stubDisposedError = () =>
1687+ new Error("RPC stub used after being disposed.");
1688+// Shared brand value for RpcTarget instances; see the RpcTarget
1689+// constructor.
1690+const __rpcNoClone = () => {};
1691+// Workerd method-visibility rules by target kind: an RpcTarget
1692+// exposes inherited methods/accessors (never own instance state,
1693+// never Object.prototype); a plain object or function exposes own
1694+// properties only. Property reads go through normal [[Get]] so
1695+// Proxy handlers participate, as in Workerd.
1696+const __rpcNoSuchMethod = (prop) => new TypeError(
1697+ 'The RPC receiver does not implement the method "' + prop + '".');
1698+const __stubResolve = (target, prop) => {
1699+ if (target instanceof __cf.RpcTarget) {
1700+ if (Object.hasOwn(target, prop) || !(prop in target) ||
1701+ prop in Object.prototype) throw __rpcNoSuchMethod(prop);
1702+ } else if (!Object.hasOwn(target, prop)) {
1703+ throw __rpcNoSuchMethod(prop);
1704+ }
1705+ const value = target[prop];
1706+ // Bind plain methods to their receiver, but never touch `.bind` on
1707+ // a stub or pipeline node — property access on those is remote.
1708+ return typeof value === "function" && !__stubMeta.has(value) &&
1709+ !(value instanceof __cf.RpcPromise) &&
1710+ !(value instanceof __cf.RpcProperty)
1711+ ? value.bind(target) : value;
1712+};
1713+// ---- streams over RPC ------------------------------------------
1714+// A live stream crosses as a handle in the caps table: the sender
1715+// locks the origin (reader/writer acquired at lift) behind a
1716+// bridge entry, and the receiver's endpoint is an ordinary
1717+// ReadableStream/WritableStream whose pulls and writes are stub
1718+// ops against the bridge — one bounded reverse call per chunk,
1719+// the clone being the one wire copy. Backpressure is the op in
1720+// flight: hwm 0 pulls only on demand, and the writable carries
1721+// one chunk per op. EOF, close, and errors cross as op results;
1722+// teardown (param disposal, context end, context abort) runs the
1723+// bridge disposer, which cancels or aborts an unfinished origin
1724+// with Workerd's generic disconnect errors — reasons do not
1725+// propagate, matching Workerd's own TODOs (and its verbatim
1726+// "endeded" typo).
1727+const __wsDisconnect = () => new Error(
1728+ "WritableStream received over RPC was disconnected because " +
1729+ "the remote execution context has endeded.");
1730+const __rsDisconnect = () => new Error(
1731+ "ReadableStream received over RPC disconnected prematurely.");
1732+// Receiver wrapper stream -> its handle meta, for forwarding.
1733+const __rpcStreamMeta = new WeakMap();
1734+const __readableBridge = (reader) => {
1735+ const bridge = {
1736+ done: false,
1737+ async read() {
1738+ let result;
1739+ try {
1740+ result = await reader.read();
1741+ } catch (error) {
1742+ bridge.done = true;
1743+ throw error;
1744+ }
1745+ if (result.done) bridge.done = true;
1746+ return result;
1747+ },
1748+ cancel() {
1749+ if (bridge.done) return;
1750+ bridge.done = true;
1751+ reader.cancel(__rsDisconnect()).catch(() => {});
1752+ },
1753+ [Symbol.dispose]() { bridge.cancel(); },
1754+ };
1755+ return bridge;
1756+};
1757+const __writableBridge = (writer) => {
1758+ const bridge = {
1759+ done: false,
1760+ write: (chunk) => writer.write(chunk),
1761+ close() {
1762+ bridge.done = true;
1763+ return writer.close();
1764+ },
1765+ abort() {
1766+ bridge.done = true;
1767+ return writer.abort(__wsDisconnect());
1768+ },
1769+ [Symbol.dispose]() {
1770+ if (!bridge.done) bridge.abort().catch(() => {});
1771+ },
1772+ };
1773+ return bridge;
1774+};
1775+const __liftStream = (v) => {
1776+ const readable = v instanceof ReadableStream;
1777+ const key = readable ? "__celld$rs" : "__celld$ws";
1778+ const meta = __rpcStreamMeta.get(v);
1779+ if (meta !== undefined && !meta.disposed && !v.locked) {
1780+ // Re-serializing a received, untouched stream forwards the
1781+ // original handle: the reference moves (like a stub) and
1782+ // the local wrapper is dead — a round trip stays one hop.
1783+ meta.disposed = true;
1784+ __ctxUnregister(meta);
1785+ return { [key]: meta.entry.id, t: __stubIsolate };
1786+ }
1787+ if (v.locked)
1788+ throw new TypeError(readable
1789+ ? "The ReadableStream has been locked to a reader."
1790+ : "The WritableStream has been locked to a writer.");
1791+ const bridge = readable
1792+ ? __readableBridge(v.getReader())
1793+ : __writableBridge(v.getWriter());
1794+ return { [key]: __newEntry(bridge).id, t: __stubIsolate };
1795+};
1796+// Replace stub-able values with wire markers. Runs only after a
1797+// plain clone failed, so plain-data serialization never pays for
1798+// it. Passing an existing stub transfers its reference: the
1799+// sender's handle is disposed (dup() first to keep one) and the
1800+// receiver adopts it. Returns null when nothing was liftable.
1801+const __stubLift = (value) => {
1802+ let lifted = false;
1803+ // Capabilities (stubs, disposers) root the callee context;
1804+ // by-value host types do not — they pick the 0x02 envelope.
1805+ let caps = false;
1806+ const seen = new Map();
1807+ const ctx = __ctxNow();
1808+ // A buffered body crosses as its bytes; a live-stream body
1809+ // crosses as a stream handle (a capability, so the reply
1810+ // roots its callee context and the pulls keep working).
1811+ const liftBody = (v) => {
1812+ if (v._bodyBytes !== null) return v._bodyBytes;
1813+ caps = true;
1814+ return __liftStream(v.body);
1815+ };
1816+ const lift = (v) => {
1817+ if (v === null ||
1818+ (typeof v !== "object" && typeof v !== "function")) return v;
1819+ const cached = seen.get(v);
1820+ if (cached !== undefined) return cached;
1821+ const meta = __stubMeta.get(v);
1822+ if (meta) {
1823+ lifted = true;
1824+ caps = true;
1825+ if (meta.disposed) throw __stubDisposedError();
1826+ // A stub belongs to the request that received it; another
1827+ // request cannot serialize it (Workerd's IoContext rule).
1828+ if (meta.ctx !== ctx) throw __ctxError("Client");
1829+ meta.disposed = true; // the ref moves to the receiver
1830+ __ctxUnregister(meta);
1831+ const marker = { "__celld$stub": meta.entry.id,
1832+ t: __stubIsolate, c: meta.callable };
1833+ seen.set(v, marker);
1834+ return marker;
1835+ }
1836+ const svc = __svcMeta.get(v);
1837+ if (svc !== undefined) {
1838+ // A loopback service stub (ctx.exports): name + props cross
1839+ // as plain data and revive as a fresh loopback stub. Props
1840+ // are lifted too — they may nest further stubs (Workerd's
1841+ // nested channel tokens).
1842+ lifted = true;
1843+ caps = true;
1844+ const marker = { "__celld$svc": svc.name, t: __stubIsolate };
1845+ seen.set(v, marker);
1846+ if (svc.props !== undefined) marker.p = lift(svc.props);
1847+ return marker;
1848+ }
1849+ // Workerd refuses to serialize its promise/property handles.
1850+ if (v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty)
1851+ throw new DOMException(
1852+ 'Could not serialize object of type "' +
1853+ (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") +
1854+ '". This type does not support serialization.',
1855+ "DataCloneError");
1856+ if (typeof v === "function" || v instanceof __cf.RpcTarget) {
1857+ lifted = true;
1858+ caps = true;
1859+ const marker = { "__celld$stub": __newEntry(v).id,
1860+ t: __stubIsolate,
1861+ c: typeof v === "function" };
1862+ seen.set(v, marker);
1863+ return marker;
1864+ }
1865+ const doId = v.__celldDo;
1866+ if (doId !== undefined) {
1867+ lifted = true;
1868+ caps = true;
1869+ const marker = { "__celld$do": doId._className,
1870+ v: doId._value, n: v.name ?? null };
1871+ seen.set(v, marker);
1872+ return marker;
1873+ }
1874+ // HTTP host types cross by value, as in Workerd's RPC
1875+ // serialization: entry lists for Headers, the buffered bytes
1876+ // for bodies (the marker aliases the live buffer; the clone
1877+ // is the one wire copy), and no signal — the receiver mints
1878+ // a fresh one. A live stream body cannot cross yet.
1879+ let marker;
1880+ if (v instanceof Headers) {
1881+ marker = { "__celld$hdr": [...v] };
1882+ } else if (v instanceof Blob) {
1883+ marker = { "__celld$blob": v._bytes, y: v.type };
1884+ if (v instanceof File) {
1885+ marker.n = v.name;
1886+ marker.m = v.lastModified;
1887+ }
1888+ } else if (v instanceof Request) {
1889+ marker = { "__celld$req": v.url, m: v.method,
1890+ h: [...v.headers], r: v.redirect, c: v.cf,
1891+ b: liftBody(v) };
1892+ } else if (v instanceof Response) {
1893+ marker = { "__celld$res": v.status,
1894+ t: v.statusText ||
1895+ __STATUS_TEXT[v.status] || "",
1896+ h: [...v.headers], c: v.cf,
1897+ b: v.body === null ? null : liftBody(v) };
1898+ } else if (v instanceof ReadableStream ||
1899+ v instanceof WritableStream) {
1900+ caps = true;
1901+ marker = __liftStream(v);
1902+ } else if (v instanceof AbortSignal) {
1903+ // A live signal handle: the receiver mints a fresh signal
1904+ // wired to this one (same isolate); foreign bytes revive
1905+ // a snapshot of the aborted flag.
1906+ caps = true;
1907+ marker = { "__celld$sig": __newEntry(v).id,
1908+ t: __stubIsolate, a: v.aborted };
1909+ }
1910+ if (marker !== undefined) {
1911+ lifted = true;
1912+ seen.set(v, marker);
1913+ return marker;
1914+ }
1915+ const proto = Object.getPrototypeOf(v);
1916+ if (!Array.isArray(v) &&
1917+ proto !== Object.prototype && proto !== null) {
1918+ // A Proxy emulating neither a plain object nor an RpcTarget
1919+ // is Workerd's canonical proxy serialization error.
1920+ if (__util_proxy_details(v) !== undefined)
1921+ throw new DOMException(
1922+ "Proxy could not be serialized because it is not a " +
1923+ "valid RPC receiver type. The Proxy must emulate either " +
1924+ "a plain object or an RpcTarget, as indicated by the " +
1925+ "Proxy's prototype chain.", "DataCloneError");
1926+ return v; // host/other: leave to the clone
1927+ }
1928+ const out = Array.isArray(v) ? [] : {};
1929+ seen.set(v, out);
1930+ for (const key of Object.keys(v)) out[key] = lift(v[key]);
1931+ const disposer = v[Symbol.dispose];
1932+ if (!Array.isArray(v) && typeof disposer === "function") {
1933+ lifted = true;
1934+ caps = true;
1935+ out["__celld$disp"] = __newEntry(disposer.bind(v)).id;
1936+ }
1937+ return out;
1938+ };
1939+ const tree = lift(value);
1940+ return lifted ? { tree, caps } : null;
1941+};
1942+// Revive host-type markers into real instances, adopting the wire
1943+// bytes directly — no copy beyond the clone's own.
1944+const __reviveBlob = (marker, bytes) => {
1945+ const blob = marker.n !== undefined
1946+ ? new File([], marker.n,
1947+ { type: marker.y, lastModified: marker.m })
1948+ : new Blob([], { type: marker.y });
1949+ blob._bytes = bytes;
1950+ blob.size = bytes.byteLength;
1951+ return blob;
1952+};
1953+const __adoptBody = (target, bytes) => {
1954+ target._bodyBytes = bytes;
1955+ target._body = new TextDecoder().decode(bytes);
1956+ const body = target.body;
1957+ if (body !== null) {
1958+ body._st.bytes = bytes;
1959+ body.__celldBodyBytes = bytes;
1960+ body._expectedLength = bytes.byteLength;
1961+ }
1962+};
1963+// A non-bytes `b` is a live-stream body marker: revive it and
1964+// let the constructor adopt it as a streaming body.
1965+const __reviveRequest = (marker, url, revive) => {
1966+ if (!(marker.b instanceof Uint8Array))
1967+ return new Request(url, { method: marker.m,
1968+ headers: marker.h, redirect: marker.r, cf: marker.c,
1969+ body: revive(marker.b) });
1970+ const req = new Request(url, { method: marker.m,
1971+ headers: marker.h, redirect: marker.r, cf: marker.c });
1972+ __adoptBody(req, marker.b);
1973+ return req;
1974+};
1975+const __reviveResponse = (marker, revive) => {
1976+ const bytes = marker.b instanceof Uint8Array;
1977+ const res = new Response(
1978+ marker.b === null ? null : bytes ? "" : revive(marker.b), {
1979+ status: marker["__celld$res"], statusText: marker.t,
1980+ headers: marker.h, cf: marker.c });
1981+ if (bytes) __adoptBody(res, marker.b);
1982+ return res;
1983+};
1984+// Wire a received stream handle to a local endpoint built with
1985+// the ordinary constructors — nothing new threads through the
1986+// stream hot paths. Read errors surface as Workerd's generic
1987+// premature-disconnect; write errors propagate (Workerd sends
1988+// real errors back through the write loop).
1989+const __foreignStreamOp = () => Promise.reject(new Error(
1990+ "RPC streams cannot cross isolate boundaries yet."));
1991+const __reviveStream = (marker, id, readable, handles) => {
1992+ const entry = marker.t === __stubIsolate
1993+ ? __stubEntries.get(id) : undefined;
1994+ if (entry === undefined)
1995+ return readable
1996+ ? new ReadableStream({ pull: __foreignStreamOp })
1997+ : new WritableStream({ write: __foreignStreamOp,
1998+ close: __foreignStreamOp, abort: __foreignStreamOp });
1999+ const meta = { entry, disposed: false, ctx: __ctxNow() };
2000+ __ctxRegister(meta);
2001+ handles.push(meta);
2002+ const stream = readable
2003+ ? new ReadableStream({
2004+ async pull(controller) {
2005+ let result;
2006+ try {
2007+ result = await __stubOp(meta, ["read"], []);
2008+ } catch {
2009+ throw __rsDisconnect();
2010+ }
2011+ if (result.done) controller.close();
2012+ else controller.enqueue(result.value);
2013+ },
2014+ cancel: () =>
2015+ __stubOp(meta, ["cancel"], []).catch(() => {}),
2016+ }, { highWaterMark: 0 })
2017+ : new WritableStream({
2018+ write: (chunk) => __stubOp(meta, ["write"], [chunk]),
2019+ close: () => __stubOp(meta, ["close"], []),
2020+ abort: () =>
2021+ __stubOp(meta, ["abort"], []).catch(() => {}),
2022+ });
2023+ __rpcStreamMeta.set(stream, meta);
2024+ return stream;
2025+};
2026+const __reviveSignal = (marker, id) => {
2027+ const entry = marker.t === __stubIsolate
2028+ ? __stubEntries.get(id) : undefined;
2029+ const controller = new AbortController();
2030+ if (entry === undefined) {
2031+ if (marker.a) controller.abort();
2032+ return controller.signal;
2033+ }
2034+ __stubEntries.delete(id);
2035+ const signal = entry.target;
2036+ if (signal.aborted) controller.abort(signal.reason);
2037+ else signal.addEventListener("abort",
2038+ () => controller.abort(signal.reason), { once: true });
2039+ return controller.signal;
2040+};
2041+// The inverse: markers become live handles. `handles` collects the
2042+// revived stubs (for call-end param disposal or result-tree
2043+// disposal); `disposers` collects remote Symbol.dispose entries.
2044+const __stubRevive = (value) => {
2045+ const handles = [];
2046+ const disposers = [];
2047+ const seen = new Set();
2048+ const revive = (v) => {
2049+ if (v === null || typeof v !== "object") return v;
2050+ const stubId = v["__celld$stub"];
2051+ if (stubId !== undefined) {
2052+ const entry = v.t === __stubIsolate
2053+ ? __stubEntries.get(stubId) : undefined;
2054+ const stub = entry === undefined
2055+ ? __foreignStub()
2056+ : __makeStub(entry, v.c);
2057+ const meta = __stubMeta.get(stub);
2058+ if (meta) handles.push(meta);
2059+ return stub;
2060+ }
2061+ const svcName = v["__celld$svc"];
2062+ if (svcName !== undefined)
2063+ return v.t === __stubIsolate
2064+ ? __entrypointStub(svcName, revive(v.p))
2065+ : __foreignStub();
2066+ const doClass = v["__celld$do"];
2067+ if (doClass !== undefined) {
2068+ const namespace = __cell.makeNamespace(doClass);
2069+ return namespace.get(
2070+ new DurableObjectId(doClass, v.v, v.n ?? undefined));
2071+ }
2072+ const hdr = v["__celld$hdr"];
2073+ if (hdr !== undefined) return new Headers(hdr);
2074+ const blobBytes = v["__celld$blob"];
2075+ if (blobBytes !== undefined) return __reviveBlob(v, blobBytes);
2076+ const reqUrl = v["__celld$req"];
2077+ if (reqUrl !== undefined)
2078+ return __reviveRequest(v, reqUrl, revive);
2079+ if (v["__celld$res"] !== undefined)
2080+ return __reviveResponse(v, revive);
2081+ const rsId = v["__celld$rs"];
2082+ if (rsId !== undefined)
2083+ return __reviveStream(v, rsId, true, handles);
2084+ const wsId = v["__celld$ws"];
2085+ if (wsId !== undefined)
2086+ return __reviveStream(v, wsId, false, handles);
2087+ const sigId = v["__celld$sig"];
2088+ if (sigId !== undefined) return __reviveSignal(v, sigId);
2089+ if (seen.has(v)) return v;
2090+ seen.add(v);
2091+ if (Array.isArray(v)) {
2092+ for (let i = 0; i < v.length; i++) v[i] = revive(v[i]);
2093+ return v;
2094+ }
2095+ const proto = Object.getPrototypeOf(v);
2096+ if (proto !== Object.prototype && proto !== null) return v;
2097+ for (const key of Object.keys(v)) {
2098+ if (key === "__celld$disp") {
2099+ const entry = __stubEntries.get(v[key]);
2100+ if (entry) disposers.push(entry);
2101+ delete v[key];
2102+ continue;
2103+ }
2104+ v[key] = revive(v[key]);
2105+ }
2106+ return v;
2107+ };
2108+ return { value: revive(value), handles, disposers };
2109+};
2110+// A marker that crossed an isolate boundary: fail on use, loudly.
2111+const __foreignStub = () => new Proxy(function () {}, {
2112+ get: (_b, prop) => {
2113+ if (prop === "then" || typeof prop !== "string") return undefined;
2114+ return () => Promise.reject(new Error(
2115+ "RPC stubs cannot cross isolate boundaries yet."));
2116+ },
2117+ apply: () => Promise.reject(new Error(
2118+ "RPC stubs cannot cross isolate boundaries yet.")),
2119+});
2120+// Workerd's entrypoint method-visibility rules (worker-rpc.c++):
2121+// reserved lifecycle names are refused outright; only prototype
2122+// methods and accessors are visible — never own instance state
2123+// (env/ctx live there) and never Object.prototype.
2124+const __entrypointReserved = new Set([
2125+ "constructor", "fetch", "connect", "alarm", "scheduled",
2126+ "webSocketMessage", "webSocketClose", "webSocketError", "dup",
2127+]);
2128+const __entrypointResolve = (inst, prop) => {
2129+ if (__entrypointReserved.has(prop))
2130+ throw new TypeError("'" + prop +
2131+ "' is a reserved method and cannot be called over RPC.");
2132+ if (Object.hasOwn(inst, prop) || !(prop in inst) ||
2133+ prop in Object.prototype)
2134+ throw __rpcNoSuchMethod(prop);
2135+ const value = inst[prop];
2136+ return typeof value === "function" && !__stubMeta.has(value) &&
2137+ !(value instanceof __cf.RpcPromise) &&
2138+ !(value instanceof __cf.RpcProperty)
2139+ ? value.bind(inst) : value;
2140+};
2141+// A pipeline hop may continue only through plain data, functions,
2142+// RpcTargets, and stubs — never through an RPC promise/property
2143+// handle or a class instance (Workerd's receiver rules).
2144+const __walkable = (v) =>
2145+ v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty
2146+ ? false
2147+ : typeof v === "function" || v instanceof __cf.RpcTarget ||
2148+ (typeof v === "object" && v !== null &&
2149+ (Object.getPrototypeOf(v) === Object.prototype ||
2150+ Array.isArray(v)));
2151+// Receiver-side pipeline walk: resolve `path` from `root`, then
2152+// GET the final member (`args` null) or CALL it. Errors name the
2153+// path walked so far, as Workerd's do. A stub mid-walk continues
2154+// against its own target, in the stub's owning context.
2155+const __rpcWalk = async (root, path, args, entrypointRoot) => {
2156+ let value = root;
2157+ for (let i = 0; i < path.length; i++) {
2158+ const meta = __stubMeta.get(value);
2159+ if (meta) {
2160+ if (meta.disposed) throw __stubDisposedError();
2161+ const rest = path.slice(i);
2162+ return await __ctxRun(meta.entry.ctx,
2163+ () => __rpcWalk(meta.entry.target, rest, args, false));
2164+ }
2165+ if (i > 0 && !__walkable(value))
2166+ throw __rpcNoSuchMethod(path[i - 1]);
2167+ const prop = path[i];
2168+ const next = entrypointRoot && i === 0
2169+ ? __entrypointResolve(value, prop)
2170+ : __stubResolve(value, prop);
2171+ if (i === path.length - 1) {
2172+ if (args === null) return next;
2173+ if (typeof next !== "function")
2174+ throw new TypeError(
2175+ '"' + path.join(".") + '" is not a function.');
2176+ return next(...args);
2177+ }
2178+ if (next instanceof __cf.RpcPromise ||
2179+ next instanceof __cf.RpcProperty)
2180+ throw __rpcNoSuchMethod(prop);
2181+ value = next;
2182+ }
2183+ // An empty path applies the root itself (a callable stub).
2184+ if (args === null) return value;
2185+ if (typeof value !== "function")
2186+ throw new TypeError("The RPC stub is not callable.");
2187+ return value(...args);
2188+};
2189+// One stub-mediated op: clone through the RPC envelope both ways,
2190+// so nested stubs, errors, and uncloneables behave exactly as a
2191+// dispatched call. Args serialize in the caller's context (its
2192+// stubs must be its own to transfer); the decode, the walk, and
2193+// the reply serialization run in the stub's owning context, so
2194+// stubs minted by the target belong to the target's context.
2195+// Params received by the target are disposed when the op ends
2196+// (Workerd's param-disposal rule).
2197+const __stubOp = (meta, path, args) => {
2198+ if (meta.disposed) return Promise.reject(__stubDisposedError());
2199+ const entry = meta.entry;
2200+ // A stub rooted in an aborted context is broken: reject with the
2201+ // abort reason, before and after the dispatch (the target may
2202+ // abort its own context mid-call). Gated on one field read.
2203+ if (__abortedCtxs.size !== 0) {
2204+ const aborted = __abortedCtxs.get(entry.ctx);
2205+ if (aborted !== undefined)
2206+ return Promise.reject(__postAbortError(aborted));
2207+ }
2208+ const argsSc = args === null ? null : __rpcOut(args, true);
2209+ const dispatch = (async () => {
2210+ // Workerd delivers RPC asynchronously: the callee must not run
2211+ // before the caller's synchronous code. A call made just after
2212+ // a not-yet-delivered ctx.abort counts as in flight (rejects
2213+ // with the reason, not the post-abort message). Bodies queue
2214+ // in call order, so e-order holds.
2215+ await null;
2216+ const reply = await __ctxRun(entry.ctx,
2217+ () => __rpcRun(async () => {
2218+ const decoded =
2219+ argsSc === null ? null : __rpcDesArgs(argsSc);
2220+ try {
2221+ return await __rpcWalk(entry.target, path,
2222+ decoded === null ? null : decoded.args, false);
2223+ } finally {
2224+ if (decoded !== null)
2225+ for (const handle of decoded.received)
2226+ __disposeStub(handle);
2227+ }
2228+ }, true));
2229+ if (__abortedCtxs.size !== 0) {
2230+ const aborted = __abortedCtxs.get(entry.ctx);
2231+ if (aborted !== undefined)
2232+ throw aborted instanceof __ActorAbort
2233+ ? aborted.reason : aborted;
2234+ }
2235+ return __rpcDes(reply);
2236+ })();
2237+ if (entry.ctx === undefined) return dispatch;
2238+ // Race the op against its hosting context's abort: a hung callee
2239+ // never settles, so the settlement check above cannot reach it.
2240+ // A late settlement lands on an already-settled promise (no-op).
2241+ return new Promise((resolve, reject) => {
2242+ const untrack = __opTrack(entry.ctx, reject);
2243+ dispatch.then(
2244+ (value) => { untrack(); resolve(value); },
2245+ (error) => { untrack(); reject(error); });
2246+ });
2247+};
2248+// Resolve a path against a local, already-revived value. A hop
2249+// landing on a same-isolate stub delegates the rest of the path
2250+// to the stub's target; everything else is a plain [[Get]] so
2251+// Durable Object stubs and Proxies participate.
2252+const __walkLocal = (parent, path, args) => {
2253+ for (let i = 0; i < path.length; i++) {
2254+ const meta = __stubMeta.get(parent);
2255+ if (meta) return __stubOp(meta, path.slice(i), args);
2256+ const prop = path[i];
2257+ const member = parent == null ? undefined : parent[prop];
2258+ if (i < path.length - 1) {
2259+ parent = member;
2260+ continue;
2261+ }
2262+ if (args === null) return member;
2263+ if (typeof member !== "function") {
2264+ if (member === undefined) throw __rpcNoSuchMethod(prop);
2265+ throw new TypeError('"' + prop + '" is not a function.');
2266+ }
2267+ // [[Call]] directly: `.apply` on a stub proxy would be a
2268+ // remote property access, not an invocation.
2269+ return Reflect.apply(member, parent, args);
2270+ }
2271+ if (args === null) return parent;
2272+ const meta = __stubMeta.get(parent);
2273+ if (meta) return __stubOp(meta, [], args);
2274+ if (typeof parent !== "function")
2275+ throw new TypeError("The RPC value is not callable.");
2276+ return parent(...args);
2277+};
2278+// A session is one place pipeline ops resolve: the local value a
2279+// call returned, a same-isolate stub's target, or a named
2280+// entrypoint (whose paths resolve receiver-side in one op).
2281+const __valueSession = (promise) => ({
2282+ root: () => promise,
2283+ get: (path) => promise.then((v) => __walkLocal(v, path, null)),
2284+ call: (path, args) =>
2285+ promise.then((v) => __walkLocal(v, path, args)),
2286+});
2287+const __stubSession = (meta) => ({
2288+ get: (path) => __stubOp(meta, path, null),
2289+ call: (path, args) => __stubOp(meta, path, args),
2290+});
2291+const __entrypointSession = (name, local, script, makeInst) => ({
2292+ get: (path) => local
2293+ ? (async () => __rpcDes(
2294+ await __entrypointOp(name, path, null, true, makeInst)))()
2295+ : Promise.reject(new Error(
2296+ "Awaitable properties on cross-script service bindings " +
2297+ "are not supported yet.")),
2298+ call: (path, args) => (async () => {
2299+ const argsSc = __rpcOut(args, local);
2300+ if (local)
2301+ return __rpcDes(await __entrypointOp(
2302+ name, path, argsSc, true, makeInst));
2303+ if (path.length !== 1)
2304+ throw new Error(
2305+ "Pipelined property paths on cross-script service " +
2306+ "bindings are not supported yet.");
2307+ return __rpcDes(
2308+ await __svc_rpc(script, name, path[0], argsSc));
2309+ })(),
2310+});
2311+// Workerd's JsRpcPromise/JsRpcProperty: awaitable, callable, and
2312+// property access extends a path resolved at the far end, so
2313+// intermediates obey Workerd's receiver rules. `ctx` is the node's
2314+// owning request context — null marks a context-free node (a
2315+// property path rooted directly at a service binding, which
2316+// starts a fresh session per await); a foreign context awaiting a
2317+// property or calling through the node gets Workerd's
2318+// cross-context error. Depth is capped like Workerd's
2319+// MAX_PROPERTY_DEPTH.
2320+const __makeNode = (session, path, ctx) => {
2321+ let promise;
2322+ const value = () => promise ??= (() => {
2323+ if (path.length === 0) return session.root();
2324+ if (ctx !== null && ctx !== __ctxNow())
2325+ return Promise.reject(__ctxError("Pipeline"));
2326+ return session.get(path);
2327+ })();
2328+ const brand =
2329+ path.length === 0 ? __cf.RpcPromise : __cf.RpcProperty;
2330+ return new Proxy(function () {}, {
2331+ getPrototypeOf: () => brand.prototype,
2332+ get: (_b, p) => {
2333+ if (p === "then")
2334+ return (onOk, onErr) => value().then(onOk, onErr);
2335+ if (p === "catch") return (onErr) => value().catch(onErr);
2336+ if (p === "finally")
2337+ return (onDone) => value().finally(onDone);
2338+ if (typeof p !== "string") return undefined;
2339+ if (path.length >= 5120)
2340+ throw new TypeError(
2341+ "RPC pipelined property chain is too deep.");
2342+ return __makeNode(session, [...path, p], ctx);
2343+ },
2344+ apply: (_b, _this, args) => {
2345+ let call;
2346+ if (ctx !== null && ctx !== __ctxNow()) {
2347+ call = Promise.reject(__ctxError("JsRpcPromise"));
2348+ call.catch(() => {});
2349+ } else {
2350+ // Eager, so concurrent calls keep e-order.
2351+ call = session.call(path, args);
2352+ }
2353+ return __makeNode(
2354+ __valueSession(call), [], ctx ?? __ctxNow());
2355+ },
2356+ });
2357+};
2358+const __makeStub = (entry, callable) => {
2359+ const meta =
2360+ { entry, callable, disposed: false, ctx: __ctxNow() };
2361+ __ctxRegister(meta);
2362+ const stub = new Proxy(function () {}, {
2363+ getPrototypeOf: () => __cf.RpcStub.prototype,
2364+ get: (_b, prop) => {
2365+ if (prop === "then") return undefined;
2366+ if (prop === Symbol.dispose) return () => __disposeStub(meta);
2367+ if (prop === "dup") return () => {
2368+ if (meta.disposed) throw __stubDisposedError();
2369+ entry.refs++;
2370+ return __makeStub(entry, callable);
2371+ };
2372+ if (typeof prop !== "string") return undefined;
2373+ return __makeNode(__stubSession(meta), [prop], __ctxNow());
2374+ },
2375+ apply: (_b, _this, args) => __makeNode(
2376+ __valueSession(__stubOp(meta, [], args)), [], __ctxNow()),
2377+ });
2378+ __stubMeta.set(stub, meta);
2379+ return stub;
2380+};
2381+// A loopback service stub for one of this worker's own
2382+// entrypoints — the ctx.exports surface. Calling the stub itself
2383+// returns a new stub carrying per-instance props, delivered to
2384+// the class constructor as ctx.props (Workerd's
2385+// ctx.exports.Name({ props })).
2386+const __svcMeta = new WeakMap();
2387+const __entrypointStub = (name, props) => {
2388+ let inst;
2389+ const makeInst = props === undefined ? undefined : () => {
2390+ if (inst !== undefined) return inst;
2391+ const cls = __cell.entrypoints[name];
2392+ if (typeof cls !== "function")
2393+ throw new TypeError(
2394+ "The entrypoint " + name + " cannot carry props.");
2395+ // Construction gets its own event, like __entrypointInstance.
2396+ const ctx = __beginEvent(props);
2397+ try {
2398+ inst = new cls(ctx, __cell.env);
2399+ } finally {
2400+ __endEvent();
2401+ }
2402+ return inst;
2403+ };
2404+ const session = __entrypointSession(name, true, null, makeInst);
2405+ const stub = new Proxy(function () {}, {
2406+ getPrototypeOf: () => __cf.ServiceStub.prototype,
2407+ get: (_b, prop) => {
2408+ if (prop === "then") return undefined;
2409+ if (typeof prop !== "string") return undefined;
2410+ if (prop === "getRpcMethodForTestOnly")
2411+ return (n) => __makeNode(session, [String(n)], null);
2412+ return __makeNode(session, [prop], null);
2413+ },
2414+ apply: (_b, _this, args) =>
2415+ __entrypointStub(name, args[0]?.props),
2416+ });
2417+ __svcMeta.set(stub, { name, props });
2418+ return stub;
2419+};
2420+// ---- stored stubs ----------------------------------------------
2421+// Durable Object storage accepts only stubs with durable identity:
2422+// loopback service stubs (entrypoint name + props re-mint a fresh
2423+// stub on read) and Durable Object stubs (HMAC'd id + class revive
2424+// in any isolate). A transient handle — a received RPC stub, a
2425+// function, an RpcTarget — dies with its isolate; persisting its
2426+// entry id would revive garbage after a restart, so it is refused.
2427+// A stub-bearing row is written as 0x01 + clone(marker tree), off
2428+// the plain-clone fast path (the lift runs only after the plain
2429+// clone already threw, exactly like the RPC envelope). Reads hand
2430+// tagged rows to JS as [sentinel, tree]; the sentinel never leaves
2431+// this script and no user value can decode to it, so revival
2432+// cannot be spoofed by data shaped like a marker.
2433+const __storedSentinel = {};
2434+const __storedLift = (value) => {
2435+ let lifted = false;
2436+ const seen = new Map();
2437+ const lift = (v) => {
2438+ if (v === null ||
2439+ (typeof v !== "object" && typeof v !== "function")) return v;
2440+ const cached = seen.get(v);
2441+ if (cached !== undefined) return cached;
2442+ // Ordering mirrors __stubLift: identify proxies by their
2443+ // side tables and brands before touching any property — a
2444+ // stub or pipeline proxy answers every property read with a
2445+ // fresh RpcProperty node.
2446+ if (__stubMeta.has(v) || v instanceof __cf.RpcTarget)
2447+ throw new DOMException(
2448+ "Durable Object storage can only store stubs with " +
2449+ "durable identity: service stubs from ctx.exports and " +
2450+ "Durable Object stubs. This value is a transient RPC " +
2451+ "handle that would not survive a restart.",
2452+ "DataCloneError");
2453+ const svc = __svcMeta.get(v);
2454+ if (svc !== undefined) {
2455+ lifted = true;
2456+ const marker = { "__celld$svc": svc.name };
2457+ seen.set(v, marker);
2458+ if (svc.props !== undefined) marker.p = lift(svc.props);
2459+ return marker;
2460+ }
2461+ if (v instanceof __cf.RpcPromise ||
2462+ v instanceof __cf.RpcProperty)
2463+ throw new DOMException(
2464+ 'Could not serialize object of type "' +
2465+ (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") +
2466+ '". This type does not support serialization.',
2467+ "DataCloneError");
2468+ if (typeof v === "function") return v; // leave to the clone
2469+ const doId = v.__celldDo;
2470+ if (doId !== undefined) {
2471+ lifted = true;
2472+ const marker = { "__celld$do": doId._className,
2473+ v: doId._value, n: v.name ?? null };
2474+ seen.set(v, marker);
2475+ return marker;
2476+ }
2477+ if (Array.isArray(v)) {
2478+ const out = [];
2479+ seen.set(v, out);
2480+ for (let i = 0; i < v.length; i++) out[i] = lift(v[i]);
2481+ return out;
2482+ }
2483+ const proto = Object.getPrototypeOf(v);
2484+ if (proto !== Object.prototype && proto !== null)
2485+ return v; // host/other: leave to the clone
2486+ const out = {};
2487+ seen.set(v, out);
2488+ for (const key of Object.keys(v)) out[key] = lift(v[key]);
2489+ return out;
2490+ };
2491+ const tree = lift(value);
2492+ return lifted ? tree : null;
2493+};
2494+// Encode one stub-bearing value for storage. Rethrows the original
2495+// clone error when nothing was liftable, so plain uncloneables
2496+// fail exactly as they always did.
2497+const __storedBytes = (value, error) => {
2498+ const tree = __storedLift(value);
2499+ if (tree === null) throw error;
2500+ return __tagged(1, __sc_encode(tree));
2501+};
2502+const __storedRevive = (value) => {
2503+ const seen = new Set();
2504+ const revive = (v) => {
2505+ if (v === null || typeof v !== "object") return v;
2506+ const svcName = v["__celld$svc"];
2507+ if (svcName !== undefined)
2508+ return __entrypointStub(svcName, revive(v.p));
2509+ const doClass = v["__celld$do"];
2510+ if (doClass !== undefined)
2511+ return __cell.makeNamespace(doClass).get(
2512+ new DurableObjectId(doClass, v.v, v.n ?? undefined));
2513+ if (seen.has(v)) return v;
2514+ seen.add(v);
2515+ if (Array.isArray(v)) {
2516+ for (let i = 0; i < v.length; i++) v[i] = revive(v[i]);
2517+ return v;
2518+ }
2519+ const proto = Object.getPrototypeOf(v);
2520+ if (proto !== Object.prototype && proto !== null) return v;
2521+ for (const key of Object.keys(v)) v[key] = revive(v[key]);
2522+ return v;
2523+ };
2524+ return revive(value);
2525+};
2526+const __unwrapStored = (v) =>
2527+ Array.isArray(v) && v[0] === __storedSentinel
2528+ ? __storedRevive(v[1]) : v;
2529+// A map result is wrapped as a whole only when it holds at least
2530+// one tagged row, so the per-entry walk never runs on plain data.
2531+const __unwrapStoredMap = (v) => {
2532+ if (!Array.isArray(v) || v[0] !== __storedSentinel) return v;
2533+ const map = v[1];
2534+ for (const [key, value] of map)
2535+ map.set(key, __unwrapStored(value));
2536+ return map;
2537+};
2538+// ctx.exports: loopback stubs for every exported entrypoint plus
2539+// this worker's Durable Object namespaces. Built once, on first
2540+// access — ctx construction itself only carries the getter.
2541+let __ctxExportsCache;
2542+const __ctxExports = () => __ctxExportsCache ??= (() => {
2543+ const out = {};
2544+ for (const name of Object.keys(__cell.entrypoints))
2545+ out[name] = __entrypointStub(name, undefined);
2546+ for (const name of Object.keys(__cell.objectEntrypoints))
2547+ if (name !== "default")
2548+ out[name] = __entrypointStub(name, undefined);
2549+ for (const name of Object.keys(__cell.namespaceKeys))
2550+ out[name] = __cell.makeNamespace(name);
2551+ return out;
2552+})();
2553+// ---- RPC envelope ----------------------------------------------
2554+// Serialize one payload. `lift` marks a same-isolate transport,
2555+// where stub-able values may cross as markers; elsewhere they stay
2556+// a DataCloneError, exactly as before stubs existed.
2557+const __rpcOut = (value, lift) => {
2558+ try {
2559+ return __sc_encode(value);
2560+ } catch (error) {
2561+ const lifted = lift ? __stubLift(value) : null;
2562+ if (lifted === null) throw __dataCloneError(error);
2563+ try {
2564+ return __tagged(
2565+ lifted.caps ? 1 : 2, __sc_encode(lifted.tree));
2566+ } catch (error_) {
2567+ throw __dataCloneError(error_);
2568+ }
2569+ }
2570+};
2571+// A callee exception as tagged bytes: the Error crosses by value
2572+// (V8 serializes Error natively), custom own properties beside it.
2573+const __rpcErrOut = (error) => {
2574+ // `name` rides in the props: V8 only round-trips the standard
2575+ // Error subclass names, and e.g. DataCloneError must survive.
2576+ const props = error instanceof Error
2577+ ? { ...error, name: error.name } : {};
2578+ let sc;
2579+ try {
2580+ sc = __sc_encode([error, props]);
2581+ } catch {
2582+ const error_ = new Error(String(error?.message ?? error));
2583+ sc = __sc_encode([error_, { name: String(error?.name ?? "Error") }]);
2584+ }
2585+ return __tagged(0, sc);
2586+};
2587+// The callee half of one RPC: run `body`, answer tagged bytes.
2588+const __rpcRun = async (body, lift) => {
2589+ try {
2590+ return __rpcOut(await body(), lift);
2591+ } catch (error) {
2592+ return __rpcErrOut(error);
2593+ }
2594+};
2595+const __rpcDesArgs = (bytes) => {
2596+ if (bytes[0] === 0xff)
2597+ return { args: __sc_decode(bytes), received: [] };
2598+ const revived = __stubRevive(__sc_decode(bytes.subarray(1)));
2599+ return { args: revived.value, received: revived.handles };
2600+};
2601+// The caller half: decode a reply, rebuilding stubs and rethrowing
2602+// callee exceptions as real Errors with the callee's own
2603+// properties, `.remote`, and a local (caller-side) stack.
2604+const __rpcDes = (bytes) => {
2605+ if (bytes[0] === 0xff) return __sc_decode(bytes);
2606+ if (bytes[0] === 1 || bytes[0] === 2) {
2607+ const { value, handles, disposers } =
2608+ __stubRevive(__sc_decode(bytes.subarray(1)));
2609+ if (value !== null && typeof value === "object" &&
2610+ !__stubMeta.has(value) &&
2611+ (handles.length > 0 || disposers.length > 0)) {
2612+ Object.defineProperty(value, Symbol.dispose, {
2613+ configurable: true,
2614+ value: () => {
2615+ for (const handle of handles) __disposeStub(handle);
2616+ for (const entry of disposers) {
2617+ __stubEntries.delete(entry.id);
2618+ Promise.resolve().then(() => entry.target());
2619+ }
2620+ },
2621+ });
2622+ }
2623+ return value;
2624+ }
2625+ const [error, props] = __sc_decode(bytes.subarray(1));
2626+ if (error instanceof Error) {
2627+ Object.assign(error, props);
2628+ error.remote = true;
2629+ const local = new Error().stack;
2630+ error.stack = error.name + ": " + error.message +
2631+ local.slice(local.indexOf("\n"));
2632+ }
2633+ throw error;
2634+};
2635+// Deprecated Fetcher `get()`/`put()`/`delete()` HTTP helpers, kept by
2636+// the fetcher_has_get_put_delete compat flag (Workerd http.c++):
2637+// shortcuts for fetch() with the corresponding method.
2638+const __fetcherStatus = (res, method) => {
2639+ if (res.status >= 200 && res.status < 300) return;
2640+ throw new Error("HTTP " + method + " request failed: " + res.status +
2641+ " " + (res.statusText || __STATUS_TEXT[res.status] || ""));
2642+};
2643+const __fetcherHelper = (fetch, prop) => {
2644+ if (prop === "get") return async (url, type) => {
2645+ const res = await fetch(url, { method: "GET" });
2646+ if (res.status === 404 || res.status === 410) return null;
2647+ __fetcherStatus(res, "GET");
2648+ if (type === "stream")
2649+ return res.body ?? new ReadableStream({ start(c) { c.close(); } });
2650+ if (type === "arrayBuffer") return res.arrayBuffer();
2651+ if (type === "json") return res.json();
2652+ return res.text();
2653+ };
2654+ if (prop === "put") return async (url, body, options) => {
2655+ const { expiration, expirationTtl } = options ?? {};
2656+ if (expiration !== undefined || expirationTtl !== undefined) {
2657+ const url_ = new URL(url);
2658+ if (expiration !== undefined)
2659+ url_.searchParams.append("expiration", expiration);
2660+ if (expirationTtl !== undefined)
2661+ url_.searchParams.append("expiration_ttl", expirationTtl);
2662+ url = url_.toString();
2663+ }
2664+ __fetcherStatus(await fetch(url, { method: "PUT", body }), "PUT");
2665+ };
2666+ return async (url) => {
2667+ __fetcherStatus(await fetch(url, { method: "DELETE" }), "DELETE");
2668+ };
2669+};
2670+function makeNamespace(className) {
2671+ const namespaceKey = __cell.namespaceKeys[className];
2672+ if (typeof namespaceKey !== "string")
2673+ 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;
2696+ 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);
2738+ }
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(
2761+ 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))),
2799+ );
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.
2803+ return async (...args) => invoke(
2804+ async () => __rpcDes(await __rpc_call(
2805+ scope, dispatchName ?? null, prop, __rpcOut(args, true),
2806+ )),
2807+ );
2808+ }});
2809+ return stub;
2810+ }
2811+ };
2812+ return namespace;
2813+}
2814+const __attachResponseRequestCancellation = (
2815+ response,
2816+ requestController,
2817+ wrapBody,
2818+) => {
2819+ if (!(response instanceof Response) ||
2820+ response._bodyBytes !== null ||
2821+ response.body === null) {
2822+ return;
2823+ }
2824+ const requestControllers = Array.isArray(
2825+ response.__celldRequestControllers,
2826+ )
2827+ ? response.__celldRequestControllers
2828+ : [requestController];
2829+ if (requestControllers !== response.__celldRequestControllers) {
2830+ Object.defineProperty(response, "__celldRequestControllers", {
2831+ value: requestControllers,
2832+ });
2833+ } else {
2834+ requestControllers.push(requestController);
2835+ }
2836+ if (!wrapBody || response.__celldCancellationWrapped) return;
2837+ const reader = response.body.getReader();
2838+ response.body = new ReadableStream({
2839+ async pull(controller) {
2840+ const result = await reader.read();
2841+ if (result.done) controller.close();
2842+ else controller.enqueue(result.value);
2843+ },
2844+ async cancel() {
2845+ const reason = new Error("The client has disconnected");
2846+ for (const controller of requestControllers) {
2847+ if (!controller.signal.aborted) controller.abort(reason);
2848+ }
2849+ try {
2850+ await reader.cancel(reason);
2851+ } catch {}
2852+ },
2853+ }, { highWaterMark: 0 });
2854+ Object.defineProperty(response, "__celldCancellationWrapped", {
2855+ value: true,
2856+ });
2857+};
2858+// called on the owner node by the /__do/<scope> endpoint: run one object.
2859+// Returns the Response; Rust's read_response unwraps it (don't double-wrap).
2860+// A top-level (non-actor) request whose signal can be aborted by id, so a
2861+// disconnected HTTP or service-binding caller reaches the target's
2862+// `request.signal`.
2863+globalThis.__makeIncomingRequest = (
2864+ url, method, body, headersJson,
2865+) => __makeRequest(
2866+ url, method, body, headersJson, undefined, true);
2867+globalThis.__dispatchTo = async (
2868+ scope, url, method, body, headersJson, requestId = null, inline = false,
2869+ callerSignal = null,
2870+) => {
2871+ // Request already allocates a default controller for an absent signal.
2872+ // Retain that same allocation so a streamed response can report reader
2873+ // cancellation after the handler has returned.
2874+ const requestController = new AbortController();
2875+ if (requestId !== null)
2876+ __incomingRequestSignals.set(
2877+ String(requestId), requestController.signal);
2878+ __actorEventStack.push(scope);
2879+ try {
2880+ // Output gate for the co-hosted fast path: the routed path is gated in the
2881+ // host, but an owned in-isolate dispatch bypasses it, so sample the cell's
2882+ // committed-write position here and hold the response below until durable.
2883+ const gateBefore = inline ? __writePosition(scope) : null;
2884+ const dispatch = (async () => {
2885+ const inst = await _readyInstance(scope);
2886+ return await __ctxRun(undefined, () => inst.fetch(
2887+ __makeRequest(
2888+ url,
2889+ method,
2890+ body,
2891+ headersJson,
2892+ requestController.signal,
2893+ true,
2894+ )));
2895+ })();
2896+ // The owned in-isolate fast path carries the caller's signal here
2897+ // directly (the routed channel reaches this signal through
2898+ // __do_call_cancel/__abortIncomingRequest instead). Mirror those
2899+ // semantics: abandonment aborts the target's fresh incoming signal
2900+ // with the canonical disconnect reason and rejects the caller with
2901+ // its own reason; the abandoned dispatch keeps its settle handlers
2902+ // and drains its waitUntil work.
2903+ const response = callerSignal === null
2904+ ? await dispatch
2905+ : await __raceCallerAbort(dispatch, callerSignal, () =>
2906+ requestController.abort(
2907+ new Error("The client has disconnected")));
2908+ __attachResponseRequestCancellation(
2909+ response,
2910+ requestController,
2911+ inline,
2912+ );
2913+ if (response instanceof Response && response.status === 101 &&
2914+ response.webSocket && !response.webSocket._target) {
2915+ const socket = response.webSocket._peer;
2916+ const target = { id: response.webSocket._id, scope };
2917+ response.webSocket._target = target;
2918+ if (socket) {
2919+ socket._target = target;
2920+ if (!socket._hibernatable)
2921+ __ws_accept_regular(socket._id, scope);
2922+ __sockets.set(socket._id, socket);
2923+ socket._flushPending();
2924+ }
2925+ }
2926+ // Hold the inline response until the write is durable (rejects if it can
2927+ // not be proved, breaking the call as a routed gate failure would). A null
2928+ // `before` means this thread opened the cell's connection during the
2929+ // handler; a fresh connection's change counter starts at zero, so treat it
2930+ // as zero — a write advances past it, a read leaves it there.
2931+ if (inline) {
2932+ const after = __writePosition(scope);
2933+ if (after !== null && after > (gateBefore ?? 0)) await __gateWrite(scope, after);
2934+ }
2935+ return response;
2936+ } finally {
2937+ if (requestId !== null)
2938+ __incomingRequestSignals.delete(String(requestId));
2939+ if (__actorEventStack[__actorEventStack.length - 1] === scope)
2940+ __actorEventStack.pop();
2941+ }
2942+};
2943+const __rpcTargetMethod = async (scope, method) => {
2944+ const inst = await _readyInstance(scope);
2945+ if (!inst.__celldState._rpcOk)
2946+ throw new TypeError(
2947+ "The receiving Durable Object does not support RPC, because " +
2948+ "its class was not declared with `extends DurableObject`. In " +
2949+ "order to enable RPC, make sure your class extends the " +
2950+ "special class `DurableObject`, which can be imported from " +
2951+ "the module \"cloudflare:workers\".");
2952+ const fn = inst[method];
2953+ if (typeof fn !== "function")
2954+ throw new TypeError(method + " is not a function");
2955+ return [inst, fn];
2956+};
2957+// The byte path always lifts stub-able values into the reply: the
2958+// markers carry the isolate token, so they revive only back in this
2959+// isolate (the owned fast path and same-process routed dispatch)
2960+// and fail loudly on use anywhere else. Callee exceptions cross in
2961+// the error envelope on every flavor.
2962+globalThis.__dispatchRpc = async (scope, method, args) => {
2963+ __actorEventStack.push(scope);
2964+ try {
2965+ // A string is the legacy JSON flavor (test harness, old cross-node
2966+ // envelope); bytes are V8 structured clone. Answer in kind.
2967+ if (typeof args === "string") {
2968+ const [inst, fn] = await __rpcTargetMethod(scope, method);
2969+ const result = await fn.apply(inst, JSON.parse(args));
2970+ return JSON.stringify(result) ?? "null";
2971+ }
2972+ return await __ctxRun(undefined, () => (async () => {
2973+ const decoded = __rpcDesArgs(args);
2974+ try {
2975+ return await __rpcRun(async () => {
2976+ // A broken actor (JS-flavored ctx.abort) rejects every
2977+ // later call with the reason. One gated field read.
2978+ if (__brokenActors.size !== 0) {
2979+ const broken = __brokenActors.get(scope);
2980+ if (broken !== undefined) throw broken;
2981+ }
2982+ const [inst, fn] = await __rpcTargetMethod(scope, method);
2983+ return fn.apply(inst, decoded.args);
2984+ }, true);
2985+ } finally {
2986+ for (const handle of decoded.received) __disposeStub(handle);
2987+ }
2988+ })());
2989+ } finally {
2990+ if (__actorEventStack[__actorEventStack.length - 1] === scope)
2991+ __actorEventStack.pop();
2992+ }
2993+};
2994+// Invoke a method on a named WorkerEntrypoint. Instances are cached per
2995+// entrypoint: the class is stateless across calls the way a Worker is,
2996+// so re-constructing per call would only add allocation.
2997+const __entrypointInstances = new Map();
2998+const __entrypointInstance = (name) => {
2999+ const cls = __cell.entrypoints[name];
3000+ if (typeof cls !== "function") {
3001+ // Workerd getExportedHandler(): distinguish a Durable Object class
3002+ // misused as a stateless entrypoint from a name that resolves to
3003+ // nothing. Error path only; both lookups are O(1).
3004+ if (__cell.classes[name] !== undefined || __cell.doExports[name])
3005+ throw new TypeError(
3006+ `The entrypoint name ${name} refers to a Durable Object ` +
3007+ "class, but the incoming request is trying to invoke it as " +
3008+ "a stateless worker.");
3009+ throw new TypeError(
3010+ `The entrypoint name ${name} was not found in this worker. ` +
3011+ "Ensure the worker exports an entrypoint with that name.");
3012+ }
3013+ let inst = __entrypointInstances.get(name);
3014+ if (inst === undefined) {
3015+ // End the construction event immediately: ctx.waitUntil registers
3016+ // into whichever event is current at call time, so leaving this
3017+ // event on the stack would swallow every later registration in the
3018+ // isolate.
3019+ const ctx = __beginEvent();
3020+ try {
3021+ inst = new cls(ctx, __cell.env);
3022+ } finally {
3023+ __endEvent();
3024+ }
3025+ __entrypointInstances.set(name, inst);
3026+ }
3027+ return inst;
3028+};
3029+// `env.NAME.fetch()` where NAME is bound with `entrypoint = "..."` goes
3030+// to that class's fetch, not the module's default export. A plain
3031+// object export (Workerd's non-class entrypoint) dispatches its
3032+// handler functions as fn(arg, env, ctx).
3033+globalThis.__dispatchEntrypointFetch = async (name, request) => {
3034+ const handler = __cell.objectEntrypoints[name];
3035+ if (handler !== undefined) {
3036+ if (typeof handler.fetch !== "function")
3037+ throw new TypeError(
3038+ `Entrypoint ${JSON.stringify(name)} has no fetch handler`);
3039+ const ctx = __beginEvent();
3040+ try {
3041+ return await __ctxRun(undefined,
3042+ () => handler.fetch(request, __cell.env, ctx));
3043+ } finally {
3044+ __endEvent();
3045+ }
3046+ }
3047+ const inst = __entrypointInstance(name);
3048+ if (typeof inst.fetch !== "function")
3049+ throw new TypeError(
3050+ `Entrypoint ${JSON.stringify(name)} has no fetch handler`);
3051+ return await __ctxRun(undefined, () => inst.fetch(request));
3052+};
3053+// Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class
3054+// handler method is called as fn(arg, env, ctx), the client must send
3055+// exactly one argument, and the handler must not declare more than
3056+// (arg, env, ctx). The messages are Workerd's, verbatim.
3057+const __callObjectEntrypoint = (handler, method, args) => {
3058+ const fn = handler[method];
3059+ if (typeof fn !== "function")
3060+ throw new TypeError(
3061+ 'The RPC receiver does not implement the method "' + method +
3062+ '".');
3063+ if (fn.length > 3)
3064+ throw new TypeError(
3065+ 'Cannot call handler function "' + method + '" over RPC ' +
3066+ "because it has the wrong number of arguments. A simple " +
3067+ "function handler can only be called over RPC if it has " +
3068+ "exactly the arguments (arg, env, ctx), where only the first " +
3069+ "argument comes from the client. To support multi-argument " +
3070+ "RPC functions, use class-based syntax (extending " +
3071+ "WorkerEntrypoint) instead.");
3072+ if (args.length !== 1)
3073+ throw new TypeError(
3074+ 'Attempted to call RPC function "' + method + '" with the ' +
3075+ "wrong number of arguments. When calling a top-level handler " +
3076+ "function that is not declared as part of a class, you must " +
3077+ "always send exactly one argument. In order to support " +
3078+ "variable numbers of arguments, the server must use " +
3079+ "class-based syntax (extending WorkerEntrypoint) instead.");
3080+ const ctx = {
3081+ waitUntil: globalThis.__registerWaitUntil,
3082+ passThroughOnException() {},
3083+ abort: __ctxAbortCurrent,
3084+ props: __defaultProps,
3085+ get exports() { return __ctxExports(); },
3086+ };
3087+ return fn.call(handler, args[0], __cell.env, ctx);
3088+};
3089+// One entrypoint op (a call, or a property GET when argsSc is
3090+// null), inside a fresh request context — the callee owns stubs
3091+// revived from its params, and stubs it mints belong to it.
3092+const __entrypointOp = (name, path, argsSc, local, makeInst) => {
3093+ const id = __nextCtxId++;
3094+ return __ctxRun(id, () => (async () => {
3095+ const decoded = argsSc === null ? null : __rpcDesArgs(argsSc);
3096+ let drain = null;
3097+ try {
3098+ const reply = await __rpcRun(async () => {
3099+ // The handler's synchronous part runs inside its own event so
3100+ // ctx.waitUntil and the imported waitUntil have a target. The
3101+ // event pops before the first await — the event stack is
3102+ // strictly LIFO and an event held across an await would be
3103+ // popped by whichever event settles next — and its registered
3104+ // work drains before a plain reply (below).
3105+ __beginEvent();
3106+ let result;
3107+ try {
3108+ const handler = __cell.objectEntrypoints[name];
3109+ if (handler !== undefined && makeInst === undefined) {
3110+ // Simple-handler entrypoints expose single-method calls
3111+ // only; property GETs and deeper paths are refused.
3112+ if (argsSc === null || path.length !== 1)
3113+ throw __rpcNoSuchMethod(path[0]);
3114+ result = __callObjectEntrypoint(
3115+ handler, path[0], decoded.args);
3116+ } else {
3117+ const inst = makeInst === undefined
3118+ ? __entrypointInstance(name) : makeInst();
3119+ result = __rpcWalk(inst, path,
3120+ decoded === null ? null : decoded.args, true);
3121+ }
3122+ } finally {
3123+ drain = __endEvent();
3124+ }
3125+ return await result;
3126+ }, local);
3127+ // Registered work drains before a plain reply. A
3128+ // capability-bearing reply (tag 1) must not wait: a returned
3129+ // stream's chunks may be produced by that very work, which
3130+ // cannot finish until the caller pulls (returnReadableStream's
3131+ // waitUntil writer would deadlock behind its own reply).
3132+ if (reply[0] !== 1 && drain !== null) await drain;
3133+ // ctx.abort() during the call supersedes its result; the raw
3134+ // reason rejects the caller (same isolate — identity holds).
3135+ if (__abortedCtxs.size !== 0) {
3136+ const reason = __abortedCtxs.get(id);
3137+ if (reason !== undefined) throw reason;
3138+ }
3139+ // A reply that exports no stubs (tag 0xff plain, tag 0 error)
3140+ // leaves nothing rooting this context: tear it down now, so a
3141+ // dup() the callee leaked reaches its disposal callback
3142+ // promptly (Workerd tears the IoContext down at call end
3143+ // unless returned capabilities hold it open).
3144+ if (reply[0] !== 1) __ctxEnd(id);
3145+ return reply;
3146+ } finally {
3147+ if (decoded !== null)
3148+ for (const handle of decoded.received) __disposeStub(handle);
3149+ }
3150+})());
3151+};
3152+// Cross-isolate and host callers still pass a single method name.
3153+globalThis.__dispatchEntrypointRpc =
3154+ (name, path, argsSc, local = false) => __entrypointOp(
3155+ name, typeof path === "string" ? [path] : path, argsSc, local,
3156+ undefined);
3157+// WebSocket: the host holds the socket; these deliver events into the DO.
3158+// `ws` is a lightweight stub whose send/close route back to the host task
3159+// by wsId — so the isolate can be hibernated between messages.
3160+globalThis.__wsStub = (wsId) => ({
3161+ _hibernatable: true,
3162+ send: (data) => {
3163+ if (data instanceof ArrayBuffer)
3164+ __ws_send_binary(wsId, new Uint8Array(data));
3165+ else if (ArrayBuffer.isView(data))
3166+ __ws_send_binary(wsId,
3167+ new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
3168+ else
3169+ __ws_send(wsId, String(data));
3170+ },
3171+ close: (code = 1000, reason = "") => __ws_close(wsId, code, reason),
3172+});
3173+globalThis.__wsOpen = async (scope, wsId, protocol) => {
3174+ __actorEventStack.push(scope);
3175+ try {
3176+ const inst = await _readyInstance(scope);
3177+ const socket = inst.__celldState._socket(wsId);
3178+ if (socket.readyState !== WebSocket.READY_STATE_CONNECTING) return;
3179+ socket.protocol = protocol;
3180+ socket.readyState = WebSocket.READY_STATE_OPEN;
3181+ socket.dispatchEvent(new Event("open"));
3182+ } finally {
3183+ if (__actorEventStack[__actorEventStack.length - 1] === scope)
3184+ __actorEventStack.pop();
3185+ }
3186+};
3187+globalThis.__wsMessage = async (scope, wsId, msg) => {
3188+ __actorEventStack.push(scope);
3189+ try {
3190+ const inst = await _readyInstance(scope);
3191+ const socket = inst.__celldState._socket(wsId);
3192+ if (!socket._hibernatable && typeof socket._dispatchMessage === "function")
3193+ socket._dispatchMessage(msg);
3194+ else if (typeof inst.webSocketMessage === "function")
3195+ await inst.webSocketMessage(socket, msg);
3196+ } finally {
3197+ if (__actorEventStack[__actorEventStack.length - 1] === scope)
3198+ __actorEventStack.pop();
3199+ }
3200+};
3201+globalThis.__wsBinary = async (scope, wsId, data) => {
3202+ __actorEventStack.push(scope);
3203+ try {
3204+ const inst = await _readyInstance(scope);
3205+ const socket = inst.__celldState._socket(wsId);
3206+ const bytes = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
3207+ if (!socket._hibernatable && typeof socket._dispatchMessage === "function")
3208+ socket._dispatchMessage(bytes);
3209+ else if (typeof inst.webSocketMessage === "function")
3210+ await inst.webSocketMessage(socket, bytes);
3211+ } finally {
3212+ if (__actorEventStack[__actorEventStack.length - 1] === scope)
3213+ __actorEventStack.pop();
3214+ }
3215+};
3216+globalThis.__wsClosed = async (scope, wsId, code, reason, wasClean) => {
3217+ __actorEventStack.push(scope);
3218+ try {
3219+ const inst = await _readyInstance(scope);
3220+ const socket = inst.__celldState._socket(wsId);
3221+ if (!socket._hibernatable && typeof socket._dispatchClose === "function")
3222+ socket._dispatchClose(code, reason, wasClean);
3223+ else if (!wasClean && typeof inst.webSocketError === "function")
3224+ // A hibernatable socket reports an abnormal closure through
3225+ // webSocketError, which celld listed as a handler name and never
3226+ // called.
3227+ await inst.webSocketError(
3228+ socket,
3229+ new Error(reason ? `WebSocket closed abnormally: ${reason}` : "WebSocket closed abnormally"),
3230+ );
3231+ else if (typeof inst.webSocketClose === "function")
3232+ await inst.webSocketClose(socket, code, reason, wasClean);
3233+ } finally {
3234+ if (__actorEventStack[__actorEventStack.length - 1] === scope)
3235+ __actorEventStack.pop();
3236+ }
3237+};
3238+// called by celld's scheduler when an alarm is due. Returns a promise.
3239+globalThis.__fireAlarm = async (scope, scheduledTime, retryCount) => {
3240+ __actorEventStack.push(scope);
3241+ try {
3242+ const inst = await _readyInstance(scope);
3243+ if (typeof inst.alarm !== "function") return;
3244+ await inst.alarm({ scheduledTime, retryCount, isRetry: retryCount > 0 });
3245+ } finally {
3246+ if (__actorEventStack[__actorEventStack.length - 1] === scope)
3247+ __actorEventStack.pop();
3248+ }
3249+};
3250+globalThis.__cell = {
3251+ entrypoints: {},
3252+ objectEntrypoints: {},
3253+ doExports: {},
3254+ classes: {},
3255+ instances: {},
3256+ env: {},
3257+ owned: {},
3258+ idNames: {},
3259+ namespaceKeys: {},
3260+ node: "",
3261+ deleteAllDeletesAlarm: false,
3262+ compat: { jsRpc: false, fetcherGetPutDelete: false },
3263+ makeNamespace,
3264+};
3265+// `cloudflare:workers` module surface. The DO base class sets ctx/env the
3266+// way `class X extends DurableObject` expects; env aliases the cell env.
3267+globalThis.__cf = {
3268+ DurableObject: class DurableObject {
3269+ constructor(ctx, env) { this.ctx = ctx; this.env = env; }
3270+ },
3271+ // The enumerable function-valued brand makes V8's structured clone
3272+ // fail on every RpcTarget instance, forcing it off the silent
3273+ // plain-clone path and into the stub lift (Workerd rejects these
3274+ // from plain serialization outright).
3275+ RpcTarget: class RpcTarget {
3276+ constructor() {
3277+ Object.defineProperty(this, "__celldRpcTarget", {
3278+ value: __rpcNoClone, enumerable: true,
3279+ });
3280+ }
3281+ },
3282+ // Named entrypoint for `[[services]]` with `entrypoint = "Name"`.
3283+ WorkerEntrypoint: class WorkerEntrypoint {
3284+ constructor(ctx, env) { this.ctx = ctx; this.env = env; }
3285+ },
3286+ // `new RpcStub(target)` wraps any local object or function in a
3287+ // loopback stub; the constructor returns the proxy, so instanceof
3288+ // works through __makeStub's getPrototypeOf trap.
3289+ RpcStub: class RpcStub {
3290+ constructor(target) {
3291+ if (target === null ||
3292+ (typeof target !== "object" && typeof target !== "function"))
3293+ throw new TypeError(
3294+ "RpcStub requires an object or function.");
3295+ return __makeStub(
3296+ __newEntry(target), typeof target === "function");
3297+ }
3298+ },
3299+ RpcPromise: class RpcPromise extends Promise {},
3300+ RpcProperty: class RpcProperty {},
3301+ ServiceStub: class ServiceStub {},
3302+ // `import { waitUntil } from "cloudflare:workers"`: register into
3303+ // the current event; outside any event this is Workerd's
3304+ // global-scope error.
3305+ waitUntil(promise) {
3306+ if (__eventStack.length === 0)
3307+ throw new Error(
3308+ "Disallowed operation called within global scope.");
3309+ globalThis.__registerWaitUntil(promise);
3310+ },
3311+ exports: {},
3312+ get env() { return globalThis.__cell.env; },
3313+};
3314+// Pass-through proxy standing in for unsupported node:* builtins: callable,
3315+// constructable, and every property returns itself — so bundle evaluation
3316+// never crashes on a builtin the fetch path doesn't actually exercise.
3317+globalThis.__nodeStub = new Proxy(function () {}, {
3318+ get: (_t, p) => {
3319+ // Never masquerade as a thenable. `await` probes `.then`; returning
3320+ // the callable proxy here creates a promise that can never settle.
3321+ if (p === "then") return undefined;
3322+ // coerce cleanly in string/number contexts so evaluation never throws
3323+ if (p === Symbol.toPrimitive || p === "toString" || p === "valueOf") return () => "";
3324+ if (p === Symbol.toStringTag) return "NodeStub";
3325+ if (p === Symbol.iterator) return function* () {};
3326+ return globalThis.__nodeStub;
3327+ },
3328+ apply: () => globalThis.__nodeStub,
3329+ construct: () => globalThis.__nodeStub,
3330+});
3331+if (!globalThis.Event) {
3332+ globalThis.Event = class Event {
3333+ // Private fields: stored in the object itself, so an Event costs no
3334+ // side allocation and no defineProperty call at construction. The
3335+ // public members are accessors because the DOM standard makes them
3336+ // read-only; EventTarget drives them through _begin/_end.
3337+ #type; #bubbles; #cancelable; #composed;
3338+ #defaultPrevented = false;
3339+ #eventPhase = 0;
3340+ #target; #currentTarget; #path;
3341+ #stop = false; #stopImmediate = false; #dispatching = false;
3342+ // Workerd: events the runtime delivers are trusted; events a
3343+ // script constructs and dispatches itself are not.
3344+ #trusted = false;
3345+ constructor(type, init = {}) {
3346+ if (arguments.length === 0)
3347+ throw new TypeError(
3348+ "Failed to construct 'Event': 1 argument required, but only " +
3349+ "0 present.");
3350+ if (init !== undefined && init !== null &&
3351+ typeof init !== "object")
3352+ throw new TypeError(
3353+ "Failed to construct 'Event': The provided value is not of " +
3354+ "type 'EventInit'.");
3355+ const options = init || {};
3356+ // Template interpolation, not String(): it must throw for a
3357+ // Symbol, which String() would happily format.
3358+ this.#type = `${type}`;
3359+ this.#bubbles = !!options.bubbles;
3360+ this.#cancelable = !!options.cancelable;
3361+ this.#composed = !!options.composed;
3362+ }
3363+ get type() { return this.#type; }
3364+ get bubbles() { return this.#bubbles; }
3365+ get cancelable() { return this.#cancelable; }
3366+ get composed() { return this.#composed; }
3367+ get defaultPrevented() { return this.#defaultPrevented; }
3368+ get eventPhase() { return this.#eventPhase; }
3369+ get target() { return this.#target; }
3370+ get currentTarget() { return this.#currentTarget; }
3371+ get isTrusted() { return this.#trusted; }
3372+ get timeStamp() { return 0; }
3373+ get returnValue() { return !this.#defaultPrevented; }
3374+ // The one writable member, per the DOM standard.
3375+ get cancelBubble() { return this.#stop; }
3376+ set cancelBubble(value) { if (value) this.#stop = true; }
3377+ composedPath() { return this.#path ? this.#path.slice() : []; }
3378+ preventDefault() {
3379+ if (this.#cancelable) this.#defaultPrevented = true;
3380+ }
3381+ stopPropagation() { this.#stop = true; }
3382+ stopImmediatePropagation() {
3383+ this.#stop = true;
3384+ this.#stopImmediate = true;
3385+ }
3386+ // Internal dispatch hooks used by EventTarget.
3387+ get _dispatching() { return this.#dispatching; }
3388+ get _stopImmediate() { return this.#stopImmediate; }
3389+ _trust() { this.#trusted = true; }
3390+ _begin(target) {
3391+ this.#dispatching = true;
3392+ this.#target = target;
3393+ this.#currentTarget = target;
3394+ this.#eventPhase = 2; // AT_TARGET
3395+ this.#path = [target];
3396+ this.#stop = false;
3397+ this.#stopImmediate = false;
3398+ }
3399+ // Workerd leaves currentTarget set after dispatch (the DOM standard
3400+ // nulls it); only the phase is reset.
3401+ _end() {
3402+ this.#eventPhase = 0;
3403+ this.#dispatching = false;
3404+ }
3405+ };
3406+ {
3407+ const phases = {
3408+ NONE: 0, CAPTURING_PHASE: 1, AT_TARGET: 2, BUBBLING_PHASE: 3,
3409+ };
3410+ for (const [name, value] of Object.entries(phases)) {
3411+ const d = { value, writable: false, enumerable: true,
3412+ configurable: false };
3413+ Object.defineProperty(globalThis.Event, name, d);
3414+ Object.defineProperty(globalThis.Event.prototype, name, d);
3415+ }
3416+ }
3417+}
3418+if (!globalThis.CustomEvent) {
3419+ globalThis.CustomEvent = class CustomEvent extends Event {
3420+ constructor(type, init = {}) {
3421+ super(type, init);
3422+ this.detail = init.detail === undefined ? null : init.detail;
3423+ }
3424+ };
3425+}
3426+if (!globalThis.ExtendableEvent) {
3427+ // Exists as a type but is not constructable from user code.
3428+ globalThis.ExtendableEvent = class ExtendableEvent extends Event {
3429+ constructor() {
3430+ throw new TypeError("Illegal constructor");
3431+ }
3432+ };
3433+}
3434+if (!globalThis.EventTarget) {
3435+ globalThis.EventTarget = class EventTarget {
3436+ constructor() { this._listeners = new Map(); }
3437+ addEventListener(type, callback, options = {}) {
3438+ if (callback === null || callback === undefined) return;
3439+ if (typeof callback !== "function" &&
3440+ typeof callback.handleEvent !== "function")
3441+ throw new TypeError(
3442+ "Failed to execute 'addEventListener' on 'EventTarget': " +
3443+ "parameter 2 is not of type 'EventListener'.");
3444+ const object = typeof options === "object" && options !== null;
3445+ // Capture and passive are accepted for portability but must be
3446+ // false: Cells dispatches only at the target, so honouring them
3447+ // would silently change ordering.
3448+ if (object ? options.capture || options.passive : !!options)
3449+ throw new TypeError(
3450+ "Cells does not support the 'capture' or 'passive' options " +
3451+ "on addEventListener().");
3452+ const signal = object ? options.signal : undefined;
3453+ if (signal && signal.aborted) return;
3454+ const key = String(type);
3455+ const list = this._listeners.get(key) || [];
3456+ if (list.some((e) => e.callback === callback)) return;
3457+ list.push({ callback, once: object && !!options.once });
3458+ this._listeners.set(key, list);
3459+ if (signal)
3460+ signal.addEventListener("abort", () =>
3461+ this.removeEventListener(key, callback), { once: true });
3462+ }
3463+ removeEventListener(type, callback, options = {}) {
3464+ const object = typeof options === "object" && options !== null;
3465+ if (object ? options.capture : !!options)
3466+ throw new TypeError(
3467+ "Cells does not support the 'capture' option on " +
3468+ "removeEventListener().");
3469+ const list = this._listeners.get(String(type));
3470+ if (!list) return;
3471+ const index = list.findIndex((e) => e.callback === callback);
3472+ if (index >= 0) list.splice(index, 1);
3473+ }
3474+ dispatchEvent(event) {
3475+ if (!(event instanceof Event))
3476+ throw new TypeError("argument is not an Event");
3477+ if (event._dispatching)
3478+ throw new DOMException(
3479+ "The event is already being dispatched.",
3480+ "InvalidStateError");
3481+ event._begin(this);
3482+ // Copy: a listener may add or remove listeners mid-dispatch.
3483+ for (const item of (this._listeners.get(event.type) || []).slice()) {
3484+ if (event._stopImmediate) break;
3485+ if (item.once)
3486+ this.removeEventListener(event.type, item.callback);
3487+ if (typeof item.callback === "function")
3488+ item.callback.call(this, event);
3489+ else item.callback.handleEvent(event);
3490+ }
3491+ const handler = this["on" + event.type];
3492+ if (!event._stopImmediate && typeof handler === "function")
3493+ handler.call(this, event);
3494+ event._end();
3495+ return !event.defaultPrevented;
3496+ }
3497+ };
3498+}
3499+// The global scope is itself an EventTarget.
3500+if (typeof globalThis.addEventListener !== "function") {
3501+ const globalTarget = new EventTarget();
3502+ for (const name of
3503+ ["addEventListener", "removeEventListener", "dispatchEvent"])
3504+ globalThis[name] = globalTarget[name].bind(globalTarget);
3505+}
3506+if (!globalThis.MessageEvent) {
3507+ globalThis.MessageEvent = class MessageEvent extends Event {
3508+ constructor(type, init = {}) {
3509+ super(type, init);
3510+ this.data = init.data;
3511+ this.origin = String(init.origin || "");
3512+ this.lastEventId = String(init.lastEventId || "");
3513+ }
3514+ };
3515+}
3516+if (!globalThis.CloseEvent) {
3517+ globalThis.CloseEvent = class CloseEvent extends Event {
3518+ constructor(type, init = {}) {
3519+ super(type, init);
3520+ this.code = Number(init.code || 0);
3521+ // `reason` is a USVString: a lone surrogate becomes U+FFFD rather than
3522+ // travelling as an unpaired code unit.
3523+ this.reason = String(init.reason || "").toWellFormed
3524+ ? String(init.reason || "").toWellFormed()
3525+ : String(init.reason || "").replace(
3526+ /[\uD800-\uDFFF]/g,
3527+ (unit, index, whole) => {
3528+ const code = unit.charCodeAt(0);
3529+ const next = whole.charCodeAt(index + 1);
3530+ const prev = whole.charCodeAt(index - 1);
3531+ const paired = code <= 0xDBFF
3532+ ? next >= 0xDC00 && next <= 0xDFFF
3533+ : prev >= 0xD800 && prev <= 0xDBFF;
3534+ return paired ? unit : "\uFFFD";
3535+ },
3536+ );
3537+ this.wasClean = !!init.wasClean;
3538+ }
3539+ };
3540+}
3541+if (!globalThis.DOMException) {
3542+ globalThis.DOMException = class DOMException extends Error {
3543+ constructor(message = "", name = "Error") { super(message); this.name = name; }
3544+ };
3545+ // WebIDL legacy code constants, enumerable on both the interface
3546+ // object and its prototype, in spec order.
3547+ {
3548+ const codes = [
3549+ ["INDEX_SIZE_ERR", 1], ["DOMSTRING_SIZE_ERR", 2],
3550+ ["HIERARCHY_REQUEST_ERR", 3], ["WRONG_DOCUMENT_ERR", 4],
3551+ ["INVALID_CHARACTER_ERR", 5], ["NO_DATA_ALLOWED_ERR", 6],
3552+ ["NO_MODIFICATION_ALLOWED_ERR", 7], ["NOT_FOUND_ERR", 8],
3553+ ["NOT_SUPPORTED_ERR", 9], ["INUSE_ATTRIBUTE_ERR", 10],
3554+ ["INVALID_STATE_ERR", 11], ["SYNTAX_ERR", 12],
3555+ ["INVALID_MODIFICATION_ERR", 13], ["NAMESPACE_ERR", 14],
3556+ ["INVALID_ACCESS_ERR", 15], ["VALIDATION_ERR", 16],
3557+ ["TYPE_MISMATCH_ERR", 17], ["SECURITY_ERR", 18],
3558+ ["NETWORK_ERR", 19], ["ABORT_ERR", 20],
3559+ ["URL_MISMATCH_ERR", 21], ["QUOTA_EXCEEDED_ERR", 22],
3560+ ["TIMEOUT_ERR", 23], ["INVALID_NODE_TYPE_ERR", 24],
3561+ ["DATA_CLONE_ERR", 25],
3562+ ];
3563+ for (const [name, value] of codes) {
3564+ const d = { value, writable: false, enumerable: true,
3565+ configurable: false };
3566+ Object.defineProperty(globalThis.DOMException, name, d);
3567+ Object.defineProperty(globalThis.DOMException.prototype, name, d);
3568+ }
3569+ }
3570+}
3571+if (!globalThis.AbortSignal) {
3572+ globalThis.AbortSignal = class AbortSignal extends EventTarget {
3573+ // The Headers/Blob clone-poisoning brand: V8's structured
3574+ // clone throws on functions, so a live signal reaches the
3575+ // RPC lift instead of silently flattening to plain data.
3576+ constructor() {
3577+ super();
3578+ this.aborted = false;
3579+ this.reason = undefined;
3580+ this.__celldHost = __rpcNoClone;
3581+ }
3582+ throwIfAborted() { if (this.aborted) throw this.reason; }
3583+ static abort(reason = new DOMException("This operation was aborted", "AbortError")) {
3584+ const c = new AbortController(); c.abort(reason); return c.signal;
3585+ }
3586+ static timeout(ms) {
3587+ const c = new AbortController();
3588+ setTimeout(() => c.abort(new DOMException(
3589+ "The operation was aborted due to timeout", "TimeoutError",
3590+ )), ms);
3591+ return c.signal;
3592+ }
3593+ static any(signals) {
3594+ const c = new AbortController();
3595+ for (const signal of signals) {
3596+ if (signal.aborted) { c.abort(signal.reason); break; }
3597+ signal.addEventListener("abort", () => c.abort(signal.reason), { once: true });
3598+ }
3599+ return c.signal;
3600+ }
3601+ };
3602+ globalThis.AbortController = class AbortController {
3603+ constructor() { this.signal = new AbortSignal(); }
3604+ abort(reason = new DOMException("This operation was aborted", "AbortError")) {
3605+ __abortSignal(this.signal, reason);
3606+ }
3607+ };
3608+}
3609+if (!globalThis.Blob) {
3610+ // Same clone-poisoning brand as Headers: an enumerable
3611+ // function-valued property makes V8's structured clone throw, so
3612+ // a Blob reaches the RPC lift instead of silently flattening.
3613+ const __blobNoClone = () => {};
3614+ globalThis.Blob = class Blob {
3615+ constructor(parts = [], options = {}) {
3616+ // size is assigned before type so both land in the order the
3617+ // inspect output below reports them.
3618+ if (options && options.endings !== undefined)
3619+ throw new Error(
3620+ "The 'endings' field on 'Options' is not implemented.");
3621+ this.size = 0;
3622+ // A type outside U+0020..U+007E is not a valid MIME type and is
3623+ // dropped rather than stored.
3624+ const rawType = String(options.type || "");
3625+ this.type = /^[\u0020-\u007e]*$/.test(rawType)
3626+ ? rawType.toLowerCase() : "";
3627+ this.__celldHost = __blobNoClone;
3628+ // Two passes. First convert every part in order — string
3629+ // conversion runs user code (Symbol.toPrimitive), which may
3630+ // resize a backing buffer. Buffers and views are carried through
3631+ // as-is so a length-tracking view is measured *after* those side
3632+ // effects, matching Workerd. Then allocate once and copy.
3633+ //
3634+ // The previous shape pushed every byte into a plain array with a
3635+ // spread, costing roughly 8x the memory and exceeding the
3636+ // argument limit on multi-megabyte parts.
3637+ const sources = [];
3638+ for (const part of parts) {
3639+ if (part instanceof Blob) sources.push(part._bytes);
3640+ else if (part instanceof ArrayBuffer ||
3641+ ArrayBuffer.isView(part)) sources.push(part);
3642+ else sources.push(new TextEncoder().encode(String(part)));
3643+ }
3644+ const chunks = sources.map((source) =>
3645+ source instanceof Uint8Array ? source
3646+ : source instanceof ArrayBuffer ? new Uint8Array(source)
3647+ : new Uint8Array(
3648+ source.buffer, source.byteOffset, source.byteLength));
3649+ let total = 0;
3650+ for (const chunk of chunks) total += chunk.byteLength;
3651+ const LIMIT = 134217728;
3652+ if (total > LIMIT)
3653+ throw new RangeError(
3654+ `Blob size ${total} exceeds limit ${LIMIT}`);
3655+ const bytes = new Uint8Array(total);
3656+ let offset = 0;
3657+ for (const chunk of chunks) {
3658+ bytes.set(chunk, offset);
3659+ offset += chunk.byteLength;
3660+ }
3661+ // Non-enumerable: the backing store is not part of the object's
3662+ // observable shape (inspect, JSON, spread).
3663+ Object.defineProperty(this, "_bytes", {
3664+ value: bytes, writable: true, configurable: true,
3665+ });
3666+ this.size = total;
3667+ }
3668+ async arrayBuffer() { return this._bytes.slice().buffer; }
3669+ async bytes() { return this._bytes.slice(); }
3670+ async text() { return new TextDecoder().decode(this._bytes); }
3671+ stream() {
3672+ const bytes = this._bytes;
3673+ return new ReadableStream({
3674+ start(controller) {
3675+ if (bytes.byteLength) controller.enqueue(bytes.slice());
3676+ controller.close();
3677+ },
3678+ });
3679+ }
3680+ [Symbol.for("nodejs.util.inspect.custom")]() {
3681+ return `Blob { size: ${this.size}, type: '${this.type}' }`;
3682+ }
3683+ slice(start = 0, end = this.size, type = "") {
3684+ const norm = (n, fallback) => {
3685+ n = n === undefined ? fallback : Number(n);
3686+ return n < 0 ? Math.max(this.size + n, 0) : Math.min(n, this.size);
3687+ };
3688+ const a = norm(start, 0), b = norm(end, this.size);
3689+ return new Blob(
3690+ [this._bytes.subarray(a, Math.max(a, b))], { type });
3691+ }
3692+ get [Symbol.toStringTag]() { return "Blob"; }
3693+ };
3694+}
3695+if (!globalThis.File) {
3696+ // WebIDL-ish per Workerd: name is required, name/lastModified are
3697+ // brand-checked prototype getters (enumerable, matching the
3698+ // workers_api_getters_setters_on_prototype flag), and lastModified
3699+ // coerces via ToNumber (throws for BigInt), NaN becoming 0.
3700+ globalThis.File = class File extends Blob {
3701+ #name;
3702+ #lastModified;
3703+ constructor(parts, name, options = {}) {
3704+ if (arguments.length < 2)
3705+ throw new TypeError(
3706+ "Failed to construct 'File': 2 arguments required, but " +
3707+ `only ${arguments.length} present.`);
3708+ super(parts, options);
3709+ this.#name = String(name);
3710+ const lm = options == null ? undefined : options.lastModified;
3711+ if (lm === undefined) this.#lastModified = Date.now();
3712+ else {
3713+ const n = +lm; // ToNumber: throws for BigInt, like WebIDL
3714+ this.#lastModified = Number.isFinite(n) ? Math.trunc(n) : 0;
3715+ }
3716+ }
3717+ get name() { return this.#name; }
3718+ get lastModified() { return this.#lastModified; }
3719+ get [Symbol.toStringTag]() { return "File"; }
3720+ [Symbol.for("nodejs.util.inspect.custom")]() {
3721+ return `File { name: '${this.name}', ` +
3722+ `lastModified: ${this.lastModified}, size: ${this.size}, ` +
3723+ `type: '${this.type}' }`;
3724+ }
3725+ };
3726+ for (const key of ["name", "lastModified"]) {
3727+ const desc =
3728+ Object.getOwnPropertyDescriptor(File.prototype, key);
3729+ desc.enumerable = true;
3730+ Object.defineProperty(File.prototype, key, desc);
3731+ }
3732+}
3733+if (!globalThis.FormData) {
3734+// Body -> FormData for multipart/form-data and
3735+// application/x-www-form-urlencoded. Kept out of the class so V8 only
3736+// pre-parses it; the body is compiled on first actual formData() call.
3737+globalThis.__parseFormData = (text, contentType) => {
3738+ const ct = String(contentType || "");
3739+ if (/^\s*application\/x-www-form-urlencoded/i.test(ct)) {
3740+ const form = new FormData();
3741+ for (const [key, value] of new URLSearchParams(text))
3742+ form.append(key, value);
3743+ return form;
3744+ }
3745+ if (!/^\s*multipart\/form-data/i.test(ct))
3746+ throw new TypeError(
3747+ "Unrecognized Content-Type header value. FormData can only " +
3748+ "parse the following MIME types: multipart/form-data, " +
3749+ "application/x-www-form-urlencoded");
3750+ const found = /boundary\s*=\s*(?:"([^"]*)"|([^;]+))/i.exec(ct);
3751+ if (!found)
3752+ throw new TypeError(
3753+ "No boundary was found in the multipart/form-data " +
3754+ "Content-Type header.");
3755+ const boundary = (found[1] !== undefined ? found[1] : found[2]).trim();
3756+ const form = new FormData();
3757+ 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/, "");
3765+ const split = /\r?\n\r?\n/.exec(chunk);
3766+ if (!split) continue;
3767+ 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$/, "");
3772+ let disposition = null;
3773+ let type = "";
3774+ for (const line of rawHeaders.split(/\r?\n/)) {
3775+ const colon = line.indexOf(":");
3776+ if (colon < 0) continue;
3777+ const name = line.slice(0, colon).trim().toLowerCase();
3778+ const value = line.slice(colon + 1).trim();
3779+ if (name === "content-disposition") disposition = value;
3780+ else if (name === "content-type") type = value;
3781+ }
3782+ if (disposition === null)
3783+ throw new TypeError(
3784+ "Content-Disposition header is required for each FormData " +
3785+ "part.");
3786+ const kind = disposition.split(";")[0].trim();
3787+ if (kind.toLowerCase() !== "form-data")
3788+ throw new TypeError(
3789+ "Content-Disposition header for FormData part must have the " +
3790+ "value \"form-data\", possibly followed by parameters. Got: " +
3791+ "\"" + kind + "\"");
3792+ const param = (key) => {
3793+ const m = new RegExp(
3794+ key + "\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^;]*))", "i",
3795+ ).exec(disposition);
3796+ if (!m) return undefined;
3797+ const raw = m[1] !== undefined ? m[1] : (m[2] || "").trim();
3798+ if (/\\$/.test(raw.replace(/\\\\/g, "")))
3799+ throw new TypeError(
3800+ "Name or filename can't end with backslash");
3801+ return raw.replace(/\\(.)/g, "$1");
3802+ };
3803+ const name = param("name");
3804+ if (name === undefined)
3805+ throw new TypeError(
3806+ "Content-Disposition header for FormData part must have a " +
3807+ "name parameter.");
3808+ const filename = param("filename");
3809+ if (filename === undefined) form.append(name, body);
3810+ else
3811+ form.append(
3812+ name, new File([body], filename, { type: type || "" }));
3813+ }
3814+ return form;
3815+};
3816+ // Spec entry conversion: strings stay strings; a Blob becomes a
3817+ // File named "blob" (or `filename`); a File is renamed only when a
3818+ // filename is supplied.
3819+ const __formDataValue = (value, filename) => {
3820+ if (!(value instanceof Blob)) return String(value);
3821+ if (value instanceof File && filename === undefined) return value;
3822+ return new File(
3823+ [value],
3824+ filename === undefined ? "blob" : String(filename),
3825+ {
3826+ type: value.type,
3827+ lastModified:
3828+ value instanceof File ? value.lastModified : undefined,
3829+ },
3830+ );
3831+ };
3832+ globalThis.FormData = class FormData {
3833+ constructor() { this._entries = []; }
3834+ append(name, value, filename) {
3835+ this._entries.push(
3836+ [String(name), __formDataValue(value, filename)]);
3837+ }
3838+ set(name, value, filename) {
3839+ value = __formDataValue(value, filename);
3840+ const key = String(name);
3841+ // Spec: replace the first match in place, keeping its position,
3842+ // and drop any later matches.
3843+ const first = this._entries.findIndex(([k]) => k === key);
3844+ if (first < 0) { this._entries.push([key, value]); return; }
3845+ this._entries[first] = [key, value];
3846+ for (let i = this._entries.length - 1; i > first; i--)
3847+ if (this._entries[i][0] === key) this._entries.splice(i, 1);
3848+ }
3849+ get(name) {
3850+ const row = this._entries.find(([key]) => key === String(name));
3851+ return row ? row[1] : null;
3852+ }
3853+ getAll(name) {
3854+ return this._entries.filter(([key]) => key === String(name)).map(([, value]) => value);
3855+ }
3856+ has(name) { return this._entries.some(([key]) => key === String(name)); }
3857+ delete(name) {
3858+ const key = String(name);
3859+ // Splice in place: the iterators below read the live list, so the
3860+ // array identity must survive a delete during iteration.
3861+ for (let i = this._entries.length - 1; i >= 0; i--)
3862+ if (this._entries[i][0] === key) this._entries.splice(i, 1);
3863+ }
3864+ // Iteration is live: the iterator holds an index and re-reads the
3865+ // entry list, so entries appended during iteration are visited and
3866+ // an exhausted iterator resumes if entries are added later. A
3867+ // generator cannot do this — once it returns it is done forever.
3868+ _iterate(pick) {
3869+ const self = this;
3870+ let index = 0;
3871+ const iterator = {
3872+ next() {
3873+ if (index >= self._entries.length)
3874+ return { value: undefined, done: true };
3875+ return { value: pick(self._entries[index++]), done: false };
3876+ },
3877+ [Symbol.iterator]() { return iterator; },
3878+ };
3879+ return iterator;
3880+ }
3881+ entries() { return this._iterate((e) => [e[0], e[1]]); }
3882+ keys() { return this._iterate((e) => e[0]); }
3883+ values() { return this._iterate((e) => e[1]); }
3884+ [Symbol.iterator]() { return this.entries(); }
3885+ forEach(callback, thisArg) {
3886+ if (typeof callback !== "function")
3887+ throw new TypeError(
3888+ "Failed to execute 'forEach' on 'FormData': parameter 1 is " +
3889+ "not of type 'Function'.");
3890+ for (const [key, value] of this.entries())
3891+ callback.call(thisArg, value, key, this);
3892+ }
3893+ };
3894+}
3895+// Node's Buffer lives in src/js/node_buffer.js, compiled
3896+// lazily (LAZY_GLOBALS / LAZY_MODULES) on first use.
3897+if (!globalThis.ErrorEvent) {
3898+ globalThis.ErrorEvent = class ErrorEvent extends Event {
3899+ constructor(type, init = {}) {
3900+ super(type, init);
3901+ this.message = String(init.message ?? "");
3902+ this.filename = String(init.filename ?? "");
3903+ this.lineno = Number(init.lineno ?? 0);
3904+ this.colno = Number(init.colno ?? 0);
3905+ this.error = init.error;
3906+ }
3907+ };
3908+}
3909+// Web API globals a real bundle references at module scope but that the
3910+// prelude doesn't provide. Stub as empty classes (guarded so we never
3911+// clobber a real prelude implementation). Enough to LOAD; runtime use of
3912+// an unimplemented one is a separate gap.
3913+for (const n of ["WebSocket", "EventTarget", "Event", "MessageEvent",
3914+ "CloseEvent", "ErrorEvent", "EventSource", "MessageChannel",
3915+ "MessagePort", "BroadcastChannel", "SubtleCrypto", "TransformStream",
3916+ "ReadableStream", "WritableStream", "ReadableStreamDefaultReader",
3917+ "WritableStreamDefaultWriter",
3918+ "ByteLengthQueuingStrategy", "CountQueuingStrategy",
3919+ "TextEncoderStream", "TextDecoderStream", "FileReader"]) {
3920+ if (!globalThis[n]) globalThis[n] = class {};
3921+}
3922+globalThis.__sockets = new Map();
3923+globalThis.WebSocket = class WebSocket extends EventTarget {
3924+ // The spec names, which workerd exposes and real bundles use. celld only
3925+ // had the READY_STATE_* aliases, which no other runtime defines.
3926+ static CONNECTING = 0;
3927+ static OPEN = 1;
3928+ static CLOSING = 2;
3929+ static CLOSED = 3;
3930+ static READY_STATE_CONNECTING = 0;
3931+ static READY_STATE_OPEN = 1;
3932+ static READY_STATE_CLOSING = 2;
3933+ static READY_STATE_CLOSED = 3;
3934+ constructor(id, protocols = []) {
3935+ super();
3936+ const outbound = typeof id === "string";
3937+ this._outbound = outbound;
3938+ this._pendingClose = null;
3939+ this._id = outbound ? __ws_alloc() : Number(id);
3940+ this._attachment = undefined;
3941+ this._target = null;
3942+ this._accepted = false;
3943+ this._hibernatable = false;
3944+ this._pending = [];
3945+ // The other end of an in-isolate upgrade (a WebSocketPair served
3946+ // over a same-script service binding); frames route to it
3947+ // directly instead of through the host connection.
3948+ this._loopback = null;
3949+ this.readyState = outbound ? 0 : 1;
3950+ this._binaryType = __cell.compat?.websocketStandardBinaryType
3951+ ? "blob"
3952+ : "arraybuffer";
3953+ // A server-side socket has no URL, and reports null rather than an empty
3954+ // string -- workerd's inspect output pins this.
3955+ this.url = outbound ? id : null;
3956+ this.protocol = "";
3957+ this.extensions = "";
3958+ if (outbound) {
3959+ // workerd validates the URL in the constructor and throws
3960+ // synchronously; letting the connector reject later would surface a
3961+ // scheme mistake as a network failure instead of a TypeError.
3962+ let parsed;
3963+ try {
3964+ parsed = new URL(id);
3965+ } catch {
3966+ throw new DOMException(
3967+ "WebSocket Constructor: The url is invalid.",
3968+ "SyntaxError");
3969+ }
3970+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
3971+ throw new DOMException(
3972+ "WebSocket Constructor: The url scheme must be ws or wss.",
3973+ "SyntaxError");
3974+ }
3975+ // A Durable Object socket is pushed events by the host so it can revive
3976+ // a hibernated cell. A Worker socket has no cell: the isolate polls it,
3977+ // and it lives and dies with the request, which is the lifetime
3978+ // Cloudflare gives one too.
3979+ const scope = __actorEventStack[__actorEventStack.length - 1] || "";
3980+ this._polled = !scope;
3981+ const requested = typeof protocols === "string"
3982+ ? [protocols]
3983+ : Array.from(protocols, String);
3984+ for (const value of requested) {
3985+ // RFC 6455 subprotocols are HTTP tokens; a space or separator would
3986+ // otherwise be smuggled into the Sec-WebSocket-Protocol header.
3987+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) {
3988+ throw new DOMException(
3989+ `WebSocket Constructor: The subprotocol '${value}' is invalid.`,
3990+ "SyntaxError");
3991+ }
3992+ }
3993+ if (new Set(requested).size !== requested.length) {
3994+ throw new DOMException(
3995+ "WebSocket Constructor: The subprotocols must be unique.",
3996+ "SyntaxError");
3997+ }
3998+ __sockets.set(this._id, this);
3999+ const connection = __ws_connect(this._id, scope, id, JSON.stringify(requested));
4000+ __registerWaitUntil(connection);
4001+ if (this._polled) this._startPump();
4002+ connection.then((protocol) => {
4003+ if (this.readyState === WebSocket.READY_STATE_CLOSING) {
4004+ if (this._pendingClose) {
4005+ const [code, reason] = this._pendingClose;
4006+ __ws_close(this._id, code, reason);
4007+ }
4008+ return;
4009+ }
4010+ if (this.readyState !== WebSocket.READY_STATE_CONNECTING) return;
4011+ this.protocol = protocol;
4012+ this.readyState = WebSocket.READY_STATE_OPEN;
4013+ this.dispatchEvent(new Event("open"));
4014+ }, (error) => {
4015+ this.readyState = WebSocket.READY_STATE_CLOSED;
4016+ __sockets.delete(this._id);
4017+ this.dispatchEvent(new ErrorEvent("error", { message: String(error?.message || error), error }));
4018+ this._dispatchClose(1006, "", false);
4019+ });
4020+ }
4021+ }
4022+ // The pump ends only when the socket closes, so it must NOT be registered
4023+ // as waitUntil work: that would hold the request open for as long as the
4024+ // socket lives, and the region can only reclaim an abandoned socket by
4025+ // exiting. Its `__ws_next` ops still belong to the region and are driven
4026+ // while the request runs, then aborted with it.
4027+ _startPump() {
4028+ if (this._pumping) return;
4029+ this._pumping = true;
4030+ this._pump().catch(() => {});
4031+ }
4032+ // Drain the host queue for an isolate-polled socket. Each `__ws_next` is an
4033+ // ordinary async op, so the request's region owns it and aborts it if the
4034+ // request ends first — the socket is closed by the region on the way out.
4035+ async _pump() {
4036+ for (;;) {
4037+ const frame = await __ws_next(this._id);
4038+ const tag = frame[0];
4039+ const body = frame.subarray(1);
4040+ if (tag === 0) {
4041+ this._dispatchMessage(new TextDecoder().decode(body));
4042+ } else if (tag === 1) {
4043+ this._dispatchMessage(
4044+ body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength),
4045+ );
4046+ } else if (tag === 2) {
4047+ if (this.readyState === WebSocket.READY_STATE_CONNECTING) {
4048+ this.protocol = new TextDecoder().decode(body);
4049+ this.readyState = WebSocket.READY_STATE_OPEN;
4050+ this.dispatchEvent(new Event("open"));
4051+ }
4052+ } else {
4053+ const info = JSON.parse(new TextDecoder().decode(body));
4054+ this._dispatchClose(info.code, info.reason, info.wasClean);
4055+ return;
4056+ }
4057+ }
4058+ }
4059+ // Deliver whatever this end queued before it had somewhere to send.
4060+ _flushToPeer() {
4061+ const peer = this._loopback;
4062+ if (!peer) return;
4063+ for (const frame of this._pending.splice(0)) {
4064+ if (frame[0] === "send") {
4065+ queueMicrotask(() => peer._dispatchMessage(frame[1]));
4066+ } else if (frame[0] === "send-binary") {
4067+ const data = frame[1];
4068+ const bytes = data instanceof ArrayBuffer
4069+ ? data
4070+ : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
4071+ queueMicrotask(() => peer._dispatchMessage(bytes));
4072+ } else {
4073+ queueMicrotask(() => peer._dispatchClose(frame[1], frame[2], true));
4074+ }
4075+ }
4076+ }
4077+ get binaryType() { return this._binaryType; }
4078+ // The spec ignores an unrecognised value rather than throwing.
4079+ set binaryType(value) {
4080+ if (value === "blob" || value === "arraybuffer") this._binaryType = value;
4081+ }
4082+ accept() {
4083+ this._accepted = true;
4084+ // A pair used directly, without being returned through a 101 response,
4085+ // still has to carry frames once both ends are accepted. celld only
4086+ // linked a pair on the upgrade path, so such a pair queued forever.
4087+ if (this._peer && this._peer._accepted && !this._loopback) {
4088+ this._loopback = this._peer;
4089+ this._peer._loopback = this;
4090+ this._flushToPeer();
4091+ this._peer._flushToPeer();
4092+ }
4093+ // A socket obtained from a `fetch()` upgrade is already connected and
4094+ // delivers nothing until it is accepted; this is where it starts.
4095+ if (this._outbound && this.readyState === WebSocket.READY_STATE_CONNECTING) {
4096+ this.readyState = WebSocket.READY_STATE_OPEN;
4097+ if (this._polled) this._startPump();
4098+ }
4099+ }
4100+ send(data) {
4101+ if (this.readyState !== WebSocket.READY_STATE_OPEN)
4102+ throw new DOMException("WebSocket is not open", "InvalidStateError");
4103+ const binary = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
4104+ const text = binary ? null : String(data);
4105+ if (this._loopback) {
4106+ const peer = this._loopback;
4107+ const message = binary
4108+ ? (data instanceof ArrayBuffer ? data.slice(0) : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength))
4109+ : text;
4110+ queueMicrotask(() => peer._dispatchMessage(message));
4111+ return;
4112+ }
4113+ // The pending queue belongs to an inbound pair socket that has been
4114+ // accepted but not yet bound to a host transport. An outbound socket is
4115+ // already bound -- queueing here would silently swallow its frames.
4116+ if (!this._outbound && this._accepted && !this._target) {
4117+ this._pending.push([binary ? "send-binary" : "send", binary ? data : text]);
4118+ return;
4119+ }
4120+ if (binary) {
4121+ const bytes = data instanceof ArrayBuffer
4122+ ? new Uint8Array(data)
4123+ : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
4124+ __ws_send_binary(this._id, bytes);
4125+ } else {
4126+ __ws_send(this._id, text);
4127+ }
4128+ }
4129+ close(code = 1000, reason = "") {
4130+ // WHATWG: an application may send 1000 or 3000-4999. Everything else is
4131+ // reserved for the protocol itself.
4132+ const wanted = Number(code);
4133+ if (wanted !== 1000 && !(wanted >= 3000 && wanted <= 4999)) {
4134+ throw new DOMException(
4135+ `WebSocket close code ${code} is not permitted`,
4136+ "InvalidAccessError");
4137+ }
4138+ // RFC 6455 5.5: the close frame body is at most 125 bytes, two of which
4139+ // are the code. Measured in UTF-8, so a multibyte reason can exceed the
4140+ // cap at well under 123 characters.
4141+ if (new TextEncoder().encode(String(reason)).length > 123) {
4142+ throw new DOMException(
4143+ "WebSocket close reason must not exceed 123 bytes",
4144+ "SyntaxError");
4145+ }
4146+ // Outbound sockets follow the WebSocket spec: closing a closed socket is a
4147+ // no-op. Inbound sockets must NOT take that shortcut -- a Durable Object
4148+ // answers a peer-initiated close from inside `webSocketClose`, by which
4149+ // point `_dispatchClose` has already marked this side closed, and its
4150+ // reply carries the reason the client is entitled to see.
4151+ if (this._outbound && this.readyState === WebSocket.READY_STATE_CLOSED) {
4152+ return;
4153+ }
4154+ const connecting = this.readyState === WebSocket.READY_STATE_CONNECTING;
4155+ this.readyState = WebSocket.READY_STATE_CLOSING;
4156+ if (this._outbound && connecting) {
4157+ this._pendingClose = [code, reason];
4158+ return;
4159+ }
4160+ if (this._outbound) {
4161+ __ws_close(this._id, code, reason);
4162+ return;
4163+ }
4164+ this.readyState = 3;
4165+ if (this._loopback) {
4166+ const peer = this._loopback;
4167+ queueMicrotask(() => peer._dispatchClose(code, reason, true));
4168+ return;
4169+ }
4170+ if (this._accepted && !this._target) {
4171+ this._pending.push(["close", code, reason]);
4172+ return;
4173+ }
4174+ __ws_close(this._id, code, reason);
4175+ }
4176+ _flushPending() {
4177+ const pending = this._pending.splice(0);
4178+ for (const frame of pending) {
4179+ if (frame[0] === "send") __ws_send(this._id, frame[1]);
4180+ else if (frame[0] === "send-binary") {
4181+ const data = frame[1];
4182+ const bytes = data instanceof ArrayBuffer
4183+ ? new Uint8Array(data)
4184+ : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
4185+ __ws_send_binary(this._id, bytes);
4186+ }
4187+ else __ws_close(this._id, frame[1], frame[2]);
4188+ }
4189+ }
4190+ serializeAttachment(value) {
4191+ this._attachment = value;
4192+ __ws_attachment_set(this._id, JSON.stringify(value));
4193+ }
4194+ deserializeAttachment() { return this._attachment; }
4195+ _dispatchMessage(data) {
4196+ if (this._binaryType === "blob" && data instanceof ArrayBuffer) {
4197+ data = new Blob([data]);
4198+ }
4199+ const event = new MessageEvent("message", { data });
4200+ event._trust();
4201+ this.dispatchEvent(event);
4202+ }
4203+ _dispatchClose(code, reason, wasClean) {
4204+ if (this.readyState === WebSocket.READY_STATE_CLOSED) return;
4205+ this.readyState = WebSocket.READY_STATE_CLOSED;
4206+ __sockets.delete(this._id);
4207+ // An abnormal closure fires `error` before `close`. Code written against
4208+ // the standard onerror never ran otherwise, which matters most for an
4209+ // outbound socket: its peer is a remote server that can simply vanish.
4210+ // An abnormal closure fires `error` before `close`. Code written against
4211+ // the standard onerror never ran otherwise, which matters most for an
4212+ // outbound socket: its peer is a remote server that can simply vanish.
4213+ // An abnormal closure fires `error` before `close`. Code written against
4214+ // the standard onerror never ran otherwise, which matters most for an
4215+ // outbound socket: its peer is a remote server that can simply vanish.
4216+ if (!wasClean) {
4217+ this.dispatchEvent(new ErrorEvent("error", {
4218+ message: reason
4219+ ? `WebSocket closed abnormally: ${reason}`
4220+ : "WebSocket closed abnormally",
4221+ }));
4222+ }
4223+ const event = new CloseEvent("close", { code, reason, wasClean });
4224+ event._trust();
4225+ this.dispatchEvent(event);
4226+ }
4227+};
4228+globalThis.__makeSocket = (id) => new WebSocket(id);
4229+globalThis.__socketFromRow = (row) => {
4230+ let ws = __sockets.get(Number(row.id));
4231+ if (!ws) {
4232+ ws = __makeSocket(row.id);
4233+ __sockets.set(Number(row.id), ws);
4234+ }
4235+ ws._tags = row.tags || [];
4236+ ws._hibernatable = true;
4237+ if (row.attachment != null) {
4238+ try { ws._attachment = JSON.parse(row.attachment); } catch { ws._attachment = undefined; }
4239+ }
4240+ return ws;
4241+};
4242+globalThis.WebSocketPair = function WebSocketPair() {
4243+ const id = __ws_alloc();
4244+ const client = __makeSocket(id);
4245+ const server = __makeSocket(id);
4246+ client._peer = server;
4247+ server._peer = client;
4248+ // Indexed AND iterable: `const [client, server] = new WebSocketPair()` is
4249+ // the form most Cloudflare code uses.
4250+ return {
4251+ 0: client,
4252+ 1: server,
4253+ length: 2,
4254+ [Symbol.iterator]() {
4255+ return [client, server][Symbol.iterator]();
4256+ },
4257+ };
4258+};
4259+if (!globalThis.performance)
4260+ globalThis.performance = { now: () => Date.now(), timeOrigin: 0, mark() {}, measure() {} };
4261+if (!globalThis.navigator) globalThis.navigator = {
4262+ userAgent: "Cloudflare-Workers", hardwareConcurrency: 1,
4263+ language: "en", languages: ["en"],
4264+};
4265+if (!globalThis.queueMicrotask)
4266+ globalThis.queueMicrotask = (f) => Promise.resolve().then(f);
4267+if (!globalThis.scheduler)
4268+ globalThis.scheduler = {
4269+ wait: (ms) => new Promise((resolve) => setTimeout(resolve, Number(ms) || 0)),
4270+ };
4271+if (!globalThis.structuredClone) {
4272+ globalThis.structuredClone = (value, options) => {
4273+ const seen = new Map();
4274+ const clone = (input) => {
4275+ if (input === null || typeof input !== "object") return input;
4276+ if (seen.has(input)) return seen.get(input);
4277+ if (input instanceof Date) return new Date(input.getTime());
4278+ if (input instanceof ArrayBuffer) return input.slice(0);
4279+ if (ArrayBuffer.isView(input))
4280+ return new input.constructor(input.buffer.slice(
4281+ input.byteOffset, input.byteOffset + input.byteLength,
4282+ ));
4283+ if (input instanceof Map) {
4284+ const out = new Map(); seen.set(input, out);
4285+ for (const [k, v] of input) out.set(clone(k), clone(v));
4286+ return out;
4287+ }
4288+ if (input instanceof Set) {
4289+ const out = new Set(); seen.set(input, out);
4290+ for (const v of input) out.add(clone(v));
4291+ return out;
4292+ }
4293+ const out = Array.isArray(input) ? [] : Object.create(Object.getPrototypeOf(input));
4294+ seen.set(input, out);
4295+ for (const key of Reflect.ownKeys(input)) out[key] = clone(input[key]);
4296+ return out;
4297+ };
4298+ const result = clone(value);
4299+ // Transfer semantics: the source buffer is detached. The clone
4300+ // above already copied its bytes, which is what the spec's
4301+ // "transferred" clone observes.
4302+ for (const item of (options && options.transfer) || []) {
4303+ if (item instanceof ArrayBuffer) item.transfer();
4304+ }
4305+ return result;
4306+ };
4307+}
4308+// Web Crypto is installed after the rest of the harness so it can use
4309+// DOMException, structuredClone, and Buffer.
4310+// `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+)));
4315+globalThis.__zlibModule = {
4316+ constants: {
4317+ Z_NO_FLUSH: 0,
4318+ Z_PARTIAL_FLUSH: 1,
4319+ Z_SYNC_FLUSH: 2,
4320+ Z_FULL_FLUSH: 3,
4321+ Z_FINISH: 4,
4322+ Z_BLOCK: 5,
4323+ },
4324+ gzipSync: (data, _options) => __zlibSync("gzip", data),
4325+ gunzipSync: (data, _options) => __zlibSync("gunzip", data),
4326+ deflateSync: (data, _options) => __zlibSync("deflate", data),
4327+ inflateSync: (data, _options) => __zlibSync("inflate", data),
4328+ deflateRawSync: (data, _options) => __zlibSync("deflateRaw", data),
4329+ inflateRawSync: (data, _options) => __zlibSync("inflateRaw", data),
4330+};
4331+if (!globalThis.process) globalThis.process = {
4332+ env: {}, platform: "linux", arch: "x64", version: "v20.0.0",
4333+ versions: { node: "20.0.0" }, argv: [], cwd: () => "/",
4334+ stdin: { fd: 0, isTTY: false },
4335+ stdout: { fd: 1, isTTY: false, write: (s) => { __log(String(s)); return true; } },
4336+ stderr: { fd: 2, isTTY: false, write: (s) => { __log(String(s)); return true; } },
4337+ nextTick: (f, ...a) => queueMicrotask(() => f(...a)),
4338+ on() {}, once() {}, off() {}, emit() {}, hrtime: () => [0, 0],
4339+};
4340+globalThis.process.exit = (code = 0) => {
4341+ const actorScope = __actorEventStack[__actorEventStack.length - 1] || "";
4342+ if (actorScope) {
4343+ const instance = __cell.instances[actorScope];
4344+ if (instance?.__celldState)
4345+ instance.__celldState._resetAfterConcurrencyFailure();
4346+ }
4347+ __process_exit(Number(code) || 0, actorScope);
4348+};
4349+globalThis.process.getBuiltinModule =
4350+ (id) => __builtin_module(String(id));
4351+if (!globalThis.global) globalThis.global = globalThis;
4352+const __eventStack = [];
4353+globalThis.__registerWaitUntil = (promise) => {
4354+ const event = __eventStack[__eventStack.length - 1];
4355+ const tracked = Promise.resolve(promise).catch((error) => {
4356+ console.error("waitUntil rejected", error);
4357+ });
4358+ if (event) event.waitUntil.push(tracked);
4359+};
4360+// `props` are the per-stub props a loopback service stub carries
4361+// (ctx.props); `exports` is built once, on first access.
4362+const __defaultProps = {};
4363+globalThis.__beginEvent = (props = __defaultProps) => {
4364+ const event = { waitUntil: [] };
4365+ __eventStack.push(event);
4366+ return {
4367+ waitUntil: globalThis.__registerWaitUntil,
4368+ passThroughOnException() {},
4369+ abort: __ctxAbortCurrent,
4370+ props,
4371+ get exports() { return __ctxExports(); },
4372+ };
4373+};
4374+globalThis.__endEvent = () => {
4375+ const event = __eventStack.pop();
4376+ if (!event || event.waitUntil.length === 0) return null;
4377+ return Promise.allSettled(event.waitUntil);
4378+};
4379+// fs stub that behaves like a no-filesystem env: reads throw ENOENT and
4380+// existsSync is false, so the common `try { readFileSync } catch (ENOENT)`
4381+// fallbacks in real deps (e.g. pi-agent config) take their default path.
4382+const __enoent = () => { const e = new Error("ENOENT: no filesystem"); e.code = "ENOENT"; throw e; };
4383+globalThis.__fs = new Proxy({}, { get: (_t, p) => {
4384+ if (p === "existsSync") return () => false;
4385+ if (["readFileSync", "readdirSync", "statSync", "lstatSync", "realpathSync", "readlinkSync"].includes(p)) return __enoent;
4386+ return globalThis.__nodeStub;
4387+}});
4388+const __bridgeResponseStream = (body, requestControllers) => {
4389+ const streamId = __response_stream_create();
4390+ const pump = (async () => {
4391+ const reader = body.getReader();
4392+ const consumerClosed = __response_stream_closed(streamId)
4393+ .then((status) => status === "cancelled"
4394+ ? { consumerClosed: true }
4395+ : new Promise(() => {}));
4396+ const cancelProducer = async () => {
4397+ const reason = new Error("The client has disconnected");
4398+ for (const controller of requestControllers || []) {
4399+ if (!controller.signal.aborted) controller.abort(reason);
4400+ }
4401+ try {
4402+ await reader.cancel(reason);
4403+ } catch {}
4404+ await __response_stream_close(streamId, "");
4405+ };
4406+ try {
4407+ for (;;) {
4408+ const result = await Promise.race([
4409+ reader.read().then((read) => ({ read })),
4410+ consumerClosed,
4411+ ]);
4412+ if (result.consumerClosed) {
4413+ await cancelProducer();
4414+ return;
4415+ }
4416+ if (result.read.done) {
4417+ await __response_stream_close(streamId, "");
4418+ return;
4419+ }
4420+ const bytes = __bodyBytes(result.read.value);
4421+ for (let offset = 0; offset < bytes.byteLength; offset += 64 * 1024) {
4422+ await __response_stream_write(
4423+ streamId,
4424+ bytes.subarray(offset, offset + 64 * 1024),
4425+ );
4426+ }
4427+ }
4428+ } catch (error) {
4429+ if (String(error).includes("response stream consumer canceled")) {
4430+ await cancelProducer();
4431+ return;
4432+ }
4433+ await __response_stream_close(streamId, String(error));
4434+ }
4435+ })();
4436+ globalThis.__registerWaitUntil(pump);
4437+ return streamId;
4438+};
4439+globalThis.__readResponse = (r) => {
4440+ if (!(r instanceof Response)) {
4441+ return {
4442+ status: 200,
4443+ bodyBytes: new TextEncoder().encode(String(r)),
4444+ bodyStreamId: 0,
4445+ headersJson: "[]",
4446+ wsTargetJson: "null",
4447+ };
4448+ }
4449+ const bodyStreamId = r._bodyBytes === null
4450+ ? typeof r.body?.__celldStreamId === "number" &&
4451+ !r.__celldRequestControllers
4452+ ? r.body.__celldStreamId
4453+ : __bridgeResponseStream(
4454+ r.body,
4455+ r.__celldRequestControllers,
4456+ )
4457+ : 0;
4458+ if (bodyStreamId) {
4459+ return {
4460+ status: r.status,
4461+ bodyBytes: new Uint8Array(),
4462+ bodyStreamId,
4463+ headersJson: JSON.stringify(Array.from(r.headers)),
4464+ wsTargetJson: JSON.stringify(
4465+ r._wsTarget || (r.webSocket && r.webSocket._target) || null,
4466+ ),
4467+ };
4468+ }
4469+ const bytes = r._bodyBytes;
4470+ return {
4471+ status: r.status,
4472+ bodyBytes: bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes),
4473+ bodyStreamId: 0,
4474+ headersJson: JSON.stringify(Array.from(r.headers)),
4475+ wsTargetJson: JSON.stringify(
4476+ r._wsTarget || (r.webSocket && r.webSocket._target) || null,
4477+ ),
4478+ };
4479+};
addedcrates/celld/js/headers.js+164−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/identity_transform_stream.js+426−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_assert.js+302−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_async_hooks.js+148−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_buffer.js+774−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_crypto.js+1346−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_events.js+609−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_path.js+1108−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_stream.js+5520−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_test.js+86−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_timers.js+50−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_util.js+4633−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/set_immediate.js+16−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/streams.js+853−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/text_encoding.js+444−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/text_encoding_streams.js+54−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/url.js+288−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/url_pattern.js+105−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/url_search_params.js+257−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/writable_stream.js+716−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/lib.rs+137−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/ltx_repl.rs+516−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/main.rs+5329−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/ownership_store.rs+498−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/peer_auth.rs+384−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/peer_probe.rs+233−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/protocol.rs+166−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/replication.rs+1166−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/runtime.rs+1426−0View file
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/assets.rs+0−1243
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/asyncrt.rs+0−97
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/control_plane.rs+0−2945
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/deploy.rs+0−1094
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/fault.rs+0−315
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js.rs+0−7731
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/atob_btoa.js+0−42
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/byte_streams.js+0−693
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/compression_streams.js+0−73
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/crypto.js+0−317
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/harness.js+0−4462
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/headers.js+0−164
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/identity_transform_stream.js+0−426
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_assert.js+0−302
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_async_hooks.js+0−148
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_buffer.js+0−774
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_crypto.js+0−1346
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_events.js+0−609
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_path.js+0−1108
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_stream.js+0−5520
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_test.js+0−86
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_timers.js+0−50
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/node_util.js+0−4633
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/set_immediate.js+0−16
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/streams.js+0−853
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/text_encoding.js+0−444
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/text_encoding_streams.js+0−54
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/url.js+0−288
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/url_pattern.js+0−105
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/url_search_params.js+0−257
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/js/writable_stream.js+0−716
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/lib.rs+0−6296
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/main.rs+0−5
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/ownership.rs+0−1486
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/peer_auth.rs+0−385
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/peer_probe.rs+0−237
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/protocol.rs+0−166
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/replication.rs+0−1122
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/startup.rs+0−996
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/storage.rs+0−2602
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/src/wake.rs+0−230
Diff not rendered to keep this page fast. View the file
addedcrates/celld/startup.rs+302−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/storage.rs+2383−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/wake.rs+288−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/Cargo.toml+8−9View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/alarm.rs+44−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/cache.rs+47−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/dead_node_reconciliation.rs+43−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/lib.rs+4081−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/peer.rs+35−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/pressure.rs+163−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/restore.rs+37−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/routing.rs+90−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/schedule.rs+55−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/sqlite.rs+52−0View file
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/alarm.rs+0−44
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/cache.rs+0−47
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/cell.rs+0−67
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/dead_node_reconciliation.rs+0−36
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/evict.rs+0−247
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/lease.rs+0−172
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/lib.rs+0−120
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/lifecycle.rs+0−437
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/peer.rs+0−36
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/pressure.rs+0−167
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/restore.rs+0−38
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/routing.rs+0−90
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/schedule.rs+0−31
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/sqlite.rs+0−53
Diff not rendered to keep this page fast. View the file
deletedcrates/logic/src/wake.rs+0−344
Diff not rendered to keep this page fast. View the file
addedcrates/logic/wake.rs+413−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/Cargo.toml+47−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/LICENSE+202−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/README.md+37−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/reference/litestream-go/testdata/db/enforce-retention/database+0−0View file
Binary file not shown.
addedcrates/ltx/reference/litestream-go/testdata/db/write-snapshot-to/database+0−0View file
Binary file not shown.
addedcrates/ltx/reference/litestream-go/testdata/wal-reader/frame-checksum-mismatch/wal+0−0View file
Binary file not shown.
addedcrates/ltx/reference/litestream-go/testdata/wal-reader/frame-salts/wal+0−0View file
Binary file not shown.
addedcrates/ltx/reference/litestream-go/testdata/wal-reader/ok/wal+0−0View file
Binary file not shown.
addedcrates/ltx/reference/litestream-go/testdata/wal-reader/salt-mismatch/wal+0−0View file
Binary file not shown.
addedcrates/ltx/reference/ltx-format.md+84−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/scripts/capture-golden.sh+74−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/scripts/db_equal.sh+72−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/scripts/guards.sh+42−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/client/file.rs+219−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/client/mod.rs+195−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/client/object_store.rs+1291−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/db.rs+2032−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/error.rs+353−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/leaser.rs+1665−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/lib.rs+533−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/ltx.rs+909−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/replica.rs+1106−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/replica_url.rs+719−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/store.rs+263−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/wal.rs+939−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/conformance.rs+1−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/differential_xtool.rs+454−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/faults_inject.rs+448−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/fixtures/golden/.gitkeep+1−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/fixtures/golden/MANIFEST.md+39−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000001-0000000000000001.ltx+0−0View file
Binary file not shown.
addedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000002-0000000000000002.ltx+0−0View file
Binary file not shown.
addedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000003-0000000000000003.ltx+0−0View file
Binary file not shown.
addedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000004-0000000000000004.ltx+0−0View file
Binary file not shown.
addedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000005-0000000000000005.ltx+0−0View file
Binary file not shown.
addedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000006-0000000000000006.ltx+0−0View file
Binary file not shown.
addedcrates/ltx/tests/fixtures/golden/sample.wal+0−0View file
Binary file not shown.
addedcrates/ltx/tests/fuzz_parsers.rs+536−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/integration_file.rs+282−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/integration_minio.rs+287−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/integration_resilience.rs+349−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/litestream_helpers.rs+560−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/property_roundtrip.rs+243−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/README.md+154−149View file
Diff not rendered to keep this page fast. View the file
modifieddocs/cloudflare-compat.md+139−52View file
Diff not rendered to keep this page fast. View the file
modifieddocs/limitations.md+22−23View file
Diff not rendered to keep this page fast. View the file
modifieddocs/security.md+1−1View file
Diff not rendered to keep this page fast. View the file
addeddocs/simulations.md+93−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/support.md+31−28View file
Diff not rendered to keep this page fast. View the file