v0.4.1
You can do a rolling upgrade from v0.4.0. Highlights: - **Balance cell ownership across the fleet.** A node that joins takes hibernated cells from the nodes that hold the most, so it carries its share within minutes instead of waiting for new traffic. The fleet evens out again after a node leaves. One node samples the leases for the whole fleet, so the cost does not grow with the square of the fleet. - **Restore a large cell page by page.** The cell reads each page from the object store on first use, so it serves requests before the download completes. A large cell also hands off through its LTX chain instead of a whole-database snapshot. - **Queue throughput improves by an order of magnitude.** Producer calls share transactions and durability rounds, and each message gets a time-ordered id. One Queue sustained 7,357 sends per second over a 300,000-send soak with exact delivery, up from a few hundred. - **Fewer false durability timeouts under load.** The budget measures a stall: a queued write waits while the node keeps landing proofs. A follower commits a burst of frames as one fsync chain, and CRC64 verification uses SIMD. - **Alarms scale to the due work.** The waker lists one bucket per armed minute and opens only the due ones. Only the elected waker probes the fleet, and the activation bound derives from store latency, so alarms of evicted cells fire on time under load. - **Recover from a whole-fleet restart.** A restarting node serves follower fragments while it recovers its own predecessor, so nodes that restart together recover acknowledged writes. Recovery checkpoints its progress and holds a heartbeat, so a retry skips finished work and peers do not repeat it. - **Durable Object facets.** `ctx.facets` provides `get()`, `abort()`, and `delete()`. Each facet gets an isolated SQLite database that celld replicates with the root object. - **More Node.js and web platform APIs.** `node:fs`, `node:os`, `node:diagnostics_channel`, a read-only `/bundle`, and a per-request `/tmp`. `HTMLRewriter`, `EventSource`, `MessageChannel`, the `Cache` API surface, outbound TCP through `cloudflare:sockets`, and Web Crypto KDF derivation, key wrapping, and RSA signing. - **A tighter output gate.** An error answer, each chunk of a streaming body, a call into a loaded Worker, and the answer of a handler that fails after it commits all wait for the proof of the writes they depend on. `storage.sync()` returns after the cell's writes are proven durable, and a rollback discards writes submitted without `await`. - **A lease reports why it lost authority.** A self-fence names its cause, and a failed renewal retries before the authority expires. - **Operator commands page.** A cell listing and a KV bulk export no longer load a namespace into memory. A lease records store outcomes and owned cell count, so `celld diagnose` shows each node's load. `celld dev --clean` discards the local state. Issues fixed: - #176 - #178 - #179 - #180 - #182 - #183 - #184 - #185 - #186 Co-authored-by: Bartek Iwańczuk <[email protected]> Co-authored-by: Bert Belder <[email protected]> Co-authored-by: Daniel Acuna <[email protected]> Co-authored-by: Daniel Levi-Minzi <[email protected]> Co-authored-by: Josh Collinsworth <[email protected]> Co-authored-by: Nathan Whitaker <[email protected]> Co-authored-by: Yusuke Tanaka <[email protected]>
Ryan Dahl authored signed1 parent a52f990commit 10cb1303dac710dcb3b557e318e08c855261f68bBrowse files
106 files changed+89817−57368
Files (106)
- Cargo.lock+264−5
- Cargo.toml+23−11
- README.md+52−6
- crates/celld/Cargo.toml+5−2
- crates/celld/actor.rs+478−102
- crates/celld/assets.rs+10−1
- crates/celld/asyncrt.rs+168−18
- crates/celld/bucket.rs+278−36
- crates/celld/cell_cli.rs+10−1
- crates/celld/cli_options.rs+9−13
- crates/celld/control_plane.rs+9−7
- crates/celld/d1_cli.rs+15−10
- crates/celld/dead_node_gc.rs+60−10
- crates/celld/deploy.rs+67−7
- crates/celld/dev.rs+224−33
- crates/celld/drain_token.rs+47−5
- crates/celld/env_vars.rs+61−2
- crates/celld/fleet.rs+70−43
- crates/celld/host_services.rs+44−0
- crates/celld/js.rs+12949−9018
- crates/celld/js/bootstrap.rs+55−2
- crates/celld/js/cache.js+105−0
- crates/celld/js/crypto.js+252−60
- crates/celld/js/crypto.rs+264−94
- crates/celld/js/event_source.js+289−0
- crates/celld/js/harness.js+10834−9522
- crates/celld/js/html_rewriter.js+498−0
- crates/celld/js/html_rewriter.rs+687−0
- crates/celld/js/input_gate_lifecycle.rs+256−0
- crates/celld/js/message_channel.js+111−0
- crates/celld/js/modules.rs+33−7
- crates/celld/js/node_crypto.js+11−14
- crates/celld/js/node_diagnostics_channel.js+242−0
- crates/celld/js/node_os.js+248−0
- crates/celld/js/r2_ops.rs+4−2
- crates/celld/js/sockets.js+231−0
- crates/celld/js/storage_ops.rs+841−560
- crates/celld/js/tcp.rs+289−0
- crates/celld/js/websocket.rs+1266−926
- crates/celld/kv_cli.rs+531−451
- crates/celld/lib.rs+10−6
- crates/celld/ltx_repl.rs+4134−3320
- crates/celld/machine.rs+178−125
- crates/celld/main.rs+5540−4729
- crates/celld/main/cli.rs+382−369
- crates/celld/main/peer_tunnel.rs+462−408
- crates/celld/main/websocket.rs+1054−921
- crates/celld/node_log.rs+5943−4869
- crates/celld/node_log/recovery_progress.rs+150−0
- crates/celld/ownership_store.rs+1162−581
- crates/celld/peer_auth.rs+239−246
- crates/celld/pool.rs+750−624
- crates/celld/protocol.rs+40−7
- crates/celld/replication.rs+6−0
- crates/celld/runtime.rs+3988−3431
- crates/celld/startup.rs+3−12
- crates/celld/storage.rs+4209−3700
- crates/celld/telemetry.rs+943−726
- crates/celld/wake.rs+159−51
- crates/logic/drain.rs+123−100
- crates/logic/durability.rs+76−0
- crates/logic/format.rs+40−0
- crates/logic/gate.rs+105−105
- crates/logic/isolate.rs+22−0
- crates/logic/lib.rs+6445−5486
- crates/logic/log_tier.rs+213−150
- crates/logic/output_gate.rs+335−222
- crates/logic/peer.rs+8−6
- crates/logic/rebalance.rs+163−0
- crates/logic/schedule.rs+27−14
- crates/logic/types.rs+1054−881
- crates/logic/wake.rs+471−437
- crates/ltx/Cargo.toml+4−0
- crates/ltx/README.md+4−1
- crates/ltx/src/bundle.rs+115−109
- crates/ltx/src/client/epochs.rs+176−0
- crates/ltx/src/client/mod.rs+56−32
- crates/ltx/src/client/object_store.rs+1251−861
- crates/ltx/src/codec.rs+74−13
- crates/ltx/src/db.rs+2325−2076
- crates/ltx/src/error.rs+3−0
- crates/ltx/src/lib.rs+2−0
- crates/ltx/src/ltx.rs+27−47
- crates/ltx/src/paged.rs+546−0
- crates/ltx/src/paged_vfs.rs+681−0
- crates/ltx/src/replica_compactor.rs+72−61
- crates/ltx/src/replica_url.rs+294−295
- docs/README.md+924−694
- docs/cloudflare-compat.md+493−330
- docs/guarantees.md+277−212
- docs/library-api.md+0−60
- docs/limitations.md+4−2
- docs/telemetry.md+81−61
- docs/wasm.md+1−1
- examples/README.md+21−19
- examples/opencode/README.md+35−0
- examples/opencode/index.js+144−0
- examples/opencode/package-lock.json+8679−0
- examples/opencode/package.json+10−0
- examples/opencode/wrangler.jsonc+10−0
- examples/pi/.gitignore+1−0
- examples/pi/README.md+43−0
- examples/pi/index.js+94−0
- examples/pi/package-lock.json+3011−0
- examples/pi/package.json+11−0
- examples/pi/wrangler.jsonc+24−0
modifiedCargo.lock+264−5View file
| @@ -67,6 +67,12 @@ | ||
| 67 | 67 | ] |
| 68 | 68 | |
| 69 | 69 | [[package]] |
| 70 | +name = "allocator-api2" | |
| 71 | +version = "0.2.21" | |
| 72 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 73 | +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" | |
| 74 | + | |
| 75 | +[[package]] | |
| 70 | 76 | name = "android_system_properties" |
| 71 | 77 | version = "0.1.6" |
| 72 | 78 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -179,6 +185,12 @@ | ||
| 179 | 185 | checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" |
| 180 | 186 | |
| 181 | 187 | [[package]] |
| 188 | +name = "base64" | |
| 189 | +version = "0.23.1" | |
| 190 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 191 | +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" | |
| 192 | + | |
| 193 | +[[package]] | |
| 182 | 194 | name = "base64ct" |
| 183 | 195 | version = "1.8.3" |
| 184 | 196 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -273,7 +285,7 @@ | ||
| 273 | 285 | |
| 274 | 286 | [[package]] |
| 275 | 287 | name = "celld" |
| 276 | -version = "0.4.0" | |
| 288 | +version = "0.4.1" | |
| 277 | 289 | dependencies = [ |
| 278 | 290 | "aes", |
| 279 | 291 | "aes-gcm", |
| @@ -295,12 +307,15 @@ | ||
| 295 | 307 | "flate2", |
| 296 | 308 | "futures-util", |
| 297 | 309 | "getrandom 0.3.4", |
| 310 | + "glob", | |
| 298 | 311 | "hkdf", |
| 299 | 312 | "hmac", |
| 300 | 313 | "http-body-util", |
| 314 | + "httpdate", | |
| 301 | 315 | "hyper", |
| 302 | 316 | "hyper-util", |
| 303 | 317 | "libc", |
| 318 | + "lol_html", | |
| 304 | 319 | "lz4_flex", |
| 305 | 320 | "md-5", |
| 306 | 321 | "nix", |
| @@ -354,13 +369,17 @@ | ||
| 354 | 369 | "async-trait", |
| 355 | 370 | "bytes", |
| 356 | 371 | "chrono", |
| 372 | + "crc-fast", | |
| 357 | 373 | "futures-util", |
| 374 | + "http", | |
| 358 | 375 | "lz4_flex", |
| 359 | 376 | "object_store", |
| 377 | + "percent-encoding", | |
| 360 | 378 | "rusqlite", |
| 361 | 379 | "thiserror 2.0.19", |
| 362 | 380 | "tokio", |
| 363 | 381 | "tracing", |
| 382 | + "ureq", | |
| 364 | 383 | ] |
| 365 | 384 | |
| 366 | 385 | [[package]] |
| @@ -513,6 +532,16 @@ | ||
| 513 | 532 | checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" |
| 514 | 533 | |
| 515 | 534 | [[package]] |
| 535 | +name = "crc-fast" | |
| 536 | +version = "1.10.0" | |
| 537 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 538 | +checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5" | |
| 539 | +dependencies = [ | |
| 540 | + "digest", | |
| 541 | + "spin 0.10.1", | |
| 542 | +] | |
| 543 | + | |
| 544 | +[[package]] | |
| 516 | 545 | name = "crc32fast" |
| 517 | 546 | version = "1.5.0" |
| 518 | 547 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -566,6 +595,29 @@ | ||
| 566 | 595 | ] |
| 567 | 596 | |
| 568 | 597 | [[package]] |
| 598 | +name = "cssparser" | |
| 599 | +version = "0.36.0" | |
| 600 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 601 | +checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2" | |
| 602 | +dependencies = [ | |
| 603 | + "cssparser-macros", | |
| 604 | + "dtoa-short", | |
| 605 | + "itoa", | |
| 606 | + "phf", | |
| 607 | + "smallvec", | |
| 608 | +] | |
| 609 | + | |
| 610 | +[[package]] | |
| 611 | +name = "cssparser-macros" | |
| 612 | +version = "0.6.1" | |
| 613 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 614 | +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" | |
| 615 | +dependencies = [ | |
| 616 | + "quote", | |
| 617 | + "syn 2.0.119", | |
| 618 | +] | |
| 619 | + | |
| 620 | +[[package]] | |
| 569 | 621 | name = "ctr" |
| 570 | 622 | version = "0.9.2" |
| 571 | 623 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -619,6 +671,27 @@ | ||
| 619 | 671 | checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" |
| 620 | 672 | |
| 621 | 673 | [[package]] |
| 674 | +name = "derive_more" | |
| 675 | +version = "2.1.1" | |
| 676 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 677 | +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" | |
| 678 | +dependencies = [ | |
| 679 | + "derive_more-impl", | |
| 680 | +] | |
| 681 | + | |
| 682 | +[[package]] | |
| 683 | +name = "derive_more-impl" | |
| 684 | +version = "2.1.1" | |
| 685 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 686 | +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" | |
| 687 | +dependencies = [ | |
| 688 | + "proc-macro2", | |
| 689 | + "quote", | |
| 690 | + "rustc_version", | |
| 691 | + "syn 2.0.119", | |
| 692 | +] | |
| 693 | + | |
| 694 | +[[package]] | |
| 622 | 695 | name = "digest" |
| 623 | 696 | version = "0.10.7" |
| 624 | 697 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -690,6 +763,21 @@ | ||
| 690 | 763 | ] |
| 691 | 764 | |
| 692 | 765 | [[package]] |
| 766 | +name = "dtoa" | |
| 767 | +version = "1.0.11" | |
| 768 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 769 | +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" | |
| 770 | + | |
| 771 | +[[package]] | |
| 772 | +name = "dtoa-short" | |
| 773 | +version = "0.3.5" | |
| 774 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 775 | +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" | |
| 776 | +dependencies = [ | |
| 777 | + "dtoa", | |
| 778 | +] | |
| 779 | + | |
| 780 | +[[package]] | |
| 693 | 781 | name = "ecdsa" |
| 694 | 782 | version = "0.16.9" |
| 695 | 783 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -858,6 +946,12 @@ | ||
| 858 | 946 | checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" |
| 859 | 947 | |
| 860 | 948 | [[package]] |
| 949 | +name = "foldhash" | |
| 950 | +version = "0.2.0" | |
| 951 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 952 | +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" | |
| 953 | + | |
| 954 | +[[package]] | |
| 861 | 955 | name = "form_urlencoded" |
| 862 | 956 | version = "1.2.2" |
| 863 | 957 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -1061,9 +1155,9 @@ | ||
| 1061 | 1155 | |
| 1062 | 1156 | [[package]] |
| 1063 | 1157 | name = "h2" |
| 1064 | -version = "0.4.15" | |
| 1158 | +version = "0.4.18" | |
| 1065 | 1159 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1066 | -checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" | |
| 1160 | +checksum = "839c0e8a181239723652be9062bb56ca5bf5f64011f73b623f6f4fc59086a228" | |
| 1067 | 1161 | dependencies = [ |
| 1068 | 1162 | "atomic-waker", |
| 1069 | 1163 | "bytes", |
| @@ -1104,6 +1198,11 @@ | ||
| 1104 | 1198 | version = "0.17.1" |
| 1105 | 1199 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1106 | 1200 | checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" |
| 1201 | +dependencies = [ | |
| 1202 | + "allocator-api2", | |
| 1203 | + "equivalent", | |
| 1204 | + "foldhash", | |
| 1205 | +] | |
| 1107 | 1206 | |
| 1108 | 1207 | [[package]] |
| 1109 | 1208 | name = "hashlink" |
| @@ -1550,7 +1649,7 @@ | ||
| 1550 | 1649 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1551 | 1650 | checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" |
| 1552 | 1651 | dependencies = [ |
| 1553 | - "spin", | |
| 1652 | + "spin 0.9.9", | |
| 1554 | 1653 | ] |
| 1555 | 1654 | |
| 1556 | 1655 | [[package]] |
| @@ -1620,6 +1719,25 @@ | ||
| 1620 | 1719 | checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" |
| 1621 | 1720 | |
| 1622 | 1721 | [[package]] |
| 1722 | +name = "lol_html" | |
| 1723 | +version = "3.0.1" | |
| 1724 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1725 | +checksum = "5adbb62638edf7e6bc88835cd3ea388bdd53382af42045da0e414ea78aa0c91a" | |
| 1726 | +dependencies = [ | |
| 1727 | + "bitflags", | |
| 1728 | + "cfg-if", | |
| 1729 | + "cssparser", | |
| 1730 | + "encoding_rs", | |
| 1731 | + "foldhash", | |
| 1732 | + "hashbrown 0.17.1", | |
| 1733 | + "memchr", | |
| 1734 | + "mime", | |
| 1735 | + "precomputed-hash", | |
| 1736 | + "selectors", | |
| 1737 | + "thiserror 2.0.19", | |
| 1738 | +] | |
| 1739 | + | |
| 1740 | +[[package]] | |
| 1623 | 1741 | name = "lru-slab" |
| 1624 | 1742 | version = "0.1.2" |
| 1625 | 1743 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -1712,11 +1830,17 @@ | ||
| 1712 | 1830 | "httparse", |
| 1713 | 1831 | "memchr", |
| 1714 | 1832 | "mime", |
| 1715 | - "spin", | |
| 1833 | + "spin 0.9.9", | |
| 1716 | 1834 | "version_check", |
| 1717 | 1835 | ] |
| 1718 | 1836 | |
| 1719 | 1837 | [[package]] |
| 1838 | +name = "new_debug_unreachable" | |
| 1839 | +version = "1.0.6" | |
| 1840 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1841 | +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" | |
| 1842 | + | |
| 1843 | +[[package]] | |
| 1720 | 1844 | name = "nix" |
| 1721 | 1845 | version = "0.31.3" |
| 1722 | 1846 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -2002,6 +2126,59 @@ | ||
| 2002 | 2126 | checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" |
| 2003 | 2127 | |
| 2004 | 2128 | [[package]] |
| 2129 | +name = "phf" | |
| 2130 | +version = "0.13.1" | |
| 2131 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2132 | +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" | |
| 2133 | +dependencies = [ | |
| 2134 | + "phf_macros", | |
| 2135 | + "phf_shared", | |
| 2136 | + "serde", | |
| 2137 | +] | |
| 2138 | + | |
| 2139 | +[[package]] | |
| 2140 | +name = "phf_codegen" | |
| 2141 | +version = "0.13.1" | |
| 2142 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2143 | +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" | |
| 2144 | +dependencies = [ | |
| 2145 | + "phf_generator", | |
| 2146 | + "phf_shared", | |
| 2147 | +] | |
| 2148 | + | |
| 2149 | +[[package]] | |
| 2150 | +name = "phf_generator" | |
| 2151 | +version = "0.13.1" | |
| 2152 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2153 | +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" | |
| 2154 | +dependencies = [ | |
| 2155 | + "fastrand", | |
| 2156 | + "phf_shared", | |
| 2157 | +] | |
| 2158 | + | |
| 2159 | +[[package]] | |
| 2160 | +name = "phf_macros" | |
| 2161 | +version = "0.13.1" | |
| 2162 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2163 | +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" | |
| 2164 | +dependencies = [ | |
| 2165 | + "phf_generator", | |
| 2166 | + "phf_shared", | |
| 2167 | + "proc-macro2", | |
| 2168 | + "quote", | |
| 2169 | + "syn 2.0.119", | |
| 2170 | +] | |
| 2171 | + | |
| 2172 | +[[package]] | |
| 2173 | +name = "phf_shared" | |
| 2174 | +version = "0.13.1" | |
| 2175 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2176 | +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" | |
| 2177 | +dependencies = [ | |
| 2178 | + "siphasher", | |
| 2179 | +] | |
| 2180 | + | |
| 2181 | +[[package]] | |
| 2005 | 2182 | name = "pin-project" |
| 2006 | 2183 | version = "1.1.13" |
| 2007 | 2184 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -2110,6 +2287,12 @@ | ||
| 2110 | 2287 | ] |
| 2111 | 2288 | |
| 2112 | 2289 | [[package]] |
| 2290 | +name = "precomputed-hash" | |
| 2291 | +version = "0.1.1" | |
| 2292 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2293 | +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" | |
| 2294 | + | |
| 2295 | +[[package]] | |
| 2113 | 2296 | name = "prettyplease" |
| 2114 | 2297 | version = "0.2.37" |
| 2115 | 2298 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -2506,6 +2689,7 @@ | ||
| 2506 | 2689 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2507 | 2690 | checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" |
| 2508 | 2691 | dependencies = [ |
| 2692 | + "log", | |
| 2509 | 2693 | "once_cell", |
| 2510 | 2694 | "ring", |
| 2511 | 2695 | "rustls-pki-types", |
| @@ -2650,6 +2834,25 @@ | ||
| 2650 | 2834 | ] |
| 2651 | 2835 | |
| 2652 | 2836 | [[package]] |
| 2837 | +name = "selectors" | |
| 2838 | +version = "0.37.0" | |
| 2839 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2840 | +checksum = "2cfaaa6035167f0e604e42723c7650d59ee269ef220d7bbe0565602c8a0173b9" | |
| 2841 | +dependencies = [ | |
| 2842 | + "bitflags", | |
| 2843 | + "cssparser", | |
| 2844 | + "derive_more", | |
| 2845 | + "log", | |
| 2846 | + "new_debug_unreachable", | |
| 2847 | + "phf", | |
| 2848 | + "phf_codegen", | |
| 2849 | + "precomputed-hash", | |
| 2850 | + "rustc-hash", | |
| 2851 | + "servo_arc", | |
| 2852 | + "smallvec", | |
| 2853 | +] | |
| 2854 | + | |
| 2855 | +[[package]] | |
| 2653 | 2856 | name = "semver" |
| 2654 | 2857 | version = "1.0.28" |
| 2655 | 2858 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -2728,6 +2931,15 @@ | ||
| 2728 | 2931 | ] |
| 2729 | 2932 | |
| 2730 | 2933 | [[package]] |
| 2934 | +name = "servo_arc" | |
| 2935 | +version = "0.4.3" | |
| 2936 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2937 | +checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" | |
| 2938 | +dependencies = [ | |
| 2939 | + "stable_deref_trait", | |
| 2940 | +] | |
| 2941 | + | |
| 2942 | +[[package]] | |
| 2731 | 2943 | name = "sha1" |
| 2732 | 2944 | version = "0.10.7" |
| 2733 | 2945 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -2797,6 +3009,12 @@ | ||
| 2797 | 3009 | checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" |
| 2798 | 3010 | |
| 2799 | 3011 | [[package]] |
| 3012 | +name = "siphasher" | |
| 3013 | +version = "1.0.3" | |
| 3014 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3015 | +checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" | |
| 3016 | + | |
| 3017 | +[[package]] | |
| 2800 | 3018 | name = "slab" |
| 2801 | 3019 | version = "0.4.12" |
| 2802 | 3020 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -2825,6 +3043,12 @@ | ||
| 2825 | 3043 | checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" |
| 2826 | 3044 | |
| 2827 | 3045 | [[package]] |
| 3046 | +name = "spin" | |
| 3047 | +version = "0.10.1" | |
| 3048 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3049 | +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" | |
| 3050 | + | |
| 3051 | +[[package]] | |
| 2828 | 3052 | name = "spki" |
| 2829 | 3053 | version = "0.7.3" |
| 2830 | 3054 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -3342,6 +3566,35 @@ | ||
| 3342 | 3566 | checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" |
| 3343 | 3567 | |
| 3344 | 3568 | [[package]] |
| 3569 | +name = "ureq" | |
| 3570 | +version = "3.4.0" | |
| 3571 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3572 | +checksum = "972d7902c8735f2695410b8aed7df6ed12a47394aa1c8d7af49f0497b731a94d" | |
| 3573 | +dependencies = [ | |
| 3574 | + "base64 0.23.1", | |
| 3575 | + "flate2", | |
| 3576 | + "log", | |
| 3577 | + "percent-encoding", | |
| 3578 | + "rustls", | |
| 3579 | + "rustls-pki-types", | |
| 3580 | + "ureq-proto", | |
| 3581 | + "utf8-zero", | |
| 3582 | + "webpki-roots", | |
| 3583 | +] | |
| 3584 | + | |
| 3585 | +[[package]] | |
| 3586 | +name = "ureq-proto" | |
| 3587 | +version = "0.6.1" | |
| 3588 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3589 | +checksum = "da5f78b09e6941e1a0f2e30e695e4b120377b54d5e0aec11b594bb57b3971613" | |
| 3590 | +dependencies = [ | |
| 3591 | + "base64 0.23.1", | |
| 3592 | + "http", | |
| 3593 | + "httparse", | |
| 3594 | + "log", | |
| 3595 | +] | |
| 3596 | + | |
| 3597 | +[[package]] | |
| 3345 | 3598 | name = "url" |
| 3346 | 3599 | version = "2.5.8" |
| 3347 | 3600 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -3372,6 +3625,12 @@ | ||
| 3372 | 3625 | checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" |
| 3373 | 3626 | |
| 3374 | 3627 | [[package]] |
| 3628 | +name = "utf8-zero" | |
| 3629 | +version = "0.8.1" | |
| 3630 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3631 | +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" | |
| 3632 | + | |
| 3633 | +[[package]] | |
| 3375 | 3634 | name = "utf8_iter" |
| 3376 | 3635 | version = "1.0.4" |
| 3377 | 3636 | source = "registry+https://github.com/rust-lang/crates.io-index" |
modifiedCargo.toml+23−11View file
| @@ -60,6 +60,7 @@ | ||
| 60 | 60 | flate2 = "1" |
| 61 | 61 | futures-util = "0.3" |
| 62 | 62 | getrandom = "0.3" |
| 63 | +glob = "0.3" | |
| 63 | 64 | hex = "0.4" |
| 64 | 65 | # The two node:crypto KDFs. Both crates already reach this build without a |
| 65 | 66 | # line here -- `pbkdf2` through `pkcs5`, `hkdf` through `elliptic-curve` -- |
| @@ -68,7 +69,13 @@ | ||
| 68 | 69 | hmac = "0.12" |
| 69 | 70 | pbkdf2 = "0.12" |
| 70 | 71 | http-body-util = "0.1" |
| 72 | +# hyper also accepts h2 releases before 0.4.18, which retain the remotely | |
| 73 | +# triggerable resource-exhaustion advisory. Keep a direct floor here because a | |
| 74 | +# lockfile-only update does not preserve that security boundary when resolved. | |
| 75 | +h2 = "0.4.18" | |
| 71 | 76 | hyper = { version = "1", features = ["client", "server", "http1"] } |
| 77 | +httpdate = "1" | |
| 78 | +lol_html = "3.0" | |
| 72 | 79 | hyper-util = { version = "0.1", features = ["tokio"] } |
| 73 | 80 | libc = "0.2" |
| 74 | 81 | lz4_flex = { version = "0.11", features = ["frame"] } |
| @@ -82,11 +89,11 @@ | ||
| 82 | 89 | # schema ever grows nested columns. |
| 83 | 90 | parquet = { version = "59.2.0", default-features = false, features = ["zstd"] } |
| 84 | 91 | p256 = { version = "0.13", features = ["ecdh", "ecdsa", "pkcs8"] } |
| 85 | -# The other NIST curves the Workers key surface accepts. Parsing and JWK | |
| 86 | -# only -- signing stays on P-256, so neither needs `ecdsa`. Versions follow | |
| 87 | -# deno's workspace. | |
| 88 | -p384 = { version = "0.13", features = ["ecdh", "pkcs8"] } | |
| 89 | -p521 = { version = "0.13", features = ["ecdh", "pkcs8"] } | |
| 92 | +# The other NIST curves the Workers key surface accepts. Node-compatible key | |
| 93 | +# derivation and signatures use them beside the Web Crypto parsing surface. | |
| 94 | +# Versions follow deno's workspace. | |
| 95 | +p384 = { version = "0.13", features = ["ecdh", "ecdsa", "pkcs8"] } | |
| 96 | +p521 = { version = "0.13", features = ["ecdh", "ecdsa", "pkcs8"] } | |
| 90 | 97 | # Encrypted PKCS#8, for private keys that arrive password-protected. `rsa` |
| 91 | 98 | # already pulls pkcs8 in; naming it here adds the pkcs5 cipher suite on top. |
| 92 | 99 | # Feature set follows deno's ext/node_crypto. |
| @@ -101,6 +108,10 @@ | ||
| 101 | 108 | # CRC32/CRC32C/CRC64-NVME for DigestStream. Cloudflare accepts these |
| 102 | 109 | # alongside the real digests because S3 and the AWS SDKs checksum with them. |
| 103 | 110 | crc = "3" |
| 111 | +# LTX uses CRC-64/GO-ISO for every file and for snapshot page checksums. The | |
| 112 | +# generic `crc` crate above does not use the SIMD folding path that large-cell | |
| 113 | +# restore needs. | |
| 114 | +crc-fast = { version = "1.10", default-features = false, features = ["std"] } | |
| 104 | 115 | percent-encoding = "2" |
| 105 | 116 | proptest = "1" |
| 106 | 117 | rand = "0.8" |
| @@ -110,7 +121,7 @@ | ||
| 110 | 121 | rusqlite = "0.31" |
| 111 | 122 | rustls = { version = "0.23", default-features = false, features = ["ring"] } |
| 112 | 123 | serde = { version = "1", features = ["derive"] } |
| 113 | -serde_json = "1" | |
| 124 | +serde_json = { version = "1", features = ["raw_value"] } | |
| 114 | 125 | sha1 = "0.10" |
| 115 | 126 | sha2 = "0.10" |
| 116 | 127 | # sqlite-vec is pre-v1, and its Rust binding is outside its compatibility |
| @@ -119,12 +130,13 @@ | ||
| 119 | 130 | subtle = "2" |
| 120 | 131 | tempfile = "3" |
| 121 | 132 | thiserror = "2" |
| 122 | -# `stats` is what makes `stats.allocated` and `stats.resident` readable. The | |
| 123 | -# pressure classifier needs their difference: the pages jemalloc keeps but no | |
| 124 | -# cell uses. Without it a node that sheds its whole working set stays latched | |
| 125 | -# on an RSS number the allocator, not celld, controls. | |
| 133 | +# `stats` makes `stats.allocated` and `stats.resident` readable. The pressure | |
| 134 | +# classifier needs their difference: the pages jemalloc keeps but no cell uses. | |
| 135 | +# `background_threads` makes the shipped allocator purge those freed pages on | |
| 136 | +# its timer. Runtime enablement alone failed in the Linux image, so the cgroup | |
| 137 | +# hard-cap latch stayed closed after a node shed its cells. | |
| 126 | 138 | tikv-jemalloc-ctl = { version = "0.6", features = ["stats"] } |
| 127 | -tikv-jemallocator = { version = "0.6", features = ["stats"] } | |
| 139 | +tikv-jemallocator = { version = "0.6", features = ["background_threads", "stats"] } | |
| 128 | 140 | tokio = "1" |
| 129 | 141 | tokio-rustls = { version = "0.26", default-features = false, features = ["ring"] } |
| 130 | 142 | tokio-stream = "0.1" |
modifiedREADME.md+52−6View file
| @@ -2,9 +2,11 @@ | ||
| 2 | 2 | |
| 3 | 3 | Self-hosted, distributed **Durable Objects**. |
| 4 | 4 | |
| 5 | -celld is an open-source daemon that runs Cloudflare Workers and Durable | |
| 6 | -Objects on your own machines. Each object is a cell: a named server with | |
| 7 | -its own SQLite database. celld stores the long-term state in a bucket | |
| 5 | +celld is an open-source daemon that runs a Cloudflare Workers application | |
| 6 | +on your own machines: Workers, Durable Objects, KV, Queues, D1, R2, | |
| 7 | +Workflows, Cron Triggers, and static assets, deployed from the | |
| 8 | +`wrangler.json` that you already have. Each object is a cell: a named | |
| 9 | +server with its own SQLite database. celld stores the long-term state in a bucket | |
| 8 | 10 | that you own — S3-compatible, Google Cloud Storage, or Azure Blob |
| 9 | 11 | Storage — and needs no serving control plane and no consensus service. |
| 10 | 12 | A cell that nothing is serving costs almost nothing. Learn more at |
| @@ -33,6 +35,30 @@ | ||
| 33 | 35 | replaceable. See [what celld guarantees](docs/guarantees.md) for the |
| 34 | 36 | complete protocol. |
| 35 | 37 | |
| 38 | +## What runs on celld | |
| 39 | + | |
| 40 | +celld runs the programmatic Workers platform: the runtime, and each binding | |
| 41 | +that Cloudflare builds on Workers and Durable Objects. A KV namespace, a | |
| 42 | +queue, a D1 database, a Workflow, and the R2 index are each a cell, so | |
| 43 | +they get the same lease, the same replication, and the same failover as a | |
| 44 | +Durable Object. Each row links to a project that deploys as-is: | |
| 45 | + | |
| 46 | +| service | example | | |
| 47 | +| --- | --- | | |
| 48 | +| Workers: fetch handlers, service bindings, JS RPC, Node.js compat | [`hello`](examples/hello) | | |
| 49 | +| Durable Objects: SQLite storage, alarms, hibernating WebSockets | [`counter`](examples/counter) | | |
| 50 | +| KV: list, metadata, expiration, bulk import | [`kv`](examples/kv) | | |
| 51 | +| Queues: producers, batching consumers, retries, dead letters | [docs](docs/cloudflare-compat.md#queues) | | |
| 52 | +| D1: SQL databases, batches, migrations | [`d1`](examples/d1) | | |
| 53 | +| R2: reads, writes, lists, multipart uploads | [`r2`](examples/r2) | | |
| 54 | +| Workflows: durable steps, sleeps, events, pause and restart | [`workflow`](examples/workflow) | | |
| 55 | +| Cron Triggers: one run for each occurrence across the fleet | [`cron`](examples/cron) | | |
| 56 | +| Static assets: asset-only or with a Worker, `_headers`, `_redirects` | [docs](docs/cloudflare-compat.md#static-assets) | | |
| 57 | + | |
| 58 | +A product that needs the Cloudflare network, a GPU, or a browser farm is out | |
| 59 | +of scope. The [Cloudflare compatibility](docs/cloudflare-compat.md) page | |
| 60 | +lists each gap in the services above. | |
| 61 | + | |
| 36 | 62 | ## Install |
| 37 | 63 | |
| 38 | 64 | The installer downloads the `celld` binary (provenance is verifiable with |
| @@ -103,6 +129,11 @@ | ||
| 103 | 129 | operator listener stays on loopback. The command keeps the application state |
| 104 | 130 | in `.celld/dev`, so a later invocation uses the same durable data. |
| 105 | 131 | |
| 132 | +The state also survives a configuration change, and celld does not migrate it, | |
| 133 | +so an object can keep a value that the new configuration rejects. The failure | |
| 134 | +then looks unrelated to the change. Use `celld dev --clean` to delete | |
| 135 | +`.celld/dev` before the server starts and run from an empty local state. | |
| 136 | + | |
| 106 | 137 | The default display highlights the application URL and hides the node |
| 107 | 138 | warning and information logs. Use `celld dev --logs` to show these logs. |
| 108 | 139 | The errors remain visible without this flag. Set `NO_COLOR` to disable color, |
| @@ -210,9 +241,9 @@ | ||
| 210 | 241 | |
| 211 | 242 | The report keeps checking after an individual failure and distinguishes |
| 212 | 243 | expired records, malformed or unsafe advertise addresses, unreachable peers, |
| 213 | -and incompatible protocols. It also prints each node's coarse resident-cell, | |
| 214 | -WebSocket, RSS, CPU, file-descriptor, pressure, and shedding sample. Pass one | |
| 215 | -or more `--peer NODE_ID` options to restrict the check. | |
| 244 | +and incompatible protocols. It also prints each node's coarse owned-cell, | |
| 245 | +resident-cell, WebSocket, RSS, CPU, file-descriptor, pressure, and shedding | |
| 246 | +sample. Pass one or more `--peer NODE_ID` options to restrict the check. | |
| 216 | 247 | |
| 217 | 248 | `celld cell list` lists the Durable Object instances in the fleet bucket: |
| 218 | 249 | |
| @@ -239,6 +270,9 @@ | ||
| 239 | 270 | celld d1 migrations apply ledger --bucket s3://my-cells-bucket |
| 240 | 271 | ``` |
| 241 | 272 | |
| 273 | +The migration file extension is ASCII case-insensitive, so `.sql` and `.SQL` | |
| 274 | +files are migrations. The command ignores a file with a different extension. | |
| 275 | + | |
| 242 | 276 | `celld kv` reads and writes a deployed KV namespace. Its bulk commands use the |
| 243 | 277 | Wrangler file format, so a Wrangler export can migrate directly into celld: |
| 244 | 278 | |
| @@ -264,6 +298,18 @@ | ||
| 264 | 298 | --internal-listen 10.0.0.12:8081 --advertise node-a.internal:8081 |
| 265 | 299 | ``` |
| 266 | 300 | |
| 301 | +celld balances ownership across the fleet. Every node reads a shared fleet | |
| 302 | +sample every five seconds. One node refreshes the sample from the node | |
| 303 | +leases, so each refresh reads each lease once for the fleet. The node with | |
| 304 | +the most owned cells per unit of weight hands at most 32 hibernated cells | |
| 305 | +per sample to the peer that is furthest below its share. A hibernated cell moves as one record write, and | |
| 306 | +its parked hibernatable WebSockets close with code 1012 so the clients | |
| 307 | +reconnect to the new owner. A resident cell moves only after idle eviction | |
| 308 | +hibernates it (`CELLD_IDLE_EVICT_S`). Set `CELLD_PLACEMENT_WEIGHT` to give a | |
| 309 | +node a larger or a smaller share than its CPU count, and set | |
| 310 | +`CELLD_REBALANCE_INTERVAL_MS=0` to disable balancing. `POST /rebalance/pause` | |
| 311 | +on the internal listener of any node pauses the fleet. | |
| 312 | + | |
| 267 | 313 | celld enables a memory-pressure threshold at 80% of the available memory by |
| 268 | 314 | default. Set `CELLD_MAX_RSS_MB` to change the threshold, or set it to `0` to |
| 269 | 315 | disable memory-pressure shedding. In a Linux cgroup, the threshold uses the |
modifiedcrates/celld/Cargo.toml+5−2View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [package] |
| 2 | 2 | name = "celld" |
| 3 | -version = "0.4.0" | |
| 3 | +version = "0.4.1" | |
| 4 | 4 | edition = "2021" |
| 5 | 5 | rust-version = "1.94.1" |
| 6 | 6 | license = "Apache-2.0" |
| @@ -39,9 +39,12 @@ | ||
| 39 | 39 | flate2.workspace = true |
| 40 | 40 | futures-util.workspace = true |
| 41 | 41 | getrandom.workspace = true |
| 42 | +glob.workspace = true | |
| 42 | 43 | hkdf.workspace = true |
| 44 | +lol_html.workspace = true | |
| 43 | 45 | hmac.workspace = true |
| 44 | 46 | http-body-util.workspace = true |
| 47 | +httpdate.workspace = true | |
| 45 | 48 | hyper.workspace = true |
| 46 | 49 | hyper-util.workspace = true |
| 47 | 50 | md-5.workspace = true |
| @@ -61,7 +64,7 @@ | ||
| 61 | 64 | rand.workspace = true |
| 62 | 65 | regex.workspace = true |
| 63 | 66 | reqwest = { workspace = true, features = ["rustls-tls", "stream", "json"] } |
| 64 | -rusqlite = { workspace = true, features = ["backup", "bundled", "hooks"] } | |
| 67 | +rusqlite = { workspace = true, features = ["backup", "bundled", "hooks", "serialize"] } | |
| 65 | 68 | sqlite-vec.workspace = true |
| 66 | 69 | rustls.workspace = true |
| 67 | 70 | rsa.workspace = true |
modifiedcrates/celld/actor.rs+478−102View file
| @@ -6,8 +6,9 @@ | ||
| 6 | 6 | use crate::machine::{ |
| 7 | 7 | ownership_on_evict_from_environment, pressure_config_from_environment, |
| 8 | 8 | random_process_generation, DEFAULT_MAX_OUTBOUND_WEBSOCKETS, |
| 9 | + DEFAULT_OWNER_LOG_RECOVERY_ATTEMPTS, DEFAULT_OWNER_LOG_RECOVERY_BACKOFF_MS, | |
| 9 | 10 | }; |
| 10 | -use crate::ownership_store::{now_ms, BucketOwnership}; | |
| 11 | +use crate::ownership_store::{now_ms, BucketOwnership, LeaseCasError}; | |
| 11 | 12 | use crate::peer_auth::{self, PeerAuth}; |
| 12 | 13 | use crate::runtime::{CellHost, RuntimeManager}; |
| 13 | 14 | use anyhow::Context as _; |
| @@ -32,7 +33,8 @@ | ||
| 32 | 33 | /// The shell's deadline for one actor operation. Queue leases include this |
| 33 | 34 | /// exact budget for their settlement call, so the actor and broker must read |
| 34 | 35 | /// one accessor rather than duplicate the environment default. |
| 35 | -pub(crate) fn operation_deadline_ms() -> anyhow::Result<u64> { | |
| 36 | +#[doc(hidden)] | |
| 37 | +pub fn operation_deadline_ms() -> anyhow::Result<u64> { | |
| 36 | 38 | crate::env_vars::positive_or("CELLD_OPERATION_DEADLINE_MS", DEFAULT_OPERATION_DEADLINE_MS) |
| 37 | 39 | } |
| 38 | 40 | |
| @@ -51,6 +53,9 @@ | ||
| 51 | 53 | /// above: a node parks many cells at once, and one slot per cell would |
| 52 | 54 | /// let a later parking disarm an earlier one. |
| 53 | 55 | QueuedActivation(String, u64), |
| 56 | + /// Keyed like `QueuedActivation`: one pending retry per cell, and a | |
| 57 | + /// newer episode's arming supersedes a stale one. | |
| 58 | + OwnerLogRecoveryRetry(String, u64), | |
| 54 | 59 | } |
| 55 | 60 | |
| 56 | 61 | impl TimerSlot { |
| @@ -63,6 +68,9 @@ | ||
| 63 | 68 | Timer::QueuedActivation { cell, generation } => { |
| 64 | 69 | Self::QueuedActivation(cell.clone(), *generation) |
| 65 | 70 | } |
| 71 | + Timer::OwnerLogRecoveryRetry { cell, generation } => { | |
| 72 | + Self::OwnerLogRecoveryRetry(cell.clone(), *generation) | |
| 73 | + } | |
| 66 | 74 | } |
| 67 | 75 | } |
| 68 | 76 | } |
| @@ -188,6 +196,17 @@ | ||
| 188 | 196 | } |
| 189 | 197 | } |
| 190 | 198 | |
| 199 | + /// The shared fleet sample and the instant it was taken, for placement. | |
| 200 | + async fn read_capacity_view(&self) -> Result<(u64, Vec<celld_logic::CapacityPeer>), Failure> { | |
| 201 | + match self { | |
| 202 | + Self::Memory(_) => Ok((now_ms(), Vec::new())), | |
| 203 | + Self::Bucket(bucket) => bucket.read_shared_capacity_view().await.map_err(|error| { | |
| 204 | + eprintln!("celld capacity view read failed: {error:#}"); | |
| 205 | + Failure::Definite | |
| 206 | + }), | |
| 207 | + } | |
| 208 | + } | |
| 209 | + | |
| 191 | 210 | async fn read_self_node_lease(&self, node: &str) -> Result<Option<NodeLeaseRecord>, Failure> { |
| 192 | 211 | match self { |
| 193 | 212 | Self::Memory(memory) => Ok(memory.lock().await.leases.get(node).cloned()), |
| @@ -309,9 +328,20 @@ | ||
| 309 | 328 | Self::Bucket(bucket) => bucket |
| 310 | 329 | .cas_node_lease(guard, &record, stamped) |
| 311 | 330 | .await |
| 312 | - .map_err(|error| { | |
| 313 | - eprintln!("celld node-lease CAS ambiguous: {error:#}"); | |
| 314 | - Failure::Ambiguous | |
| 331 | + .map_err(|error| match error { | |
| 332 | + // The write provably did not commit, so the record | |
| 333 | + // still holds what the prior attempt left. A readback | |
| 334 | + // would only spend authority to re-learn that, and the | |
| 335 | + // renewal window is exactly what a store blip is | |
| 336 | + // eating. | |
| 337 | + LeaseCasError::NotCommitted(error) => { | |
| 338 | + eprintln!("celld node-lease CAS did not commit: {error:#}"); | |
| 339 | + Failure::Definite | |
| 340 | + } | |
| 341 | + LeaseCasError::Ambiguous(error) => { | |
| 342 | + eprintln!("celld node-lease CAS ambiguous: {error:#}"); | |
| 343 | + Failure::Ambiguous | |
| 344 | + } | |
| 315 | 345 | }), |
| 316 | 346 | } |
| 317 | 347 | } |
| @@ -349,6 +379,12 @@ | ||
| 349 | 379 | /// bounded by the drain deadline, so a wedged store still cannot hold |
| 350 | 380 | /// the exit hostage. |
| 351 | 381 | ReleaseAll, |
| 382 | + /// Give up to `cells` idle cells to the fleet. The balancing loop sends | |
| 383 | + /// this after it has confirmed from the leases that this node is the | |
| 384 | + /// densest and a peer has room. | |
| 385 | + Rebalance { | |
| 386 | + cells: usize, | |
| 387 | + }, | |
| 352 | 388 | /// Has the shutdown handoff finished? True once no cell occupies |
| 353 | 389 | /// capacity: nothing resident, restoring, or mid-eviction. The drain |
| 354 | 390 | /// loop polls this to exit as soon as the handoff completes instead of |
| @@ -394,19 +430,21 @@ | ||
| 394 | 430 | /// whichever adapter is holding the effect. |
| 395 | 431 | Output { |
| 396 | 432 | request: u64, |
| 397 | - channel: Channel, | |
| 398 | - position: Option<u64>, | |
| 433 | + ticket: GateTicket, | |
| 399 | 434 | reply: oneshot::Sender<Result<(), RequestError>>, |
| 400 | 435 | }, |
| 401 | 436 | /// A `webSocketMessage` finished; hand its captured outbound frames to the |
| 402 | 437 | /// cell's output gate. `write_position` present means the handler wrote, so |
| 403 | 438 | /// the frames are held behind that write until it is durable; absent means |
| 404 | - /// flush them (behind any earlier still-pending write, else immediately). | |
| 439 | + /// flush them behind the proof of what the handler observed, if a proof is | |
| 440 | + /// still owed for that (`observed`, as on [`GateTicket`]), else behind any | |
| 441 | + /// earlier still-pending write, else immediately. | |
| 405 | 442 | WsOutput { |
| 406 | 443 | request: u64, |
| 407 | 444 | scope: String, |
| 408 | 445 | frames: Vec<(u64, WsOut)>, |
| 409 | 446 | write_position: Option<u64>, |
| 447 | + observed: Option<u64>, | |
| 410 | 448 | reply: oneshot::Sender<()>, |
| 411 | 449 | }, |
| 412 | 450 | WebSocketOpened { |
| @@ -426,6 +464,8 @@ | ||
| 426 | 464 | }, |
| 427 | 465 | WakeHint { |
| 428 | 466 | cell: String, |
| 467 | + entry_ms: i64, | |
| 468 | + scope: celld_logic::WakeHintScope, | |
| 429 | 469 | }, |
| 430 | 470 | Evict { |
| 431 | 471 | cell: String, |
| @@ -575,42 +615,50 @@ | ||
| 575 | 615 | /// connection without dropping its service future, so the connection also |
| 576 | 616 | /// aborts these requests explicitly when its transport ends. |
| 577 | 617 | #[derive(Clone, Default)] |
| 578 | -pub struct ConnectionWorkerRequests(Arc<std::sync::Mutex<BTreeSet<crate::js::RequestId>>>); | |
| 618 | +pub struct ConnectionWorkerRequests( | |
| 619 | + Arc<std::sync::Mutex<Vec<Arc<crate::runtime::RequestCancellationLifetime>>>>, | |
| 620 | +); | |
| 579 | 621 | |
| 580 | 622 | impl ConnectionWorkerRequests { |
| 581 | - pub fn register(&self, request: crate::js::RequestId) { | |
| 582 | - self.0.lock().unwrap().insert(request); | |
| 623 | + pub fn register(&self, cancellation: Arc<crate::runtime::RequestCancellationLifetime>) { | |
| 624 | + self.0.lock().unwrap().push(cancellation); | |
| 583 | 625 | } |
| 584 | 626 | |
| 585 | - pub fn complete(&self, request: crate::js::RequestId) { | |
| 586 | - self.0.lock().unwrap().remove(&request); | |
| 627 | + pub fn complete(&self, cancellation: &Arc<crate::runtime::RequestCancellationLifetime>) { | |
| 628 | + self.0 | |
| 629 | + .lock() | |
| 630 | + .unwrap() | |
| 631 | + .retain(|active| !Arc::ptr_eq(active, cancellation)); | |
| 587 | 632 | } |
| 588 | 633 | |
| 589 | 634 | pub fn abort_all(&self) { |
| 590 | - let requests = std::mem::take(&mut *self.0.lock().unwrap()); | |
| 591 | - for request in requests { | |
| 592 | - crate::js::abort_request(request); | |
| 635 | + let cancellations = std::mem::take(&mut *self.0.lock().unwrap()); | |
| 636 | + for cancellation in cancellations { | |
| 637 | + cancellation.publish_abort(); | |
| 593 | 638 | } |
| 594 | 639 | } |
| 595 | 640 | } |
| 596 | 641 | |
| 597 | 642 | pub struct IngressAbortGuard { |
| 598 | - request: Option<crate::js::RequestId>, | |
| 643 | + cancellation: Option<Arc<crate::runtime::RequestCancellationLifetime>>, | |
| 599 | 644 | connection: ConnectionWorkerRequests, |
| 600 | 645 | } |
| 601 | 646 | |
| 602 | 647 | impl IngressAbortGuard { |
| 603 | - pub fn new(request: crate::js::RequestId, connection: ConnectionWorkerRequests) -> Self { | |
| 604 | - connection.register(request); | |
| 648 | + pub fn new( | |
| 649 | + cancellation: Arc<crate::runtime::RequestCancellationLifetime>, | |
| 650 | + connection: ConnectionWorkerRequests, | |
| 651 | + ) -> Self { | |
| 652 | + connection.register(cancellation.clone()); | |
| 605 | 653 | Self { |
| 606 | - request: Some(request), | |
| 654 | + cancellation: Some(cancellation), | |
| 607 | 655 | connection, |
| 608 | 656 | } |
| 609 | 657 | } |
| 610 | 658 | |
| 611 | 659 | pub fn disarm(&mut self) { |
| 612 | - if let Some(request) = self.request.take() { | |
| 613 | - self.connection.complete(request); | |
| 660 | + if let Some(cancellation) = self.cancellation.take() { | |
| 661 | + self.connection.complete(&cancellation); | |
| 614 | 662 | } |
| 615 | 663 | } |
| 616 | 664 | } |
| @@ -645,9 +693,9 @@ | ||
| 645 | 693 | |
| 646 | 694 | impl Drop for IngressAbortGuard { |
| 647 | 695 | fn drop(&mut self) { |
| 648 | - if let Some(request) = self.request.take() { | |
| 649 | - self.connection.complete(request); | |
| 650 | - crate::js::abort_request(request); | |
| 696 | + if let Some(cancellation) = self.cancellation.take() { | |
| 697 | + self.connection.complete(&cancellation); | |
| 698 | + cancellation.publish_abort(); | |
| 651 | 699 | } |
| 652 | 700 | } |
| 653 | 701 | } |
| @@ -1047,6 +1095,7 @@ | ||
| 1047 | 1095 | cell: String, |
| 1048 | 1096 | epoch: u64, |
| 1049 | 1097 | event: &'static str, |
| 1098 | + deadline_mono_ms: Option<u64>, | |
| 1050 | 1099 | mut release: F, |
| 1051 | 1100 | ) -> CompletedEffect |
| 1052 | 1101 | where |
| @@ -1054,6 +1103,16 @@ | ||
| 1054 | 1103 | Fut: std::future::Future<Output = anyhow::Result<()>>, |
| 1055 | 1104 | { |
| 1056 | 1105 | while let Err(error) = release().await { |
| 1106 | + if deadline_mono_ms.is_some_and(|deadline| crate::asyncrt::mono_ms() >= deadline) { | |
| 1107 | + tracing::warn!( | |
| 1108 | + event, | |
| 1109 | + %cell, | |
| 1110 | + epoch, | |
| 1111 | + %error, | |
| 1112 | + "the host did not release the cell before the deadline; restarting it in place" | |
| 1113 | + ); | |
| 1114 | + return CompletedEffect::plain(Event::RuntimeStopFailed { op }); | |
| 1115 | + } | |
| 1057 | 1116 | tracing::warn!( |
| 1058 | 1117 | event, |
| 1059 | 1118 | %cell, |
| @@ -1160,8 +1219,8 @@ | ||
| 1160 | 1219 | /// unhealthy and a load balancer stops routing here before teardown. |
| 1161 | 1220 | pub draining: Arc<std::sync::atomic::AtomicBool>, |
| 1162 | 1221 | /// The one-shot fleet gate on the first health 200. A fresh process |
| 1163 | - /// reports ready only after no peer donor is mid-handoff, or after a | |
| 1164 | - /// bounded wait, so a rolling update cannot advance faster than the | |
| 1222 | + /// reports ready only after no peer donor is mid-handoff and the fleet has | |
| 1223 | + /// successor capacity, so a rolling update cannot advance faster than the | |
| 1165 | 1224 | /// fleet recovers. Fleet state never demotes readiness after the gate |
| 1166 | 1225 | /// opens; peers reach owned cells directly regardless. |
| 1167 | 1226 | pub fleet_ready: Arc<std::sync::atomic::AtomicBool>, |
| @@ -1181,6 +1240,10 @@ | ||
| 1181 | 1240 | /// Object ingress. The same value must govern both entry points because a |
| 1182 | 1241 | /// caller can choose either route for an ordinary Durable Object. |
| 1183 | 1242 | pub max_request_body_bytes: usize, |
| 1243 | + /// The complete retry budget for a contradicted remote ownership | |
| 1244 | + /// generation. This is the same operation deadline that bounds the | |
| 1245 | + /// decision core, so a shell retry cannot outlive its core operation. | |
| 1246 | + pub operation_deadline_ms: u64, | |
| 1184 | 1247 | } |
| 1185 | 1248 | |
| 1186 | 1249 | impl AppHandle { |
| @@ -1380,7 +1443,7 @@ | ||
| 1380 | 1443 | // `PoolLoad` — a snapshot with no isolates and no affiliations, which |
| 1381 | 1444 | // could only ever answer "yes" once pressure stopped refusing |
| 1382 | 1445 | // outright. A decision made against a fake reading is not a fast path. |
| 1383 | - let js_request = crate::js::next_request_id(); | |
| 1446 | + let cancellation = crate::runtime::RequestCancellationLifetime::stateless(); | |
| 1384 | 1447 | // The Worker entry is stateless — run it in the pool, always. Routing it |
| 1385 | 1448 | // to a "landing cell" existed only to make an `env.NS.get(id)` call |
| 1386 | 1449 | // resolve inline; but a cell runs one fetch at a time, so under any real |
| @@ -1388,10 +1451,9 @@ | ||
| 1388 | 1451 | // round-trip is paid for nothing — on top of the DO call's own routing. |
| 1389 | 1452 | // A DO call reaches its owning cell (with fencing and the output gate) on |
| 1390 | 1453 | // the host path, so one routing round-trip per request, never two. |
| 1391 | - let mut abort = IngressAbortGuard::new(js_request, connection); | |
| 1392 | - let result = runtime | |
| 1393 | - .fetch_worker_pool(url, method, body, headers, js_request) | |
| 1394 | - .await; | |
| 1454 | + let fetching = runtime.fetch_worker_pool(url, method, body, headers, cancellation.clone()); | |
| 1455 | + let mut abort = IngressAbortGuard::new(cancellation, connection); | |
| 1456 | + let result = fetching.await; | |
| 1395 | 1457 | abort.disarm(); |
| 1396 | 1458 | result |
| 1397 | 1459 | } |
| @@ -1420,14 +1482,12 @@ | ||
| 1420 | 1482 | |
| 1421 | 1483 | /// Hold a response until every write it can reveal is durable. A write |
| 1422 | 1484 | /// supplies its ending position. A read supplies `None` and trails the |
| 1423 | - /// newest outstanding write on the same cell, if one exists. | |
| 1424 | - pub async fn gate_output( | |
| 1425 | - &self, | |
| 1426 | - request: u64, | |
| 1427 | - channel: Channel, | |
| 1428 | - position: Option<u64>, | |
| 1429 | - ) -> Result<(), RequestError> { | |
| 1430 | - match self.gate_output_path(request, channel, position).await { | |
| 1485 | + /// newest outstanding write on the same cell, if one exists. A ticket | |
| 1486 | + /// whose position was sampled before `request` pinned the cell supplies | |
| 1487 | + /// the epoch it sampled at, and the core refuses it when the cell has | |
| 1488 | + /// since moved to another epoch. | |
| 1489 | + pub async fn gate_output(&self, request: u64, ticket: GateTicket) -> Result<(), RequestError> { | |
| 1490 | + match self.gate_output_path(request, ticket).await { | |
| 1431 | 1491 | OutputGateOutcome::Returned(result) => result, |
| 1432 | 1492 | OutputGateOutcome::SubmissionFailure | OutputGateOutcome::ReplyChannelClosed => { |
| 1433 | 1493 | Err(RequestError::NodeFenced) |
| @@ -1435,20 +1495,14 @@ | ||
| 1435 | 1495 | } |
| 1436 | 1496 | } |
| 1437 | 1497 | |
| 1438 | - async fn gate_output_path( | |
| 1439 | - &self, | |
| 1440 | - request: u64, | |
| 1441 | - channel: Channel, | |
| 1442 | - position: Option<u64>, | |
| 1443 | - ) -> OutputGateOutcome { | |
| 1498 | + async fn gate_output_path(&self, request: u64, ticket: GateTicket) -> OutputGateOutcome { | |
| 1444 | 1499 | let started_mono_ms = crate::asyncrt::mono_ms(); |
| 1445 | 1500 | let (reply, receive) = oneshot::channel(); |
| 1446 | 1501 | if self |
| 1447 | 1502 | .tx |
| 1448 | 1503 | .send(Message::Output { |
| 1449 | 1504 | request, |
| 1450 | - channel, | |
| 1451 | - position, | |
| 1505 | + ticket, | |
| 1452 | 1506 | reply, |
| 1453 | 1507 | }) |
| 1454 | 1508 | .is_err() |
| @@ -1476,10 +1530,9 @@ | ||
| 1476 | 1530 | pub(crate) async fn gate_output_with_receipt_for_test( |
| 1477 | 1531 | &self, |
| 1478 | 1532 | request: u64, |
| 1479 | - channel: Channel, | |
| 1480 | - position: Option<u64>, | |
| 1533 | + ticket: GateTicket, | |
| 1481 | 1534 | ) -> OutputGateReceiptForTest { |
| 1482 | - match self.gate_output_path(request, channel, position).await { | |
| 1535 | + match self.gate_output_path(request, ticket).await { | |
| 1483 | 1536 | OutputGateOutcome::SubmissionFailure => { |
| 1484 | 1537 | OutputGateReceiptForTest::SubmissionFailure { request } |
| 1485 | 1538 | } |
| @@ -1493,7 +1546,7 @@ | ||
| 1493 | 1546 | } |
| 1494 | 1547 | |
| 1495 | 1548 | pub async fn gate_write(&self, request: u64, position: u64) -> Result<(), RequestError> { |
| 1496 | - self.gate_output(request, Channel::Response, Some(position)) | |
| 1549 | + self.gate_output(request, GateTicket::response(Some(position), None)) | |
| 1497 | 1550 | .await |
| 1498 | 1551 | } |
| 1499 | 1552 | |
| @@ -1501,27 +1554,30 @@ | ||
| 1501 | 1554 | /// Awaited so the request stays pinned until the actor has registered the |
| 1502 | 1555 | /// gate (the core reads the still-active request when it opens); frames flush |
| 1503 | 1556 | /// or fail asynchronously as durability resolves, not here. |
| 1557 | + /// | |
| 1558 | + /// An error means the actor has stopped and registered nothing: no | |
| 1559 | + /// barrier opened, so a caller that relied on one for an unproven write | |
| 1560 | + /// must not treat the write as covered. | |
| 1504 | 1561 | pub async fn ws_output( |
| 1505 | 1562 | &self, |
| 1506 | 1563 | request: u64, |
| 1507 | 1564 | scope: String, |
| 1508 | 1565 | frames: Vec<(u64, WsOut)>, |
| 1509 | 1566 | write_position: Option<u64>, |
| 1510 | - ) { | |
| 1567 | + observed: Option<u64>, | |
| 1568 | + ) -> Result<(), ActorStopped> { | |
| 1511 | 1569 | let (reply, receive) = oneshot::channel(); |
| 1512 | - if self | |
| 1513 | - .tx | |
| 1570 | + self.tx | |
| 1514 | 1571 | .send(Message::WsOutput { |
| 1515 | 1572 | request, |
| 1516 | 1573 | scope, |
| 1517 | 1574 | frames, |
| 1518 | 1575 | write_position, |
| 1576 | + observed, | |
| 1519 | 1577 | reply, |
| 1520 | 1578 | }) |
| 1521 | - .is_ok() | |
| 1522 | - { | |
| 1523 | - let _ = receive.await; | |
| 1524 | - } | |
| 1579 | + .map_err(|_| ActorStopped)?; | |
| 1580 | + receive.await.map_err(|_| ActorStopped) | |
| 1525 | 1581 | } |
| 1526 | 1582 | |
| 1527 | 1583 | pub async fn websocket_opened( |
| @@ -1705,6 +1761,57 @@ | ||
| 1705 | 1761 | frames: Vec<(u64, WsOut)>, |
| 1706 | 1762 | } |
| 1707 | 1763 | |
| 1764 | +/// The actor stopped before it answered: its channel is closed, and nothing | |
| 1765 | +/// it was asked to register exists. | |
| 1766 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 1767 | +pub struct ActorStopped; | |
| 1768 | + | |
| 1769 | +impl std::fmt::Display for ActorStopped { | |
| 1770 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 1771 | + f.write_str("the cell actor stopped before it registered the output") | |
| 1772 | + } | |
| 1773 | +} | |
| 1774 | + | |
| 1775 | +impl std::error::Error for ActorStopped {} | |
| 1776 | + | |
| 1777 | +/// What one output-gate ticket asks: the route it holds, the committed-write | |
| 1778 | +/// position it must see proven, and the activation epoch that position was | |
| 1779 | +/// sampled at. | |
| 1780 | +/// | |
| 1781 | +/// One value rather than three arguments, because a position without its | |
| 1782 | +/// epoch is a ticket a reset can satisfy at the wrong epoch (see | |
| 1783 | +/// `Event::Output`): the routed path samples in the handler's turn and only | |
| 1784 | +/// then acquires the request that pins the cell, and a caller that could pass | |
| 1785 | +/// the position alone would drop the epoch without the compiler noticing. | |
| 1786 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 1787 | +pub struct GateTicket { | |
| 1788 | + pub channel: Channel, | |
| 1789 | + pub position: Option<u64>, | |
| 1790 | + /// The committed-write position a read-only output observed above the | |
| 1791 | + /// cell's published baseline, when a handler had advanced it. The core | |
| 1792 | + /// holds the output until a verified proof covers it, whether or not the | |
| 1793 | + /// handler that wrote has taken a ticket yet. Read only when `position` | |
| 1794 | + /// is `None`. | |
| 1795 | + pub observed: Option<u64>, | |
| 1796 | + pub epoch: Option<u64>, | |
| 1797 | +} | |
| 1798 | + | |
| 1799 | +impl GateTicket { | |
| 1800 | + /// The handler's own response. Its request was active on the cell before | |
| 1801 | + /// the positions were sampled, and a reset deactivates every request of | |
| 1802 | + /// the cell it discards, so the core already refuses a stale one: no | |
| 1803 | + /// epoch needs to travel. Both positions come from one sample, so a | |
| 1804 | + /// read-only response cannot leave its observed position behind. | |
| 1805 | + pub const fn response(position: Option<u64>, observed: Option<u64>) -> Self { | |
| 1806 | + Self { | |
| 1807 | + channel: Channel::Response, | |
| 1808 | + position, | |
| 1809 | + observed, | |
| 1810 | + epoch: None, | |
| 1811 | + } | |
| 1812 | + } | |
| 1813 | +} | |
| 1814 | + | |
| 1708 | 1815 | /// The shell identity for one output held by the core. |
| 1709 | 1816 | /// |
| 1710 | 1817 | /// One request can hold output on multiple channels. Keeping both values in |
| @@ -1731,6 +1838,7 @@ | ||
| 1731 | 1838 | peer_http: reqwest::Client, |
| 1732 | 1839 | peer_auth: Arc<PeerAuth>, |
| 1733 | 1840 | paced_handoff: bool, |
| 1841 | + operation_deadline_ms: u64, | |
| 1734 | 1842 | handoff_directory: Arc<Mutex<HandoffDirectory>>, |
| 1735 | 1843 | host: Option<CellHost>, |
| 1736 | 1844 | drain_pins: DrainPinRegistry, |
| @@ -1818,8 +1926,7 @@ | ||
| 1818 | 1926 | const HANDOFF_DIRECTORY_MAX_AGE_MS: u64 = 500; |
| 1819 | 1927 | const HANDOFF_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(250); |
| 1820 | 1928 | |
| 1821 | -/// A deterministic final tie-break spreads one concurrent batch across peers | |
| 1822 | -/// whose published load is equal. The load remains the primary ranking input. | |
| 1929 | +/// A deterministic final tie-break spreads peers whose projected load is equal. | |
| 1823 | 1930 | fn handoff_tie_break(cell: &str, node: &str) -> u64 { |
| 1824 | 1931 | let mut hash = 0xcbf2_9ce4_8422_2325_u64; |
| 1825 | 1932 | for byte in cell |
| @@ -1840,6 +1947,7 @@ | ||
| 1840 | 1947 | directory: &Arc<Mutex<HandoffDirectory>>, |
| 1841 | 1948 | source: &str, |
| 1842 | 1949 | cell: &str, |
| 1950 | + rebalance: bool, | |
| 1843 | 1951 | ) -> Result<Vec<CapacityPeer>, Failure> { |
| 1844 | 1952 | let mut directory = directory.lock().await; |
| 1845 | 1953 | let now_mono_ms = crate::asyncrt::mono_ms(); |
| @@ -1850,10 +1958,43 @@ | ||
| 1850 | 1958 | directory.peers = ownership.read_capacity_peers().await?; |
| 1851 | 1959 | directory.sampled_at_mono_ms = Some(now_mono_ms); |
| 1852 | 1960 | } |
| 1853 | - let current_ms = now_ms(); | |
| 1854 | - let mut peers: Vec<_> = directory | |
| 1855 | - .peers | |
| 1856 | - .iter() | |
| 1961 | + let peers = directory.peers.clone(); | |
| 1962 | + let mut ranked = rank_handoff_candidates(peers, source, cell, now_ms()); | |
| 1963 | + if rebalance { | |
| 1964 | + // A drain takes any peer with room. A balancing move takes only a | |
| 1965 | + // peer below its ownership target, least dense first; a fuller peer | |
| 1966 | + // would hand the cell straight back on its own next sample. | |
| 1967 | + let receivers = celld_logic::rebalance::receivers( | |
| 1968 | + &directory.peers, | |
| 1969 | + source, | |
| 1970 | + now_ms(), | |
| 1971 | + crate::machine::lease_ttl_ms_from_environment(), | |
| 1972 | + ); | |
| 1973 | + ranked.retain(|peer| receivers.contains(&peer.node)); | |
| 1974 | + ranked.sort_by_key(|peer| receivers.iter().position(|node| *node == peer.node)); | |
| 1975 | + if ranked.is_empty() { | |
| 1976 | + // The plan saw room that this sample does not. The adoption | |
| 1977 | + // retries until its deadline, so this repeats; without it a | |
| 1978 | + // failed balancing move left no trace of why. | |
| 1979 | + tracing::debug!( | |
| 1980 | + event = "rebalance_no_receiver", | |
| 1981 | + %cell, | |
| 1982 | + below_target = receivers.len(), | |
| 1983 | + "no peer below its target can take the cell" | |
| 1984 | + ); | |
| 1985 | + } | |
| 1986 | + } | |
| 1987 | + Ok(ranked) | |
| 1988 | +} | |
| 1989 | + | |
| 1990 | +fn rank_handoff_candidates( | |
| 1991 | + peers: Vec<CapacityPeer>, | |
| 1992 | + source: &str, | |
| 1993 | + cell: &str, | |
| 1994 | + current_ms: u64, | |
| 1995 | +) -> Vec<CapacityPeer> { | |
| 1996 | + let mut peers: Vec<_> = peers | |
| 1997 | + .into_iter() | |
| 1857 | 1998 | .filter(|peer| { |
| 1858 | 1999 | peer.node != source |
| 1859 | 2000 | && peer.expires_ms > current_ms |
| @@ -1861,20 +2002,20 @@ | ||
| 1861 | 2002 | && peer.peer_protocol == peer_auth::PROTOCOL_VERSION |
| 1862 | 2003 | && peer.sampled_ms != 0 |
| 1863 | 2004 | && !peer.pressured |
| 2005 | + && peer.memory_headroom != Some(false) | |
| 1864 | 2006 | && peer.paced_handoff |
| 1865 | 2007 | }) |
| 1866 | - .cloned() | |
| 1867 | 2008 | .collect(); |
| 1868 | 2009 | peers.sort_by_key(|peer| { |
| 1869 | 2010 | ( |
| 1870 | 2011 | peer.resident_cells, |
| 1871 | 2012 | peer.host_websockets, |
| 1872 | - peer.rss_bytes, | |
| 2013 | + peer.in_use_bytes.unwrap_or(peer.rss_bytes), | |
| 1873 | 2014 | handoff_tie_break(cell, &peer.node), |
| 1874 | 2015 | peer.node.clone(), |
| 1875 | 2016 | ) |
| 1876 | 2017 | }); |
| 1877 | - Ok(peers) | |
| 2018 | + peers | |
| 1878 | 2019 | } |
| 1879 | 2020 | |
| 1880 | 2021 | pub enum HandoffAttempt { |
| @@ -1925,6 +2066,8 @@ | ||
| 1925 | 2066 | pub activations: usize, |
| 1926 | 2067 | pub evictions: usize, |
| 1927 | 2068 | pub releases: usize, |
| 2069 | + /// The ownership share this node publishes for rebalancing. | |
| 2070 | + pub placement_weight: u64, | |
| 1928 | 2071 | } |
| 1929 | 2072 | |
| 1930 | 2073 | pub struct ActorIdentity { |
| @@ -1933,6 +2076,18 @@ | ||
| 1933 | 2076 | pub region: String, |
| 1934 | 2077 | } |
| 1935 | 2078 | |
| 2079 | +/// The test-only decision state that must be installed as one unit. | |
| 2080 | +/// | |
| 2081 | +/// A scripted Actor cannot read process-wide configuration while concurrent | |
| 2082 | +/// Worlds construct other nodes. The resume generation and the core | |
| 2083 | +/// configuration therefore travel together to the private constructor. | |
| 2084 | +#[cfg(all(test, celld_internal_tests))] | |
| 2085 | +pub(crate) struct ScriptedActorDecisionState { | |
| 2086 | + pub(crate) resume_generation: Option<String>, | |
| 2087 | + pub(crate) placement_weight: u64, | |
| 2088 | + pub(crate) config: Config, | |
| 2089 | +} | |
| 2090 | + | |
| 1936 | 2091 | pub struct ActorServices { |
| 1937 | 2092 | pub runtime: Option<RuntimeManager>, |
| 1938 | 2093 | pub drain_pins: DrainPinRegistry, |
| @@ -2043,6 +2198,61 @@ | ||
| 2043 | 2198 | .await |
| 2044 | 2199 | } |
| 2045 | 2200 | |
| 2201 | + /// Build the scripted Actor with one recorded core configuration. | |
| 2202 | + /// | |
| 2203 | + /// Concurrent node construction cannot safely mutate process-wide | |
| 2204 | + /// environment variables. Build the ordinary scripted shell first, then | |
| 2205 | + /// install the supplied configuration in both the unstarted decision core | |
| 2206 | + /// and the shell fields that consume it. The shell services, ownership, | |
| 2207 | + /// and host boundary stay identical to the ordinary constructor. | |
| 2208 | + #[cfg(all(test, celld_internal_tests))] | |
| 2209 | + pub(crate) async fn from_environment_with_scripted_host_and_config( | |
| 2210 | + fail_publish_once: bool, | |
| 2211 | + fence: mpsc::UnboundedSender<i32>, | |
| 2212 | + host: crate::conformance_sim_cell_host::SimCellHost, | |
| 2213 | + ownership: Option<Ownership>, | |
| 2214 | + identity: ActorIdentity, | |
| 2215 | + decision_state: ScriptedActorDecisionState, | |
| 2216 | + ) -> anyhow::Result<Self> { | |
| 2217 | + let ScriptedActorDecisionState { | |
| 2218 | + resume_generation, | |
| 2219 | + placement_weight, | |
| 2220 | + config, | |
| 2221 | + } = decision_state; | |
| 2222 | + let operation_deadline_ms = config | |
| 2223 | + .operation_deadline_ms | |
| 2224 | + .filter(|deadline| *deadline > 0) | |
| 2225 | + .ok_or_else(|| { | |
| 2226 | + anyhow::anyhow!( | |
| 2227 | + "the scripted Actor configuration requires a positive operation deadline" | |
| 2228 | + ) | |
| 2229 | + })?; | |
| 2230 | + let limits = AdmissionLimits { | |
| 2231 | + resident: config.max_resident, | |
| 2232 | + activations: config.max_activations, | |
| 2233 | + evictions: config.max_evictions, | |
| 2234 | + releases: config.max_releases, | |
| 2235 | + placement_weight, | |
| 2236 | + }; | |
| 2237 | + let node = identity.node.clone(); | |
| 2238 | + let mut actor = Self::from_environment_with_scripted_host( | |
| 2239 | + limits, | |
| 2240 | + fail_publish_once, | |
| 2241 | + fence, | |
| 2242 | + host, | |
| 2243 | + ownership, | |
| 2244 | + identity, | |
| 2245 | + resume_generation, | |
| 2246 | + ) | |
| 2247 | + .await?; | |
| 2248 | + // The shell uses this deadline for handoff and stop retries while the | |
| 2249 | + // core uses the same value to arm operation timers. Installing only | |
| 2250 | + // the core configuration creates two different clocks in one Actor. | |
| 2251 | + actor.operation_deadline_ms = operation_deadline_ms; | |
| 2252 | + actor.state = ActorState::from(State::new(node, config)); | |
| 2253 | + Ok(actor) | |
| 2254 | + } | |
| 2255 | + | |
| 2046 | 2256 | async fn from_environment_with_cell_host( |
| 2047 | 2257 | limits: AdmissionLimits, |
| 2048 | 2258 | fail_publish_once: bool, |
| @@ -2079,6 +2289,8 @@ | ||
| 2079 | 2289 | Ownership::Memory(_) => None, |
| 2080 | 2290 | }; |
| 2081 | 2291 | if let Some(live) = &live_load { |
| 2292 | + live.placement_weight | |
| 2293 | + .store(limits.placement_weight.max(1), Ordering::Relaxed); | |
| 2082 | 2294 | crate::ownership_store::set_node_load(live.clone()); |
| 2083 | 2295 | } |
| 2084 | 2296 | let process_generation = match &ownership { |
| @@ -2089,6 +2301,7 @@ | ||
| 2089 | 2301 | Ownership::Memory(_) => random_process_generation(), |
| 2090 | 2302 | }; |
| 2091 | 2303 | let ttl_ms = crate::env_vars::positive_or("CELLD_TTL_MS", 10_000)?; |
| 2304 | + let operation_deadline_ms = operation_deadline_ms()?; | |
| 2092 | 2305 | let lease_spec = NodeLeaseSpec { |
| 2093 | 2306 | // Startup has already resolved the environment and CLI settings |
| 2094 | 2307 | // into this validated internal address. Reading the environment |
| @@ -2112,7 +2325,15 @@ | ||
| 2112 | 2325 | alarm_resident_ms: crate::wake::resident_ms().max(0) as u64, |
| 2113 | 2326 | require_node_lease: true, |
| 2114 | 2327 | peer_protocol: crate::peer_auth::PROTOCOL_VERSION, |
| 2115 | - operation_deadline_ms: Some(operation_deadline_ms()?), | |
| 2328 | + operation_deadline_ms: Some(operation_deadline_ms), | |
| 2329 | + owner_log_recovery_backoff_ms: crate::env_vars::positive_or( | |
| 2330 | + "CELLD_RECOVERY_RETRY_MS", | |
| 2331 | + DEFAULT_OWNER_LOG_RECOVERY_BACKOFF_MS, | |
| 2332 | + )?, | |
| 2333 | + owner_log_recovery_attempts: crate::env_vars::positive_or( | |
| 2334 | + "CELLD_RECOVERY_RETRIES", | |
| 2335 | + DEFAULT_OWNER_LOG_RECOVERY_ATTEMPTS, | |
| 2336 | + )?, | |
| 2116 | 2337 | idle_evict_ms: crate::env_vars::positive::<u64>("CELLD_IDLE_EVICT_S")? |
| 2117 | 2338 | .map(|seconds| seconds.saturating_mul(1_000)), |
| 2118 | 2339 | pressure: pressure_config_from_environment()?, |
| @@ -2135,6 +2356,7 @@ | ||
| 2135 | 2356 | peer_http, |
| 2136 | 2357 | peer_auth, |
| 2137 | 2358 | paced_handoff, |
| 2359 | + operation_deadline_ms, | |
| 2138 | 2360 | handoff_directory: Arc::new(Mutex::new(HandoffDirectory::default())), |
| 2139 | 2361 | host, |
| 2140 | 2362 | drain_pins, |
| @@ -2301,6 +2523,8 @@ | ||
| 2301 | 2523 | self.drive(Event::WorkerRequest { request }, out); |
| 2302 | 2524 | } |
| 2303 | 2525 | Message::ReleaseAll => self.drive(Event::ReleaseAll, out), |
| 2526 | + Message::Rebalance { .. } if self.preserving => {} | |
| 2527 | + Message::Rebalance { cells } => self.drive(Event::Rebalance { cells }, out), | |
| 2304 | 2528 | Message::GenerationChanged { |
| 2305 | 2529 | generation, |
| 2306 | 2530 | max_age_ms, |
| @@ -2390,6 +2614,10 @@ | ||
| 2390 | 2614 | // latch just saw: a node that reports last tick's residency |
| 2391 | 2615 | // attracts work it has already refused. |
| 2392 | 2616 | if let Some(live) = &self.live_load { |
| 2617 | + live.owned_cells | |
| 2618 | + .store(self.state.owned_cells(), Ordering::Relaxed); | |
| 2619 | + live.ownership_confirmed | |
| 2620 | + .store(self.state.ownership_confirmed(), Ordering::Relaxed); | |
| 2393 | 2621 | live.resident_cells.store(occupied, Ordering::Relaxed); |
| 2394 | 2622 | live.host_websockets |
| 2395 | 2623 | .store(self.state.host_websockets(), Ordering::Relaxed); |
| @@ -2400,21 +2628,30 @@ | ||
| 2400 | 2628 | live.cpu_percent_x100.store(cpu, Ordering::Relaxed); |
| 2401 | 2629 | live.restoring |
| 2402 | 2630 | .store(self.state.activation_backlog() as u64, Ordering::Relaxed); |
| 2631 | + live.draining | |
| 2632 | + .store(self.state.draining(), Ordering::Relaxed); | |
| 2403 | 2633 | } |
| 2404 | 2634 | } |
| 2405 | 2635 | Message::Output { |
| 2406 | 2636 | request, |
| 2407 | - channel, | |
| 2408 | - position, | |
| 2637 | + ticket, | |
| 2409 | 2638 | reply, |
| 2410 | 2639 | } => { |
| 2411 | - self.gated_responses | |
| 2412 | - .insert(HeldOutputKey { request, channel }, reply); | |
| 2640 | + self.gated_responses.insert( | |
| 2641 | + HeldOutputKey { | |
| 2642 | + request, | |
| 2643 | + channel: ticket.channel, | |
| 2644 | + }, | |
| 2645 | + reply, | |
| 2646 | + ); | |
| 2413 | 2647 | self.drive( |
| 2414 | - Event::Output { | |
| 2648 | + Event::OutputAt { | |
| 2415 | 2649 | request, |
| 2416 | - channel, | |
| 2417 | - position, | |
| 2650 | + channel: ticket.channel, | |
| 2651 | + position: ticket.position, | |
| 2652 | + observed: ticket.observed, | |
| 2653 | + epoch: ticket.epoch, | |
| 2654 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2418 | 2655 | }, |
| 2419 | 2656 | out, |
| 2420 | 2657 | ); |
| @@ -2424,6 +2661,7 @@ | ||
| 2424 | 2661 | scope, |
| 2425 | 2662 | frames, |
| 2426 | 2663 | write_position, |
| 2664 | + observed, | |
| 2427 | 2665 | reply, |
| 2428 | 2666 | } => { |
| 2429 | 2667 | // Open a barrier for every batch, then let the core decide |
| @@ -2457,10 +2695,13 @@ | ||
| 2457 | 2695 | // alarm: its consuming commit opens a barrier of its own, so a |
| 2458 | 2696 | // read-only batch trails that too. |
| 2459 | 2697 | self.drive( |
| 2460 | - Event::Output { | |
| 2698 | + Event::OutputAt { | |
| 2461 | 2699 | request, |
| 2462 | 2700 | channel: Channel::WsHibernatable, |
| 2463 | 2701 | position: write_position, |
| 2702 | + observed, | |
| 2703 | + epoch: None, | |
| 2704 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2464 | 2705 | }, |
| 2465 | 2706 | out, |
| 2466 | 2707 | ); |
| @@ -2564,10 +2805,16 @@ | ||
| 2564 | 2805 | ); |
| 2565 | 2806 | } |
| 2566 | 2807 | Message::WakeHint { .. } if self.preserving => {} |
| 2567 | - Message::WakeHint { cell } => { | |
| 2808 | + Message::WakeHint { | |
| 2809 | + cell, | |
| 2810 | + entry_ms, | |
| 2811 | + scope, | |
| 2812 | + } => { | |
| 2568 | 2813 | self.drive( |
| 2569 | 2814 | Event::WakeHintAt { |
| 2570 | 2815 | cell, |
| 2816 | + entry_ms, | |
| 2817 | + scope, | |
| 2571 | 2818 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2572 | 2819 | }, |
| 2573 | 2820 | out, |
| @@ -2756,8 +3003,11 @@ | ||
| 2756 | 3003 | } => Some(*op), |
| 2757 | 3004 | _ => None, |
| 2758 | 3005 | }; |
| 3006 | + // A bounded stop that gave up also ends the eviction the | |
| 3007 | + // waiters asked about; without this branch `/evict/` waited | |
| 3008 | + // forever on a cell that had already restarted in place. | |
| 2759 | 3009 | let stopped = match &event { |
| 2760 | - Event::RuntimeStopped { op } => Some(*op), | |
| 3010 | + Event::RuntimeStopped { op } | Event::RuntimeStopFailed { op } => Some(*op), | |
| 2761 | 3011 | _ => None, |
| 2762 | 3012 | }; |
| 2763 | 3013 | let effects = apply_core_event(&mut self.state, event); |
| @@ -3043,13 +3293,14 @@ | ||
| 3043 | 3293 | let timing_cell = cell; |
| 3044 | 3294 | out.effects.push(Box::pin(async move { |
| 3045 | 3295 | let started = crate::asyncrt::mono_ms(); |
| 3046 | - let result = ownership.read_capacity_peers().await; | |
| 3296 | + // The shared sample, judged at the instant it was taken: | |
| 3297 | + // its leases are copies that age while the nodes renew. | |
| 3298 | + let (now_ms, result) = match ownership.read_capacity_view().await { | |
| 3299 | + Ok((view_ms, peers)) => (view_ms, Ok(peers)), | |
| 3300 | + Err(error) => (now_ms(), Err(error)), | |
| 3301 | + }; | |
| 3047 | 3302 | CompletedEffect::timed( |
| 3048 | - Event::CapacityPeersRead { | |
| 3049 | - op, | |
| 3050 | - now_ms: now_ms(), | |
| 3051 | - result, | |
| 3052 | - }, | |
| 3303 | + Event::CapacityPeersRead { op, now_ms, result }, | |
| 3053 | 3304 | timing_cell, |
| 3054 | 3305 | RouteStage::CapacityLookup, |
| 3055 | 3306 | started, |
| @@ -3082,6 +3333,9 @@ | ||
| 3082 | 3333 | ) |
| 3083 | 3334 | })); |
| 3084 | 3335 | } |
| 3336 | + Effect::AdoptWakeEntry { cell, entry_ms } => { | |
| 3337 | + crate::js::adopt_wake_entry(&cell, entry_ms); | |
| 3338 | + } | |
| 3085 | 3339 | Effect::ReconcileWakeEntry { |
| 3086 | 3340 | cell, |
| 3087 | 3341 | next_alarm_ms, |
| @@ -3141,6 +3395,7 @@ | ||
| 3141 | 3395 | op, |
| 3142 | 3396 | cell, |
| 3143 | 3397 | released_epoch, |
| 3398 | + rebalance, | |
| 3144 | 3399 | } => { |
| 3145 | 3400 | // The in-memory adapter is one process, so it has no successor |
| 3146 | 3401 | // to acknowledge a handoff. The feature switch is an escape |
| @@ -3163,6 +3418,12 @@ | ||
| 3163 | 3418 | let http = self.peer_http.clone(); |
| 3164 | 3419 | let auth = self.peer_auth.clone(); |
| 3165 | 3420 | let source = self.state.node().to_string(); |
| 3421 | + // A drain retries until the process deadline ends it. A | |
| 3422 | + // balancing move has no such end, so it fails after the | |
| 3423 | + // operation deadline and the cell stays unowned for the | |
| 3424 | + // next request to claim. | |
| 3425 | + let deadline = | |
| 3426 | + rebalance.then(|| std::time::Duration::from_millis(self.operation_deadline_ms)); | |
| 3166 | 3427 | out.effects.push(Box::pin(async move { |
| 3167 | 3428 | let started_mono_ms = crate::asyncrt::mono_ms(); |
| 3168 | 3429 | let request = HandoffRequest { |
| @@ -3170,10 +3431,11 @@ | ||
| 3170 | 3431 | released_epoch, |
| 3171 | 3432 | }; |
| 3172 | 3433 | let mut attempts = 0_u64; |
| 3173 | - loop { | |
| 3174 | - let peers = handoff_candidates(&ownership, &directory, &source, &cell) | |
| 3175 | - .await | |
| 3176 | - .unwrap_or_default(); | |
| 3434 | + let adoption = async { loop { | |
| 3435 | + let peers = | |
| 3436 | + handoff_candidates(&ownership, &directory, &source, &cell, rebalance) | |
| 3437 | + .await | |
| 3438 | + .unwrap_or_default(); | |
| 3177 | 3439 | for peer in peers { |
| 3178 | 3440 | let mut target = AdoptedCell { |
| 3179 | 3441 | node: peer.node, |
| @@ -3223,6 +3485,27 @@ | ||
| 3223 | 3485 | // No peer can accept yet. Retain the core permit and |
| 3224 | 3486 | // retry until the process-wide shutdown deadline. |
| 3225 | 3487 | crate::asyncrt::sleep(HANDOFF_RETRY_DELAY).await; |
| 3488 | + } }; | |
| 3489 | + match deadline { | |
| 3490 | + Some(deadline) => crate::asyncrt::timeout(deadline, adoption) | |
| 3491 | + .await | |
| 3492 | + .unwrap_or_else(|_| { | |
| 3493 | + // The cell is left unowned and its next request | |
| 3494 | + // re-reads ownership; the donor's counter shows | |
| 3495 | + // it, and this names the cell and the wait. | |
| 3496 | + tracing::warn!( | |
| 3497 | + event = "rebalance_adoption_timed_out", | |
| 3498 | + %cell, | |
| 3499 | + released_epoch, | |
| 3500 | + deadline_ms = deadline.as_millis() as u64, | |
| 3501 | + "no peer acquired a balanced cell before the deadline" | |
| 3502 | + ); | |
| 3503 | + CompletedEffect::plain(Event::SuccessorAdopted { | |
| 3504 | + op, | |
| 3505 | + result: Err(Failure::Definite), | |
| 3506 | + }) | |
| 3507 | + }), | |
| 3508 | + None => adoption.await, | |
| 3226 | 3509 | } |
| 3227 | 3510 | })); |
| 3228 | 3511 | } |
| @@ -3230,6 +3513,7 @@ | ||
| 3230 | 3513 | cell, |
| 3231 | 3514 | requests, |
| 3232 | 3515 | websockets, |
| 3516 | + alarm, | |
| 3233 | 3517 | keep_hibernatable, |
| 3234 | 3518 | } => { |
| 3235 | 3519 | self.handoff_timings |
| @@ -3242,17 +3526,21 @@ | ||
| 3242 | 3526 | release_us: None, |
| 3243 | 3527 | }); |
| 3244 | 3528 | for request in requests { |
| 3245 | - if let Some((request_id, phase)) = self | |
| 3529 | + if let Some((request_id, _)) = self | |
| 3246 | 3530 | .drain_pins |
| 3247 | 3531 | .cancel_core_request(request, "shutdown_quiesce") |
| 3248 | 3532 | { |
| 3249 | - if phase == "handler" { | |
| 3250 | - if let (Some(runtime), Some(request_id)) = (&self.host, request_id) { | |
| 3251 | - runtime.abort_fetch(&cell, request_id); | |
| 3252 | - } | |
| 3533 | + // The handler can answer before its output gate or | |
| 3534 | + // waitUntil work settles. Cancel every pinned phase, | |
| 3535 | + // or that background work can outlive the donor. | |
| 3536 | + if let (Some(runtime), Some(request_id)) = (&self.host, request_id) { | |
| 3537 | + runtime.abort_activity(request_id); | |
| 3253 | 3538 | } |
| 3254 | 3539 | } |
| 3255 | 3540 | } |
| 3541 | + if let (Some(runtime), Some(op)) = (&self.host, alarm) { | |
| 3542 | + runtime.abort_alarm(&cell, op); | |
| 3543 | + } | |
| 3256 | 3544 | if !websockets.is_empty() { |
| 3257 | 3545 | if keep_hibernatable { |
| 3258 | 3546 | for websocket in &websockets { |
| @@ -3269,6 +3557,48 @@ | ||
| 3269 | 3557 | }); |
| 3270 | 3558 | } |
| 3271 | 3559 | } |
| 3560 | + // The arm gate can finish after the core's earlier alarm | |
| 3561 | + // observation. Refresh once when the cell enters the handoff | |
| 3562 | + // cohort, under the same registry ordering as the reporter. | |
| 3563 | + // An uncovered alarm needs more than another cache read: the | |
| 3564 | + // successor stays dormant after adoption, so await the wake | |
| 3565 | + // entry PUT before telling the core this cell can leave. | |
| 3566 | + if let Some(runtime) = self.host.clone() { | |
| 3567 | + match runtime.alarm_observation(&cell) { | |
| 3568 | + Some((Some(at_ms), false)) => { | |
| 3569 | + out.effects.push(Box::pin(async move { | |
| 3570 | + let started = crate::asyncrt::mono_ms(); | |
| 3571 | + let (observed, covered) = runtime | |
| 3572 | + .refresh_handoff_alarm_coverage(&cell, at_ms) | |
| 3573 | + .await | |
| 3574 | + .unwrap_or((Some(at_ms), false)); | |
| 3575 | + tracing::info!( | |
| 3576 | + event = "handoff_alarm_coverage", | |
| 3577 | + %cell, | |
| 3578 | + at_ms, | |
| 3579 | + covered, | |
| 3580 | + elapsed_ms = crate::asyncrt::mono_ms().saturating_sub(started), | |
| 3581 | + "refreshed alarm coverage for graceful handoff" | |
| 3582 | + ); | |
| 3583 | + CompletedEffect::plain(Event::AlarmObserved { | |
| 3584 | + cell, | |
| 3585 | + at_ms: observed, | |
| 3586 | + covered, | |
| 3587 | + now_ms: now_ms(), | |
| 3588 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 3589 | + }) | |
| 3590 | + })); | |
| 3591 | + } | |
| 3592 | + Some((at_ms, covered)) => immediate.push_back(Event::AlarmObserved { | |
| 3593 | + cell, | |
| 3594 | + at_ms, | |
| 3595 | + covered, | |
| 3596 | + now_ms: now_ms(), | |
| 3597 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 3598 | + }), | |
| 3599 | + None => {} | |
| 3600 | + } | |
| 3601 | + } | |
| 3272 | 3602 | } |
| 3273 | 3603 | Effect::Restore { op, cell, spec } => { |
| 3274 | 3604 | self.route_effect_started(&cell); |
| @@ -3405,7 +3735,13 @@ | ||
| 3405 | 3735 | let waiters = self.eviction_waiters.remove(&cell).unwrap_or_default(); |
| 3406 | 3736 | self.durability_waiters.insert(op, (cell.clone(), waiters)); |
| 3407 | 3737 | if let Some(runtime) = self.host.clone() { |
| 3408 | - out.effects.push(Box::pin(async move { | |
| 3738 | + // A hot cell can merge thousands of staged LTX rows while | |
| 3739 | + // this future is between awaits. Keep that synchronous | |
| 3740 | + // merge on the host runtime: `out` is polled by the | |
| 3741 | + // dedicated core thread, which also owns the node-lease | |
| 3742 | + // renew and fence timers. Polling the proof inline can | |
| 3743 | + // therefore turn a graceful handoff into a self-fence. | |
| 3744 | + let task = crate::asyncrt::spawn(async move { | |
| 3409 | 3745 | let result = runtime.ensure_durable(&cell, epoch).await.map_err(|error| { |
| 3410 | 3746 | eprintln!( |
| 3411 | 3747 | "celld durability proof failed for {cell} epoch {epoch}: {error:#}" |
| @@ -3413,6 +3749,9 @@ | ||
| 3413 | 3749 | Failure::Ambiguous |
| 3414 | 3750 | }); |
| 3415 | 3751 | CompletedEffect::plain(Event::DurabilityChecked { op, result }) |
| 3752 | + }); | |
| 3753 | + out.effects.push(Box::pin(async move { | |
| 3754 | + task.await.expect("durability proof task panicked") | |
| 3416 | 3755 | })); |
| 3417 | 3756 | } else { |
| 3418 | 3757 | immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) }); |
| @@ -3488,10 +3827,12 @@ | ||
| 3488 | 3827 | })); |
| 3489 | 3828 | } |
| 3490 | 3829 | // The shell's only per-channel code: how the effect was held, and |
| 3491 | - // how it is released. Five of the six channels take a durability | |
| 3492 | - // ticket and wait on a oneshot, so they collapse onto one adapter. | |
| 3493 | - // Only `WsHibernatable` needs another, and only because a socket is | |
| 3494 | - // an ordered stream whose frames must drain in barrier order. | |
| 3830 | + // how it is released. Every channel but one takes a durability | |
| 3831 | + // ticket and waits on a oneshot, so they collapse onto one adapter; | |
| 3832 | + // `Sync` holds nothing but the ticket itself, because the effect it | |
| 3833 | + // releases is the handler's promise. Only `WsHibernatable` needs | |
| 3834 | + // another, and only because a socket is an ordered stream whose | |
| 3835 | + // frames must drain in barrier order. | |
| 3495 | 3836 | // |
| 3496 | 3837 | // The channel says which way the effect leaves; `ws_gated` says how |
| 3497 | 3838 | // this one is being held. They agree except in one case, and there |
| @@ -3517,7 +3858,8 @@ | ||
| 3517 | 3858 | | Channel::WsSelf |
| 3518 | 3859 | | Channel::Service |
| 3519 | 3860 | | Channel::CellRpc |
| 3520 | - | Channel::Queue => { | |
| 3861 | + | Channel::Queue | |
| 3862 | + | Channel::Sync => { | |
| 3521 | 3863 | if let Some(reply) = self.gated_responses.remove(&held) { |
| 3522 | 3864 | let _ = reply.send(result); |
| 3523 | 3865 | } |
| @@ -3529,6 +3871,7 @@ | ||
| 3529 | 3871 | cell, |
| 3530 | 3872 | epoch, |
| 3531 | 3873 | cause, |
| 3874 | + bounded, | |
| 3532 | 3875 | } => { |
| 3533 | 3876 | if self.handoff_timings.contains_key(&cell) { |
| 3534 | 3877 | self.handoff_phase_ops.insert( |
| @@ -3551,6 +3894,7 @@ | ||
| 3551 | 3894 | cell, |
| 3552 | 3895 | epoch, |
| 3553 | 3896 | "generation_swap_out_retry", |
| 3897 | + None, | |
| 3554 | 3898 | move || { |
| 3555 | 3899 | let runtime = runtime.clone(); |
| 3556 | 3900 | let cell = released.clone(); |
| @@ -3600,11 +3944,15 @@ | ||
| 3600 | 3944 | // core thread starves the lease renew and the lease fence, |
| 3601 | 3945 | // and the node then fences itself. |
| 3602 | 3946 | let released = cell.clone(); |
| 3947 | + let deadline_mono_ms = bounded.then(|| { | |
| 3948 | + crate::asyncrt::mono_ms().saturating_add(self.operation_deadline_ms) | |
| 3949 | + }); | |
| 3603 | 3950 | let task = crate::asyncrt::spawn(report_stopped_when_released( |
| 3604 | 3951 | op, |
| 3605 | 3952 | cell, |
| 3606 | 3953 | epoch, |
| 3607 | 3954 | "stop_runtime_retry", |
| 3955 | + deadline_mono_ms, | |
| 3608 | 3956 | move || { |
| 3609 | 3957 | let runtime = runtime.clone(); |
| 3610 | 3958 | let cell = released.clone(); |
| @@ -3639,7 +3987,7 @@ | ||
| 3639 | 3987 | // re-arms or resets; either way the entry stays |
| 3640 | 3988 | // discoverable and at-least-once holds. |
| 3641 | 3989 | let result = runtime |
| 3642 | - .fire_alarm(cell.clone(), scheduled_ms) | |
| 3990 | + .fire_alarm(op, cell.clone(), scheduled_ms) | |
| 3643 | 3991 | .await |
| 3644 | 3992 | .map_err(|error| { |
| 3645 | 3993 | eprintln!("celld alarm dispatch failed: {error:#}"); |
| @@ -3737,6 +4085,16 @@ | ||
| 3737 | 4085 | code, |
| 3738 | 4086 | "SELF-FENCE: node lease not renewed within TTL — halting" |
| 3739 | 4087 | ), |
| 4088 | + celld_logic::HaltReason::NodeLeaseMissing => tracing::warn!( | |
| 4089 | + event = "node_lease_record_missing_fence", | |
| 4090 | + code, | |
| 4091 | + "SELF-FENCE: node lease record is missing — halting" | |
| 4092 | + ), | |
| 4093 | + celld_logic::HaltReason::NodeLeaseMismatch => tracing::warn!( | |
| 4094 | + event = "node_lease_record_mismatch_fence", | |
| 4095 | + code, | |
| 4096 | + "SELF-FENCE: node lease record no longer matches this process — halting" | |
| 4097 | + ), | |
| 3740 | 4098 | } |
| 3741 | 4099 | let _ = self.fence.send(code); |
| 3742 | 4100 | } |
| @@ -3744,6 +4102,20 @@ | ||
| 3744 | 4102 | } |
| 3745 | 4103 | |
| 3746 | 4104 | fn state_json(&self) -> String { |
| 4105 | + // The lease sample reads counts the load tick last stored. Store them | |
| 4106 | + // now, so the sample below agrees with the state beside it. | |
| 4107 | + let node_load = self.live_load.as_ref().map(|live| { | |
| 4108 | + live.owned_cells | |
| 4109 | + .store(self.state.owned_cells(), Ordering::Relaxed); | |
| 4110 | + live.ownership_confirmed | |
| 4111 | + .store(self.state.ownership_confirmed(), Ordering::Relaxed); | |
| 4112 | + live.resident_cells | |
| 4113 | + .store(self.state.occupied(), Ordering::Relaxed); | |
| 4114 | + live.host_websockets | |
| 4115 | + .store(self.state.host_websockets(), Ordering::Relaxed); | |
| 4116 | + serde_json::to_string(&crate::ownership_store::process_load(live)) | |
| 4117 | + .expect("node load serializes") | |
| 4118 | + }); | |
| 3747 | 4119 | let activity = self.state.presence_snapshot().activity; |
| 3748 | 4120 | let residents = self |
| 3749 | 4121 | .state |
| @@ -3776,8 +4148,9 @@ | ||
| 3776 | 4148 | .collect::<Vec<_>>() |
| 3777 | 4149 | .join(","); |
| 3778 | 4150 | format!( |
| 3779 | - "{{\"ownership\":{:?},\"occupied\":{},\"quiescing\":{},\"evicting\":{},\"releasing\":{},\"adopting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"handed_off\":{},\"handoff_failed\":{},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"cgroup_working_set_bytes\":{},\"cgroup_current_bytes\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}", | |
| 4151 | + "{{\"ownership\":{:?},\"owned_cells\":{},\"occupied\":{},\"quiescing\":{},\"evicting\":{},\"releasing\":{},\"adopting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"handed_off\":{},\"handoff_failed\":{},\"rebalanced\":{},\"rebalance_failed\":{},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"cgroup_working_set_bytes\":{},\"cgroup_current_bytes\":{},\"node_load\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}", | |
| 3780 | 4152 | self.ownership.name(), |
| 4153 | + self.state.owned_cells(), | |
| 3781 | 4154 | self.state.occupied(), |
| 3782 | 4155 | self.state.quiescing(), |
| 3783 | 4156 | self.state.evicting(), |
| @@ -3790,6 +4163,8 @@ | ||
| 3790 | 4163 | phases, |
| 3791 | 4164 | activity.handed_off, |
| 3792 | 4165 | activity.handoff_failed, |
| 4166 | + activity.rebalanced, | |
| 4167 | + activity.rebalance_failed, | |
| 3793 | 4168 | self.state |
| 3794 | 4169 | .shed_reason() |
| 3795 | 4170 | .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")), |
| @@ -3801,6 +4176,7 @@ | ||
| 3801 | 4176 | memory |
| 3802 | 4177 | .cgroup_current_bytes |
| 3803 | 4178 | .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()), |
| 4179 | + node_load.unwrap_or_else(|| "null".to_string()), | |
| 3804 | 4180 | residents, |
| 3805 | 4181 | published, |
| 3806 | 4182 | self.publishes, |
modifiedcrates/celld/assets.rs+10−1View file
| @@ -404,6 +404,7 @@ | ||
| 404 | 404 | headers: vec![("content-type".into(), "text/plain; charset=utf-8".into())], |
| 405 | 405 | websocket: None, |
| 406 | 406 | write_position: None, |
| 407 | + observed_position: None, | |
| 407 | 408 | }); |
| 408 | 409 | } |
| 409 | 410 | let path = url::Url::parse(url).context("invalid assets binding URL")?; |
| @@ -455,6 +456,7 @@ | ||
| 455 | 456 | .collect(), |
| 456 | 457 | websocket: None, |
| 457 | 458 | write_position: None, |
| 459 | + observed_position: None, | |
| 458 | 460 | }) |
| 459 | 461 | } |
| 460 | 462 | |
| @@ -1366,7 +1368,7 @@ | ||
| 1366 | 1368 | } |
| 1367 | 1369 | let mut total = 0_u64; |
| 1368 | 1370 | for (path, entry) in &index.entries { |
| 1369 | - if decode_path(path).as_deref() != Some(path.as_str()) | |
| 1371 | + if !is_canonical_asset_path(path) | |
| 1370 | 1372 | || path == "/" |
| 1371 | 1373 | || asset_blob_key(&entry.sha256).is_none() |
| 1372 | 1374 | || entry.bytes > 25 * 1024 * 1024 |
| @@ -1409,6 +1411,13 @@ | ||
| 1409 | 1411 | Some(decoded) |
| 1410 | 1412 | } |
| 1411 | 1413 | |
| 1414 | +/// A stored path must survive request-path decoding unchanged. The deployer | |
| 1415 | +/// uses this same predicate because publishing an index with a second decoded | |
| 1416 | +/// spelling would make every node reject the complete deployment. | |
| 1417 | +pub(crate) fn is_canonical_asset_path(path: &str) -> bool { | |
| 1418 | + decode_path(path).as_deref() == Some(path) | |
| 1419 | +} | |
| 1420 | + | |
| 1412 | 1421 | fn route_pattern_matches(pattern: &str, path: &str) -> bool { |
| 1413 | 1422 | let mut expression = String::from("^"); |
| 1414 | 1423 | for part in pattern.split('*') { |
modifiedcrates/celld/asyncrt.rs+168−18View file
| @@ -13,25 +13,27 @@ | ||
| 13 | 13 | use crate::host_services::HostServices; |
| 14 | 14 | use rand::{CryptoRng, RngCore}; |
| 15 | 15 | use std::cell::RefCell; |
| 16 | +use std::collections::HashMap; | |
| 16 | 17 | use std::fmt; |
| 17 | 18 | use std::future::{poll_fn, Future}; |
| 18 | 19 | use std::pin::Pin; |
| 19 | 20 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 20 | -use std::sync::{Arc, OnceLock}; | |
| 21 | +use std::sync::{Arc, Mutex, OnceLock, Weak}; | |
| 21 | 22 | use std::task::{Context, Poll}; |
| 22 | 23 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 23 | 24 | |
| 24 | 25 | static PROCESS_DOMAIN: OnceLock<ProductionDomain> = OnceLock::new(); |
| 25 | 26 | static FALLBACK_SERVICES: OnceLock<Arc<HostServices>> = OnceLock::new(); |
| 27 | +static RUNTIME_SERVICES: OnceLock<Mutex<HashMap<tokio::runtime::Id, Weak<HostServices>>>> = | |
| 28 | + OnceLock::new(); | |
| 26 | 29 | static SELECT_STATE: OnceLock<AtomicU64> = OnceLock::new(); |
| 27 | 30 | |
| 28 | 31 | thread_local! { |
| 29 | - static SPAWNS: RefCell<Vec<(u64, OpFuture)>> = const { RefCell::new(Vec::new()) }; | |
| 32 | + static SPAWNS: RefCell<Vec<(u64, OpFuture, OpLifetime)>> = const { RefCell::new(Vec::new()) }; | |
| 30 | 33 | } |
| 31 | 34 | |
| 32 | 35 | struct ProductionDomain { |
| 33 | - handle: tokio::runtime::Handle, | |
| 34 | - started_at: Instant, | |
| 36 | + owner: Arc<ProductionDomainOwner>, | |
| 35 | 37 | services: Arc<HostServices>, |
| 36 | 38 | filesystem: Arc<dyn celld_ltx::FileSystem>, |
| 37 | 39 | next_core_request: AtomicU64, |
| @@ -41,10 +43,13 @@ | ||
| 41 | 43 | |
| 42 | 44 | impl ProductionDomain { |
| 43 | 45 | fn new(handle: tokio::runtime::Handle) -> Self { |
| 46 | + let owner = Arc::new(ProductionDomainOwner::new(handle)); | |
| 47 | + let token = DomainToken::new(&owner); | |
| 48 | + let services = Arc::new(HostServices::production()); | |
| 49 | + services.bind_domain(token.clone()); | |
| 44 | 50 | Self { |
| 45 | - handle, | |
| 46 | - started_at: Instant::now(), | |
| 47 | - services: Arc::new(HostServices::production()), | |
| 51 | + owner, | |
| 52 | + services, | |
| 48 | 53 | filesystem: Arc::new(celld_ltx::DirectFileSystem), |
| 49 | 54 | next_core_request: AtomicU64::new(1), |
| 50 | 55 | next_async_op: AtomicU64::new(1), |
| @@ -57,6 +62,85 @@ | ||
| 57 | 62 | PROCESS_DOMAIN.get_or_init(|| ProductionDomain::new(tokio::runtime::Handle::current())) |
| 58 | 63 | } |
| 59 | 64 | |
| 65 | +struct ProductionDomainOwner { | |
| 66 | + handle: tokio::runtime::Handle, | |
| 67 | + started_at: Instant, | |
| 68 | +} | |
| 69 | + | |
| 70 | +impl ProductionDomainOwner { | |
| 71 | + fn new(handle: tokio::runtime::Handle) -> Self { | |
| 72 | + Self { | |
| 73 | + handle, | |
| 74 | + started_at: Instant::now(), | |
| 75 | + } | |
| 76 | + } | |
| 77 | +} | |
| 78 | + | |
| 79 | +/// A cloneable capability for scheduling work on one execution domain. | |
| 80 | +#[derive(Clone)] | |
| 81 | +pub(crate) struct DomainToken { | |
| 82 | + inner: Weak<ProductionDomainOwner>, | |
| 83 | +} | |
| 84 | + | |
| 85 | +/// The execution domain no longer accepts work. | |
| 86 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 87 | +pub(crate) struct DomainClosed; | |
| 88 | + | |
| 89 | +impl fmt::Display for DomainClosed { | |
| 90 | + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| 91 | + formatter.write_str("execution domain is closed") | |
| 92 | + } | |
| 93 | +} | |
| 94 | + | |
| 95 | +impl std::error::Error for DomainClosed {} | |
| 96 | + | |
| 97 | +impl DomainToken { | |
| 98 | + fn new(owner: &Arc<ProductionDomainOwner>) -> Self { | |
| 99 | + Self { | |
| 100 | + inner: Arc::downgrade(owner), | |
| 101 | + } | |
| 102 | + } | |
| 103 | + | |
| 104 | + fn owner(&self) -> Result<Arc<ProductionDomainOwner>, DomainClosed> { | |
| 105 | + self.inner.upgrade().ok_or(DomainClosed) | |
| 106 | + } | |
| 107 | + | |
| 108 | + pub(crate) fn same_owner(&self, other: &Self) -> bool { | |
| 109 | + Weak::ptr_eq(&self.inner, &other.inner) | |
| 110 | + } | |
| 111 | + | |
| 112 | + pub(crate) fn mono_ms(&self) -> Result<u64, DomainClosed> { | |
| 113 | + Ok(self.owner()?.started_at.elapsed().as_millis() as u64) | |
| 114 | + } | |
| 115 | + | |
| 116 | + pub(crate) fn sleep_until(&self, deadline_ms: u64) -> Result<Sleep, DomainClosed> { | |
| 117 | + let owner = self.owner()?; | |
| 118 | + let now_ms = owner.started_at.elapsed().as_millis() as u64; | |
| 119 | + let wait = Duration::from_millis(deadline_ms.saturating_sub(now_ms)); | |
| 120 | + // Tokio binds a sleep to the current timer driver when it constructs | |
| 121 | + // the future. Enter this token's runtime so an ambient runtime cannot | |
| 122 | + // capture a timer that belongs to another execution domain. | |
| 123 | + let _entered = owner.handle.enter(); | |
| 124 | + Ok(Box::pin(tokio::time::sleep(wait))) | |
| 125 | + } | |
| 126 | + | |
| 127 | + #[track_caller] | |
| 128 | + pub(crate) fn spawn_detached<T, F>( | |
| 129 | + &self, | |
| 130 | + _root: impl Into<String>, | |
| 131 | + future: F, | |
| 132 | + ) -> Result<TaskHandle<T>, DomainClosed> | |
| 133 | + where | |
| 134 | + T: Send + 'static, | |
| 135 | + F: Future<Output = T> + Send + 'static, | |
| 136 | + { | |
| 137 | + let owner = self.owner()?; | |
| 138 | + Ok(TaskHandle { | |
| 139 | + inner: owner.handle.spawn(future), | |
| 140 | + }) | |
| 141 | + } | |
| 142 | +} | |
| 143 | + | |
| 60 | 144 | /// A normalized task panic returned by a typed task handle. |
| 61 | 145 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 62 | 146 | pub struct TaskPanic { |
| @@ -104,7 +188,7 @@ | ||
| 104 | 188 | |
| 105 | 189 | /// Return the Tokio handle for the V8 arm. |
| 106 | 190 | pub fn op_handle() -> tokio::runtime::Handle { |
| 107 | - current_domain().handle.clone() | |
| 191 | + current_domain().owner.handle.clone() | |
| 108 | 192 | } |
| 109 | 193 | |
| 110 | 194 | pub fn spawn<T, F>(future: F) -> TaskHandle<T> |
| @@ -113,7 +197,7 @@ | ||
| 113 | 197 | F: Future<Output = T> + Send + 'static, |
| 114 | 198 | { |
| 115 | 199 | TaskHandle { |
| 116 | - inner: current_domain().handle.spawn(future), | |
| 200 | + inner: current_domain().owner.handle.spawn(future), | |
| 117 | 201 | } |
| 118 | 202 | } |
| 119 | 203 | |
| @@ -123,7 +207,7 @@ | ||
| 123 | 207 | F: FnOnce() -> T + Send + 'static, |
| 124 | 208 | { |
| 125 | 209 | TaskHandle { |
| 126 | - inner: current_domain().handle.spawn_blocking(operation), | |
| 210 | + inner: current_domain().owner.handle.spawn_blocking(operation), | |
| 127 | 211 | } |
| 128 | 212 | } |
| 129 | 213 | |
| @@ -132,7 +216,7 @@ | ||
| 132 | 216 | F: Future + Send + 'static, |
| 133 | 217 | F::Output: Send + 'static, |
| 134 | 218 | { |
| 135 | - current_domain().handle.block_on(future) | |
| 219 | + current_domain().owner.handle.block_on(future) | |
| 136 | 220 | } |
| 137 | 221 | |
| 138 | 222 | /// Return the local filesystem for the process. |
| @@ -154,12 +238,12 @@ | ||
| 154 | 238 | } |
| 155 | 239 | |
| 156 | 240 | pub fn mono_ms() -> u64 { |
| 157 | - current_domain().started_at.elapsed().as_millis() as u64 | |
| 241 | + current_domain().owner.started_at.elapsed().as_millis() as u64 | |
| 158 | 242 | } |
| 159 | 243 | |
| 160 | 244 | /// Return monotonic process time in microseconds for timing instrumentation. |
| 161 | 245 | pub fn mono_us() -> u64 { |
| 162 | - current_domain().started_at.elapsed().as_micros() as u64 | |
| 246 | + current_domain().owner.started_at.elapsed().as_micros() as u64 | |
| 163 | 247 | } |
| 164 | 248 | |
| 165 | 249 | pub fn rng(consumer: &'static str) -> rng::Stream { |
| @@ -207,6 +291,46 @@ | ||
| 207 | 291 | }) |
| 208 | 292 | } |
| 209 | 293 | |
| 294 | +/// Return services bound to the current runtime without installing a process domain. | |
| 295 | +pub(crate) fn runtime_services() -> Arc<HostServices> { | |
| 296 | + if let Some(domain) = PROCESS_DOMAIN.get() { | |
| 297 | + return domain.services.clone(); | |
| 298 | + } | |
| 299 | + let Ok(handle) = tokio::runtime::Handle::try_current() else { | |
| 300 | + return services(); | |
| 301 | + }; | |
| 302 | + let mut runtimes = RUNTIME_SERVICES | |
| 303 | + .get_or_init(|| Mutex::new(HashMap::new())) | |
| 304 | + .lock() | |
| 305 | + .unwrap(); | |
| 306 | + // The map owns each runtime ID even after its weak service expires. A | |
| 307 | + // caller can also retain a service after its runtime anchor closes, which | |
| 308 | + // leaves a live Arc with a dead owner token. Prune both states before an ID | |
| 309 | + // can resolve to services from an earlier runtime. | |
| 310 | + runtimes.retain(|_, services| { | |
| 311 | + services.upgrade().is_some_and(|services| { | |
| 312 | + services | |
| 313 | + .domain_token() | |
| 314 | + .is_some_and(|domain| domain.mono_ms().is_ok()) | |
| 315 | + }) | |
| 316 | + }); | |
| 317 | + if let Some(services) = runtimes.get(&handle.id()).and_then(Weak::upgrade) { | |
| 318 | + return services; | |
| 319 | + } | |
| 320 | + let owner = Arc::new(ProductionDomainOwner::new(handle.clone())); | |
| 321 | + let token = DomainToken::new(&owner); | |
| 322 | + let services = Arc::new(HostServices::production()); | |
| 323 | + services.bind_domain(token); | |
| 324 | + let anchor_services = services.clone(); | |
| 325 | + let anchor_owner = owner; | |
| 326 | + handle.spawn(async move { | |
| 327 | + std::future::pending::<()>().await; | |
| 328 | + drop((anchor_services, anchor_owner)); | |
| 329 | + }); | |
| 330 | + runtimes.insert(handle.id(), Arc::downgrade(&services)); | |
| 331 | + services | |
| 332 | +} | |
| 333 | + | |
| 210 | 334 | pub type Sleep = Pin<Box<dyn Future<Output = ()> + Send>>; |
| 211 | 335 | |
| 212 | 336 | pub fn sleep_until(deadline_ms: u64) -> Sleep { |
| @@ -330,22 +454,48 @@ | ||
| 330 | 454 | |
| 331 | 455 | pub type OpFuture = Pin<Box<dyn Future<Output = Result<OpOut, String>> + Send>>; |
| 332 | 456 | |
| 333 | -/// Register an asynchronous operation. The request driver polls the operation. | |
| 334 | -pub fn enqueue<T: Into<OpOut>>( | |
| 457 | +#[derive(Clone, Copy)] | |
| 458 | +enum OpLifetime { | |
| 459 | + Handler, | |
| 460 | + IoContext, | |
| 461 | +} | |
| 462 | + | |
| 463 | +fn enqueue_with_lifetime<T: Into<OpOut>>( | |
| 335 | 464 | future: impl Future<Output = Result<T, String>> + Send + 'static, |
| 465 | + lifetime: OpLifetime, | |
| 336 | 466 | ) -> u64 { |
| 337 | 467 | let id = current_domain() |
| 338 | 468 | .next_async_op |
| 339 | 469 | .fetch_add(1, Ordering::Relaxed); |
| 340 | 470 | let future: OpFuture = Box::pin(async move { future.await.map(Into::into) }); |
| 341 | - SPAWNS.with(|spawns| spawns.borrow_mut().push((id, future))); | |
| 471 | + SPAWNS.with(|spawns| spawns.borrow_mut().push((id, future, lifetime))); | |
| 342 | 472 | id |
| 343 | 473 | } |
| 344 | 474 | |
| 345 | -pub fn drain_spawns() -> Vec<(u64, OpFuture)> { | |
| 346 | - SPAWNS.with(|spawns| spawns.borrow_mut().drain(..).collect()) | |
| 475 | +/// Register an asynchronous operation. The request driver polls the operation. | |
| 476 | +pub fn enqueue<T: Into<OpOut>>( | |
| 477 | + future: impl Future<Output = Result<T, String>> + Send + 'static, | |
| 478 | +) -> u64 { | |
| 479 | + enqueue_with_lifetime(future, OpLifetime::Handler) | |
| 347 | 480 | } |
| 348 | 481 | |
| 482 | +/// Register an operation that keeps its `IoContext` alive after the handler ends. | |
| 483 | +pub(crate) fn enqueue_io_context<T: Into<OpOut>>( | |
| 484 | + future: impl Future<Output = Result<T, String>> + Send + 'static, | |
| 485 | +) -> u64 { | |
| 486 | + enqueue_with_lifetime(future, OpLifetime::IoContext) | |
| 487 | +} | |
| 488 | + | |
| 489 | +pub fn drain_spawns() -> Vec<(u64, OpFuture, bool)> { | |
| 490 | + SPAWNS.with(|spawns| { | |
| 491 | + spawns | |
| 492 | + .borrow_mut() | |
| 493 | + .drain(..) | |
| 494 | + .map(|(id, future, lifetime)| (id, future, matches!(lifetime, OpLifetime::IoContext))) | |
| 495 | + .collect() | |
| 496 | + }) | |
| 497 | +} | |
| 498 | + | |
| 349 | 499 | pub use crate::__celld_domain_select as select; |
| 350 | 500 | pub use crate::__celld_domain_select_biased as select_biased; |
| 351 | 501 |
modifiedcrates/celld/bucket.rs+278−36View file
| @@ -18,10 +18,12 @@ | ||
| 18 | 18 | //! read answers and a conditional write consumes. |
| 19 | 19 | //! |
| 20 | 20 | //! Error contract, relied on by the self-fence: `put_cas` answers |
| 21 | -//! `Ok(None)` only for a clean 412/409 rejection; every other failure is | |
| 22 | -//! ambiguous — the write may have committed — and surfaces as `Err`. | |
| 23 | -//! In the same spirit a response that carries no CAS token is an error, | |
| 24 | -//! never an empty token a later conditional write would trust. | |
| 21 | +//! `Ok(None)` only for a clean 412/409 rejection; every other failure | |
| 22 | +//! surfaces as `Err`. An `Err` is ambiguous — the write may have | |
| 23 | +//! committed — unless `cas_write_did_not_commit` recognizes an answer | |
| 24 | +//! that proves the store wrote no object. In the same spirit a response | |
| 25 | +//! that carries no CAS token is an error, never an empty token a later | |
| 26 | +//! conditional write would trust. | |
| 25 | 27 | |
| 26 | 28 | use anyhow::anyhow; |
| 27 | 29 | use anyhow::Context; |
| @@ -175,6 +177,12 @@ | ||
| 175 | 177 | pub page_token: Option<String>, |
| 176 | 178 | } |
| 177 | 179 | |
| 180 | +/// One bounded page of object descriptions from a recursive listing. | |
| 181 | +pub(crate) struct ObjectPage { | |
| 182 | + pub objects: Vec<ObjectMeta>, | |
| 183 | + pub page_token: Option<String>, | |
| 184 | +} | |
| 185 | + | |
| 178 | 186 | /// Whether a conditional write reached a provider-enforced conflict. |
| 179 | 187 | /// Azure reports a failed `If-None-Match` as `Precondition`, while some |
| 180 | 188 | /// stores report the same create conflict as `AlreadyExists`. Both are a |
| @@ -187,11 +195,51 @@ | ||
| 187 | 195 | ) |
| 188 | 196 | } |
| 189 | 197 | |
| 198 | +/// Whether a failed conditional write proves that the store holds no new | |
| 199 | +/// object. A caller that renews a lease uses this to skip the readback | |
| 200 | +/// that resolves an ambiguous write, because the readback costs a round | |
| 201 | +/// trip out of the authority a store blip is already eating. | |
| 202 | +/// | |
| 203 | +/// Every variant below is either a rejection the client made before it | |
| 204 | +/// sent a request, or a store answer that precedes the object write: | |
| 205 | +/// `object_store` maps 401 to `Unauthenticated` and 403 to | |
| 206 | +/// `PermissionDenied`, and each of the four object stores this engine | |
| 207 | +/// speaks to authorizes a `PUT` before it applies one. A `PUT` that | |
| 208 | +/// answers 404 reached no bucket, so it wrote nothing. | |
| 209 | +/// | |
| 210 | +/// `Error::Generic` is absent on purpose, and it carries every 5xx, every | |
| 211 | +/// timeout and every connection failure. A connection that never opened | |
| 212 | +/// also wrote nothing, but `object_store` 0.12 keeps `RetryError` (and so | |
| 213 | +/// the `Connect` error kind) private, so no public API separates it from | |
| 214 | +/// a 500 that can have committed. Matching the message text would decide | |
| 215 | +/// a lease fence on a string, therefore the whole variant stays ambiguous | |
| 216 | +/// until the upstream type is reachable. | |
| 217 | +#[doc(hidden)] | |
| 218 | +pub fn cas_write_did_not_commit(error: &anyhow::Error) -> bool { | |
| 219 | + // `put_cas` wraps the store error in context, so read the chain rather | |
| 220 | + // than the outermost error. A chain that carries no `object_store` | |
| 221 | + // error at all -- an applied write whose response had no CAS token -- | |
| 222 | + // does not match, which leaves it ambiguous. That is the safe answer. | |
| 223 | + error.downcast_ref::<Error>().is_some_and(|error| { | |
| 224 | + matches!( | |
| 225 | + error, | |
| 226 | + Error::Unauthenticated { .. } | |
| 227 | + | Error::PermissionDenied { .. } | |
| 228 | + | Error::NotFound { .. } | |
| 229 | + | Error::InvalidPath { .. } | |
| 230 | + | Error::NotSupported { .. } | |
| 231 | + | Error::NotImplemented | |
| 232 | + | Error::UnknownConfigurationKey { .. } | |
| 233 | + ) | |
| 234 | + }) | |
| 235 | +} | |
| 236 | + | |
| 190 | 237 | /// Split a `[s3://|gs://|az://]NAME[/PREFIX]` bucket spec into the |
| 191 | 238 | /// backend, the bucket name and a normalized key prefix: empty, or |
| 192 | 239 | /// slash-terminated. A spec without a scheme stays S3-compatible, and a |
| 193 | 240 | /// spec without a PREFIX keeps every key at the bucket root, so a fleet |
| 194 | 241 | /// provisioned before either existed never moves its objects. |
| 242 | +/// Scheme names are ASCII case-insensitive, as URI schemes require. | |
| 195 | 243 | /// |
| 196 | 244 | /// On `az://` the NAME is the container, and the storage account comes |
| 197 | 245 | /// from `AZURE_STORAGE_ACCOUNT_NAME`. The second path segment is the key |
| @@ -199,11 +247,20 @@ | ||
| 199 | 247 | /// making `az://` parse differently from the other two. |
| 200 | 248 | #[doc(hidden)] |
| 201 | 249 | pub fn split_spec(spec: &str) -> (StorageBackend, &str, String) { |
| 202 | - let (backend, spec) = match (spec.strip_prefix("gs://"), spec.strip_prefix("az://")) { | |
| 203 | - (Some(rest), _) => (StorageBackend::Gcs, rest), | |
| 204 | - (_, Some(rest)) => (StorageBackend::Azure, rest), | |
| 205 | - _ => (StorageBackend::S3, spec.trim_start_matches("s3://")), | |
| 250 | + let strip_scheme = |scheme: &str| { | |
| 251 | + spec.get(..scheme.len()) | |
| 252 | + .filter(|candidate| candidate.eq_ignore_ascii_case(scheme)) | |
| 253 | + .map(|_| &spec[scheme.len()..]) | |
| 206 | 254 | }; |
| 255 | + let (backend, spec) = if let Some(rest) = strip_scheme("gs://") { | |
| 256 | + (StorageBackend::Gcs, rest) | |
| 257 | + } else if let Some(rest) = strip_scheme("az://") { | |
| 258 | + (StorageBackend::Azure, rest) | |
| 259 | + } else if let Some(rest) = strip_scheme("s3://") { | |
| 260 | + (StorageBackend::S3, rest) | |
| 261 | + } else { | |
| 262 | + (StorageBackend::S3, spec) | |
| 263 | + }; | |
| 207 | 264 | let (name, prefix) = spec.split_once('/').unwrap_or((spec, "")); |
| 208 | 265 | let parts = prefix.split('/').filter(|part| !part.is_empty()); |
| 209 | 266 | ( |
| @@ -455,6 +512,24 @@ | ||
| 455 | 512 | } |
| 456 | 513 | |
| 457 | 514 | impl Bucket { |
| 515 | + /// Builds a bucket from separate ordinary and paginated stores. | |
| 516 | + #[cfg(celld_internal_tests)] | |
| 517 | + #[doc(hidden)] | |
| 518 | + pub fn with_paginated_store_for_test( | |
| 519 | + store: Arc<dyn ObjectStore>, | |
| 520 | + paginated: Arc<dyn PaginatedListStore>, | |
| 521 | + prefix: String, | |
| 522 | + ) -> Self { | |
| 523 | + Self { | |
| 524 | + cas_store: store.clone(), | |
| 525 | + store, | |
| 526 | + paginated, | |
| 527 | + backend: StorageBackend::S3, | |
| 528 | + name: "telemetry-test".to_string(), | |
| 529 | + prefix, | |
| 530 | + } | |
| 531 | + } | |
| 532 | + | |
| 458 | 533 | /// Builds a bucket over injected ordinary and conditional-write stores. |
| 459 | 534 | #[cfg(celld_internal_tests)] |
| 460 | 535 | #[doc(hidden)] |
| @@ -573,6 +648,17 @@ | ||
| 573 | 648 | retry_timeout: Duration::from_secs(30), |
| 574 | 649 | ..RetryConfig::default() |
| 575 | 650 | }; |
| 651 | + // A conditional write retries zero times, and that is a correctness | |
| 652 | + // bound rather than a conservative default. A retry inside the | |
| 653 | + // transport repeats a `PUT` that can already have committed, and it | |
| 654 | + // repeats it with the same If-Match token, so the second attempt | |
| 655 | + // answers 412 for a write the first one applied. The caller then | |
| 656 | + // reads a clean lost race where it in fact still holds the record. | |
| 657 | + // A transport retry also spends the renewal attempt's own deadline: | |
| 658 | + // the actor bounds a renewal CAS to half of the remaining authority, | |
| 659 | + // and a hidden second attempt inside that bound removes the readback | |
| 660 | + // the core needs to resolve the first. Ownership of the retry belongs | |
| 661 | + // to the core, which schedules it against the authority that remains. | |
| 576 | 662 | let cas_retry = RetryConfig { |
| 577 | 663 | max_retries: 0, |
| 578 | 664 | retry_timeout: Duration::from_secs(30), |
| @@ -955,8 +1041,46 @@ | ||
| 955 | 1041 | } |
| 956 | 1042 | } |
| 957 | 1043 | |
| 958 | - /// One page of the immediate child "directories" under `prefix/`. | |
| 1044 | + /// One provider page of objects under `prefix/`. | |
| 959 | 1045 | /// |
| 1046 | + /// The opaque token resumes the same listing with the same prefix and | |
| 1047 | + /// limit. A maintenance caller must finish and release this page before | |
| 1048 | + /// it asks for the next one, or pagination would bound requests without | |
| 1049 | + /// bounding retained object descriptions. | |
| 1050 | + pub(crate) async fn objects_page( | |
| 1051 | + &self, | |
| 1052 | + prefix: &str, | |
| 1053 | + page_token: Option<String>, | |
| 1054 | + max_keys: usize, | |
| 1055 | + ) -> anyhow::Result<ObjectPage> { | |
| 1056 | + // `PaginatedListStore` does not append the separator that | |
| 1057 | + // `ObjectStore::list` appends to a path-segment prefix. | |
| 1058 | + let path = self.key(&format!("{}/", prefix.trim_end_matches('/'))); | |
| 1059 | + let mut result = self | |
| 1060 | + .paginated | |
| 1061 | + .list_paginated( | |
| 1062 | + Some(path.as_str()), | |
| 1063 | + PaginatedListOptions { | |
| 1064 | + max_keys: Some(max_keys), | |
| 1065 | + page_token, | |
| 1066 | + ..PaginatedListOptions::default() | |
| 1067 | + }, | |
| 1068 | + ) | |
| 1069 | + .await | |
| 1070 | + .with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; | |
| 1071 | + if !self.prefix.is_empty() { | |
| 1072 | + for object in &mut result.result.objects { | |
| 1073 | + object.location = Path::parse(self.unkey(object.location.as_ref())).unwrap(); | |
| 1074 | + } | |
| 1075 | + } | |
| 1076 | + Ok(ObjectPage { | |
| 1077 | + objects: result.result.objects, | |
| 1078 | + page_token: result.page_token, | |
| 1079 | + }) | |
| 1080 | + } | |
| 1081 | + | |
| 1082 | + /// One page of the immediate child "directories" that start with `prefix`. | |
| 1083 | + /// | |
| 960 | 1084 | /// `start_after` resumes from a child a previous page returned, and |
| 961 | 1085 | /// `page_token` continues the same walk. Pass one or the other: a |
| 962 | 1086 | /// token is exact and works on every backend, while `start_after` |
| @@ -975,9 +1099,10 @@ | ||
| 975 | 1099 | page_token: Option<String>, |
| 976 | 1100 | max_keys: usize, |
| 977 | 1101 | ) -> anyhow::Result<CommonPrefixPage> { |
| 978 | - // `PaginatedListStore` does not append the delimiter the way | |
| 979 | - // `ObjectStore::list_with_delimiter` does, so the prefix carries it. | |
| 980 | - let path = self.key(&format!("{}/", prefix.trim_end_matches('/'))); | |
| 1102 | + // Keep the caller's exact prefix. Most callers use a directory prefix | |
| 1103 | + // such as `cells/`, but a class-filtered cell walk uses `cells/Class:` | |
| 1104 | + // so the store excludes every other class before it applies the bound. | |
| 1105 | + let path = self.key(prefix); | |
| 981 | 1106 | if start_after.is_some() && self.backend == StorageBackend::Azure { |
| 982 | 1107 | anyhow::bail!( |
| 983 | 1108 | "az:// cannot resume a listing by name, because Azure listing has no \ |
| @@ -1366,19 +1491,8 @@ | ||
| 1366 | 1491 | /// clears, so it can stop a node. An `Err` is ambiguous — a network |
| 1367 | 1492 | /// fault, a rejected credential — and a retry can clear it, so a |
| 1368 | 1493 | /// caller that must not fail on a transient blip keeps serving. |
| 1369 | - pub(crate) async fn probe_cas_steps(&self) -> anyhow::Result<CasVerdict> { | |
| 1370 | - let nanos = crate::asyncrt::wall_ms().max(0) as u128 * 1_000_000; | |
| 1371 | - // Unique per probe, so several nodes probing at once touch | |
| 1372 | - // disjoint keys and no probe reads another one's object as the | |
| 1373 | - // store misbehaving — a collision surfaces as a false `Violation`, | |
| 1374 | - // which stops a node. The random half carries that alone, because | |
| 1375 | - // a container fleet shares pid 1 and a clock before the epoch | |
| 1376 | - // leaves `nanos` at zero. | |
| 1377 | - let key = format!( | |
| 1378 | - "probe/cas-{nanos}-{}-{:016x}", | |
| 1379 | - crate::asyncrt::process_tag(), | |
| 1380 | - rand::RngCore::next_u64(&mut crate::asyncrt::rng("cas_probe")) | |
| 1381 | - ); | |
| 1494 | + pub(crate) async fn probe_cas_steps(&self) -> anyhow::Result<StorageProbeVerdict> { | |
| 1495 | + let key = Self::probe_key("cas"); | |
| 1382 | 1496 | let verdict = self.cas_contract(&key).await; |
| 1383 | 1497 | // The object is debris on every path, so retire it before the |
| 1384 | 1498 | // verdict. A delete that fails leaves one tiny object under |
| @@ -1390,18 +1504,62 @@ | ||
| 1390 | 1504 | verdict |
| 1391 | 1505 | } |
| 1392 | 1506 | |
| 1507 | + /// Run every storage check that a node needs before it serves. | |
| 1508 | + /// | |
| 1509 | + /// A clear unsupported-operation response is permanent, so it becomes a | |
| 1510 | + /// contract violation. Other errors remain ambiguous so the startup | |
| 1511 | + /// caller can retry the complete probe with fresh keys. | |
| 1512 | + pub(crate) async fn probe_startup_storage_steps(&self) -> anyhow::Result<StorageProbeVerdict> { | |
| 1513 | + match self.probe_cas_steps().await { | |
| 1514 | + Ok(StorageProbeVerdict::Conformant) => {} | |
| 1515 | + Ok(violation) => return Ok(violation), | |
| 1516 | + Err(error) if is_unsupported_operation(&error) => { | |
| 1517 | + return Ok(StorageProbeVerdict::Violation( | |
| 1518 | + "the store does not support conditional writes, so celld cannot acquire a cell" | |
| 1519 | + .to_string(), | |
| 1520 | + )); | |
| 1521 | + } | |
| 1522 | + Err(error) => return Err(error), | |
| 1523 | + } | |
| 1524 | + | |
| 1525 | + match self.probe_range_steps().await { | |
| 1526 | + Err(error) if is_unsupported_operation(&error) || is_invalid_range_response(&error) => { | |
| 1527 | + Ok(StorageProbeVerdict::Violation( | |
| 1528 | + "the store does not honor ranged reads, so celld cannot read stored cell data" | |
| 1529 | + .to_string(), | |
| 1530 | + )) | |
| 1531 | + } | |
| 1532 | + result => result, | |
| 1533 | + } | |
| 1534 | + } | |
| 1535 | + | |
| 1536 | + fn probe_key(kind: &str) -> String { | |
| 1537 | + let nanos = crate::asyncrt::wall_ms().max(0) as u128 * 1_000_000; | |
| 1538 | + // Unique per probe, so several nodes probing at once touch | |
| 1539 | + // disjoint keys and no probe reads another one's object as the | |
| 1540 | + // store misbehaving — a collision surfaces as a false `Violation`, | |
| 1541 | + // which stops a node. The random half carries that alone, because | |
| 1542 | + // a container fleet shares pid 1 and a clock before the epoch | |
| 1543 | + // leaves `nanos` at zero. | |
| 1544 | + format!( | |
| 1545 | + "probe/{kind}-{nanos}-{}-{:016x}", | |
| 1546 | + crate::asyncrt::process_tag(), | |
| 1547 | + rand::RngCore::next_u64(&mut crate::asyncrt::rng("cas_probe")) | |
| 1548 | + ) | |
| 1549 | + } | |
| 1550 | + | |
| 1393 | 1551 | /// [`Self::probe_cas_steps`] collapsed to one answer, where any wrong |
| 1394 | 1552 | /// answer fails the check. |
| 1395 | 1553 | pub async fn probe_cas(&self) -> anyhow::Result<()> { |
| 1396 | 1554 | match self.probe_cas_steps().await? { |
| 1397 | - CasVerdict::Conformant => Ok(()), | |
| 1398 | - CasVerdict::Violation(reason) => Err(anyhow!(reason)), | |
| 1555 | + StorageProbeVerdict::Conformant => Ok(()), | |
| 1556 | + StorageProbeVerdict::Violation(reason) => Err(anyhow!(reason)), | |
| 1399 | 1557 | } |
| 1400 | 1558 | } |
| 1401 | 1559 | |
| 1402 | 1560 | /// The four steps, against one key. Steps 2 and 4 must be rejected; |
| 1403 | 1561 | /// a store that applies either one cannot fence. |
| 1404 | - async fn cas_contract(&self, key: &str) -> anyhow::Result<CasVerdict> { | |
| 1562 | + async fn cas_contract(&self, key: &str) -> anyhow::Result<StorageProbeVerdict> { | |
| 1405 | 1563 | let precondition = self.backend.precondition(); |
| 1406 | 1564 | let ambiguous = || { |
| 1407 | 1565 | format!( |
| @@ -1418,7 +1576,7 @@ | ||
| 1418 | 1576 | .await |
| 1419 | 1577 | .context("the conditional-write probe could not create its object")? |
| 1420 | 1578 | else { |
| 1421 | - return Ok(CasVerdict::Violation( | |
| 1579 | + return Ok(StorageProbeVerdict::Violation( | |
| 1422 | 1580 | "the store rejected a conditional create of an object that does not exist" |
| 1423 | 1581 | .to_string(), |
| 1424 | 1582 | )); |
| @@ -1431,7 +1589,7 @@ | ||
| 1431 | 1589 | .with_context(ambiguous)? |
| 1432 | 1590 | .is_some() |
| 1433 | 1591 | { |
| 1434 | - return Ok(CasVerdict::Violation(format!( | |
| 1592 | + return Ok(StorageProbeVerdict::Violation(format!( | |
| 1435 | 1593 | "the store overwrote an object although the write was conditional on that object \ |
| 1436 | 1594 | being absent; the store accepts {precondition} and does not enforce it, so two \ |
| 1437 | 1595 | nodes can own one cell" |
| @@ -1446,7 +1604,7 @@ | ||
| 1446 | 1604 | .context("the conditional-write probe could not update its object")? |
| 1447 | 1605 | .is_none() |
| 1448 | 1606 | { |
| 1449 | - return Ok(CasVerdict::Violation( | |
| 1607 | + return Ok(StorageProbeVerdict::Violation( | |
| 1450 | 1608 | "the store rejected a conditional update that carried the current token" |
| 1451 | 1609 | .to_string(), |
| 1452 | 1610 | )); |
| @@ -1460,25 +1618,109 @@ | ||
| 1460 | 1618 | .with_context(ambiguous)? |
| 1461 | 1619 | .is_some() |
| 1462 | 1620 | { |
| 1463 | - return Ok(CasVerdict::Violation(format!( | |
| 1621 | + return Ok(StorageProbeVerdict::Violation(format!( | |
| 1464 | 1622 | "the store applied a conditional write that carried a stale token; the store \ |
| 1465 | 1623 | accepts {precondition} and does not enforce it, so two nodes can own one cell" |
| 1466 | 1624 | ))); |
| 1467 | 1625 | } |
| 1468 | 1626 | |
| 1469 | - Ok(CasVerdict::Conformant) | |
| 1627 | + Ok(StorageProbeVerdict::Conformant) | |
| 1470 | 1628 | } |
| 1629 | + | |
| 1630 | + async fn probe_range_steps(&self) -> anyhow::Result<StorageProbeVerdict> { | |
| 1631 | + let key = Self::probe_key("range"); | |
| 1632 | + let verdict = self.range_contract(&key).await; | |
| 1633 | + if let Err(error) = self.delete(&key).await { | |
| 1634 | + tracing::warn!(%error, "the ranged-read probe could not delete its object"); | |
| 1635 | + } | |
| 1636 | + verdict | |
| 1637 | + } | |
| 1638 | + | |
| 1639 | + async fn range_contract(&self, key: &str) -> anyhow::Result<StorageProbeVerdict> { | |
| 1640 | + const BODY: &[u8] = b"celld-range-probe"; | |
| 1641 | + const START: u64 = 6; | |
| 1642 | + const END: u64 = 11; | |
| 1643 | + let requested = START..END; | |
| 1644 | + | |
| 1645 | + self.put(key, BODY.to_vec()) | |
| 1646 | + .await | |
| 1647 | + .context("the ranged-read probe could not create its object")?; | |
| 1648 | + let scoped = self.key(key); | |
| 1649 | + let result = self | |
| 1650 | + .store | |
| 1651 | + .get_opts( | |
| 1652 | + &Path::from(scoped.as_str()), | |
| 1653 | + GetOptions { | |
| 1654 | + range: Some(GetRange::Bounded(requested.clone())), | |
| 1655 | + ..GetOptions::default() | |
| 1656 | + }, | |
| 1657 | + ) | |
| 1658 | + .await | |
| 1659 | + .with_context(|| { | |
| 1660 | + format!( | |
| 1661 | + "the ranged-read probe could not read {}://{}/{scoped}", | |
| 1662 | + self.scheme(), | |
| 1663 | + self.name | |
| 1664 | + ) | |
| 1665 | + })?; | |
| 1666 | + let served = result.range.clone(); | |
| 1667 | + let bytes = result | |
| 1668 | + .bytes() | |
| 1669 | + .await | |
| 1670 | + .context("the ranged-read probe could not read its response body")?; | |
| 1671 | + if served != requested || bytes.as_ref() != &BODY[START as usize..END as usize] { | |
| 1672 | + return Ok(StorageProbeVerdict::Violation( | |
| 1673 | + "the store does not honor ranged reads because it returned a different range or different bytes" | |
| 1674 | + .to_string(), | |
| 1675 | + )); | |
| 1676 | + } | |
| 1677 | + Ok(StorageProbeVerdict::Conformant) | |
| 1678 | + } | |
| 1471 | 1679 | } |
| 1472 | 1680 | |
| 1473 | -/// What [`Bucket::probe_cas_steps`] found. | |
| 1474 | -pub(crate) enum CasVerdict { | |
| 1475 | - /// The store rejected both writes it had to reject. | |
| 1681 | +/// What one storage-contract check found. | |
| 1682 | +pub(crate) enum StorageProbeVerdict { | |
| 1683 | + /// The store returned every result that this check requires. | |
| 1476 | 1684 | Conformant, |
| 1477 | 1685 | /// The store answered wrongly, and the string says how. This never |
| 1478 | 1686 | /// clears on a retry, so a caller can act on it. |
| 1479 | 1687 | Violation(String), |
| 1480 | 1688 | } |
| 1481 | 1689 | |
| 1690 | +/// Whether an operation failed because the store clearly does not implement | |
| 1691 | +/// it. The public object-store errors preserve that result structurally, but | |
| 1692 | +/// its HTTP adapters keep a 405 or 501 status only in a private source error. | |
| 1693 | +fn is_unsupported_operation(error: &anyhow::Error) -> bool { | |
| 1694 | + error.chain().any(|cause| { | |
| 1695 | + if matches!( | |
| 1696 | + cause.downcast_ref::<Error>(), | |
| 1697 | + Some(Error::NotSupported { .. } | Error::NotImplemented) | |
| 1698 | + ) { | |
| 1699 | + return true; | |
| 1700 | + } | |
| 1701 | + let text = cause.to_string(); | |
| 1702 | + text.contains("status 405") | |
| 1703 | + || text.contains("status 501") | |
| 1704 | + || text.contains("405 Method Not Allowed") | |
| 1705 | + || text.contains("501 Not Implemented") | |
| 1706 | + }) | |
| 1707 | +} | |
| 1708 | + | |
| 1709 | +/// Whether the object-store client rejected a successful HTTP response because | |
| 1710 | +/// it did not describe the requested byte range. The locked object-store | |
| 1711 | +/// library keeps these parser types private, so their messages are the only | |
| 1712 | +/// available boundary. A dependency update must verify these messages. | |
| 1713 | +fn is_invalid_range_response(error: &anyhow::Error) -> bool { | |
| 1714 | + error.chain().any(|cause| { | |
| 1715 | + let text = cause.to_string(); | |
| 1716 | + text == "Received non-partial response when range requested" | |
| 1717 | + || text == "Content-Range header not present in partial response" | |
| 1718 | + || text.starts_with("Failed to parse value for CONTENT_RANGE header:") | |
| 1719 | + || text == "Content-Range header contained non UTF-8 characters" | |
| 1720 | + || (text.starts_with("Requested ") && text.contains(", got ")) | |
| 1721 | + }) | |
| 1722 | +} | |
| 1723 | + | |
| 1482 | 1724 | /// The replica-lane store for a `gs://` fleet bucket: its own transport |
| 1483 | 1725 | /// and connection pool, authenticated like [`Bucket::open`]'s gs:// path |
| 1484 | 1726 | /// (OAuth via Application Default Credentials or the `GOOGLE_*` env), |
modifiedcrates/celld/cell_cli.rs+10−1View file
| @@ -122,6 +122,11 @@ | ||
| 122 | 122 | } |
| 123 | 123 | } |
| 124 | 124 | options.bounds.validate()?; |
| 125 | + if let Some(class) = options.class.as_deref() { | |
| 126 | + if class.contains(':') || !celld_logic::cell::valid_cell_scope(class) { | |
| 127 | + bail!("a cell class must use ASCII letters, digits, and `_ - . $`, not {class:?}"); | |
| 128 | + } | |
| 129 | + } | |
| 125 | 130 | if let Some(after) = options.bounds.after.as_deref() { |
| 126 | 131 | if !celld_logic::cell::valid_cell_scope(after) { |
| 127 | 132 | bail!("--after takes a cell scope this command printed, not {after:?}"); |
| @@ -202,10 +207,14 @@ | ||
| 202 | 207 | }); |
| 203 | 208 | let started = std::time::Instant::now(); |
| 204 | 209 | let class = options.class.clone(); |
| 210 | + let prefix = class | |
| 211 | + .as_deref() | |
| 212 | + .map_or_else(|| "cells/".to_string(), |class| format!("cells/{class}:")); | |
| 205 | 213 | |
| 206 | 214 | let listed = list(&mut out, &options.bounds, |resume, want| { |
| 207 | 215 | let store = &store; |
| 208 | 216 | let class = class.clone(); |
| 217 | + let prefix = prefix.clone(); | |
| 209 | 218 | // The store resumes from a child of `cells/`, while the cursor an |
| 210 | 219 | // operator sees is the scope. The two differ by the prefix, and |
| 211 | 220 | // passing the scope raw silently matches nothing, which reads as a |
| @@ -218,7 +227,7 @@ | ||
| 218 | 227 | }; |
| 219 | 228 | async move { |
| 220 | 229 | let page = store |
| 221 | - .common_prefixes_page("cells/", start_after.as_deref(), token, want) | |
| 230 | + .common_prefixes_page(&prefix, start_after.as_deref(), token, want) | |
| 222 | 231 | .await |
| 223 | 232 | .context("enumerate Durable Object instances")?; |
| 224 | 233 | Ok(Page { |
modifiedcrates/celld/cli_options.rs+9−13View file
| @@ -27,6 +27,10 @@ | ||
| 27 | 27 | .filter(|value| !value.trim().is_empty()) |
| 28 | 28 | } |
| 29 | 29 | |
| 30 | +pub(crate) fn bucket_from_environment() -> Option<String> { | |
| 31 | + env("CELLD_BUCKET").map(|value| value.trim().to_string()) | |
| 32 | +} | |
| 33 | + | |
| 30 | 34 | /// Which fleet a command acts on. |
| 31 | 35 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 32 | 36 | pub struct FleetFlags { |
| @@ -55,12 +59,10 @@ | ||
| 55 | 59 | value: &mut impl FnMut(&str) -> anyhow::Result<String>, |
| 56 | 60 | ) -> anyhow::Result<bool> { |
| 57 | 61 | match argument { |
| 58 | - // The scheme survives into `Bucket::open`, which parses it to | |
| 59 | - // pick a backend. Only the default `s3://` is stripped, because | |
| 60 | - // a bare name means S3 there too. | |
| 61 | - "--bucket" => { | |
| 62 | - self.bucket = Some(value("--bucket")?.trim_start_matches("s3://").to_string()); | |
| 63 | - } | |
| 62 | + // `Bucket::open` is the one parser for the complete spec. Keeping | |
| 63 | + // the spelling intact here prevents CLI paths from disagreeing | |
| 64 | + // about scheme case or changing where the prefix begins. | |
| 65 | + "--bucket" => self.bucket = Some(value("--bucket")?), | |
| 64 | 66 | "--endpoint" => self.endpoint = Some(value("--endpoint")?), |
| 65 | 67 | "--region" => self.region = Some(value("--region")?), |
| 66 | 68 | _ => return Ok(false), |
| @@ -71,13 +73,7 @@ | ||
| 71 | 73 | /// Fill anything the flags left unset from the environment. |
| 72 | 74 | pub fn with_environment(mut self) -> Self { |
| 73 | 75 | if self.bucket.is_none() { |
| 74 | - self.bucket = env("CELLD_BUCKET").map(|value| { | |
| 75 | - value | |
| 76 | - .trim() | |
| 77 | - .trim_start_matches("s3://") | |
| 78 | - .trim_end_matches('/') | |
| 79 | - .to_string() | |
| 80 | - }); | |
| 76 | + self.bucket = bucket_from_environment(); | |
| 81 | 77 | } |
| 82 | 78 | if self.endpoint.is_none() { |
| 83 | 79 | self.endpoint = env("S3_ENDPOINT"); |
modifiedcrates/celld/control_plane.rs+9−7View file
| @@ -122,8 +122,8 @@ | ||
| 122 | 122 | ControlPlaneUnavailable, |
| 123 | 123 | BucketUnavailable, |
| 124 | 124 | CredentialRevoked, |
| 125 | - /// The bucket answers, and the credential works, but the store does | |
| 126 | - /// not enforce the conditional write celld fences with. Distinct from | |
| 125 | + /// The bucket answers, and the credential works, but the store does not | |
| 126 | + /// support a required conditional write or ranged read. Distinct from | |
| 127 | 127 | /// `BucketUnavailable`, which a retry can clear: this one never does. |
| 128 | 128 | StorageContractViolated, |
| 129 | 129 | } |
| @@ -174,14 +174,14 @@ | ||
| 174 | 174 | "managed storage credential was rejected; restart celld to fetch a \ |
| 175 | 175 | fresh one, or run `celld credentials refresh` if a rotation is pending" |
| 176 | 176 | ), |
| 177 | - // No remedy on this node: the store itself cannot fence, so a | |
| 177 | + // No remedy on this node: the store lacks a required operation, so a | |
| 178 | 178 | // restart repeats the refusal. Name the two exits an operator has. |
| 179 | 179 | ManagedRuntimeState::StorageContractViolated => warn!( |
| 180 | 180 | event = "managed_runtime_state", |
| 181 | 181 | managed_state, |
| 182 | - "the fleet bucket does not enforce the conditional write celld fences \ | |
| 183 | - with, so serving cannot start; move the fleet to a store that does, \ | |
| 184 | - or set CELLD_STORAGE_PROBE=0 to start without this test" | |
| 182 | + "the fleet bucket does not support a storage operation celld requires, \ | |
| 183 | + so serving cannot start; move the fleet to a compatible store, or set \ | |
| 184 | + CELLD_STORAGE_PROBE=0 to start without this test" | |
| 185 | 185 | ), |
| 186 | 186 | } |
| 187 | 187 | } |
| @@ -2042,7 +2042,9 @@ | ||
| 2042 | 2042 | let mut manifest_modules = std::collections::BTreeMap::new(); |
| 2043 | 2043 | let mut total_bytes = 0_usize; |
| 2044 | 2044 | for module in &deployment.manifest.modules { |
| 2045 | - if !valid_managed_module_name(&module.name) || !valid_lower_hex(&module.sha256, 16) { | |
| 2045 | + if !valid_managed_module_name(&module.name) | |
| 2046 | + || !(valid_lower_hex(&module.sha256, 16) || valid_lower_hex(&module.sha256, 64)) | |
| 2047 | + { | |
| 2046 | 2048 | return Err(anyhow!( |
| 2047 | 2049 | "control-plane manifest has an invalid module reference: {:?}", |
| 2048 | 2050 | module.name |
modifiedcrates/celld/d1_cli.rs+15−10View file
| @@ -308,6 +308,13 @@ | ||
| 308 | 308 | Ok(()) |
| 309 | 309 | } |
| 310 | 310 | } |
| 311 | + | |
| 312 | +fn has_sql_extension(path: &std::path::Path) -> bool { | |
| 313 | + path.extension() | |
| 314 | + .and_then(std::ffi::OsStr::to_str) | |
| 315 | + .is_some_and(|extension| extension.eq_ignore_ascii_case("sql")) | |
| 316 | +} | |
| 317 | + | |
| 311 | 318 | fn read_migrations(directory: &std::path::Path) -> anyhow::Result<Vec<Migration>> { |
| 312 | 319 | if !directory.exists() { |
| 313 | 320 | bail!( |
| @@ -327,12 +334,9 @@ | ||
| 327 | 334 | if path.is_dir() { |
| 328 | 335 | let nested = std::fs::read_dir(&path) |
| 329 | 336 | .map(|entries| { |
| 330 | - entries.flatten().any(|entry| { | |
| 331 | - entry | |
| 332 | - .path() | |
| 333 | - .extension() | |
| 334 | - .is_some_and(|extension| extension == "sql") | |
| 335 | - }) | |
| 337 | + entries | |
| 338 | + .flatten() | |
| 339 | + .any(|entry| has_sql_extension(&entry.path())) | |
| 336 | 340 | }) |
| 337 | 341 | .unwrap_or(false); |
| 338 | 342 | if nested { |
| @@ -345,7 +349,7 @@ | ||
| 345 | 349 | } |
| 346 | 350 | continue; |
| 347 | 351 | } |
| 348 | - if path.extension().is_none_or(|extension| extension != "sql") { | |
| 352 | + if !has_sql_extension(&path) { | |
| 349 | 353 | continue; |
| 350 | 354 | } |
| 351 | 355 | let name = path |
| @@ -534,9 +538,10 @@ | ||
| 534 | 538 | reads from the bucket, so it needs the same bucket credentials celld deploy |
| 535 | 539 | needs. |
| 536 | 540 | |
| 537 | -Migration files are `NNNN_description.sql` in `migrations/`, applied in the | |
| 538 | -order of their numeric prefixes as wrangler applies them. `migrations_dir` on | |
| 539 | -the d1_databases entry moves the directory, and `migrations_table` renames the | |
| 541 | +Migration files are `NNNN_description.sql` in `migrations/`. The `sql` | |
| 542 | +extension is ASCII case-insensitive. celld applies the files in the order of | |
| 543 | +their numeric prefixes as wrangler applies them. `migrations_dir` on the | |
| 544 | +d1_databases entry moves the directory, and `migrations_table` renames the | |
| 540 | 545 | bookkeeping table. celld records applied migrations in that table |
| 541 | 546 | (`d1_migrations` by default), the same table and columns |
| 542 | 547 | `wrangler d1 migrations` uses. |
modifiedcrates/celld/dead_node_gc.rs+60−10View file
| @@ -23,6 +23,8 @@ | ||
| 23 | 23 | expires_ms: u64, |
| 24 | 24 | #[serde(default, rename = "ownership_index_generation")] |
| 25 | 25 | generation: String, |
| 26 | + #[serde(default)] | |
| 27 | + probe_public_key: String, | |
| 26 | 28 | /// The folded node log: this record IS |
| 27 | 29 | /// the fleet log's root of truth, so retirement must respect its |
| 28 | 30 | /// state and the tombstone must carry it through unchanged. |
| @@ -35,6 +37,19 @@ | ||
| 35 | 37 | rest: serde_json::Map<String, serde_json::Value>, |
| 36 | 38 | } |
| 37 | 39 | |
| 40 | +impl NodeWire { | |
| 41 | + /// The process generation, which a record written after part 2 of | |
| 42 | + /// the `ownership_index_generation` retirement (see | |
| 43 | + /// `ownership_store::NodeLeaseWire`) carries only as the probe key. | |
| 44 | + fn generation(&self) -> &str { | |
| 45 | + if self.generation.is_empty() { | |
| 46 | + &self.probe_public_key | |
| 47 | + } else { | |
| 48 | + &self.generation | |
| 49 | + } | |
| 50 | + } | |
| 51 | +} | |
| 52 | + | |
| 38 | 53 | #[derive(Clone, Debug)] |
| 39 | 54 | struct DeadNode { |
| 40 | 55 | node: String, |
| @@ -68,7 +83,20 @@ | ||
| 68 | 83 | /// Run one pass while renewing the advisory fleet-waker role. No task is |
| 69 | 84 | /// spawned: the caller's existing wake-loop future polls both work and |
| 70 | 85 | /// renewal, and dropping a lost-role pass cancels remaining I/O. |
| 71 | - pub async fn run_elected_pass(&mut self, bucket: &Bucket, node: &str, tick_ms: u64) { | |
| 86 | + /// | |
| 87 | + /// Returns the node sessions whose leases were live when the pass began, | |
| 88 | + /// and only when this node held the role for the whole pass. The caller | |
| 89 | + /// uses that as its election result: the fleet-wide wake probe that | |
| 90 | + /// follows runs on the same tick, against the same leases, and only on | |
| 91 | + /// the node that holds the role. `None` means either that another node | |
| 92 | + /// holds the role or that this node lost it mid-pass; both mean "do not | |
| 93 | + /// probe this tick". | |
| 94 | + pub async fn run_elected_pass( | |
| 95 | + &mut self, | |
| 96 | + bucket: &Bucket, | |
| 97 | + node: &str, | |
| 98 | + tick_ms: u64, | |
| 99 | + ) -> Option<BTreeSet<String>> { | |
| 72 | 100 | let lease_ttl_ms = tick_ms.saturating_mul(3).min(i64::MAX as u64); |
| 73 | 101 | if !crate::wake::try_hold_waker( |
| 74 | 102 | bucket, |
| @@ -78,7 +106,7 @@ | ||
| 78 | 106 | ) |
| 79 | 107 | .await |
| 80 | 108 | { |
| 81 | - return; | |
| 109 | + return None; | |
| 82 | 110 | } |
| 83 | 111 | |
| 84 | 112 | let renew_ms = (lease_ttl_ms / 3).max(1); |
| @@ -98,17 +126,18 @@ | ||
| 98 | 126 | lease_ttl_ms as i64, |
| 99 | 127 | ).await { |
| 100 | 128 | warn!("waker lease renewal failed; cancelling dead-node GC"); |
| 101 | - return; | |
| 129 | + return None; | |
| 102 | 130 | } |
| 103 | 131 | }, |
| 104 | - _ = &mut pass => return, | |
| 132 | + live = &mut pass => return Some(live), | |
| 105 | 133 | } |
| 106 | 134 | } |
| 107 | 135 | } |
| 108 | 136 | |
| 109 | - async fn run_pass(&mut self, bucket: &Bucket, tick_ms: u64) { | |
| 137 | + /// One GC pass. Returns the live node sessions the pass observed. | |
| 138 | + async fn run_pass(&mut self, bucket: &Bucket, tick_ms: u64) -> BTreeSet<String> { | |
| 110 | 139 | let observed_ms = crate::ownership_store::now_ms(); |
| 111 | - let dead = dead_nodes(bucket, observed_ms).await; | |
| 140 | + let NodeScan { dead, live } = scan_nodes(bucket, observed_ms).await; | |
| 112 | 141 | let dead_names: BTreeSet<&str> = dead.iter().map(|record| record.node.as_str()).collect(); |
| 113 | 142 | self.swept.retain(|node| dead_names.contains(node.as_str())); |
| 114 | 143 | self.retries |
| @@ -203,16 +232,34 @@ | ||
| 203 | 232 | Err(error) => warn!(%node, %error, "dead-node lease retirement failed"), |
| 204 | 233 | } |
| 205 | 234 | } |
| 235 | + live | |
| 206 | 236 | } |
| 207 | 237 | } |
| 208 | 238 | |
| 209 | -async fn dead_nodes(bucket: &Bucket, now_ms: u64) -> Vec<DeadNode> { | |
| 239 | +/// The node sessions with a live lease, for a caller that has no GC pass to | |
| 240 | +/// take them from (the boot-time wake scan). | |
| 241 | +pub async fn live_nodes(bucket: &Bucket, now_ms: u64) -> BTreeSet<String> { | |
| 242 | + scan_nodes(bucket, now_ms).await.live | |
| 243 | +} | |
| 244 | + | |
| 245 | +/// The fleet's node records, split by lease state at one instant. | |
| 246 | +struct NodeScan { | |
| 247 | + dead: Vec<DeadNode>, | |
| 248 | + /// Sessions whose record matches its key and whose lease has not | |
| 249 | + /// expired. A record that fails to read is in neither set, so an owner | |
| 250 | + /// named by such a record counts as not live and the wake probe hints | |
| 251 | + /// its cells; the core's own lease read then decides. | |
| 252 | + live: BTreeSet<String>, | |
| 253 | +} | |
| 254 | + | |
| 255 | +async fn scan_nodes(bucket: &Bucket, now_ms: u64) -> NodeScan { | |
| 210 | 256 | let mut dead = Vec::new(); |
| 257 | + let mut live = BTreeSet::new(); | |
| 211 | 258 | let objects = match bucket.list("nodes/").await { |
| 212 | 259 | Ok(objects) => objects, |
| 213 | 260 | Err(error) => { |
| 214 | 261 | warn!(%error, "dead-node scan list failed"); |
| 215 | - return dead; | |
| 262 | + return NodeScan { dead, live }; | |
| 216 | 263 | } |
| 217 | 264 | }; |
| 218 | 265 | for object in objects { |
| @@ -234,14 +281,17 @@ | ||
| 234 | 281 | { |
| 235 | 282 | dead.push(DeadNode { |
| 236 | 283 | node: node.to_string(), |
| 237 | - generation: record.generation, | |
| 284 | + generation: record.generation().to_string(), | |
| 238 | 285 | }); |
| 239 | 286 | } |
| 287 | + Ok(Some((record, _))) if record.node == node => { | |
| 288 | + live.insert(node.to_string()); | |
| 289 | + } | |
| 240 | 290 | Ok(_) => {} |
| 241 | 291 | Err(error) => warn!(%node, %error, "dead-node scan read failed"), |
| 242 | 292 | } |
| 243 | 293 | } |
| 244 | - dead | |
| 294 | + NodeScan { dead, live } | |
| 245 | 295 | } |
| 246 | 296 | |
| 247 | 297 | async fn cells_indexed_by_nodes( |
modifiedcrates/celld/deploy.rs+67−7View file
| @@ -180,6 +180,13 @@ | ||
| 180 | 180 | const MAX_ASSET_DIRECTIVE_BYTES: u64 = 100 * 1024; |
| 181 | 181 | const ASSET_UPLOAD_CONCURRENCY: usize = 16; |
| 182 | 182 | |
| 183 | +/// Wrangler's Worker-name bound. The charset below is ASCII, so the byte and | |
| 184 | +/// character counts are identical. This also keeps a generated Workflow class | |
| 185 | +/// far below the cell-scope limit. | |
| 186 | +const MAX_SCRIPT_NAME_BYTES: usize = 63; | |
| 187 | +const _: () = | |
| 188 | + assert!(WORKFLOW_CLASS.len() + 1 + MAX_SCRIPT_NAME_BYTES <= celld_logic::cell::MAX_CELL_SCOPE); | |
| 189 | + | |
| 183 | 190 | pub struct Options { |
| 184 | 191 | pub config: Option<PathBuf>, |
| 185 | 192 | pub bucket: Option<String>, |
| @@ -204,7 +211,11 @@ | ||
| 204 | 211 | A running node polls the deployment pointer and adopts the new version in\n\ |
| 205 | 212 | place; nothing restarts." |
| 206 | 213 | ; |
| 207 | - let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text).help(text); | |
| 214 | + let text = format!( | |
| 215 | + "{text}\nThe config `name` uses lowercase ASCII letters, digits, and internal hyphens. \ | |
| 216 | + It is at most {MAX_SCRIPT_NAME_BYTES} bytes." | |
| 217 | + ); | |
| 218 | + let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text).help(&text); | |
| 208 | 219 | } |
| 209 | 220 | |
| 210 | 221 | pub fn options_from_arguments( |
| @@ -231,7 +242,7 @@ | ||
| 231 | 242 | } |
| 232 | 243 | "--bucket" => { |
| 233 | 244 | let value = arguments.next().context("--bucket requires a value")?; |
| 234 | - options.bucket = Some(value.trim_start_matches("s3://").to_string()); | |
| 245 | + options.bucket = Some(value); | |
| 235 | 246 | } |
| 236 | 247 | "--endpoint" => { |
| 237 | 248 | options.endpoint = Some(arguments.next().context("--endpoint requires a value")?); |
| @@ -504,7 +515,7 @@ | ||
| 504 | 515 | .map(|(name, bytes)| ModuleRef { |
| 505 | 516 | name: name.clone(), |
| 506 | 517 | bytes: bytes.len(), |
| 507 | - sha256: format!("{:x}", Sha256::digest(bytes))[..16].to_string(), | |
| 518 | + sha256: format!("{:x}", Sha256::digest(bytes)), | |
| 508 | 519 | kind: wasm_names.contains(name).then_some(ModuleKind::Wasm), |
| 509 | 520 | }) |
| 510 | 521 | .collect(), |
| @@ -876,13 +887,17 @@ | ||
| 876 | 887 | Some(Value::String(identity)) if !identity.is_empty() => identity.clone(), |
| 877 | 888 | Some(_) => bail!("d1 database {name:?} has an invalid `database_id`"), |
| 878 | 889 | }; |
| 890 | + let migrations_dir = match entry.get("migrations_dir") { | |
| 891 | + None => root.join("migrations"), | |
| 892 | + Some(Value::String(directory)) => { | |
| 893 | + root.join(project_relative_path(directory, "migrations_dir")?) | |
| 894 | + } | |
| 895 | + Some(_) => bail!("d1 database {name:?} has a non-string `migrations_dir`"), | |
| 896 | + }; | |
| 879 | 897 | databases.push(D1Declaration { |
| 880 | 898 | database_name: name.to_string(), |
| 881 | 899 | database_identity, |
| 882 | - migrations_dir: entry | |
| 883 | - .get("migrations_dir") | |
| 884 | - .and_then(Value::as_str) | |
| 885 | - .map_or_else(|| root.join("migrations"), |dir| root.join(dir)), | |
| 900 | + migrations_dir, | |
| 886 | 901 | migrations_table, |
| 887 | 902 | }); |
| 888 | 903 | } |
| @@ -980,6 +995,12 @@ | ||
| 980 | 995 | .and_then(Value::as_str) |
| 981 | 996 | .ok_or_else(|| anyhow!("config has no `name`"))? |
| 982 | 997 | .to_string(); |
| 998 | + if !valid_script_name(&script_name) { | |
| 999 | + bail!( | |
| 1000 | + "config `name` must contain 1 to {MAX_SCRIPT_NAME_BYTES} bytes of lowercase \ | |
| 1001 | + ASCII letters, digits, or internal hyphens: {script_name:?}" | |
| 1002 | + ); | |
| 1003 | + } | |
| 983 | 1004 | let main = object |
| 984 | 1005 | .get("main") |
| 985 | 1006 | .map(|value| { |
| @@ -1639,6 +1660,24 @@ | ||
| 1639 | 1660 | .all(|value| value == '_' || value == '-' || value.is_ascii_alphanumeric()) |
| 1640 | 1661 | } |
| 1641 | 1662 | |
| 1663 | +/// The Wrangler-compatible Worker name that is safe in every place where | |
| 1664 | +/// celld reuses it. Checking only the generated Workflow class would leave | |
| 1665 | +/// deployment keys and operator output with a different accepted language. | |
| 1666 | +fn valid_script_name(name: &str) -> bool { | |
| 1667 | + name.len() <= MAX_SCRIPT_NAME_BYTES | |
| 1668 | + && name | |
| 1669 | + .bytes() | |
| 1670 | + .next() | |
| 1671 | + .is_some_and(|first| first.is_ascii_lowercase() || first.is_ascii_digit()) | |
| 1672 | + && name | |
| 1673 | + .bytes() | |
| 1674 | + .last() | |
| 1675 | + .is_some_and(|last| last.is_ascii_lowercase() || last.is_ascii_digit()) | |
| 1676 | + && name | |
| 1677 | + .bytes() | |
| 1678 | + .all(|value| value.is_ascii_lowercase() || value.is_ascii_digit() || value == b'-') | |
| 1679 | +} | |
| 1680 | + | |
| 1642 | 1681 | /// `triggers.crons`, validated here so a malformed expression stops the deploy |
| 1643 | 1682 | /// the developer is watching instead of an activation an hour later. Wrangler |
| 1644 | 1683 | /// accepts `triggers` with other keys we do not model; only `crons` is read. |
| @@ -2050,6 +2089,10 @@ | ||
| 2050 | 2089 | if child_relative.len() + 1 > 1024 { |
| 2051 | 2090 | bail!("asset path exceeds 1024 bytes: /{child_relative}"); |
| 2052 | 2091 | } |
| 2092 | + let asset_path = format!("/{child_relative}"); | |
| 2093 | + if !crate::assets::is_canonical_asset_path(&asset_path) { | |
| 2094 | + bail!("asset path is not canonical: {asset_path:?}"); | |
| 2095 | + } | |
| 2053 | 2096 | let file_type = entry |
| 2054 | 2097 | .file_type() |
| 2055 | 2098 | .with_context(|| format!("inspect asset {}", entry.path().display()))?; |
| @@ -2120,6 +2163,22 @@ | ||
| 2120 | 2163 | // provides them. |
| 2121 | 2164 | let binary = std::env::var("CELLD_ESBUILD").unwrap_or_else(|_| "esbuild".to_string()); |
| 2122 | 2165 | let outdir = tempfile::tempdir().context("create esbuild output directory")?; |
| 2166 | + // esbuild leaves an external builtin from a CommonJS dependency behind | |
| 2167 | + // its synchronous __require helper. Workerd's Wrangler plugin rewrites | |
| 2168 | + // that call to an ESM import, but the esbuild CLI has no equivalent | |
| 2169 | + // plugin hook. Give only this generated bundle a lexical bridge to the | |
| 2170 | + // same builtin table. A runtime global would make require visible to raw | |
| 2171 | + // ESM Workers, which Workerd does not do. | |
| 2172 | + let commonjs_builtin_bridge = r#"var require = (id) => { | |
| 2173 | + const name = String(id); | |
| 2174 | + const builtin = process.getBuiltinModule(name); | |
| 2175 | + if (builtin === undefined) { | |
| 2176 | + const error = new Error(`Cannot find module '${name}'`); | |
| 2177 | + error.code = "MODULE_NOT_FOUND"; | |
| 2178 | + throw error; | |
| 2179 | + } | |
| 2180 | + return builtin; | |
| 2181 | +};"#; | |
| 2123 | 2182 | let output = Command::new(&binary) |
| 2124 | 2183 | .current_dir(root) |
| 2125 | 2184 | .arg(entry) |
| @@ -2128,6 +2187,7 @@ | ||
| 2128 | 2187 | .arg("--platform=browser") |
| 2129 | 2188 | .arg("--target=es2024") |
| 2130 | 2189 | .arg("--conditions=workerd,worker,browser") |
| 2190 | + .arg(format!("--banner:js={commonjs_builtin_bridge}")) | |
| 2131 | 2191 | .arg("--external:node:*") |
| 2132 | 2192 | .arg("--external:cloudflare:*") |
| 2133 | 2193 | .args( |
modifiedcrates/celld/dev.rs+224−33View file
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | use crate::bucket::Bucket; |
| 10 | 10 | use crate::{deploy, fleet}; |
| 11 | 11 | use anyhow::{bail, Context as _}; |
| 12 | +use glob::{MatchOptions, Pattern}; | |
| 12 | 13 | use notify::{RecursiveMode, Watcher as _}; |
| 13 | 14 | use nu_ansi_term::{Color, Style}; |
| 14 | 15 | use sha2::{Digest as _, Sha256}; |
| @@ -31,10 +32,72 @@ | ||
| 31 | 32 | Bucket::open_dev(database) |
| 32 | 33 | } |
| 33 | 34 | |
| 35 | +#[derive(Debug)] | |
| 34 | 36 | struct Options { |
| 35 | 37 | project: Option<PathBuf>, |
| 38 | + clean: bool, | |
| 39 | + stack: StackOptions, | |
| 40 | +} | |
| 41 | + | |
| 42 | +/// The local state directory of one project. | |
| 43 | +/// | |
| 44 | +/// `--clean` deletes this directory and everything below it. The path is | |
| 45 | +/// private and the only constructor takes the project directory that `run` | |
| 46 | +/// resolved, so a command-line value can never become the target of the | |
| 47 | +/// delete. A newtype carries that rule instead of a comment, because a | |
| 48 | +/// `PathBuf` field would let a later caller pass any path and lose nothing at | |
| 49 | +/// compile time. | |
| 50 | +#[derive(Debug)] | |
| 51 | +struct DevState { | |
| 52 | + path: PathBuf, | |
| 53 | +} | |
| 54 | + | |
| 55 | +impl DevState { | |
| 56 | + /// The project-relative location of the local state, and also the suffix | |
| 57 | + /// that `discard` requires before it deletes. | |
| 58 | + const DIRECTORY: &'static str = ".celld/dev"; | |
| 59 | + | |
| 60 | + fn for_project(project: &Path) -> Self { | |
| 61 | + Self { | |
| 62 | + path: project.join(Self::DIRECTORY), | |
| 63 | + } | |
| 64 | + } | |
| 65 | + | |
| 66 | + fn path(&self) -> &Path { | |
| 67 | + &self.path | |
| 68 | + } | |
| 69 | + | |
| 70 | + /// Delete the local state so the next run starts from nothing. The answer | |
| 71 | + /// reports whether a directory was present, because the console line for | |
| 72 | + /// an empty project must not claim that data was removed. | |
| 73 | + /// | |
| 74 | + /// An absent directory is the wanted result of this command, so it is not | |
| 75 | + /// an error. | |
| 76 | + #[allow(clippy::disallowed_methods)] // Local development state is an operator-owned host path. | |
| 77 | + fn discard(&self) -> anyhow::Result<bool> { | |
| 78 | + // The constructor already guarantees this. The check stays because it | |
| 79 | + // is the tripwire for a future constructor that takes a path: a | |
| 80 | + // recursive delete must never widen by accident. | |
| 81 | + anyhow::ensure!( | |
| 82 | + self.path.ends_with(Self::DIRECTORY), | |
| 83 | + "refusing to discard {}, which is not a celld dev state directory", | |
| 84 | + self.path.display() | |
| 85 | + ); | |
| 86 | + match std::fs::remove_dir_all(&self.path) { | |
| 87 | + Ok(()) => Ok(true), | |
| 88 | + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), | |
| 89 | + Err(error) => Err(error) | |
| 90 | + .with_context(|| format!("discard local state directory {}", self.path.display())), | |
| 91 | + } | |
| 92 | + } | |
| 93 | +} | |
| 94 | + | |
| 95 | +#[derive(Debug)] | |
| 96 | +struct StackOptions { | |
| 36 | 97 | listener: SocketAddr, |
| 37 | 98 | logs: bool, |
| 99 | + watch: bool, | |
| 100 | + watch_ignores: Vec<Pattern>, | |
| 38 | 101 | } |
| 39 | 102 | |
| 40 | 103 | struct Store { |
| @@ -103,12 +166,13 @@ | ||
| 103 | 166 | |
| 104 | 167 | struct ProjectWatcher { |
| 105 | 168 | project: PathBuf, |
| 169 | + ignored: Vec<Pattern>, | |
| 106 | 170 | _watcher: notify::RecommendedWatcher, |
| 107 | 171 | changes: mpsc::UnboundedReceiver<notify::Result<notify::Event>>, |
| 108 | 172 | } |
| 109 | 173 | |
| 110 | 174 | impl ProjectWatcher { |
| 111 | - fn new(project: &Path) -> anyhow::Result<Self> { | |
| 175 | + fn new(project: &Path, ignored: Vec<Pattern>) -> anyhow::Result<Self> { | |
| 112 | 176 | let (sender, changes) = mpsc::unbounded_channel(); |
| 113 | 177 | let mut watcher = notify::recommended_watcher(move |event| { |
| 114 | 178 | let _ = sender.send(event); |
| @@ -119,6 +183,7 @@ | ||
| 119 | 183 | .with_context(|| format!("watch the project directory {}", project.display()))?; |
| 120 | 184 | Ok(Self { |
| 121 | 185 | project: project.to_path_buf(), |
| 186 | + ignored, | |
| 122 | 187 | _watcher: watcher, |
| 123 | 188 | changes, |
| 124 | 189 | }) |
| @@ -148,12 +213,7 @@ | ||
| 148 | 213 | .await |
| 149 | 214 | .context("the project watcher stopped")? |
| 150 | 215 | { |
| 151 | - Ok(event) | |
| 152 | - if event | |
| 153 | - .paths | |
| 154 | - .iter() | |
| 155 | - .any(|path| !ignored_project_path(&self.project, path)) => | |
| 156 | - { | |
| 216 | + Ok(event) if relevant_project_event(&self.project, &event, &self.ignored) => { | |
| 157 | 217 | return Ok(()) |
| 158 | 218 | } |
| 159 | 219 | Ok(_) => {} |
| @@ -163,7 +223,24 @@ | ||
| 163 | 223 | } |
| 164 | 224 | } |
| 165 | 225 | |
| 166 | -fn ignored_project_path(project: &Path, path: &Path) -> bool { | |
| 226 | +fn relevant_project_event(project: &Path, event: ¬ify::Event, ignored: &[Pattern]) -> bool { | |
| 227 | + // A read is not a change. The inotify backend reports `Access(Open(Any))` | |
| 228 | + // for every file that the bundler and the deploy step read, so a rebuild | |
| 229 | + // produces the events that request the next rebuild and the supervisor | |
| 230 | + // never settles. The path filters cannot close this loop, because the | |
| 231 | + // files that the rebuild reads are the project sources it must watch. A | |
| 232 | + // write still arrives as a `Modify` event, and a `Create` or a `Remove` | |
| 233 | + // event keeps its own kind, so no real change becomes invisible. | |
| 234 | + if matches!(event.kind, notify::EventKind::Access(_)) { | |
| 235 | + return false; | |
| 236 | + } | |
| 237 | + event | |
| 238 | + .paths | |
| 239 | + .iter() | |
| 240 | + .any(|path| !ignored_project_path(project, path, ignored)) | |
| 241 | +} | |
| 242 | + | |
| 243 | +fn ignored_project_path(project: &Path, path: &Path, ignored: &[Pattern]) -> bool { | |
| 167 | 244 | const IGNORED_DIRECTORIES: &[&str] = &[ |
| 168 | 245 | ".cache", |
| 169 | 246 | ".celld", |
| @@ -175,22 +252,46 @@ | ||
| 175 | 252 | ".pnpm-store", |
| 176 | 253 | ".svn", |
| 177 | 254 | ".turbo", |
| 255 | + ".wrangler", | |
| 178 | 256 | ".yarn", |
| 179 | 257 | "bower_components", |
| 180 | 258 | "coverage", |
| 181 | 259 | "node_modules", |
| 182 | 260 | "target", |
| 183 | 261 | ]; |
| 184 | - path.strip_prefix(project) | |
| 185 | - .unwrap_or(path) | |
| 262 | + let relative = path.strip_prefix(project).unwrap_or(path); | |
| 263 | + relative | |
| 186 | 264 | .components() |
| 187 | 265 | .filter_map(|component| match component { |
| 188 | 266 | std::path::Component::Normal(name) => Some(name), |
| 189 | 267 | _ => None, |
| 190 | 268 | }) |
| 191 | 269 | .any(|name| IGNORED_DIRECTORIES.iter().any(|ignored| name == *ignored)) |
| 270 | + || relative.ancestors().any(|candidate| { | |
| 271 | + !candidate.as_os_str().is_empty() | |
| 272 | + && ignored.iter().any(|pattern| { | |
| 273 | + let options = MatchOptions { | |
| 274 | + case_sensitive: true, | |
| 275 | + require_literal_separator: true, | |
| 276 | + require_literal_leading_dot: true, | |
| 277 | + }; | |
| 278 | + pattern.matches_path_with(candidate, options) | |
| 279 | + // A directory creation event arrives before its child | |
| 280 | + // path. Probe one child so `generated/**` also ignores | |
| 281 | + // the event that creates `generated` itself. | |
| 282 | + || pattern.matches_path_with( | |
| 283 | + &candidate.join("__celld_watch_descendant__"), | |
| 284 | + options, | |
| 285 | + ) | |
| 286 | + }) | |
| 287 | + }) | |
| 192 | 288 | } |
| 193 | 289 | |
| 290 | +#[cfg(all(test, celld_internal_tests))] | |
| 291 | +mod dev_contract { | |
| 292 | + include!(env!("CELLD_INTERNAL_DEV_TESTS")); | |
| 293 | +} | |
| 294 | + | |
| 194 | 295 | struct ShutdownSignals { |
| 195 | 296 | #[cfg(unix)] |
| 196 | 297 | interrupt: tokio::signal::unix::Signal, |
| @@ -231,10 +332,13 @@ | ||
| 231 | 332 | pub fn print_help() -> anyhow::Result<()> { |
| 232 | 333 | crate::cli_output::Output::new(crate::cli_output::Format::Text).help( |
| 233 | 334 | &format!("celld dev — run an application with persistent local storage\n\n\ |
| 234 | -USAGE:\n celld dev [PROJECT] [--host IP] [--port PORT] [--logs]\n\n\ | |
| 335 | +USAGE:\n celld dev [PROJECT] [--host IP] [--port PORT] [--logs] [--no-watch] [--clean]\n\n\ | |
| 235 | 336 | PROJECT is a directory or a Wrangler config. It defaults to the current\n\ |
| 236 | -directory. celld stores all local state in PROJECT/.celld/dev.\n\n\ | |
| 237 | -OPTIONS:\n --host IP Worker listener host (default: 127.0.0.1)\n --port PORT Worker listener port (default: {DEFAULT_PORT})\n --logs Show the node warning and information logs\n -h, --help Show this help" | |
| 337 | +directory. celld stores all local state in PROJECT/.celld/dev, and it keeps\n\ | |
| 338 | +that state across a restart. A configuration change does not migrate the\n\ | |
| 339 | +state, so a cell can keep a value that the new configuration rejects. Use\n\ | |
| 340 | +--clean to start from an empty local state.\n\n\ | |
| 341 | +OPTIONS:\n --host IP Worker listener host (default: 127.0.0.1)\n --port PORT Worker listener port (default: {DEFAULT_PORT})\n --clean Delete PROJECT/.celld/dev before the server starts\n --logs Show the node warning and information logs\n --no-watch Do not rebuild when a project file changes\n --watch-ignore PATTERN Ignore a project-relative glob; repeat as needed\n -h, --help Show this help" | |
| 238 | 342 | ), |
| 239 | 343 | ) |
| 240 | 344 | } |
| @@ -243,12 +347,26 @@ | ||
| 243 | 347 | let mut project = None; |
| 244 | 348 | let mut host = IpAddr::V4(Ipv4Addr::LOCALHOST); |
| 245 | 349 | let mut port = DEFAULT_PORT; |
| 350 | + let mut clean = false; | |
| 246 | 351 | let mut logs = false; |
| 352 | + let mut watch = true; | |
| 353 | + let mut watch_ignores = Vec::new(); | |
| 247 | 354 | let mut arguments = arguments.into_iter(); |
| 248 | 355 | while let Some(argument) = arguments.next() { |
| 249 | 356 | match argument.as_str() { |
| 250 | 357 | "--help" | "-h" => return Ok(None), |
| 358 | + "--clean" => clean = true, | |
| 251 | 359 | "--logs" => logs = true, |
| 360 | + "--no-watch" => watch = false, | |
| 361 | + "--watch-ignore" => { | |
| 362 | + let value = arguments | |
| 363 | + .next() | |
| 364 | + .context("--watch-ignore requires a value")?; | |
| 365 | + watch_ignores.push( | |
| 366 | + Pattern::new(&value) | |
| 367 | + .with_context(|| format!("invalid --watch-ignore pattern {value:?}"))?, | |
| 368 | + ); | |
| 369 | + } | |
| 252 | 370 | "--host" => { |
| 253 | 371 | let value = arguments.next().context("--host requires a value")?; |
| 254 | 372 | host = value |
| @@ -269,10 +387,18 @@ | ||
| 269 | 387 | value => bail!("celld dev accepts one PROJECT, but also received {value:?}"), |
| 270 | 388 | } |
| 271 | 389 | } |
| 390 | + if !watch && !watch_ignores.is_empty() { | |
| 391 | + bail!("--watch-ignore cannot be used with --no-watch"); | |
| 392 | + } | |
| 272 | 393 | Ok(Some(Options { |
| 273 | 394 | project, |
| 274 | - listener: SocketAddr::new(host, port), | |
| 275 | - logs, | |
| 395 | + clean, | |
| 396 | + stack: StackOptions { | |
| 397 | + listener: SocketAddr::new(host, port), | |
| 398 | + logs, | |
| 399 | + watch, | |
| 400 | + watch_ignores, | |
| 401 | + }, | |
| 276 | 402 | })) |
| 277 | 403 | } |
| 278 | 404 | |
| @@ -288,26 +414,42 @@ | ||
| 288 | 414 | let project = config |
| 289 | 415 | .parent() |
| 290 | 416 | .context("the Wrangler config has no project directory")?; |
| 291 | - let state = project.join(".celld/dev"); | |
| 292 | - prepare_state(&state)?; | |
| 417 | + let state = DevState::for_project(project); | |
| 293 | 418 | let console = Console::new(); |
| 294 | 419 | console.header(); |
| 295 | 420 | console.detail("Project", &config.display().to_string()); |
| 296 | - console.detail("State", &state.display().to_string()); | |
| 297 | - if !options.logs { | |
| 421 | + console.detail("State", &state.path().display().to_string()); | |
| 422 | + // The delete runs before the directory is recreated, and the console names | |
| 423 | + // the outcome. A developer who reaches for this flag is already unsure | |
| 424 | + // which state the run uses, so a silent delete would answer nothing. | |
| 425 | + if options.clean { | |
| 426 | + let discarded = state.discard()?; | |
| 427 | + console.detail( | |
| 428 | + "Clean", | |
| 429 | + if discarded { | |
| 430 | + "discarded the existing local state" | |
| 431 | + } else { | |
| 432 | + "no local state to discard" | |
| 433 | + }, | |
| 434 | + ); | |
| 435 | + } | |
| 436 | + prepare_state(state.path())?; | |
| 437 | + if !options.stack.logs { | |
| 298 | 438 | console.detail("Logs", "hidden (use --logs)"); |
| 299 | 439 | } |
| 440 | + if !options.stack.watch { | |
| 441 | + console.detail("Watch", "disabled"); | |
| 442 | + } | |
| 300 | 443 | |
| 301 | 444 | let project_hash = format!( |
| 302 | 445 | "{:x}", |
| 303 | 446 | Sha256::digest(project.as_os_str().as_encoded_bytes()) |
| 304 | 447 | ); |
| 305 | - let store = open_store(&state, &console).await?; | |
| 448 | + let store = open_store(state.path(), &console).await?; | |
| 306 | 449 | run_stack( |
| 307 | 450 | &config, |
| 308 | - &state, | |
| 309 | - options.listener, | |
| 310 | - options.logs, | |
| 451 | + state.path(), | |
| 452 | + options.stack, | |
| 311 | 453 | &project_hash, |
| 312 | 454 | &store, |
| 313 | 455 | &console, |
| @@ -355,8 +497,7 @@ | ||
| 355 | 497 | async fn run_stack( |
| 356 | 498 | config: &Path, |
| 357 | 499 | state: &Path, |
| 358 | - listener: SocketAddr, | |
| 359 | - logs: bool, | |
| 500 | + options: StackOptions, | |
| 360 | 501 | project_hash: &str, |
| 361 | 502 | store: &Store, |
| 362 | 503 | console: &Console, |
| @@ -369,14 +510,25 @@ | ||
| 369 | 510 | let project = config |
| 370 | 511 | .parent() |
| 371 | 512 | .context("the Wrangler config has no project directory")?; |
| 372 | - let mut watcher = ProjectWatcher::new(project)?; | |
| 513 | + let mut watcher = options | |
| 514 | + .watch | |
| 515 | + .then(|| ProjectWatcher::new(project, options.watch_ignores)) | |
| 516 | + .transpose()?; | |
| 373 | 517 | |
| 374 | 518 | console.progress("building the application"); |
| 375 | - deploy_project(config, store, logs).await?; | |
| 376 | - let mut running = start_node(state, listener, logs, project_hash, store, console).await?; | |
| 519 | + deploy_project(config, store, options.logs).await?; | |
| 520 | + let mut running = start_node( | |
| 521 | + state, | |
| 522 | + options.listener, | |
| 523 | + options.logs, | |
| 524 | + project_hash, | |
| 525 | + store, | |
| 526 | + console, | |
| 527 | + ) | |
| 528 | + .await?; | |
| 377 | 529 | |
| 378 | 530 | loop { |
| 379 | - match wait_for_node_event(&mut running.child, &mut signals, &mut watcher).await? { | |
| 531 | + match wait_for_node_event(&mut running.child, &mut signals, watcher.as_mut()).await? { | |
| 380 | 532 | NodeEvent::Exited(status) => { |
| 381 | 533 | let _ = running.output.await; |
| 382 | 534 | if status.success() { |
| @@ -390,13 +542,21 @@ | ||
| 390 | 542 | } |
| 391 | 543 | NodeEvent::Reload => { |
| 392 | 544 | console.progress("change detected; rebuilding the application"); |
| 393 | - if let Err(error) = deploy_project(config, store, logs).await { | |
| 545 | + if let Err(error) = deploy_project(config, store, options.logs).await { | |
| 394 | 546 | console.failure(&format!("reload failed: {error:#}")); |
| 395 | 547 | continue; |
| 396 | 548 | } |
| 397 | 549 | console.progress("restarting the application"); |
| 398 | 550 | stop_running_node(running).await; |
| 399 | - running = start_node(state, listener, logs, project_hash, store, console).await?; | |
| 551 | + running = start_node( | |
| 552 | + state, | |
| 553 | + options.listener, | |
| 554 | + options.logs, | |
| 555 | + project_hash, | |
| 556 | + store, | |
| 557 | + console, | |
| 558 | + ) | |
| 559 | + .await?; | |
| 400 | 560 | } |
| 401 | 561 | } |
| 402 | 562 | } |
| @@ -461,6 +621,10 @@ | ||
| 461 | 621 | .stdin(Stdio::null()) |
| 462 | 622 | .stdout(Stdio::piped()) |
| 463 | 623 | .stderr(Stdio::inherit()); |
| 624 | + // `run_stack` normally consumes `RunningNode` through the graceful stop | |
| 625 | + // path. An error or cancellation can instead drop it, so the child must | |
| 626 | + // not outlive the value that proves the supervisor still owns it. | |
| 627 | + command.kill_on_drop(true); | |
| 464 | 628 | if !logs { |
| 465 | 629 | // The supervisor still forwards ERROR records and the child's stderr. |
| 466 | 630 | // INFO and WARN records stay hidden until the operator asks for them. |
| @@ -475,6 +639,26 @@ | ||
| 475 | 639 | // supervisor asks for the fast same-node preserve path. |
| 476 | 640 | command.as_std_mut().process_group(0); |
| 477 | 641 | } |
| 642 | + #[cfg(target_os = "linux")] | |
| 643 | + { | |
| 644 | + use std::os::unix::process::CommandExt as _; | |
| 645 | + | |
| 646 | + let supervisor = unsafe { libc::getpid() }; | |
| 647 | + // Drop cannot run after SIGKILL or a supervisor crash. Ask the kernel | |
| 648 | + // to kill the node in that case. The parent check closes the race in | |
| 649 | + // which the supervisor exits between `fork` and `prctl`. | |
| 650 | + unsafe { | |
| 651 | + command.as_std_mut().pre_exec(move || { | |
| 652 | + if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) == -1 { | |
| 653 | + return Err(std::io::Error::last_os_error()); | |
| 654 | + } | |
| 655 | + if libc::getppid() != supervisor { | |
| 656 | + return Err(std::io::Error::from_raw_os_error(libc::ESRCH)); | |
| 657 | + } | |
| 658 | + Ok(()) | |
| 659 | + }); | |
| 660 | + } | |
| 661 | + } | |
| 478 | 662 | let mut child = command.spawn().context("start the local celld node")?; |
| 479 | 663 | |
| 480 | 664 | let stdout = child |
| @@ -566,7 +750,7 @@ | ||
| 566 | 750 | async fn wait_for_node_event( |
| 567 | 751 | child: &mut Child, |
| 568 | 752 | signals: &mut ShutdownSignals, |
| 569 | - watcher: &mut ProjectWatcher, | |
| 753 | + watcher: Option<&mut ProjectWatcher>, | |
| 570 | 754 | ) -> anyhow::Result<NodeEvent> { |
| 571 | 755 | crate::asyncrt::select! { |
| 572 | 756 | status = child.wait() => { |
| @@ -574,13 +758,20 @@ | ||
| 574 | 758 | Ok(NodeEvent::Exited(status)) |
| 575 | 759 | } |
| 576 | 760 | _ = signals.received() => Ok(NodeEvent::Shutdown), |
| 577 | - changed = watcher.changed() => { | |
| 761 | + changed = wait_for_project_change(watcher) => { | |
| 578 | 762 | changed?; |
| 579 | 763 | Ok(NodeEvent::Reload) |
| 580 | 764 | } |
| 581 | 765 | } |
| 582 | 766 | } |
| 583 | 767 | |
| 768 | +async fn wait_for_project_change(watcher: Option<&mut ProjectWatcher>) -> anyhow::Result<()> { | |
| 769 | + match watcher { | |
| 770 | + Some(watcher) => watcher.changed().await, | |
| 771 | + None => std::future::pending().await, | |
| 772 | + } | |
| 773 | +} | |
| 774 | + | |
| 584 | 775 | async fn stop_running_node(mut running: RunningNode) { |
| 585 | 776 | stop_child(&mut running.child, Some(&running.internal)).await; |
| 586 | 777 | let _ = running.output.await; |
modifiedcrates/celld/drain_token.rs+47−5View file
| @@ -8,7 +8,8 @@ | ||
| 8 | 8 | //! within its wait bound proceeds anyway, because the orchestrator grace is |
| 9 | 9 | //! finite and an unserialized handoff is strictly better than a forced |
| 10 | 10 | //! exit. A fresh node's first readiness reads the same object through |
| 11 | -//! [`read`] and treats a live foreign claim as an unsettled fleet. | |
| 11 | +//! [`read`]. It treats a live foreign claim as an unsettled fleet and compares | |
| 12 | +//! recovery with the pre-drain restoration baseline retained after release. | |
| 12 | 13 | |
| 13 | 14 | use crate::bucket::Bucket; |
| 14 | 15 | use celld_logic::drain::DrainToken; |
| @@ -32,8 +33,16 @@ | ||
| 32 | 33 | node: String, |
| 33 | 34 | #[serde(default)] |
| 34 | 35 | expires_ms: u64, |
| 36 | + #[serde(default)] | |
| 37 | + restoration_baseline: Vec<RestorationBaselineWire>, | |
| 35 | 38 | } |
| 36 | 39 | |
| 40 | +#[derive(Clone, Serialize, Deserialize)] | |
| 41 | +struct RestorationBaselineWire { | |
| 42 | + node: String, | |
| 43 | + restoring: u64, | |
| 44 | +} | |
| 45 | + | |
| 37 | 46 | /// The token object as read from the bucket. `token: None` with an etag is |
| 38 | 47 | /// an unparseable body: claimable, and settled for the ready gate. |
| 39 | 48 | pub struct Current { |
| @@ -46,6 +55,7 @@ | ||
| 46 | 55 | pub struct Hold { |
| 47 | 56 | etag: String, |
| 48 | 57 | expires_ms: u64, |
| 58 | + restoration_baseline: Vec<RestorationBaselineWire>, | |
| 49 | 59 | } |
| 50 | 60 | |
| 51 | 61 | /// The acquisition result carried into the drain loop. |
| @@ -70,6 +80,14 @@ | ||
| 70 | 80 | .map(|wire| DrainToken { |
| 71 | 81 | node: wire.node, |
| 72 | 82 | expires_ms: wire.expires_ms, |
| 83 | + restoration_baseline: wire | |
| 84 | + .restoration_baseline | |
| 85 | + .into_iter() | |
| 86 | + .map(|baseline| celld_logic::drain::RestorationBaseline { | |
| 87 | + node: baseline.node, | |
| 88 | + restoring: baseline.restoring, | |
| 89 | + }) | |
| 90 | + .collect(), | |
| 73 | 91 | }); |
| 74 | 92 | Ok(Some(Current { token, etag })) |
| 75 | 93 | } |
| @@ -78,7 +96,12 @@ | ||
| 78 | 96 | /// conditional write lost a race; the caller retries within its bound. An |
| 79 | 97 | /// ambiguous write also returns `None`: if it committed, the next attempt |
| 80 | 98 | /// reads this node's own record back and claims over it. |
| 81 | -async fn try_claim(bucket: &Bucket, node: &str, now_ms: u64) -> Option<Hold> { | |
| 99 | +async fn try_claim( | |
| 100 | + bucket: &Bucket, | |
| 101 | + node: &str, | |
| 102 | + now_ms: u64, | |
| 103 | + restoration_baseline: &[RestorationBaselineWire], | |
| 104 | +) -> Option<Hold> { | |
| 82 | 105 | let current = read(bucket).await.ok().flatten(); |
| 83 | 106 | if !celld_logic::drain::may_claim( |
| 84 | 107 | current.as_ref().and_then(|current| current.token.as_ref()), |
| @@ -91,23 +114,40 @@ | ||
| 91 | 114 | let body = serde_json::to_vec(&Wire { |
| 92 | 115 | node: node.to_string(), |
| 93 | 116 | expires_ms, |
| 117 | + restoration_baseline: restoration_baseline.to_vec(), | |
| 94 | 118 | }) |
| 95 | 119 | .expect("encode drain token"); |
| 96 | 120 | let guard = current.as_ref().map(|current| current.etag.as_str()); |
| 97 | 121 | match bucket.put_cas(TOKEN_KEY, body, guard).await { |
| 98 | - Ok(Some(etag)) => Some(Hold { etag, expires_ms }), | |
| 122 | + Ok(Some(etag)) => Some(Hold { | |
| 123 | + etag, | |
| 124 | + expires_ms, | |
| 125 | + restoration_baseline: restoration_baseline.to_vec(), | |
| 126 | + }), | |
| 99 | 127 | Ok(None) | Err(_) => None, |
| 100 | 128 | } |
| 101 | 129 | } |
| 102 | 130 | |
| 103 | 131 | /// Claim the token, retrying until `wait` elapses. The wait is this |
| 104 | 132 | /// function's own budget: the caller's drain deadline never covers it. |
| 105 | -pub async fn acquire(bucket: &Bucket, node: &str, wait: Duration) -> Outcome { | |
| 133 | +pub async fn acquire( | |
| 134 | + bucket: &Bucket, | |
| 135 | + node: &str, | |
| 136 | + wait: Duration, | |
| 137 | + restoration_baseline: Vec<celld_logic::drain::RestorationBaseline>, | |
| 138 | +) -> Outcome { | |
| 139 | + let restoration_baseline = restoration_baseline | |
| 140 | + .into_iter() | |
| 141 | + .map(|baseline| RestorationBaselineWire { | |
| 142 | + node: baseline.node, | |
| 143 | + restoring: baseline.restoring, | |
| 144 | + }) | |
| 145 | + .collect::<Vec<_>>(); | |
| 106 | 146 | let started_mono_ms = crate::asyncrt::mono_ms(); |
| 107 | 147 | let wait_ms = wait.as_millis() as u64; |
| 108 | 148 | loop { |
| 109 | 149 | let now_ms = crate::ownership_store::now_ms(); |
| 110 | - if let Some(hold) = try_claim(bucket, node, now_ms).await { | |
| 150 | + if let Some(hold) = try_claim(bucket, node, now_ms, &restoration_baseline).await { | |
| 111 | 151 | tracing::info!( |
| 112 | 152 | event = "drain_token_acquired", |
| 113 | 153 | waited_ms = crate::asyncrt::mono_ms().saturating_sub(started_mono_ms), |
| @@ -151,6 +191,7 @@ | ||
| 151 | 191 | let body = serde_json::to_vec(&Wire { |
| 152 | 192 | node: node.to_string(), |
| 153 | 193 | expires_ms, |
| 194 | + restoration_baseline: hold.restoration_baseline.clone(), | |
| 154 | 195 | }) |
| 155 | 196 | .expect("encode drain token"); |
| 156 | 197 | match bucket.put_cas(TOKEN_KEY, body, Some(&hold.etag)).await { |
| @@ -203,6 +244,7 @@ | ||
| 203 | 244 | let body = serde_json::to_vec(&Wire { |
| 204 | 245 | node: node.to_string(), |
| 205 | 246 | expires_ms: 0, |
| 247 | + restoration_baseline: hold.restoration_baseline, | |
| 206 | 248 | }) |
| 207 | 249 | .expect("encode drain token"); |
| 208 | 250 | match bucket.put_cas(TOKEN_KEY, body, Some(&hold.etag)).await { |
modifiedcrates/celld/env_vars.rs+61−2View file
| @@ -8,6 +8,30 @@ | ||
| 8 | 8 | |
| 9 | 9 | use anyhow::{anyhow, bail}; |
| 10 | 10 | |
| 11 | +pub const DEFAULT_SHUTDOWN_TOTAL_MS: u64 = 40_000; | |
| 12 | +pub const DEFAULT_DRAIN_TOKEN_WAIT_MS: u64 = 30_000; | |
| 13 | +pub const MAX_DRAIN_TOKEN_WAIT_NUMERATOR: u64 = 3; | |
| 14 | +pub const MAX_DRAIN_TOKEN_WAIT_DENOMINATOR: u64 = 4; | |
| 15 | + | |
| 16 | +/// Calculate the largest drain-token wait that preserves the shutdown work | |
| 17 | +/// share. The split operations avoid overflow for a `u64` process bound. | |
| 18 | +pub const fn maximum_drain_token_wait_ms(total_ms: u64) -> u64 { | |
| 19 | + (total_ms / MAX_DRAIN_TOKEN_WAIT_DENOMINATOR) * MAX_DRAIN_TOKEN_WAIT_NUMERATOR | |
| 20 | + + (total_ms % MAX_DRAIN_TOKEN_WAIT_DENOMINATOR) * MAX_DRAIN_TOKEN_WAIT_NUMERATOR | |
| 21 | + / MAX_DRAIN_TOKEN_WAIT_DENOMINATOR | |
| 22 | +} | |
| 23 | + | |
| 24 | +const _: () = | |
| 25 | + assert!(DEFAULT_DRAIN_TOKEN_WAIT_MS == maximum_drain_token_wait_ms(DEFAULT_SHUTDOWN_TOTAL_MS)); | |
| 26 | + | |
| 27 | +/// The two shutdown values whose relationship controls whether handoff work | |
| 28 | +/// can start after the drain-token wait. | |
| 29 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 30 | +pub struct ShutdownTiming { | |
| 31 | + pub total_ms: u64, | |
| 32 | + pub drain_token_wait_ms: u64, | |
| 33 | +} | |
| 34 | + | |
| 11 | 35 | /// Validate every typed production variable before the runtime starts. |
| 12 | 36 | /// |
| 13 | 37 | /// Some consumers cache a value or read it from a synchronous callback, so |
| @@ -18,6 +42,7 @@ | ||
| 18 | 42 | "CELLD_CLOUD", |
| 19 | 43 | "CELLD_CLOUD_RESTART_ON_DEPLOY", |
| 20 | 44 | "CELLD_LTX_COMPACTION", |
| 45 | + "CELLD_LTX_PAGED", | |
| 21 | 46 | "CELLD_OUTPUT_GATE", |
| 22 | 47 | "CELLD_PRESENCE_SHADOW", |
| 23 | 48 | "CELLD_TRUST_FORWARDED_HEADERS", |
| @@ -43,11 +68,14 @@ | ||
| 43 | 68 | "CELLD_MAX_OUTBOUND_WEBSOCKETS", |
| 44 | 69 | "CELLD_MAX_REQUEST_BODY_BYTES", |
| 45 | 70 | "CELLD_MAX_REQUESTS", |
| 71 | + "CELLD_RECOVERY_RETRY_MS", | |
| 72 | + "CELLD_RECOVERY_RETRIES", | |
| 46 | 73 | "CELLD_MAX_STATELESS_ISOLATES", |
| 47 | 74 | "CELLD_OPERATION_DEADLINE_MS", |
| 75 | + "CELLD_PLACEMENT_WEIGHT", | |
| 76 | + "CELLD_REBALANCE_BATCH_CELLS", | |
| 48 | 77 | "CELLD_RELEASES", |
| 49 | 78 | "CELLD_SHUTDOWN_DRAIN_MS", |
| 50 | - "CELLD_SHUTDOWN_TOTAL_MS", | |
| 51 | 79 | "CELLD_TOKIO_THREADS", |
| 52 | 80 | "CELLD_TTL_MS", |
| 53 | 81 | "CELLD_WAKER_TICK_MS", |
| @@ -60,19 +88,23 @@ | ||
| 60 | 88 | "CELLD_ALARM_RESIDENT_MS", |
| 61 | 89 | "CELLD_ASSET_CACHE_BYTES", |
| 62 | 90 | "CELLD_DEPLOY_MAX_AGE_S", |
| 63 | - "CELLD_DRAIN_TOKEN_WAIT_MS", | |
| 64 | 91 | "CELLD_LOCAL_CACHE_MAX_BYTES", |
| 65 | 92 | "CELLD_LTX_TRUNCATE_PAGES", |
| 93 | + "CELLD_LOG_GROUP_COMMIT_MS", | |
| 66 | 94 | "CELLD_LOG_HEDGE_MS", |
| 67 | 95 | "CELLD_LOG_WINDOW", |
| 68 | 96 | "CELLD_LOG_WINDOW_BYTES", |
| 69 | 97 | "CELLD_MAX_RESIDENT_CELLS", |
| 70 | 98 | "CELLD_MAX_RSS_MB", |
| 99 | + "CELLD_QUEUE_PRODUCER_GROUP_MS", | |
| 71 | 100 | "CELLD_READY_FLEET_GATE_MS", |
| 101 | + "CELLD_REBALANCE_INTERVAL_MS", | |
| 72 | 102 | ] { |
| 73 | 103 | optional::<u64>(name)?; |
| 74 | 104 | } |
| 75 | 105 | |
| 106 | + shutdown_timing()?; | |
| 107 | + | |
| 76 | 108 | if let Some(value) = optional::<u64>("CELLD_PRESENCE_HEARTBEAT_MS")? { |
| 77 | 109 | if !(50..=30_000).contains(&value) { |
| 78 | 110 | bail!("CELLD_PRESENCE_HEARTBEAT_MS must be between 50 and 30000, not {value}"); |
| @@ -96,9 +128,36 @@ | ||
| 96 | 128 | bail!("CELLD_PRESSURE_OWNERSHIP must be release or sticky, not {value:?}"); |
| 97 | 129 | } |
| 98 | 130 | } |
| 131 | + if let Some(node) = value("CELLD_NODE")? { | |
| 132 | + crate::machine::validate_node_name(&node).map_err(|error| anyhow!("CELLD_NODE {error}"))?; | |
| 133 | + } | |
| 99 | 134 | Ok(()) |
| 100 | 135 | } |
| 101 | 136 | |
| 137 | +/// Read the complete shutdown bound and the drain-token wait together. | |
| 138 | +/// | |
| 139 | +/// The wait can use at most three quarters of the complete bound. The | |
| 140 | +/// remaining quarter is available for request drain, ownership handoff, | |
| 141 | +/// connection flush, and local durability shutdown. | |
| 142 | +pub fn shutdown_timing() -> anyhow::Result<ShutdownTiming> { | |
| 143 | + let total_ms = positive("CELLD_SHUTDOWN_TOTAL_MS")?.unwrap_or(DEFAULT_SHUTDOWN_TOTAL_MS); | |
| 144 | + let drain_token_wait_ms = | |
| 145 | + with_default("CELLD_DRAIN_TOKEN_WAIT_MS", DEFAULT_DRAIN_TOKEN_WAIT_MS)?; | |
| 146 | + let maximum_wait_ms = maximum_drain_token_wait_ms(total_ms); | |
| 147 | + if drain_token_wait_ms > maximum_wait_ms { | |
| 148 | + bail!( | |
| 149 | + "CELLD_DRAIN_TOKEN_WAIT_MS must be at most \ | |
| 150 | + {MAX_DRAIN_TOKEN_WAIT_NUMERATOR}/{MAX_DRAIN_TOKEN_WAIT_DENOMINATOR} of \ | |
| 151 | + CELLD_SHUTDOWN_TOTAL_MS; maximum is {maximum_wait_ms} for {total_ms}, \ | |
| 152 | + not {drain_token_wait_ms}" | |
| 153 | + ); | |
| 154 | + } | |
| 155 | + Ok(ShutdownTiming { | |
| 156 | + total_ms, | |
| 157 | + drain_token_wait_ms, | |
| 158 | + }) | |
| 159 | +} | |
| 160 | + | |
| 102 | 161 | pub fn value(name: &str) -> anyhow::Result<Option<String>> { |
| 103 | 162 | match std::env::var(name) { |
| 104 | 163 | Ok(value) => Ok(Some(value)), |
modifiedcrates/celld/fleet.rs+70−43View file
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | //! Production bucket deployment adapters reused by the clean-sheet host. |
| 10 | 10 | |
| 11 | -use crate::bucket::{Bucket, CasVerdict}; | |
| 11 | +use crate::bucket::{Bucket, StorageProbeVerdict}; | |
| 12 | 12 | use crate::deploy; |
| 13 | 13 | use crate::js::{ModuleSource, WorkerConfigOptions}; |
| 14 | 14 | use crate::ownership_store::NodeLeaseWire; |
| @@ -261,46 +261,57 @@ | ||
| 261 | 261 | } |
| 262 | 262 | } |
| 263 | 263 | |
| 264 | -/// Test the conditional write before a node serves, and refuse to start | |
| 265 | -/// when the store proves it cannot fence. | |
| 264 | +/// Test the required conditional writes and ranged reads before a node serves, | |
| 265 | +/// and refuse to start when the store proves it cannot support celld. | |
| 266 | 266 | /// |
| 267 | 267 | /// The two probe outcomes get different answers on purpose. A violation |
| 268 | -/// is a property of the store: it never clears, and a node that serves | |
| 269 | -/// anyway can share a cell with a second owner. Refusing to start turns | |
| 270 | -/// the restart loop such a store otherwise produces into one message. | |
| 268 | +/// is a property of the store: it never clears. A node that serves anyway can | |
| 269 | +/// share a cell with another owner or fail when it reads stored cell data. | |
| 270 | +/// Refusing to start reports the permanent problem before either failure. | |
| 271 | 271 | /// |
| 272 | -/// An ambiguous error is not that. `put_cas` runs with retries off, so a | |
| 273 | -/// single slow or dropped connection at boot answers `Err`. The lease | |
| 274 | -/// machinery already handles a transient fault, and a node must not | |
| 275 | -/// refuse to start over one. | |
| 272 | +/// An ambiguous error is not that. `put_cas` runs with transport retries off, | |
| 273 | +/// so a slow or dropped connection answers `Err`. The complete probe retries | |
| 274 | +/// with a fresh key twice, then preserves the existing warn-and-serve result. | |
| 276 | 275 | /// |
| 277 | 276 | /// `managed` reports the refusal to the Managed Control Plane, the way |
| 278 | 277 | /// [`validate_managed_bucket`] reports its own failures. Without it an |
| 279 | 278 | /// enrolled installation that refuses to serve leaves only local stderr |
| 280 | 279 | /// behind, so the operator who most needs the reason cannot read it. |
| 281 | 280 | pub async fn probe_storage_before_serving(bucket: &Bucket, managed: bool) -> anyhow::Result<()> { |
| 282 | - match bucket.probe_cas_steps().await { | |
| 283 | - Ok(CasVerdict::Conformant) => Ok(()), | |
| 284 | - Ok(CasVerdict::Violation(reason)) => { | |
| 285 | - if managed { | |
| 286 | - crate::control_plane::report_managed_runtime_state( | |
| 287 | - crate::control_plane::ManagedRuntimeState::StorageContractViolated, | |
| 281 | + const ATTEMPTS: usize = 3; | |
| 282 | + for attempt in 1..=ATTEMPTS { | |
| 283 | + match bucket.probe_startup_storage_steps().await { | |
| 284 | + Ok(StorageProbeVerdict::Conformant) => return Ok(()), | |
| 285 | + Ok(StorageProbeVerdict::Violation(reason)) => { | |
| 286 | + if managed { | |
| 287 | + crate::control_plane::report_managed_runtime_state( | |
| 288 | + crate::control_plane::ManagedRuntimeState::StorageContractViolated, | |
| 289 | + ); | |
| 290 | + } | |
| 291 | + bail!( | |
| 292 | + "the bucket does not keep the storage contract, so celld cannot serve cells \ | |
| 293 | + safely on it: {reason}. Set CELLD_STORAGE_PROBE=0 to start without this test" | |
| 294 | + ) | |
| 295 | + } | |
| 296 | + Err(error) if attempt < ATTEMPTS => { | |
| 297 | + tracing::warn!( | |
| 298 | + attempt, | |
| 299 | + attempts = ATTEMPTS, | |
| 300 | + error = format!("{error:#}"), | |
| 301 | + "could not verify the bucket storage contract; retrying" | |
| 288 | 302 | ); |
| 289 | 303 | } |
| 290 | - bail!( | |
| 291 | - "the bucket does not keep the conditional-write contract, so celld cannot own \ | |
| 292 | - cells safely on it: {reason}. Set CELLD_STORAGE_PROBE=0 to start without this \ | |
| 293 | - test" | |
| 294 | - ) | |
| 304 | + Err(error) => { | |
| 305 | + tracing::warn!( | |
| 306 | + attempts = ATTEMPTS, | |
| 307 | + error = format!("{error:#}"), | |
| 308 | + "could not verify the bucket storage contract; starting anyway" | |
| 309 | + ); | |
| 310 | + return Ok(()); | |
| 311 | + } | |
| 295 | 312 | } |
| 296 | - Err(error) => { | |
| 297 | - tracing::warn!( | |
| 298 | - error = format!("{error:#}"), | |
| 299 | - "could not verify the bucket conditional write; starting anyway" | |
| 300 | - ); | |
| 301 | - Ok(()) | |
| 302 | - } | |
| 303 | 313 | } |
| 314 | + unreachable!("the storage probe loop always returns on its last attempt") | |
| 304 | 315 | } |
| 305 | 316 | |
| 306 | 317 | pub async fn diagnose( |
| @@ -445,13 +456,18 @@ | ||
| 445 | 456 | .load |
| 446 | 457 | .in_use_bytes |
| 447 | 458 | .map_or_else(|| "unknown".to_string(), |bytes| bytes.to_string()); |
| 459 | + let owned_cells = node | |
| 460 | + .load | |
| 461 | + .owned_cells | |
| 462 | + .map_or_else(|| "unknown".to_string(), |cells| cells.to_string()); | |
| 448 | 463 | out.row(&Check::ok( |
| 449 | 464 | format!("peer {} at {}", node.node, node.addr), |
| 450 | 465 | format!( |
| 451 | - "(signed direct probe) protocol={} resident_cells={} \ | |
| 466 | + "(signed direct probe) protocol={} owned_cells={} resident_cells={} \ | |
| 452 | 467 | websockets={} rss_bytes={} in_use_bytes={} cpu_percent={:.2} fds={}/{} \ |
| 453 | 468 | pressured={} shed_cells={} restoring={} load_age_ms={}", |
| 454 | 469 | node.peer_protocol, |
| 470 | + owned_cells, | |
| 455 | 471 | node.load.resident_cells, |
| 456 | 472 | node.load.host_websockets, |
| 457 | 473 | rss_bytes, |
| @@ -535,7 +551,7 @@ | ||
| 535 | 551 | .filter(|value| !value.trim().is_empty()) |
| 536 | 552 | }; |
| 537 | 553 | if bucket.is_none() { |
| 538 | - *bucket = env("CELLD_BUCKET").map(|value| value.trim_start_matches("s3://").to_string()); | |
| 554 | + *bucket = crate::cli_options::bucket_from_environment(); | |
| 539 | 555 | } |
| 540 | 556 | if endpoint.is_none() { |
| 541 | 557 | *endpoint = env("S3_ENDPOINT"); |
| @@ -547,6 +563,11 @@ | ||
| 547 | 563 | .unwrap_or_else(|| "us-east-1".to_string()) |
| 548 | 564 | } |
| 549 | 565 | |
| 566 | +#[cfg(all(test, celld_internal_tests))] | |
| 567 | +mod internal_tests { | |
| 568 | + include!(env!("CELLD_INTERNAL_FLEET_TESTS")); | |
| 569 | +} | |
| 570 | + | |
| 550 | 571 | pub async fn run_deploy(arguments: Vec<String>) -> anyhow::Result<()> { |
| 551 | 572 | let Some(mut options) = deploy::options_from_arguments(arguments)? else { |
| 552 | 573 | deploy::print_help(); |
| @@ -726,8 +747,26 @@ | ||
| 726 | 747 | } |
| 727 | 748 | crate::protocol::validate_required_features(&manifest.required_features)?; |
| 728 | 749 | crate::protocol::validate_queue_manifest(&manifest)?; |
| 750 | + let prefix = &pointer.prefix; | |
| 751 | + let mut fetched = | |
| 752 | + futures_util::future::try_join_all(manifest.modules.iter().map(|module| async move { | |
| 753 | + let key = format!("{prefix}/{}", module.name); | |
| 754 | + let bytes = get_bytes(bucket, &key).await?; | |
| 755 | + module.verify(&bytes)?; | |
| 756 | + anyhow::Ok((module, bytes)) | |
| 757 | + })) | |
| 758 | + .await?; | |
| 729 | 759 | let src = match manifest.main_module.as_deref() { |
| 730 | - Some(main) => get_string(bucket, &format!("{}/{main}", pointer.prefix)).await?, | |
| 760 | + Some(main) => { | |
| 761 | + let position = fetched | |
| 762 | + .iter() | |
| 763 | + .position(|(module, _)| module.name == main) | |
| 764 | + .with_context(|| { | |
| 765 | + format!("main module {main:?} is absent from the manifest module list") | |
| 766 | + })?; | |
| 767 | + let (_, bytes) = fetched.remove(position); | |
| 768 | + String::from_utf8(bytes.into()).context("deployment main module is not UTF-8")? | |
| 769 | + } | |
| 731 | 770 | None if manifest.assets.is_some() => { |
| 732 | 771 | // Ingress is handled by the immutable asset resolver. Keeping a |
| 733 | 772 | // synthetic Worker makes the runtime construction path uniform |
| @@ -737,18 +776,6 @@ | ||
| 737 | 776 | } |
| 738 | 777 | None => bail!("deployment has neither a main module nor assets"), |
| 739 | 778 | }; |
| 740 | - let prefix = &pointer.prefix; | |
| 741 | - let fetched = futures_util::future::try_join_all( | |
| 742 | - manifest | |
| 743 | - .modules | |
| 744 | - .iter() | |
| 745 | - .filter(|module| manifest.main_module.as_deref() != Some(module.name.as_str())) | |
| 746 | - .map(|module| async move { | |
| 747 | - let key = format!("{prefix}/{}", module.name); | |
| 748 | - anyhow::Ok((module, get_bytes(bucket, &key).await?)) | |
| 749 | - }), | |
| 750 | - ) | |
| 751 | - .await?; | |
| 752 | 779 | let mut modules = Vec::new(); |
| 753 | 780 | for (module, bytes) in fetched { |
| 754 | 781 | let entry = match module.kind { |
modifiedcrates/celld/host_services.rs+44−0View file
| @@ -27,18 +27,22 @@ | ||
| 27 | 27 | |
| 28 | 28 | /// All process-like services owned by one execution domain. |
| 29 | 29 | pub struct HostServices { |
| 30 | + domain: OnceLock<crate::asyncrt::DomainToken>, | |
| 30 | 31 | node_load: OnceLock<Arc<LiveLoad>>, |
| 31 | 32 | wake_entry: crate::js::WakeEntryService, |
| 32 | 33 | websockets: crate::js::WebSocketService, |
| 34 | + http_streams: Arc<crate::js::HttpStreamService>, | |
| 33 | 35 | metrics: MetricsBackend, |
| 34 | 36 | } |
| 35 | 37 | |
| 36 | 38 | impl HostServices { |
| 37 | 39 | pub(crate) fn production() -> Self { |
| 38 | 40 | Self { |
| 41 | + domain: OnceLock::new(), | |
| 39 | 42 | node_load: OnceLock::new(), |
| 40 | 43 | wake_entry: crate::js::WakeEntryService::default(), |
| 41 | 44 | websockets: crate::js::WebSocketService::default(), |
| 45 | + http_streams: Arc::new(crate::js::HttpStreamService::default()), | |
| 42 | 46 | metrics: MetricsBackend::Production(Mutex::new(ProcessLoadSampler::default())), |
| 43 | 47 | } |
| 44 | 48 | } |
| @@ -46,9 +50,11 @@ | ||
| 46 | 50 | #[cfg(celld_internal_tests)] |
| 47 | 51 | pub fn scripted() -> Self { |
| 48 | 52 | Self { |
| 53 | + domain: OnceLock::new(), | |
| 49 | 54 | node_load: OnceLock::new(), |
| 50 | 55 | wake_entry: crate::js::WakeEntryService::default(), |
| 51 | 56 | websockets: crate::js::WebSocketService::default(), |
| 57 | + http_streams: Arc::new(crate::js::HttpStreamService::default()), | |
| 52 | 58 | metrics: MetricsBackend::Scripted(Mutex::new(HostMetricsSample::default())), |
| 53 | 59 | } |
| 54 | 60 | } |
| @@ -57,6 +63,27 @@ | ||
| 57 | 63 | let _ = self.node_load.set(load); |
| 58 | 64 | } |
| 59 | 65 | |
| 66 | + pub(crate) fn bind_domain(&self, domain: crate::asyncrt::DomainToken) { | |
| 67 | + if let Err(candidate) = self.domain.set(domain) { | |
| 68 | + assert!( | |
| 69 | + self.domain | |
| 70 | + .get() | |
| 71 | + .is_some_and(|bound| bound.same_owner(&candidate)), | |
| 72 | + "HostServices cannot belong to more than one execution domain" | |
| 73 | + ); | |
| 74 | + } | |
| 75 | + self.http_streams.bind_domain( | |
| 76 | + self.domain | |
| 77 | + .get() | |
| 78 | + .expect("a HostServices domain was just installed") | |
| 79 | + .clone(), | |
| 80 | + ); | |
| 81 | + } | |
| 82 | + | |
| 83 | + pub(crate) fn domain_token(&self) -> Option<crate::asyncrt::DomainToken> { | |
| 84 | + self.domain.get().cloned() | |
| 85 | + } | |
| 86 | + | |
| 60 | 87 | pub fn node_load(&self) -> Option<Arc<LiveLoad>> { |
| 61 | 88 | self.node_load.get().cloned() |
| 62 | 89 | } |
| @@ -69,6 +96,23 @@ | ||
| 69 | 96 | &self.websockets |
| 70 | 97 | } |
| 71 | 98 | |
| 99 | + pub(crate) fn http_streams(&self) -> Arc<crate::js::HttpStreamService> { | |
| 100 | + if let Some(domain) = self.domain_token() { | |
| 101 | + self.http_streams.bind_domain(domain); | |
| 102 | + } | |
| 103 | + self.http_streams.clone() | |
| 104 | + } | |
| 105 | + | |
| 106 | + #[cfg(all(test, celld_internal_tests))] | |
| 107 | + pub(crate) fn quarantine_http_streams(&self) { | |
| 108 | + self.http_streams.quarantine(); | |
| 109 | + } | |
| 110 | + | |
| 111 | + #[cfg(all(test, celld_internal_tests))] | |
| 112 | + pub(crate) fn close_http_streams(&self) { | |
| 113 | + self.http_streams.close(); | |
| 114 | + } | |
| 115 | + | |
| 72 | 116 | pub fn sample_metrics(&self) -> HostMetricsSample { |
| 73 | 117 | match &self.metrics { |
| 74 | 118 | MetricsBackend::Production(sampler) => { |
modifiedcrates/celld/js.rs+12949−9018View file
| @@ -21,9024 +21,12955 @@ | ||
| 21 | 21 | use std::cell::RefCell; |
| 22 | 22 | use std::collections::{HashMap, HashSet}; |
| 23 | 23 | use std::pin::Pin; |
| 24 | -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | |
| 25 | -use std::sync::{Arc, Mutex, OnceLock, Weak}; | |
| 26 | -use std::time::{Duration, Instant}; | |
| 27 | -use v8::{ValueDeserializerHelper, ValueSerializerHelper}; | |
| 28 | - | |
| 29 | -/// Bare Node builtin specifiers that the bundler leaves for the runtime. | |
| 30 | -/// Root entries also match subpaths in esbuild and in module resolution. | |
| 31 | -pub(crate) const BARE_NODE_BUILTINS: &[&str] = &[ | |
| 32 | - "assert", | |
| 33 | - "async_hooks", | |
| 34 | - "buffer", | |
| 35 | - "child_process", | |
| 36 | - "cluster", | |
| 37 | - "constants", | |
| 38 | - "crypto", | |
| 39 | - "dgram", | |
| 40 | - "diagnostics_channel", | |
| 41 | - "dns", | |
| 42 | - "events", | |
| 43 | - "fs", | |
| 44 | - "fs/promises", | |
| 45 | - "http", | |
| 46 | - "http2", | |
| 47 | - "https", | |
| 48 | - "inspector", | |
| 49 | - "module", | |
| 50 | - "net", | |
| 51 | - "os", | |
| 52 | - "path", | |
| 53 | - "perf_hooks", | |
| 54 | - "process", | |
| 55 | - "punycode", | |
| 56 | - "querystring", | |
| 57 | - "readline", | |
| 58 | - "sqlite", | |
| 59 | - "stream", | |
| 60 | - "string_decoder", | |
| 61 | - "timers", | |
| 62 | - "tls", | |
| 63 | - "tty", | |
| 64 | - "url", | |
| 65 | - "util", | |
| 66 | - "util/types", | |
| 67 | - "v8", | |
| 68 | - "vm", | |
| 69 | - "worker_threads", | |
| 70 | - "zlib", | |
| 71 | -]; | |
| 72 | - | |
| 73 | -/// The pending exception text from a TryCatch scope (a macro so it needs no | |
| 74 | -/// bound on the crate-private scope traits). | |
| 75 | -macro_rules! exc { | |
| 76 | - ($tc:expr) => { | |
| 77 | - $tc.exception() | |
| 78 | - .map(|e| e.to_rust_string_lossy(&*$tc)) | |
| 79 | - .unwrap_or_else(|| "<none>".into()) | |
| 80 | - }; | |
| 81 | -} | |
| 82 | - | |
| 83 | -/// A cross-node dispatch: the isolate hit `env.NS.get(id)` for a cell this node | |
| 84 | -/// does not own. The op hands this to the tokio runtime, which resolves the | |
| 85 | -/// owner and HTTP-proxies the fetch, replying on `reply` (an async oneshot the | |
| 86 | -/// async-op future awaits — the JS thread is never blocked). | |
| 87 | -pub struct DoCallReq { | |
| 88 | - pub request_id: Option<RequestId>, | |
| 89 | - pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, | |
| 90 | - /// An explicit JavaScript AbortSignal must reach the target handler, even | |
| 91 | - /// when it fires before cold routing completes. Transport cancellation has | |
| 92 | - /// no handler contract and can stop the cold route immediately. | |
| 93 | - pub deliver_abort_to_handler: bool, | |
| 94 | - pub scope: String, | |
| 95 | - pub name: Option<String>, | |
| 96 | - pub url: String, | |
| 97 | - pub method: String, | |
| 98 | - pub body: RequestBody, | |
| 99 | - /// Owns a streamed body while the call waits for routing or admission. | |
| 100 | - pub body_guard: RequestBodyGuard, | |
| 101 | - pub headers: Vec<(String, String)>, | |
| 102 | - pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 103 | - /// Where this call sits in its caller's order for this cell. | |
| 104 | - pub order: Option<CallOrder>, | |
| 105 | - /// The dispatching handler's trace context, read from CPED at the | |
| 106 | - /// call site, so the cell's span joins the caller's trace. | |
| 107 | - pub parent: Option<crate::telemetry::TraceIds>, | |
| 108 | -} | |
| 109 | -static DO_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<DoCallReq>> = OnceLock::new(); | |
| 110 | - | |
| 111 | -/// Delivery order, per caller and per cell. | |
| 112 | -/// | |
| 113 | -/// Two calls a script makes back-to-back on one Durable Object stub reach | |
| 114 | -/// the cell in that order. Workerd guarantees it — one pipe per stub — and | |
| 115 | -/// celld did too, while a cell's events came off one channel. Nothing | |
| 116 | -/// between the call and the cell keeps it now: the caller's two ops race to | |
| 117 | -/// the proxy channel, the proxy polls them in a `FuturesUnordered`, and two | |
| 118 | -/// drives race for the isolate. So the order is taken where it is still | |
| 119 | -/// true, synchronously in `op_do_call_impl`, and carried to the one place | |
| 120 | -/// that decides when an event is delivered. | |
| 121 | -/// | |
| 122 | -/// It is a chain, not a counter: each call leaves behind the receiver its | |
| 123 | -/// successor waits on, and takes its predecessor's. | |
| 124 | -/// | |
| 125 | -/// **The chain lives on the caller.** It was a process-wide map keyed by | |
| 126 | -/// `(context, cell)`, which made every Durable Object call in the node take | |
| 127 | -/// one global lock to record something only its own caller could ever read. | |
| 128 | -/// A shared mutex on a per-request path is a scalability cliff that a small | |
| 129 | -/// machine cannot show you, and the state was never shared to begin with. | |
| 130 | -/// | |
| 131 | -/// **Local delivery only.** A call routed to another node crosses HTTP, | |
| 132 | -/// where this order has nowhere to ride, so it is dropped there. Workerd | |
| 133 | -/// has the same seam in a different place, and a cell that moves mid-flight | |
| 134 | -/// reorders under both. | |
| 135 | -pub struct CallOrder { | |
| 136 | - /// The call before this one, or `None` if this is the first. | |
| 137 | - ahead: Option<tokio::sync::oneshot::Receiver<Place>>, | |
| 138 | - /// What the call behind this one waits on. | |
| 139 | - release: Option<tokio::sync::oneshot::Sender<Place>>, | |
| 140 | - /// The caller that owns the chain, and this call's place in it. | |
| 141 | - caller: Arc<IoContext>, | |
| 142 | - cell: String, | |
| 143 | - seq: u64, | |
| 144 | - delivered: bool, | |
| 145 | -} | |
| 146 | - | |
| 147 | -/// What a call hands to the one behind it. | |
| 148 | -/// | |
| 149 | -/// `None` once this call has been delivered: the queue has moved on. `Some` | |
| 150 | -/// when it died on the way to a cell and never took its turn, and then it | |
| 151 | -/// is this call's own unfinished place — so the call behind waits for what | |
| 152 | -/// this one was waiting for instead of jumping the queue. | |
| 153 | -/// | |
| 154 | -/// Without the handoff a failed call releases its successor immediately, | |
| 155 | -/// and a third call can be delivered ahead of a first that is still in | |
| 156 | -/// flight. Rare, since it needs a call to fail between two that do not, and | |
| 157 | -/// silent, since every call involved still gets an answer. | |
| 158 | -#[doc(hidden)] | |
| 159 | -pub struct Place(Option<Box<tokio::sync::oneshot::Receiver<Place>>>); | |
| 160 | - | |
| 161 | -impl CallOrder { | |
| 162 | - /// Wait for every call before this one to be delivered. | |
| 163 | - /// | |
| 164 | - /// A loop rather than one await because a call that died hands back | |
| 165 | - /// what *it* was waiting for. `Err` is the chain ahead going away | |
| 166 | - /// entirely, which is nothing left to wait for. | |
| 167 | - pub async fn wait(&mut self) { | |
| 168 | - let mut ahead = self.ahead.take(); | |
| 169 | - while let Some(place) = ahead { | |
| 170 | - ahead = match place.await { | |
| 171 | - Ok(Place(forward)) => forward.map(|boxed| *boxed), | |
| 172 | - Err(_) => None, | |
| 173 | - }; | |
| 174 | - } | |
| 175 | - } | |
| 176 | - | |
| 177 | - /// This call has been delivered; the one behind it may go. | |
| 178 | - pub fn delivered(&mut self) { | |
| 179 | - self.delivered = true; | |
| 180 | - } | |
| 181 | -} | |
| 182 | - | |
| 183 | -impl Drop for CallOrder { | |
| 184 | - fn drop(&mut self) { | |
| 185 | - // Nothing followed this call, so the chain is empty and its tail is | |
| 186 | - // only a leak. A caller's chains outlive its calls otherwise, and a | |
| 187 | - // cell isolate's default caller outlives everything. | |
| 188 | - let mut chains = self.caller.call_chains.lock().unwrap(); | |
| 189 | - if chains | |
| 190 | - .tails | |
| 191 | - .get(&self.cell) | |
| 192 | - .is_some_and(|(seq, _)| *seq == self.seq) | |
| 193 | - { | |
| 194 | - chains.tails.remove(&self.cell); | |
| 195 | - } | |
| 196 | - drop(chains); | |
| 197 | - if let Some(release) = self.release.take() { | |
| 198 | - let forward = (!self.delivered).then(|| self.ahead.take()).flatten(); | |
| 199 | - let _ = release.send(Place(forward.map(Box::new))); | |
| 200 | - } | |
| 201 | - } | |
| 202 | -} | |
| 203 | - | |
| 204 | -/// One caller's chains, one per cell it has called. | |
| 205 | -#[derive(Default)] | |
| 206 | -#[doc(hidden)] | |
| 207 | -pub struct CallChains { | |
| 208 | - next_seq: u64, | |
| 209 | - pub tails: HashMap<String, (u64, tokio::sync::oneshot::Receiver<Place>)>, | |
| 210 | -} | |
| 211 | - | |
| 212 | -/// Take this call's place in its caller's chain for `cell`. Synchronous, so | |
| 213 | -/// the places are taken in the order the script made the calls. | |
| 214 | -#[doc(hidden)] | |
| 215 | -pub fn enter_call_order(caller: Arc<IoContext>, cell: &str) -> CallOrder { | |
| 216 | - let (release, next) = tokio::sync::oneshot::channel(); | |
| 217 | - let (seq, ahead) = { | |
| 218 | - let mut chains = caller.call_chains.lock().unwrap(); | |
| 219 | - chains.next_seq += 1; | |
| 220 | - let seq = chains.next_seq; | |
| 221 | - let ahead = chains | |
| 222 | - .tails | |
| 223 | - .insert(cell.to_string(), (seq, next)) | |
| 224 | - .map(|(_, ahead)| ahead); | |
| 225 | - (seq, ahead) | |
| 226 | - }; | |
| 227 | - CallOrder { | |
| 228 | - ahead, | |
| 229 | - release: Some(release), | |
| 230 | - caller, | |
| 231 | - cell: cell.to_string(), | |
| 232 | - seq, | |
| 233 | - delivered: false, | |
| 234 | - } | |
| 235 | -} | |
| 236 | - | |
| 237 | -/// A ticket asking the actor whether an outbound effect may leave the process. | |
| 238 | -/// | |
| 239 | -/// Every in-handler channel takes one: `fetch`, a service binding, a call to | |
| 240 | -/// another cell, and a frame on a socket the isolate opened. `position` is | |
| 241 | -/// present when the running event wrote through it, absent when the event only | |
| 242 | -/// read and the effect must trail whatever the cell already has outstanding. | |
| 243 | -pub struct GateReq { | |
| 244 | - pub scope: String, | |
| 245 | - /// Which way the effect this ticket holds would leave the process. The | |
| 246 | - /// core stores it and hands it back, so the shell can route the release | |
| 247 | - /// to the adapter holding the effect. | |
| 248 | - pub channel: celld_logic::Channel, | |
| 249 | - pub position: Option<u64>, | |
| 250 | - pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>, | |
| 251 | -} | |
| 252 | -static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new(); | |
| 253 | -pub fn set_gate_tx(tx: tokio::sync::mpsc::UnboundedSender<GateReq>) { | |
| 254 | - let _ = GATE_TX.set(tx); | |
| 255 | -} | |
| 256 | - | |
| 257 | -/// A service-binding call: `env.NAME.fetch()`. Unlike a Durable Object call | |
| 258 | -/// there is no identity to resolve — any isolate running `script` will do — so | |
| 259 | -/// the runtime hands this straight to that script's stateless isolate pool. | |
| 260 | -pub struct SvcCallReq { | |
| 261 | - /// Fires when the caller's request signal aborts, so the router stops | |
| 262 | - /// waiting on the target instead of leaving the call outstanding. | |
| 263 | - pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, | |
| 264 | - /// The application generation of the calling isolate. The target is | |
| 265 | - /// resolved in that generation's service graph, so a caller built for | |
| 266 | - /// one deployment never reaches a target from another. | |
| 267 | - pub generation: crate::generation::GenerationId, | |
| 268 | - pub script: String, | |
| 269 | - pub url: String, | |
| 270 | - pub method: String, | |
| 271 | - pub body: RequestBody, | |
| 272 | - /// Owns a streamed body until the target installs its request context. | |
| 273 | - pub body_guard: RequestBodyGuard, | |
| 274 | - pub headers: Vec<(String, String)>, | |
| 275 | - pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 276 | -} | |
| 277 | -static SVC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcCallReq>> = OnceLock::new(); | |
| 278 | - | |
| 279 | -/// A Worker assets-binding call. The script name selects the immutable asset | |
| 280 | -/// index loaded for that Worker; unlike ingress this never falls back into the | |
| 281 | -/// Worker and therefore cannot recurse. | |
| 282 | -pub struct AssetCallReq { | |
| 283 | - /// The calling isolate's application generation; see `SvcCallReq`. | |
| 284 | - pub generation: crate::generation::GenerationId, | |
| 285 | - pub script: String, | |
| 286 | - pub url: String, | |
| 287 | - pub method: String, | |
| 288 | - pub headers: Vec<(String, String)>, | |
| 289 | - pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 290 | -} | |
| 291 | -static ASSET_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<AssetCallReq>> = OnceLock::new(); | |
| 292 | - | |
| 293 | -/// An RPC call on a named `WorkerEntrypoint` of another script. Arguments and | |
| 294 | -/// the result cross as V8 structured-clone bytes. | |
| 295 | -pub struct SvcRpcReq { | |
| 296 | - /// The calling isolate's application generation; see `SvcCallReq`. | |
| 297 | - pub generation: crate::generation::GenerationId, | |
| 298 | - pub script: String, | |
| 299 | - pub entrypoint: String, | |
| 300 | - pub method: String, | |
| 301 | - pub args: Vec<u8>, | |
| 302 | - pub reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>, | |
| 303 | -} | |
| 304 | -static SVC_RPC_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcRpcReq>> = OnceLock::new(); | |
| 305 | - | |
| 306 | -/// The persisted identity a consumer settlement must match for one message. | |
| 307 | -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] | |
| 308 | -pub struct QueueLeaseRef { | |
| 309 | - pub message_id: String, | |
| 310 | - pub seq: i64, | |
| 311 | - pub generation: u64, | |
| 312 | -} | |
| 313 | - | |
| 314 | -/// A durable broker batch released through its output gate. | |
| 315 | -pub struct QueueDispatchReq { | |
| 316 | - pub scope: String, | |
| 317 | - /// The dispatching queue cell's application generation; see | |
| 318 | - /// `SvcCallReq`. | |
| 319 | - pub generation: crate::generation::GenerationId, | |
| 320 | - pub script: String, | |
| 321 | - pub lease_id: String, | |
| 322 | - pub leases: Vec<QueueLeaseRef>, | |
| 323 | - pub batch: QueueBatch, | |
| 324 | -} | |
| 325 | -static QUEUE_DISPATCH_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<QueueDispatchReq>> = | |
| 326 | - OnceLock::new(); | |
| 327 | -/// The fleet bucket used by KV values that are too large for a namespace cell. | |
| 328 | -/// | |
| 329 | -/// The landed R2 binding established the safe pattern: a cloneable bucket | |
| 330 | -/// handle can live beside the asynchronous ops, so independent requests do not | |
| 331 | -/// queue behind one task that awaits every object-store operation in order. | |
| 332 | -static KV_BLOB_STORE: OnceLock<crate::bucket::Bucket> = OnceLock::new(); | |
| 333 | - | |
| 334 | -pub fn set_kv_blob_store(store: crate::bucket::Bucket) { | |
| 335 | - let _ = KV_BLOB_STORE.set(store); | |
| 336 | -} | |
| 337 | - | |
| 338 | -fn kv_blob_store() -> std::result::Result<&'static crate::bucket::Bucket, String> { | |
| 339 | - KV_BLOB_STORE | |
| 340 | - .get() | |
| 341 | - .ok_or_else(|| "KV large values need a fleet bucket".to_string()) | |
| 342 | -} | |
| 343 | - | |
| 344 | -pub fn set_svc_rpc_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcRpcReq>) { | |
| 345 | - let _ = SVC_RPC_TX.set(tx); | |
| 346 | -} | |
| 347 | -pub fn set_svc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcCallReq>) { | |
| 348 | - let _ = SVC_CALL_TX.set(tx); | |
| 349 | -} | |
| 350 | -pub fn set_queue_dispatch_tx(tx: tokio::sync::mpsc::UnboundedSender<QueueDispatchReq>) { | |
| 351 | - let _ = QUEUE_DISPATCH_TX.set(tx); | |
| 352 | -} | |
| 353 | -pub fn set_asset_call_tx(tx: tokio::sync::mpsc::UnboundedSender<AssetCallReq>) { | |
| 354 | - let _ = ASSET_CALL_TX.set(tx); | |
| 355 | -} | |
| 356 | -pub fn set_do_call_tx(tx: tokio::sync::mpsc::UnboundedSender<DoCallReq>) { | |
| 357 | - let _ = DO_CALL_TX.set(tx); | |
| 358 | -} | |
| 359 | - | |
| 360 | -/// Hand a Durable Object call to the dispatcher. Public HTTP ingress uses the | |
| 361 | -/// same queue a Worker's `env.NAME.get(id).fetch()` does, so both resolve | |
| 362 | -/// ownership, forward, and redispatch by one policy rather than two. | |
| 363 | -#[must_use] | |
| 364 | -pub fn submit_do_call(call: DoCallReq) -> bool { | |
| 365 | - DO_CALL_TX.get().is_some_and(|tx| tx.send(call).is_ok()) | |
| 366 | -} | |
| 367 | - | |
| 368 | -/// The arm-time wake-entry gate, output-gate style (matching Durable | |
| 369 | -/// Objects): `setAlarm()` resolves optimistically on the committed local | |
| 370 | -/// write — it never yields the cell's event scheduling to remote I/O — and | |
| 371 | -/// the cell's response edge is withheld until every wake-entry PUT that this | |
| 372 | -/// event registered before its response boundary has landed. Invariant: an | |
| 373 | -/// arm the caller has OBSERVED acknowledged (received the response) is | |
| 374 | -/// covered by a durable entry. | |
| 375 | -pub struct ArmGate { | |
| 376 | - pub bucket: crate::bucket::Bucket, | |
| 377 | - pub flusher: Arc<crate::wake::WakeFlusher>, | |
| 378 | -} | |
| 379 | - | |
| 380 | -type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>; | |
| 381 | - | |
| 382 | -#[derive(Default)] | |
| 383 | -pub(crate) struct WakeEntryService { | |
| 384 | - gate: OnceLock<ArmGate>, | |
| 385 | - #[cfg(celld_internal_tests)] | |
| 386 | - test_pending: Mutex<HashMap<String, Vec<ArmGateRx>>>, | |
| 387 | - #[cfg(celld_internal_tests)] | |
| 388 | - scripted: Mutex<std::collections::VecDeque<ArmGateRx>>, | |
| 389 | - #[cfg(celld_internal_tests)] | |
| 390 | - drop_next_gated_reply_task: AtomicBool, | |
| 391 | -} | |
| 392 | - | |
| 393 | -pub use r2_ops::set_r2_store; | |
| 394 | - | |
| 395 | -pub fn set_arm_gate(gate: ArmGate) { | |
| 396 | - let _ = asyncrt::services().wake_entry().gate.set(gate); | |
| 397 | -} | |
| 398 | - | |
| 399 | -/// Whether this node still holds a wake entry for `cell`. | |
| 400 | -pub fn wake_entry_tracked(cell: &str) -> bool { | |
| 401 | - asyncrt::services() | |
| 402 | - .wake_entry() | |
| 403 | - .gate | |
| 404 | - .get() | |
| 405 | - .is_some_and(|gate| gate.flusher.tracks(cell)) | |
| 406 | -} | |
| 407 | - | |
| 408 | -/// Drop this node's belief about `cell`'s wake entry — the cell fenced or | |
| 409 | -/// resolved to a remote owner, so the entry is no longer ours to manage. | |
| 410 | -/// A node that loses a cell must also forget its wake entry. | |
| 411 | -pub fn forget_wake_entry(cell: &str) { | |
| 412 | - let services = asyncrt::services(); | |
| 413 | - if let Some(gate) = services.wake_entry().gate.get() { | |
| 414 | - gate.flusher.forget(cell); | |
| 415 | - } | |
| 416 | -} | |
| 417 | - | |
| 418 | -/// Adopt the wake entry a restored alarm implies, so consuming that alarm | |
| 419 | -/// deletes it rather than orphaning it. | |
| 420 | -pub fn adopt_wake_entry(cell: &str, at_ms: i64) { | |
| 421 | - let services = asyncrt::services(); | |
| 422 | - if let Some(gate) = services.wake_entry().gate.get() { | |
| 423 | - gate.flusher.adopt(cell, at_ms); | |
| 424 | - } | |
| 425 | -} | |
| 426 | - | |
| 427 | -/// Bring the bucket's wake entry for `cell` into line with its alarm. | |
| 428 | -/// | |
| 429 | -/// Arming writes an entry; something has to take it away again once the alarm | |
| 430 | -/// has been consumed, or the entry outlives its alarm and every later due scan | |
| 431 | -/// finds it and wakes a cell with nothing to do. `consume_durable` gates that | |
| 432 | -/// final delete on the consuming commit being replicated -- removing the hint | |
| 433 | -/// while the commit that consumed the alarm is still only local would lose | |
| 434 | -/// both the alarm and the record that could have revived it. | |
| 435 | -pub async fn reconcile_wake_entry(cell: &str, next_alarm_ms: i64, consume_durable: bool) { | |
| 436 | - let services = asyncrt::services(); | |
| 437 | - let Some(gate) = services.wake_entry().gate.get() else { | |
| 438 | - return; | |
| 439 | - }; | |
| 440 | - gate.flusher | |
| 441 | - .reconcile(&gate.bucket, cell, next_alarm_ms, consume_durable) | |
| 442 | - .await; | |
| 443 | -} | |
| 444 | - | |
| 445 | -/// A committed alarm tightened the durable wake bound: launch the entry PUT | |
| 446 | -/// and register it against the current event's output gate. No-op when the | |
| 447 | -/// bound already covers it or no gate is configured. | |
| 448 | -fn spawn_arm_gate(cell: &str, at_ms: i64, context: Option<Arc<IoContext>>) { | |
| 449 | - #[cfg(celld_internal_tests)] | |
| 450 | - { | |
| 451 | - let services = asyncrt::services(); | |
| 452 | - if let Some(rx) = services.wake_entry().scripted.lock().unwrap().pop_front() { | |
| 453 | - register_arm_gate_with_current_event(rx, context); | |
| 454 | - return; | |
| 455 | - }; | |
| 456 | - } | |
| 457 | - if let Some(rx) = launch_arm_gate(cell, at_ms) { | |
| 458 | - register_arm_gate_with_current_event(rx, context); | |
| 459 | - } | |
| 460 | -} | |
| 461 | - | |
| 462 | -/// Launch the durable PUT and return the response edge that observes it. | |
| 463 | -/// Registration is separate because production binds the receiver to a V8 | |
| 464 | -/// event, while the private S1 driver binds it to its simulated request. | |
| 465 | -fn launch_arm_gate(cell: &str, at_ms: i64) -> Option<ArmGateRx> { | |
| 466 | - let services = asyncrt::services(); | |
| 467 | - let gate = services.wake_entry().gate.get()?; | |
| 468 | - let Some(celld_logic::wake::Op::Put { key, due_ms }) = gate.flusher.arm_op(cell, at_ms) else { | |
| 469 | - return None; | |
| 470 | - }; | |
| 471 | - let cell_ = cell.to_string(); | |
| 472 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 473 | - asyncrt::spawn(async move { | |
| 474 | - let gate = services.wake_entry().gate.get().unwrap(); | |
| 475 | - // A delete of this exact key may already be on the wire — the tracked | |
| 476 | - // entry's consume-delete, or the move-delete of a key this arm is | |
| 477 | - // about to re-PUT. Either way the PUT must land after that delete, | |
| 478 | - // not race it (S3 orders concurrent same-key writes arbitrarily). | |
| 479 | - // Deletes of the cell's OTHER keys cannot touch this PUT, and waiting | |
| 480 | - // on them would hold the response behind unrelated store latency. | |
| 481 | - gate.flusher.await_key_deletable(&cell_, &key).await; | |
| 482 | - let body = format!("{{\"cell\":{cell_:?},\"due_ms\":{due_ms}}}"); | |
| 483 | - let result = gate | |
| 484 | - .bucket | |
| 485 | - .put(&key, body.into_bytes()) | |
| 486 | - .await | |
| 487 | - .map(|_| gate.flusher.confirm_arm(&cell_, due_ms, key)) | |
| 488 | - .map_err(|e| format!("setAlarm wake entry: {e}")); | |
| 489 | - let _ = tx.send(result); | |
| 490 | - }) | |
| 491 | - .detach(); | |
| 492 | - Some(rx) | |
| 493 | -} | |
| 494 | - | |
| 495 | -fn register_arm_gate_with_current_event(gate: ArmGateRx, context: Option<Arc<IoContext>>) { | |
| 496 | - let Some(context) = context else { | |
| 497 | - drop(gate); | |
| 498 | - return; | |
| 499 | - }; | |
| 500 | - if let Err(gate) = context.register_arm_gate(gate) { | |
| 501 | - // The response boundary sealed this context. The PUT itself | |
| 502 | - // continues, but its receiver cannot migrate into a later event's | |
| 503 | - // reply batch. | |
| 504 | - drop(gate); | |
| 505 | - } | |
| 506 | -} | |
| 507 | - | |
| 508 | -#[cfg(celld_internal_tests)] | |
| 509 | -fn register_test_pending_arm_gate(cell: &str, gate: ArmGateRx) { | |
| 510 | - let services = asyncrt::services(); | |
| 511 | - let mut pending = services.wake_entry().test_pending.lock().unwrap(); | |
| 512 | - let gates = pending.entry(cell.to_string()).or_default(); | |
| 513 | - gates.retain_mut(|gate| { | |
| 514 | - matches!( | |
| 515 | - gate.try_recv(), | |
| 516 | - Err(tokio::sync::oneshot::error::TryRecvError::Empty) | |
| 517 | - ) | |
| 518 | - }); | |
| 519 | - gates.push(gate); | |
| 520 | -} | |
| 521 | - | |
| 522 | -#[cfg(celld_internal_tests)] | |
| 523 | -pub(crate) fn spawn_arm_gate_for_test(cell: &str, at_ms: i64) { | |
| 524 | - let services = asyncrt::services(); | |
| 525 | - if let Some(gate) = services.wake_entry().scripted.lock().unwrap().pop_front() { | |
| 526 | - match installed_context() { | |
| 527 | - Some(context) => register_arm_gate_with_current_event(gate, Some(context)), | |
| 528 | - None => { | |
| 529 | - // The deterministic S1 driver calls the storage seam without a | |
| 530 | - // JavaScript request. Keep that private compatibility path out of | |
| 531 | - // production and separate from a sealed event. | |
| 532 | - register_test_pending_arm_gate(cell, gate); | |
| 533 | - } | |
| 534 | - } | |
| 535 | - return; | |
| 536 | - } | |
| 537 | - let Some(gate) = launch_arm_gate(cell, at_ms) else { | |
| 538 | - return; | |
| 539 | - }; | |
| 540 | - match installed_context() { | |
| 541 | - Some(context) => register_arm_gate_with_current_event(gate, Some(context)), | |
| 542 | - None => register_test_pending_arm_gate(cell, gate), | |
| 543 | - } | |
| 544 | -} | |
| 545 | - | |
| 546 | -#[cfg(celld_internal_tests)] | |
| 547 | -#[doc(hidden)] | |
| 548 | -pub fn pause_next_arm_gate_for_test() -> tokio::sync::oneshot::Sender<Result<(), String>> { | |
| 549 | - let (resume, paused) = tokio::sync::oneshot::channel(); | |
| 550 | - asyncrt::services() | |
| 551 | - .wake_entry() | |
| 552 | - .scripted | |
| 553 | - .lock() | |
| 554 | - .unwrap() | |
| 555 | - .push_back(paused); | |
| 556 | - resume | |
| 557 | -} | |
| 558 | - | |
| 559 | -#[cfg(celld_internal_tests)] | |
| 560 | -#[doc(hidden)] | |
| 561 | -pub fn next_arm_gate_is_paused_for_test() -> bool { | |
| 562 | - !asyncrt::services() | |
| 563 | - .wake_entry() | |
| 564 | - .scripted | |
| 565 | - .lock() | |
| 566 | - .unwrap() | |
| 567 | - .is_empty() | |
| 568 | -} | |
| 569 | - | |
| 570 | -/// Drain the compatibility wake-entry PUT gates for a simulated S1 cell. | |
| 571 | -#[cfg(celld_internal_tests)] | |
| 572 | -#[doc(hidden)] | |
| 573 | -pub async fn drain_arm_gates(cell: &str) -> Result<(), String> { | |
| 574 | - let services = asyncrt::services(); | |
| 575 | - let gates = services | |
| 576 | - .wake_entry() | |
| 577 | - .test_pending | |
| 578 | - .lock() | |
| 579 | - .unwrap() | |
| 580 | - .remove(cell); | |
| 581 | - let Some(gates) = gates else { | |
| 582 | - return Ok(()); | |
| 583 | - }; | |
| 584 | - await_arm_gates(gates).await | |
| 585 | -} | |
| 586 | - | |
| 587 | -pub type RequestId = u128; | |
| 588 | - | |
| 589 | -#[derive(Clone, Copy)] | |
| 590 | -pub struct FetchRequest<'a> { | |
| 591 | - pub url: &'a str, | |
| 592 | - pub method: &'a str, | |
| 593 | - pub body: &'a [u8], | |
| 594 | - pub headers: &'a [(String, String)], | |
| 595 | - pub request_id: Option<RequestId>, | |
| 596 | -} | |
| 597 | - | |
| 598 | -/// Allocate an id for an ingress or service-binding request so it can be | |
| 599 | -/// aborted mid-flight. | |
| 600 | -pub fn next_request_id() -> RequestId { | |
| 601 | - next_do_request_id() | |
| 602 | -} | |
| 603 | - | |
| 604 | -static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1); | |
| 605 | -static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new(); | |
| 606 | -static DO_CALL_CANCELS: OnceLock< | |
| 607 | - std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>>, | |
| 608 | -> = OnceLock::new(); | |
| 609 | -fn do_call_cancels( | |
| 610 | -) -> &'static std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>> { | |
| 611 | - DO_CALL_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 612 | -} | |
| 613 | - | |
| 614 | -#[doc(hidden)] | |
| 615 | -pub fn next_do_request_id() -> RequestId { | |
| 616 | - let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| { | |
| 617 | - let mut bytes = [0; 8]; | |
| 618 | - getrandom::fill(&mut bytes).expect("OS random source unavailable"); | |
| 619 | - u64::from_ne_bytes(bytes) | |
| 620 | - }); | |
| 621 | - let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed); | |
| 622 | - (u128::from(prefix) << 64) | u128::from(sequence) | |
| 623 | -} | |
| 624 | - | |
| 625 | -pub fn request_id_string(request_id: RequestId) -> String { | |
| 626 | - format!("{request_id:032x}") | |
| 627 | -} | |
| 628 | - | |
| 629 | -pub fn parse_request_id(value: &str) -> Option<RequestId> { | |
| 630 | - u128::from_str_radix(value, 16).ok() | |
| 631 | -} | |
| 632 | - | |
| 633 | -/// Publish `request_id` on a pending call's promise as the token the JS | |
| 634 | -/// harness hands back to `__do_call_cancel`. | |
| 635 | -/// | |
| 636 | -/// The only writer of `__celldCancelId`, and the counterpart of | |
| 637 | -/// [`parse_request_id`]. Each cancellable op used to spell the property name | |
| 638 | -/// and the encoding out for itself, and `op_svc_call_impl` wrote decimal while | |
| 639 | -/// `op_do_call_cancel` reads hexadecimal. Every decimal digit is also a | |
| 640 | -/// hexadecimal digit, so the parse succeeded on a different number, the | |
| 641 | -/// registry lookup missed, and the cancel was dropped with no error — a | |
| 642 | -/// service-binding abort rejected the caller and left the target running. One | |
| 643 | -/// writer paired with one parser removes the chance to disagree. | |
| 644 | -fn attach_cancel_id( | |
| 645 | - scope: &mut v8::PinScope, | |
| 646 | - promise: v8::Local<v8::Value>, | |
| 647 | - request_id: RequestId, | |
| 648 | -) { | |
| 649 | - let Some(object) = promise.to_object(scope) else { | |
| 650 | - return; | |
| 651 | - }; | |
| 652 | - let key = v8::String::new(scope, "__celldCancelId").unwrap(); | |
| 653 | - let value = v8::String::new(scope, &request_id_string(request_id)).unwrap(); | |
| 654 | - object.set(scope, key.into(), value.into()); | |
| 655 | -} | |
| 656 | - | |
| 657 | -struct DoCallCancelGuard(Option<RequestId>); | |
| 658 | - | |
| 659 | -impl DoCallCancelGuard { | |
| 660 | - fn new(request: RequestId) -> Self { | |
| 661 | - Self(Some(request)) | |
| 662 | - } | |
| 663 | - | |
| 664 | - fn disarm(&mut self) { | |
| 665 | - if let Some(request) = self.0.take() { | |
| 666 | - do_call_cancels().lock().unwrap().remove(&request); | |
| 667 | - } | |
| 668 | - } | |
| 669 | -} | |
| 670 | - | |
| 671 | -impl Drop for DoCallCancelGuard { | |
| 672 | - fn drop(&mut self) { | |
| 673 | - let Some(request) = self.0.take() else { | |
| 674 | - return; | |
| 675 | - }; | |
| 676 | - if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request) { | |
| 677 | - let _ = cancel.send(()); | |
| 678 | - } | |
| 679 | - } | |
| 680 | -} | |
| 681 | - | |
| 682 | -/// An RPC payload crossing the host boundary. JS stubs marshal by V8 | |
| 683 | -/// structured clone (`V8`), and legacy callers use the JSON envelope (`Json`). | |
| 684 | -/// `__dispatchRpc` answers in the flavor it was asked in. | |
| 685 | -pub enum RpcData { | |
| 686 | - Json(String), | |
| 687 | - V8(bytes::Bytes), | |
| 688 | -} | |
| 689 | - | |
| 690 | -/// A native Durable Object RPC call (`stub.someMethod(...args)`). | |
| 691 | -/// Routing/activation is identical to fetch calls. | |
| 692 | -pub struct RpcCallReq { | |
| 693 | - pub scope: String, | |
| 694 | - pub name: Option<String>, | |
| 695 | - pub method: String, | |
| 696 | - pub args: RpcData, | |
| 697 | - pub reply: tokio::sync::oneshot::Sender<Result<RpcData>>, | |
| 698 | -} | |
| 699 | -static RPC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<RpcCallReq>> = OnceLock::new(); | |
| 700 | -pub fn set_rpc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<RpcCallReq>) { | |
| 701 | - let _ = RPC_CALL_TX.set(tx); | |
| 702 | -} | |
| 703 | - | |
| 704 | -pub struct OutboundWsReq { | |
| 705 | - pub scope: String, | |
| 706 | - pub id: u64, | |
| 707 | - pub url: String, | |
| 708 | - pub protocols: Vec<String>, | |
| 709 | - /// Present for an isolate-polled (Worker) socket. Created and registered | |
| 710 | - /// on the JS thread before the request is sent, so `__ws_next` can never | |
| 711 | - /// run ahead of its own queue. | |
| 712 | - pub pull: Option<WsPullSender>, | |
| 713 | - /// Extra request headers, for the `fetch()` upgrade form. | |
| 714 | - pub headers: Vec<(String, String)>, | |
| 715 | - /// A `fetch()` upgrade wants the whole handshake outcome, including the | |
| 716 | - /// ordinary response a server that declines to upgrade sent instead. | |
| 717 | - pub want_response: bool, | |
| 718 | - /// A socket already upgraded in this process, which this request joins | |
| 719 | - /// instead of dialing `url`. It is the cell end of a Durable Object | |
| 720 | - /// subrequest whose caller kept the client end, so there is no handshake | |
| 721 | - /// to run and no connection to open: the host only has to carry frames | |
| 722 | - /// between two isolates. | |
| 723 | - pub target: Option<WsTarget>, | |
| 724 | - pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>, | |
| 725 | -} | |
| 726 | - | |
| 727 | -/// The ordinary HTTP response a server sent instead of upgrading. `fetch()` | |
| 728 | -/// returns it verbatim rather than turning it into a connection error. | |
| 729 | -pub struct DeclinedUpgrade { | |
| 730 | - pub status: u16, | |
| 731 | - pub headers: Vec<(String, String)>, | |
| 732 | - pub body: Vec<u8>, | |
| 733 | -} | |
| 734 | - | |
| 735 | -/// What an outbound handshake produced. | |
| 736 | -pub struct OutboundWsOpen { | |
| 737 | - pub protocol: Option<String>, | |
| 738 | - pub declined: Option<DeclinedUpgrade>, | |
| 739 | -} | |
| 740 | -static OUTBOUND_WS_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> = | |
| 741 | - OnceLock::new(); | |
| 742 | -pub fn set_outbound_ws_tx(tx: tokio::sync::mpsc::UnboundedSender<OutboundWsReq>) { | |
| 743 | - let _ = OUTBOUND_WS_TX.set(tx); | |
| 744 | -} | |
| 745 | - | |
| 746 | -#[cfg(celld_internal_tests)] | |
| 747 | -/// An outbound connector scoped to the current internal-test JS thread. | |
| 748 | -/// | |
| 749 | -/// The production connector is process-wide. Installing a test sender there | |
| 750 | -/// captures requests from unrelated suites, and those suites have no receiver | |
| 751 | -/// that can answer them. The thread-local sender follows the current-thread V8 | |
| 752 | -/// harnesses, while this handle owns its receiver and removes the sender when | |
| 753 | -/// the case ends. | |
| 754 | -#[doc(hidden)] | |
| 755 | -pub struct TestOutboundWsConnector { | |
| 756 | - requests: tokio::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<OutboundWsReq>>, | |
| 757 | - /// A scoped connector must drop on the thread where it installed its sender. | |
| 758 | - _not_send: std::marker::PhantomData<std::rc::Rc<()>>, | |
| 759 | -} | |
| 760 | - | |
| 761 | -#[cfg(celld_internal_tests)] | |
| 762 | -impl TestOutboundWsConnector { | |
| 763 | - #[doc(hidden)] | |
| 764 | - pub fn requests( | |
| 765 | - &self, | |
| 766 | - ) -> &tokio::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<OutboundWsReq>> { | |
| 767 | - &self.requests | |
| 768 | - } | |
| 769 | -} | |
| 770 | - | |
| 771 | -#[cfg(celld_internal_tests)] | |
| 772 | -thread_local! { | |
| 773 | - static TEST_OUTBOUND_WS_TX: RefCell<Option<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>>> = | |
| 774 | - const { RefCell::new(None) }; | |
| 775 | -} | |
| 776 | - | |
| 777 | -#[cfg(celld_internal_tests)] | |
| 778 | -impl Drop for TestOutboundWsConnector { | |
| 779 | - fn drop(&mut self) { | |
| 780 | - TEST_OUTBOUND_WS_TX.with(|slot| { | |
| 781 | - assert!( | |
| 782 | - slot.borrow_mut().take().is_some(), | |
| 783 | - "test outbound WebSocket connector was not installed", | |
| 784 | - ); | |
| 785 | - }); | |
| 786 | - } | |
| 787 | -} | |
| 788 | - | |
| 789 | -#[cfg(celld_internal_tests)] | |
| 790 | -/// Install the internal-test connector for the current JS thread. | |
| 791 | -#[doc(hidden)] | |
| 792 | -pub fn install_outbound_ws_connector_for_test() -> TestOutboundWsConnector { | |
| 793 | - let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); | |
| 794 | - TEST_OUTBOUND_WS_TX.with(|slot| { | |
| 795 | - let mut slot = slot.borrow_mut(); | |
| 796 | - assert!( | |
| 797 | - slot.is_none(), | |
| 798 | - "test outbound WebSocket connector is already installed" | |
| 799 | - ); | |
| 800 | - *slot = Some(tx); | |
| 801 | - }); | |
| 802 | - TestOutboundWsConnector { | |
| 803 | - requests: tokio::sync::Mutex::new(rx), | |
| 804 | - _not_send: std::marker::PhantomData, | |
| 805 | - } | |
| 806 | -} | |
| 807 | - | |
| 808 | -/// Select the scoped internal-test connector before the production connector. | |
| 809 | -fn outbound_ws_tx() -> Option<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> { | |
| 810 | - #[cfg(celld_internal_tests)] | |
| 811 | - if let Some(tx) = TEST_OUTBOUND_WS_TX.with(|slot| slot.borrow().clone()) { | |
| 812 | - return Some(tx); | |
| 813 | - } | |
| 814 | - OUTBOUND_WS_TX.get().cloned() | |
| 815 | -} | |
| 816 | - | |
| 817 | -static NEXT_TIMER_ID: AtomicU64 = AtomicU64::new(1); | |
| 818 | -static TIMER_CANCELS: OnceLock<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>> = | |
| 819 | - OnceLock::new(); | |
| 820 | -fn timer_cancels() -> &'static std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>> { | |
| 821 | - TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 822 | -} | |
| 823 | -static NEXT_HTTP_STREAM_ID: AtomicU64 = AtomicU64::new(1); | |
| 824 | -/// What `__http_stream_read` resolves with at end of stream. | |
| 825 | -/// | |
| 826 | -/// The reader identifies the end by type, not by value. A chunk always | |
| 827 | -/// resolves as a `Uint8Array`, therefore body bytes can never look like | |
| 828 | -/// this marker. The value stays distinctive, so a reader that does compare | |
| 829 | -/// the value cannot match a plausible body. | |
| 830 | -const HTTP_STREAM_DONE: &str = "__celld_http_stream_end__"; | |
| 831 | -const HTTP_STREAM_STALE_AFTER: Duration = Duration::from_secs(60); | |
| 832 | -enum HttpStreamSource { | |
| 833 | - Response(reqwest::Response), | |
| 834 | - Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>), | |
| 835 | - Stream(HttpChunkStream), | |
| 836 | -} | |
| 837 | -struct HttpStreamEntry { | |
| 838 | - created: Instant, | |
| 839 | - source: Option<HttpStreamSource>, | |
| 840 | - cancelled: tokio::sync::watch::Sender<bool>, | |
| 841 | - /// Request contexts that can still read this source. A dispatch guard can | |
| 842 | - /// reclaim the entry only while this is zero. | |
| 843 | - owners: usize, | |
| 844 | -} | |
| 845 | -static HTTP_STREAMS: OnceLock<std::sync::Mutex<HashMap<u64, HttpStreamEntry>>> = OnceLock::new(); | |
| 846 | -fn http_streams() -> &'static std::sync::Mutex<HashMap<u64, HttpStreamEntry>> { | |
| 847 | - HTTP_STREAMS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 848 | -} | |
| 849 | -fn register_http_stream(stream_id: u64, source: HttpStreamSource) { | |
| 850 | - let (cancelled, _) = tokio::sync::watch::channel(false); | |
| 851 | - let mut streams = http_streams().lock().unwrap(); | |
| 852 | - streams.retain(|_, stream| { | |
| 853 | - stream.owners > 0 || stream.created.elapsed() < HTTP_STREAM_STALE_AFTER | |
| 854 | - }); | |
| 855 | - streams.insert( | |
| 856 | - stream_id, | |
| 857 | - HttpStreamEntry { | |
| 858 | - created: Instant::now(), | |
| 859 | - source: Some(source), | |
| 860 | - cancelled, | |
| 861 | - owners: 0, | |
| 862 | - }, | |
| 863 | - ); | |
| 864 | -} | |
| 865 | - | |
| 866 | -fn claim_http_stream(stream_id: u64) -> bool { | |
| 867 | - let mut streams = http_streams().lock().unwrap(); | |
| 868 | - let Some(stream) = streams.get_mut(&stream_id) else { | |
| 869 | - return false; | |
| 870 | - }; | |
| 871 | - stream.owners = stream.owners.saturating_add(1); | |
| 872 | - true | |
| 873 | -} | |
| 874 | - | |
| 875 | -fn release_http_stream(stream_id: u64) { | |
| 876 | - let mut streams = http_streams().lock().unwrap(); | |
| 877 | - let remove = streams.get_mut(&stream_id).is_some_and(|stream| { | |
| 878 | - stream.owners = stream.owners.saturating_sub(1); | |
| 879 | - stream.owners == 0 | |
| 880 | - }); | |
| 881 | - if remove { | |
| 882 | - streams.remove(&stream_id); | |
| 883 | - } | |
| 884 | -} | |
| 885 | - | |
| 886 | -#[cfg(celld_internal_tests)] | |
| 887 | -#[doc(hidden)] | |
| 888 | -pub fn make_http_stream_stale_for_test(stream_id: u64) { | |
| 889 | - if let Some(stream) = http_streams().lock().unwrap().get_mut(&stream_id) { | |
| 890 | - stream.created -= HTTP_STREAM_STALE_AFTER; | |
| 891 | - } | |
| 892 | -} | |
| 893 | - | |
| 894 | -#[cfg(celld_internal_tests)] | |
| 895 | -#[doc(hidden)] | |
| 896 | -pub fn http_stream_exists_for_test(stream_id: u64) -> bool { | |
| 897 | - http_streams().lock().unwrap().contains_key(&stream_id) | |
| 898 | -} | |
| 899 | - | |
| 900 | -#[cfg(celld_internal_tests)] | |
| 901 | -#[doc(hidden)] | |
| 902 | -pub fn remove_http_stream_for_test(stream_id: u64) { | |
| 903 | - http_streams().lock().unwrap().remove(&stream_id); | |
| 904 | -} | |
| 905 | -struct ResponseStreamWriter { | |
| 906 | - created: Instant, | |
| 907 | - writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 908 | - finished: tokio::sync::watch::Sender<bool>, | |
| 909 | -} | |
| 910 | -static RESPONSE_STREAM_WRITERS: OnceLock<std::sync::Mutex<HashMap<u64, ResponseStreamWriter>>> = | |
| 911 | - OnceLock::new(); | |
| 912 | -fn response_stream_writers() -> &'static std::sync::Mutex<HashMap<u64, ResponseStreamWriter>> { | |
| 913 | - RESPONSE_STREAM_WRITERS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 914 | -} | |
| 915 | - | |
| 916 | -pub type HttpChunkStream = | |
| 917 | - Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>; | |
| 918 | - | |
| 919 | -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] | |
| 920 | -pub struct WsTarget { | |
| 921 | - pub id: u64, | |
| 922 | - pub scope: String, | |
| 923 | - /// A parked tunneled 101 on the calling node (`peer_tunnel::splice`). | |
| 924 | - /// The id is meaningful only in the process that parked it, but it must | |
| 925 | - /// survive the isolate round trip, so it serializes. | |
| 926 | - #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 927 | - pub tunnel: Option<u64>, | |
| 928 | -} | |
| 929 | - | |
| 930 | -/// Encode a host response for the JS side. A text body crosses as a | |
| 931 | -/// JS string (cheap, lossless), binary as a byte array, and a streaming body | |
| 932 | -/// by id — serializing a Vec<u8> as a JSON number array is the dominant cost | |
| 933 | -/// for real DO responses. `ws_target` is carried by the paths that can answer | |
| 934 | -/// with a WebSocket upgrade: a Durable Object call and a service-binding call. | |
| 935 | -fn encode_http_response(mut response: HttpResponse, ws_target: bool) -> String { | |
| 936 | - let mut obj = serde_json::json!({ | |
| 937 | - "status": response.status, | |
| 938 | - "headers": response.headers, | |
| 939 | - }); | |
| 940 | - if ws_target { | |
| 941 | - let target = match response.websocket.as_ref() { | |
| 942 | - Some(HttpResponseWebSocket::Cell(target)) => Some(target), | |
| 943 | - _ => None, | |
| 944 | - }; | |
| 945 | - obj["wsTarget"] = serde_json::json!(target); | |
| 946 | - } | |
| 947 | - if let Some(stream) = response.stream.take() { | |
| 948 | - let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 949 | - register_http_stream(stream_id, HttpStreamSource::Stream(stream)); | |
| 950 | - obj["streamId"] = serde_json::json!(stream_id); | |
| 951 | - } else { | |
| 952 | - match std::str::from_utf8(&response.body) { | |
| 953 | - Ok(text) => obj["body"] = serde_json::Value::String(text.into()), | |
| 954 | - Err(_) => obj["bodyBytes"] = serde_json::json!(response.body), | |
| 955 | - } | |
| 956 | - } | |
| 957 | - obj.to_string() | |
| 958 | -} | |
| 959 | - | |
| 960 | -pub enum HttpResponseWebSocket { | |
| 961 | - Cell(WsTarget), | |
| 962 | - Worker(websocket::WorkerWebSocket), | |
| 963 | -} | |
| 964 | - | |
| 965 | -pub struct HttpResponse { | |
| 966 | - pub status: u16, | |
| 967 | - pub body: Vec<u8>, | |
| 968 | - /// A response body forwarded without materializing it in memory. | |
| 969 | - pub stream: Option<HttpChunkStream>, | |
| 970 | - pub headers: Vec<(String, String)>, | |
| 971 | - /// The one WebSocket target that owns this response, if it is an upgrade. | |
| 972 | - pub websocket: Option<HttpResponseWebSocket>, | |
| 973 | - /// The cell's committed-write position after the handler ran, for a local | |
| 974 | - /// Durable Object request. The shell gates the response on durability when | |
| 975 | - /// this advanced past the cell's last seen position. `None` for responses | |
| 976 | - /// with no cell storage (Worker, asset, or proxied remote). | |
| 977 | - pub write_position: Option<u64>, | |
| 978 | -} | |
| 979 | - | |
| 980 | -/// The encoding that the queue producer selected for one message body. | |
| 981 | -#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 982 | -pub enum QueueContentType { | |
| 983 | - Text, | |
| 984 | - Bytes, | |
| 985 | - Json, | |
| 986 | - V8, | |
| 987 | -} | |
| 988 | - | |
| 989 | -impl QueueContentType { | |
| 990 | - fn as_str(self) -> &'static str { | |
| 991 | - match self { | |
| 992 | - Self::Text => "text", | |
| 993 | - Self::Bytes => "bytes", | |
| 994 | - Self::Json => "json", | |
| 995 | - Self::V8 => "v8", | |
| 996 | - } | |
| 997 | - } | |
| 998 | -} | |
| 999 | - | |
| 1000 | -/// One message handed from a queue cell to a consumer isolate. | |
| 1001 | -pub struct QueueMessage { | |
| 1002 | - pub id: String, | |
| 1003 | - pub timestamp_ms: i64, | |
| 1004 | - pub body: Vec<u8>, | |
| 1005 | - pub content_type: QueueContentType, | |
| 1006 | - pub attempts: u16, | |
| 1007 | -} | |
| 1008 | - | |
| 1009 | -/// The queue state observed when a cell leases a batch. | |
| 1010 | -pub struct QueueMetrics { | |
| 1011 | - pub backlog_count: f64, | |
| 1012 | - pub backlog_bytes: f64, | |
| 1013 | - pub oldest_message_timestamp_ms: Option<i64>, | |
| 1014 | -} | |
| 1015 | - | |
| 1016 | -/// One leased batch handed to the stateless isolate pool. | |
| 1017 | -pub struct QueueBatch { | |
| 1018 | - pub queue: String, | |
| 1019 | - pub messages: Vec<QueueMessage>, | |
| 1020 | - pub metrics: QueueMetrics, | |
| 1021 | -} | |
| 1022 | - | |
| 1023 | -/// The batch-wide retry decision made by a queue handler. | |
| 1024 | -#[derive(Debug, Eq, PartialEq)] | |
| 1025 | -pub struct QueueRetryBatch { | |
| 1026 | - pub retry: bool, | |
| 1027 | - pub delay_seconds: Option<i32>, | |
| 1028 | -} | |
| 1029 | - | |
| 1030 | -/// An explicit retry decision made for one message. | |
| 1031 | -#[derive(Debug, Eq, PartialEq)] | |
| 1032 | -pub struct QueueRetryMessage { | |
| 1033 | - pub msg_id: String, | |
| 1034 | - pub delay_seconds: Option<i32>, | |
| 1035 | -} | |
| 1036 | - | |
| 1037 | -/// How the queue handler itself completed. Infrastructure failures still use | |
| 1038 | -/// the outer `Result`, so a handler exception can preserve earlier acks. | |
| 1039 | -#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 1040 | -pub enum QueueOutcome { | |
| 1041 | - Ok, | |
| 1042 | - Exception, | |
| 1043 | -} | |
| 1044 | - | |
| 1045 | -/// The handler outcome and the settlement instructions it made before return. | |
| 1046 | -#[derive(Debug, Eq, PartialEq)] | |
| 1047 | -pub struct QueueDispatchResult { | |
| 1048 | - pub outcome: QueueOutcome, | |
| 1049 | - pub error: Option<String>, | |
| 1050 | - pub ack_all: bool, | |
| 1051 | - pub retry_batch: QueueRetryBatch, | |
| 1052 | - pub explicit_acks: Vec<String>, | |
| 1053 | - pub retry_messages: Vec<QueueRetryMessage>, | |
| 1054 | -} | |
| 1055 | - | |
| 1056 | -/// Which alarm a dispatch runs, and who owns its bookkeeping. | |
| 1057 | -pub enum AlarmDispatch { | |
| 1058 | - /// Claim whatever is due now, and record the outcome. | |
| 1059 | - Due, | |
| 1060 | - #[cfg(celld_internal_tests)] | |
| 1061 | - Armed, | |
| 1062 | - #[cfg(celld_internal_tests)] | |
| 1063 | - Claimed(i64), | |
| 1064 | -} | |
| 1065 | - | |
| 1066 | -/// One event a cell receives. | |
| 1067 | -/// | |
| 1068 | -/// Every variant is something the outside world did to the cell, and each | |
| 1069 | -/// becomes an `InFlight` entry driven by its own tokio task. Lifecycle — | |
| 1070 | -/// taking a cell in, giving it back, cancelling a request — is not here: it | |
| 1071 | -/// is a direct call on the isolate, because it is not an event and has no | |
| 1072 | -/// handler to run. | |
| 1073 | -pub enum CellJob { | |
| 1074 | - Fetch { | |
| 1075 | - request_id: Option<RequestId>, | |
| 1076 | - scope: String, | |
| 1077 | - name: Option<String>, | |
| 1078 | - url: String, | |
| 1079 | - method: String, | |
| 1080 | - body: RequestBody, | |
| 1081 | - headers: Vec<(String, String)>, | |
| 1082 | - reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 1083 | - /// Where this call sits in its caller's order for this cell, if it | |
| 1084 | - /// came from a script rather than from a peer or the ingress. | |
| 1085 | - order: Option<CallOrder>, | |
| 1086 | - }, | |
| 1087 | - Rpc { | |
| 1088 | - scope: String, | |
| 1089 | - name: Option<String>, | |
| 1090 | - method: String, | |
| 1091 | - args: RpcData, | |
| 1092 | - reply: tokio::sync::oneshot::Sender<Result<RpcOutcome>>, | |
| 1093 | - }, | |
| 1094 | - WsOpen { | |
| 1095 | - scope: String, | |
| 1096 | - ws_id: u64, | |
| 1097 | - protocol: String, | |
| 1098 | - reply: tokio::sync::oneshot::Sender<Result<()>>, | |
| 1099 | - }, | |
| 1100 | - WsMessage { | |
| 1101 | - scope: String, | |
| 1102 | - ws_id: u64, | |
| 1103 | - data: WsIn, | |
| 1104 | - reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>, | |
| 1105 | - }, | |
| 1106 | - WsClosed { | |
| 1107 | - scope: String, | |
| 1108 | - ws_id: u64, | |
| 1109 | - code: u16, | |
| 1110 | - reason: String, | |
| 1111 | - was_clean: bool, | |
| 1112 | - reply: tokio::sync::oneshot::Sender<Result<()>>, | |
| 1113 | - }, | |
| 1114 | - Alarm { | |
| 1115 | - scope: String, | |
| 1116 | - scheduled_ms: i64, | |
| 1117 | - /// Which alarm to run, and who owns the bookkeeping. | |
| 1118 | - claim: AlarmDispatch, | |
| 1119 | - /// Replies with (next alarm, the handler's write delta). The delta is | |
| 1120 | - /// sampled inside the turn — cell storage must never be reached from | |
| 1121 | - /// the shell — and the shell uses it to prove the consuming commit | |
| 1122 | - /// durable before the core settles. Every answer shape samples it the | |
| 1123 | - /// same way now, in `InFlight::answer_settled`. | |
| 1124 | - reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 1125 | - }, | |
| 1126 | - #[cfg(celld_internal_tests)] | |
| 1127 | - SyncErrorForTest { | |
| 1128 | - scope: String, | |
| 1129 | - gate: ArmGateRx, | |
| 1130 | - socket_id: Option<u64>, | |
| 1131 | - terminate: bool, | |
| 1132 | - reply: tokio::sync::oneshot::Sender<Result<()>>, | |
| 1133 | - }, | |
| 1134 | -} | |
| 1135 | - | |
| 1136 | -/// A cell event that the runtime refuses before application code starts. | |
| 1137 | -/// | |
| 1138 | -/// The type survives the Rust RPC path. Its display text also survives the V8 | |
| 1139 | -/// promise boundary, so the public ingress can restore the HTTP overload | |
| 1140 | -/// contract after a Worker forwards the refusal. | |
| 1141 | -#[doc(hidden)] | |
| 1142 | -#[derive(Debug)] | |
| 1143 | -pub struct CellOverloaded; | |
| 1144 | - | |
| 1145 | -/// The V8 promise boundary preserves only an error string. Use an opaque | |
| 1146 | -/// marker so application text cannot accidentally restore an HTTP overload | |
| 1147 | -/// response, and keep the producer and ingress checks on one value. | |
| 1148 | -#[doc(hidden)] | |
| 1149 | -pub const CELL_OVERLOAD_ERROR_MARKER: &str = | |
| 1150 | - "celld-internal-cell-overload-7ec38c64-12d7-4ddc-9e77-b63f9dc14130"; | |
| 1151 | - | |
| 1152 | -impl std::fmt::Display for CellOverloaded { | |
| 1153 | - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 1154 | - formatter.write_str(CELL_OVERLOAD_ERROR_MARKER) | |
| 1155 | - } | |
| 1156 | -} | |
| 1157 | - | |
| 1158 | -impl std::error::Error for CellOverloaded {} | |
| 1159 | - | |
| 1160 | -impl CellJob { | |
| 1161 | - /// The cell this event addresses, which is also the realm it runs in. | |
| 1162 | - pub fn scope(&self) -> &str { | |
| 1163 | - match self { | |
| 1164 | - CellJob::Fetch { scope, .. } | |
| 1165 | - | CellJob::Rpc { scope, .. } | |
| 1166 | - | CellJob::WsOpen { scope, .. } | |
| 1167 | - | CellJob::WsMessage { scope, .. } | |
| 1168 | - | CellJob::WsClosed { scope, .. } | |
| 1169 | - | CellJob::Alarm { scope, .. } => scope, | |
| 1170 | - #[cfg(celld_internal_tests)] | |
| 1171 | - CellJob::SyncErrorForTest { scope, .. } => scope, | |
| 1172 | - } | |
| 1173 | - } | |
| 1174 | - | |
| 1175 | - /// The client request that can cancel this event, when it is a fetch. | |
| 1176 | - pub(crate) fn request_id(&self) -> Option<RequestId> { | |
| 1177 | - match self { | |
| 1178 | - CellJob::Fetch { request_id, .. } => *request_id, | |
| 1179 | - _ => None, | |
| 1180 | - } | |
| 1181 | - } | |
| 1182 | - | |
| 1183 | - /// Queue sends use native RPC, so the method is the narrow seam where the | |
| 1184 | - /// owner can bound producer events without limiting an ordinary Durable | |
| 1185 | - /// Object RPC or a Queue alarm and settlement. | |
| 1186 | - pub(crate) fn is_queue_producer(&self) -> bool { | |
| 1187 | - matches!(self, CellJob::Rpc { scope, method, .. } | |
| 1188 | - if scope.split_once(':').is_some_and(|(class, _)| | |
| 1189 | - class == crate::deploy::QUEUE_CLASS) && method == "__queueSend") | |
| 1190 | - } | |
| 1191 | - | |
| 1192 | - /// This event's place in its caller's order, taken out so the drive can | |
| 1193 | - /// wait on it and then release the call behind it. | |
| 1194 | - pub fn take_order(&mut self) -> Option<CallOrder> { | |
| 1195 | - match self { | |
| 1196 | - CellJob::Fetch { order, .. } => order.take(), | |
| 1197 | - _ => None, | |
| 1198 | - } | |
| 1199 | - } | |
| 1200 | - | |
| 1201 | - /// Fail this event without running it. | |
| 1202 | - pub fn fail(self, error: anyhow::Error) { | |
| 1203 | - match self { | |
| 1204 | - CellJob::Fetch { reply, .. } => drop(reply.send(Err(error))), | |
| 1205 | - CellJob::Rpc { reply, .. } => drop(reply.send(Err(error))), | |
| 1206 | - CellJob::WsOpen { reply, .. } => drop(reply.send(Err(error))), | |
| 1207 | - CellJob::WsMessage { reply, .. } => drop(reply.send(Err(error))), | |
| 1208 | - CellJob::WsClosed { reply, .. } => drop(reply.send(Err(error))), | |
| 1209 | - CellJob::Alarm { reply, .. } => drop(reply.send(Err(error))), | |
| 1210 | - #[cfg(celld_internal_tests)] | |
| 1211 | - CellJob::SyncErrorForTest { reply, .. } => drop(reply.send(Err(error))), | |
| 1212 | - } | |
| 1213 | - } | |
| 1214 | -} | |
| 1215 | - | |
| 1216 | -thread_local! { | |
| 1217 | - // One outbound HTTP client per JS thread — building it per fetch rebuilds | |
| 1218 | - // the TLS stack every call (async-op-hazards.md). | |
| 1219 | - static HTTP: reqwest::Client = reqwest::Client::new(); | |
| 1220 | - static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder() | |
| 1221 | - .redirect(reqwest::redirect::Policy::none()).build().unwrap(); | |
| 1222 | - static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new()); | |
| 1223 | -} | |
| 1224 | - | |
| 1225 | -#[doc(hidden)] | |
| 1226 | -pub mod websocket; | |
| 1227 | -pub(crate) use websocket::WebSocketService; | |
| 1228 | -pub use websocket::*; | |
| 1229 | -use websocket::{ws_capture_begin, ws_capture_take, ws_close_request_sockets}; | |
| 1230 | - | |
| 1231 | -/// What an outbound effect must trail before it leaves the process. | |
| 1232 | -/// | |
| 1233 | -/// The three cases are named rather than nested inside one another because | |
| 1234 | -/// two of them once shared a representation, and that is what issue #144 was: | |
| 1235 | -/// a reader that starts after another request committed samples the new | |
| 1236 | -/// position as its own baseline and advances nothing, so a two-state gate read | |
| 1237 | -/// it as code that owns no cell at all and let its side effect out ungated. | |
| 1238 | -/// A variant per case makes the distinction one the compiler keeps. | |
| 1239 | -enum EgressGate { | |
| 1240 | - /// No cell event is running. Stateless Worker code owns no cell state, so | |
| 1241 | - /// its egress reveals nothing that can still be lost and leaves directly. | |
| 1242 | - NoCell, | |
| 1243 | - /// This event wrote through the position. The effect waits for that write. | |
| 1244 | - Wrote(String, celld_logic::Channel, u64), | |
| 1245 | - /// A read-only output. It reveals whatever the cell holds, so it trails | |
| 1246 | - /// the newest write barrier still open on the cell. Only the core knows | |
| 1247 | - /// which writes are outstanding, so this asks rather than guesses. | |
| 1248 | - ReadOnly(String, celld_logic::Channel), | |
| 1249 | -} | |
| 1250 | - | |
| 1251 | -impl EgressGate { | |
| 1252 | - /// Whether the effect must consult the gate before it leaves. True for a | |
| 1253 | - /// read as well as a write: a read whose cell has no barrier is released | |
| 1254 | - /// at once, but only the core can say so. | |
| 1255 | - fn is_gated(&self) -> bool { | |
| 1256 | - !matches!(self, EgressGate::NoCell) | |
| 1257 | - } | |
| 1258 | - | |
| 1259 | - /// The cell whose event raised the effect. The host derives this from the | |
| 1260 | - /// active event, so JavaScript cannot claim another cell's authority. | |
| 1261 | - fn cell_scope(&self) -> Option<&str> { | |
| 1262 | - match self { | |
| 1263 | - EgressGate::NoCell => None, | |
| 1264 | - EgressGate::Wrote(cell, ..) | EgressGate::ReadOnly(cell, ..) => Some(cell), | |
| 1265 | - } | |
| 1266 | - } | |
| 1267 | -} | |
| 1268 | - | |
| 1269 | -/// Sample what the running handler's outbound effects must trail. Answers for | |
| 1270 | -/// every active cell event, including a read whose core lookup can settle | |
| 1271 | -/// immediately. | |
| 1272 | -fn egress_gate_request(channel: celld_logic::Channel) -> EgressGate { | |
| 1273 | - let context = current_context(); | |
| 1274 | - let stack = context.egress.lock().unwrap(); | |
| 1275 | - let Some((cell, before)) = stack.last() else { | |
| 1276 | - return EgressGate::NoCell; | |
| 1277 | - }; | |
| 1278 | - match storage::write_position(cell).filter(|position| position > before) { | |
| 1279 | - Some(position) => EgressGate::Wrote(cell.clone(), channel, position), | |
| 1280 | - // A read-only output in a process that configured no output gate has | |
| 1281 | - // nothing to trail. Such a process cannot acknowledge a write either | |
| 1282 | - // -- `await_egress_gate` fails a write closed for want of the same | |
| 1283 | - // channel -- so no committed-but-unproven write exists for a read to | |
| 1284 | - // reveal. Answer as | |
| 1285 | - // if no cell event were running, which keeps the effect on the direct, | |
| 1286 | - // synchronous path it has always taken; a WebSocket frame in | |
| 1287 | - // particular must not join a deferred queue whose flush needs a gate | |
| 1288 | - // to release it. A write still takes a ticket and still fails closed. | |
| 1289 | - None if GATE_TX.get().is_none() => EgressGate::NoCell, | |
| 1290 | - None => EgressGate::ReadOnly(cell.clone(), channel), | |
| 1291 | - } | |
| 1292 | -} | |
| 1293 | - | |
| 1294 | -/// Wait for the writes an outbound effect can reveal to be proven durable | |
| 1295 | -/// before it leaves the process. | |
| 1296 | -/// | |
| 1297 | -/// This is the output gate applied to egress rather than to the response. | |
| 1298 | -/// It cannot deadlock the handler that is awaiting it: the ticket is served by | |
| 1299 | -/// `dispatch_gate` on the host's own loop and resolved by the replicator's | |
| 1300 | -/// independent task, neither of which needs the isolate's event loop to run. | |
| 1301 | -/// A read-only ticket carries `None` and the core releases it at once when the | |
| 1302 | -/// cell has no barrier open, so an ordinary read pays one actor hop and no | |
| 1303 | -/// replica write. | |
| 1304 | -async fn await_egress_gate(gate: EgressGate) -> std::result::Result<(), String> { | |
| 1305 | - let (cell, channel, position) = match gate { | |
| 1306 | - EgressGate::NoCell => return Ok(()), | |
| 1307 | - EgressGate::Wrote(cell, channel, position) => (cell, channel, Some(position)), | |
| 1308 | - EgressGate::ReadOnly(cell, channel) => (cell, channel, None), | |
| 1309 | - }; | |
| 1310 | - let (tx, receive) = tokio::sync::oneshot::channel(); | |
| 1311 | - let sent = GATE_TX | |
| 1312 | - .get() | |
| 1313 | - .map(|gate| { | |
| 1314 | - gate.send(GateReq { | |
| 1315 | - scope: cell, | |
| 1316 | - channel, | |
| 1317 | - position, | |
| 1318 | - reply: tx, | |
| 1319 | - }) | |
| 1320 | - .is_ok() | |
| 1321 | - }) | |
| 1322 | - .unwrap_or(false); | |
| 1323 | - if !sent { | |
| 1324 | - return Err("no output-gate channel".into()); | |
| 1325 | - } | |
| 1326 | - match receive.await { | |
| 1327 | - Ok(Ok(())) => Ok(()), | |
| 1328 | - Ok(Err(error)) => Err(format!( | |
| 1329 | - "refusing to send: the write this request follows is not durable ({error:?})" | |
| 1330 | - )), | |
| 1331 | - Err(_) => Err("output gate dropped".into()), | |
| 1332 | - } | |
| 1333 | -} | |
| 1334 | - | |
| 1335 | -/// Hold an outbound request until the write it follows is durable, then hand | |
| 1336 | -/// it to the host. | |
| 1337 | -/// | |
| 1338 | -/// The send moves inside the future deliberately. These channels dispatch as | |
| 1339 | -/// soon as `send` is called, so gating anywhere after it would let the effect | |
| 1340 | -/// leave first -- the request would already be on its way while the caller | |
| 1341 | -/// waited for a durability answer that no longer decides anything. | |
| 1342 | -async fn gated_channel_send<T>( | |
| 1343 | - gate: EgressGate, | |
| 1344 | - channel: &'static OnceLock<tokio::sync::mpsc::UnboundedSender<T>>, | |
| 1345 | - request: T, | |
| 1346 | - missing: &'static str, | |
| 1347 | -) -> std::result::Result<(), String> { | |
| 1348 | - await_egress_gate(gate).await?; | |
| 1349 | - match channel.get() { | |
| 1350 | - Some(tx) if tx.send(request).is_ok() => Ok(()), | |
| 1351 | - _ => Err(missing.to_string()), | |
| 1352 | - } | |
| 1353 | -} | |
| 1354 | - | |
| 1355 | -/// One `celld_logic::gate::InputGate` per cell. | |
| 1356 | -/// | |
| 1357 | -/// The logic decides; this is only the map and the ids. It replaces the | |
| 1358 | -/// promise chain that used to live in `harness.js`, which serialised blocks | |
| 1359 | -/// against each other but did nothing about *delivery* — so a second event | |
| 1360 | -/// could arrive mid-block, and under real concurrency that wedged the cell. | |
| 1361 | -/// | |
| 1362 | -/// Keyed by cell scope rather than held on the isolate, because a gate | |
| 1363 | -/// belongs to a cell and cells share isolates. | |
| 1364 | -static CELL_GATES: OnceLock<Mutex<HashMap<String, celld_logic::gate::InputGate>>> = OnceLock::new(); | |
| 1365 | -static NEXT_GATE_EVENT: AtomicU64 = AtomicU64::new(1); | |
| 1366 | - | |
| 1367 | -fn cell_gates() -> &'static Mutex<HashMap<String, celld_logic::gate::InputGate>> { | |
| 1368 | - CELL_GATES.get_or_init(|| Mutex::new(HashMap::new())) | |
| 1369 | -} | |
| 1370 | - | |
| 1371 | -/// What a waiting event is told when the gate finally opens: nothing, or | |
| 1372 | -/// the reason the holder failed. | |
| 1373 | -type GateWake = tokio::sync::oneshot::Sender<Result<(), String>>; | |
| 1374 | - | |
| 1375 | -static GATE_WAITERS: OnceLock<Mutex<HashMap<String, Vec<GateWake>>>> = OnceLock::new(); | |
| 1376 | - | |
| 1377 | -/// Events waiting for a cell's input gate to open, in arrival order. | |
| 1378 | -/// | |
| 1379 | -/// An earlier implementation deleted this queue because an event the gate | |
| 1380 | -/// refused stayed on the cell's job channel until a later delivery point | |
| 1381 | -/// took it, so the channel *was* the queue and a second one could disagree | |
| 1382 | -/// with it. Drives have no channel, so a refused event needs somewhere to | |
| 1383 | -/// wait, and workerd keeps the same structure for the same reason | |
| 1384 | -/// (`io-gate.h`, `kj::List<Waiter, &Waiter::link> waiters`). | |
| 1385 | -/// | |
| 1386 | -/// In the shell rather than in `celld_logic::gate`, because what waits is a | |
| 1387 | -/// tokio task and the core is sans-IO. The core still owns the decision — | |
| 1388 | -/// `is_open` — and this owns only the waking. | |
| 1389 | -fn gate_waiters() -> &'static Mutex<HashMap<String, Vec<GateWake>>> { | |
| 1390 | - GATE_WAITERS.get_or_init(|| Mutex::new(HashMap::new())) | |
| 1391 | -} | |
| 1392 | - | |
| 1393 | -/// Take a ticket to be woken when `cell`'s gate opens, or `None` if it is | |
| 1394 | -/// open now. | |
| 1395 | -/// | |
| 1396 | -/// The gate's lock is held across the check and the enqueue, so a release | |
| 1397 | -/// that lands between the two cannot leave an event waiting on a gate that | |
| 1398 | -/// is already open. | |
| 1399 | -pub fn cell_gate_wait(cell: &str) -> Option<tokio::sync::oneshot::Receiver<Result<(), String>>> { | |
| 1400 | - let gates = cell_gates().lock().unwrap(); | |
| 1401 | - if gates.get(cell).is_none_or(|gate| gate.is_open()) { | |
| 1402 | - return None; | |
| 1403 | - } | |
| 1404 | - let (wake, waiter) = tokio::sync::oneshot::channel(); | |
| 1405 | - gate_waiters() | |
| 1406 | - .lock() | |
| 1407 | - .unwrap() | |
| 1408 | - .entry(cell.to_string()) | |
| 1409 | - .or_default() | |
| 1410 | - .push(wake); | |
| 1411 | - drop(gates); | |
| 1412 | - Some(waiter) | |
| 1413 | -} | |
| 1414 | - | |
| 1415 | -/// Wake everything waiting on `cell`'s gate. Each re-checks and re-queues if | |
| 1416 | -/// another block took the gate first, so waking all of them is correct and | |
| 1417 | -/// the order they resume in is theirs to lose, not this function's to keep. | |
| 1418 | -fn wake_gate_waiters(cell: &str, outcome: Result<(), String>) { | |
| 1419 | - let waiters = gate_waiters().lock().unwrap().remove(cell); | |
| 1420 | - for wake in waiters.into_iter().flatten() { | |
| 1421 | - let _ = wake.send(outcome.clone()); | |
| 1422 | - } | |
| 1423 | -} | |
| 1424 | - | |
| 1425 | -/// The event holding this cell's gate died without releasing it. | |
| 1426 | -/// | |
| 1427 | -/// Only execution termination reaches here: every other exit from a block | |
| 1428 | -/// runs the `finally` in `harness.js`. Without it a cell whose blocking | |
| 1429 | -/// request was killed would refuse every later event forever. | |
| 1430 | -fn cell_gate_abandon(scope: &str) { | |
| 1431 | - if let Some(gate) = cell_gates().lock().unwrap().get_mut(scope) { | |
| 1432 | - gate.abandon(); | |
| 1433 | - } | |
| 1434 | - // The holder died without running its `finally`, so nobody can say why. | |
| 1435 | - // Refuse the waiters anyway: the cell it queued behind is gone. | |
| 1436 | - wake_gate_waiters( | |
| 1437 | - scope, | |
| 1438 | - Err("the cell's critical section ended without releasing".to_string()), | |
| 1439 | - ); | |
| 1440 | -} | |
| 1441 | - | |
| 1442 | -/// JS promise resolvers awaiting an async op, keyed by the op's id. | |
| 1443 | -/// | |
| 1444 | -/// **Per isolate, and shared across threads.** Under D1 a request's turns run | |
| 1445 | -/// on whichever tokio worker picks them up, so a resolver registered on one | |
| 1446 | -/// thread is resolved from another; a thread-local map loses it, and | |
| 1447 | -/// `resolve_res` fails to find the resolver and returns silently, leaving the | |
| 1448 | -/// handler awaiting a promise nothing will ever settle. The `Mutex` is what | |
| 1449 | -/// makes that safe, not the map's location. | |
| 1450 | -/// | |
| 1451 | -/// It lives on `ActorRuntimeState` — one per isolate, reached from a scope — | |
| 1452 | -/// so a resolver is only ever looked up in the heap that owns it. One map for | |
| 1453 | -/// the whole process would also work, because op ids come from a single | |
| 1454 | -/// counter (`asyncrt::NEXT_ID`) and an id names exactly one resolver. But that | |
| 1455 | -/// makes an id-allocation bug into cross-isolate handle confusion, where this | |
| 1456 | -/// makes it a miss. | |
| 1457 | -type PromiseMap = HashMap<u64, v8::Global<v8::PromiseResolver>>; | |
| 1458 | - | |
| 1459 | -/// Requests cancelled by a reentrant `AbortFetch`. Global for the same reason | |
| 1460 | -/// as [`promises`]: the turn that observes a cancellation need not be on the | |
| 1461 | -/// thread that recorded it. | |
| 1462 | -static CANCELLED_REQUESTS: OnceLock<Mutex<HashSet<RequestId>>> = OnceLock::new(); | |
| 1463 | - | |
| 1464 | -fn cancelled_requests() -> &'static Mutex<HashSet<RequestId>> { | |
| 1465 | - CANCELLED_REQUESTS.get_or_init(|| Mutex::new(HashSet::new())) | |
| 1466 | -} | |
| 1467 | - | |
| 1468 | -fn promise_store(scope: &mut v8::PinScope, id: u64, r: v8::Global<v8::PromiseResolver>) { | |
| 1469 | - actor_runtime_state(scope) | |
| 1470 | - .promises | |
| 1471 | - .lock() | |
| 1472 | - .unwrap() | |
| 1473 | - .insert(id, r); | |
| 1474 | -} | |
| 1475 | - | |
| 1476 | -/// Resolve or reject op `id`'s promise with its outcome. | |
| 1477 | -fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) { | |
| 1478 | - let g = match actor_runtime_state(tc).promises.lock().unwrap().remove(&id) { | |
| 1479 | - Some(g) => g, | |
| 1480 | - None => return, | |
| 1481 | - }; | |
| 1482 | - let r = v8::Local::new(tc, g); | |
| 1483 | - match res { | |
| 1484 | - Ok(asyncrt::OpOut::Str(v)) => { | |
| 1485 | - let s = v8::String::new(tc, &v).unwrap(); | |
| 1486 | - r.resolve(tc, s.into()); | |
| 1487 | - } | |
| 1488 | - Ok(asyncrt::OpOut::Bytes(b)) => { | |
| 1489 | - let v = bytes_value(tc, b); | |
| 1490 | - r.resolve(tc, v); | |
| 1491 | - } | |
| 1492 | - Err(e) => { | |
| 1493 | - let s = v8::String::new(tc, &e).unwrap(); | |
| 1494 | - let ex = v8::Exception::error(tc, s); | |
| 1495 | - r.reject(tc, ex); | |
| 1496 | - } | |
| 1497 | - } | |
| 1498 | -} | |
| 1499 | - | |
| 1500 | -/// Move `bytes` into a `Uint8Array` without copying. | |
| 1501 | -fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> { | |
| 1502 | - #[cfg(celld_internal_tests)] | |
| 1503 | - let input = bytes.as_ptr() as usize; | |
| 1504 | - let len = bytes.len(); | |
| 1505 | - let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared(); | |
| 1506 | - let buffer = v8::ArrayBuffer::with_backing_store(scope, &store); | |
| 1507 | - #[cfg(celld_internal_tests)] | |
| 1508 | - record_bytes_value_allocation_for_test( | |
| 1509 | - input, | |
| 1510 | - buffer | |
| 1511 | - .get_backing_store() | |
| 1512 | - .data() | |
| 1513 | - .map(|data| data.as_ptr() as usize), | |
| 1514 | - ); | |
| 1515 | - v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into() | |
| 1516 | -} | |
| 1517 | - | |
| 1518 | -#[cfg(celld_internal_tests)] | |
| 1519 | -static BYTES_VALUE_ALLOCATION_PROBE: Mutex<Option<(usize, Option<usize>)>> = Mutex::new(None); | |
| 1520 | - | |
| 1521 | -#[cfg(celld_internal_tests)] | |
| 1522 | -#[doc(hidden)] | |
| 1523 | -pub fn capture_bytes_value_allocation_for_test(expected: *const u8) { | |
| 1524 | - *BYTES_VALUE_ALLOCATION_PROBE.lock().unwrap() = Some((expected as usize, None)); | |
| 1525 | -} | |
| 1526 | - | |
| 1527 | -#[cfg(celld_internal_tests)] | |
| 1528 | -fn record_bytes_value_allocation_for_test(input: usize, output: Option<usize>) { | |
| 1529 | - let mut probe = BYTES_VALUE_ALLOCATION_PROBE.lock().unwrap(); | |
| 1530 | - if probe | |
| 1531 | - .as_ref() | |
| 1532 | - .is_some_and(|(expected, _)| *expected == input) | |
| 1533 | - { | |
| 1534 | - *probe = Some((input, output)); | |
| 1535 | - } | |
| 1536 | -} | |
| 1537 | - | |
| 1538 | -#[cfg(celld_internal_tests)] | |
| 1539 | -#[doc(hidden)] | |
| 1540 | -pub fn take_bytes_value_allocation_for_test() -> Option<usize> { | |
| 1541 | - BYTES_VALUE_ALLOCATION_PROBE | |
| 1542 | - .lock() | |
| 1543 | - .unwrap() | |
| 1544 | - .take() | |
| 1545 | - .and_then(|(_, output)| output) | |
| 1546 | -} | |
| 1547 | - | |
| 1548 | -pub fn handler_budget() -> Duration { | |
| 1549 | - static BUDGET: OnceLock<Duration> = OnceLock::new(); | |
| 1550 | - *BUDGET.get_or_init(|| { | |
| 1551 | - Duration::from_secs( | |
| 1552 | - crate::env_vars::positive_or("CELLD_HANDLER_BUDGET_S", 300) | |
| 1553 | - .expect("validated CELLD_HANDLER_BUDGET_S"), | |
| 1554 | - ) | |
| 1555 | - }) | |
| 1556 | -} | |
| 1557 | - | |
| 1558 | -/// Aborts raised by an HTTP or service-binding caller disconnecting while the | |
| 1559 | -/// target runs in the stateless isolate pool. Durable Object aborts can also | |
| 1560 | -/// arrive as a reentrant `CellJob::AbortFetch`, so the abort has to be visible | |
| 1561 | -/// from whichever turn observes it. | |
| 1562 | -/// | |
| 1563 | -/// The counter keeps the common path to one relaxed atomic load per loop turn: | |
| 1564 | -/// with nothing pending, the mutex is never taken. | |
| 1565 | -static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> = | |
| 1566 | - OnceLock::new(); | |
| 1567 | -static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | |
| 1568 | - | |
| 1569 | -fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> { | |
| 1570 | - PENDING_ABORTS.get_or_init(Default::default) | |
| 1571 | -} | |
| 1572 | - | |
| 1573 | -/// Mark an in-flight request cancelled from any thread. | |
| 1574 | -pub fn abort_request(request_id: RequestId) { | |
| 1575 | - if pending_aborts().lock().unwrap().insert(request_id) { | |
| 1576 | - PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed); | |
| 1577 | - } | |
| 1578 | -} | |
| 1579 | - | |
| 1580 | -pub(crate) fn clear_request_cancellation(request_id: RequestId) { | |
| 1581 | - let _ = take_pending_abort(request_id); | |
| 1582 | - cancelled_requests().lock().unwrap().remove(&request_id); | |
| 1583 | -} | |
| 1584 | - | |
| 1585 | -#[cfg(celld_internal_tests)] | |
| 1586 | -#[doc(hidden)] | |
| 1587 | -pub fn clear_request_cancellation_for_test(request_id: RequestId) { | |
| 1588 | - clear_request_cancellation(request_id); | |
| 1589 | -} | |
| 1590 | - | |
| 1591 | -fn take_pending_abort(request_id: RequestId) -> bool { | |
| 1592 | - if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 { | |
| 1593 | - return false; | |
| 1594 | - } | |
| 1595 | - if pending_aborts().lock().unwrap().remove(&request_id) { | |
| 1596 | - PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed); | |
| 1597 | - return true; | |
| 1598 | - } | |
| 1599 | - false | |
| 1600 | -} | |
| 1601 | - | |
| 1602 | -pub fn take_request_cancellation(request_id: Option<RequestId>) -> bool { | |
| 1603 | - request_id.is_some_and(|request_id| { | |
| 1604 | - cancelled_requests().lock().unwrap().remove(&request_id) || take_pending_abort(request_id) | |
| 1605 | - }) | |
| 1606 | -} | |
| 1607 | - | |
| 1608 | -fn resolved_promise<'s>( | |
| 1609 | - tc: &mut v8::PinScope<'s, '_>, | |
| 1610 | - value: v8::Local<'s, v8::Value>, | |
| 1611 | -) -> Result<v8::Local<'s, v8::Promise>> { | |
| 1612 | - let resolver = | |
| 1613 | - v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?; | |
| 1614 | - resolver.resolve(tc, value); | |
| 1615 | - Ok(resolver.get_promise(tc)) | |
| 1616 | -} | |
| 1617 | - | |
| 1618 | -fn abort_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) -> Result<bool> { | |
| 1619 | - let function = event_hook(tc, |hooks| &hooks.abort_incoming_request)?; | |
| 1620 | - let request_id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 1621 | - let recv = v8::undefined(tc).into(); | |
| 1622 | - let result = function | |
| 1623 | - .call(tc, recv, &[request_id.into()]) | |
| 1624 | - .ok_or_else(|| anyhow!("__abortIncomingRequest threw"))?; | |
| 1625 | - Ok(result.boolean_value(tc)) | |
| 1626 | -} | |
| 1627 | - | |
| 1628 | -/// The rejection reason of a settled-rejected promise, with a little stack. | |
| 1629 | -fn reject_reason(tc: &mut v8::PinScope, p: v8::Local<v8::Promise>) -> String { | |
| 1630 | - let r = p.result(tc); | |
| 1631 | - let msg = r.to_rust_string_lossy(tc); | |
| 1632 | - let stk = r | |
| 1633 | - .to_object(tc) | |
| 1634 | - .and_then(|o| { | |
| 1635 | - let k = v8::String::new(tc, "stack")?; | |
| 1636 | - o.get(tc, k.into()) | |
| 1637 | - }) | |
| 1638 | - .map(|s| s.to_rust_string_lossy(tc)) | |
| 1639 | - .unwrap_or_default(); | |
| 1640 | - let tail = stk | |
| 1641 | - .lines() | |
| 1642 | - .skip(1) | |
| 1643 | - .take(3) | |
| 1644 | - .map(|l| l.trim()) | |
| 1645 | - .collect::<Vec<_>>() | |
| 1646 | - .join(" <- "); | |
| 1647 | - if tail.is_empty() { | |
| 1648 | - msg | |
| 1649 | - } else { | |
| 1650 | - format!("{msg} [{tail}]") | |
| 1651 | - } | |
| 1652 | -} | |
| 1653 | - | |
| 1654 | -pub struct Engine; | |
| 1655 | -impl Engine { | |
| 1656 | - pub fn init() { | |
| 1657 | - // V8 is process-global, so the guard belongs to the initializer. A | |
| 1658 | - // guard at each caller allowed two callers to each initialize V8 once, | |
| 1659 | - // which poisoned the global state when both ran. | |
| 1660 | - static INIT: std::sync::Once = std::sync::Once::new(); | |
| 1661 | - INIT.call_once(|| { | |
| 1662 | - #[cfg(celld_internal_tests)] | |
| 1663 | - v8::V8::set_flags_from_string("--expose-gc"); | |
| 1664 | - // No `v8::icu::set_common_data_78` call: the rusty_v8 152 prebuilt | |
| 1665 | - // statically links the complete ICU data (full locale tables and | |
| 1666 | - // regex property-of-strings, e.g. /\p{RGI_Emoji}/v — verified | |
| 1667 | - // empirically), so overriding it with an embedded icudtl.dat only | |
| 1668 | - // duplicated 10.8 MB in the binary. The required coverage is | |
| 1669 | - // explicit, so a future v8 bump that reduces the builtin data | |
| 1670 | - // fails rather than silently narrowing it; the fix would be to | |
| 1671 | - // re-embed rusty_v8's `third_party/icu/common/icudtl.dat`, | |
| 1672 | - // 16-byte-aligned. | |
| 1673 | - let platform = v8::new_default_platform(0, false).make_shared(); | |
| 1674 | - v8::V8::initialize_platform(platform); | |
| 1675 | - v8::V8::initialize(); | |
| 1676 | - }); | |
| 1677 | - } | |
| 1678 | -} | |
| 1679 | - | |
| 1680 | -/// Per-worker compatibility switches, derived from the manifest's | |
| 1681 | -/// compatibility date and flags (Workerd compatibility-date.capnp). `Default` | |
| 1682 | -/// is every switch off; production derives real values in `main`. | |
| 1683 | -#[derive(Clone, Copy, Default)] | |
| 1684 | -pub struct Compat { | |
| 1685 | - pub delete_all_deletes_alarm: bool, | |
| 1686 | - /// `js_rpc`: RPC on a Durable Object class that does not extend | |
| 1687 | - /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()). | |
| 1688 | - pub js_rpc: bool, | |
| 1689 | - /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`, | |
| 1690 | - /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/ | |
| 1691 | - /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher). | |
| 1692 | - pub fetcher_get_put_delete: bool, | |
| 1693 | - /// `sqlite_vec`: expose the pre-v1 sqlite-vec extension to SQLite-backed | |
| 1694 | - /// Durable Objects. This switch is explicit and has no date default. | |
| 1695 | - pub sqlite_vec: bool, | |
| 1696 | - /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and | |
| 1697 | - /// a binary message arrives as a `Blob`, per the WHATWG default. Without | |
| 1698 | - /// it celld keeps the historical `"arraybuffer"`. | |
| 1699 | - pub websocket_standard_binary_type: bool, | |
| 1700 | - /// Queue bodies default to JSON on compatibility dates after 2024-03-18; | |
| 1701 | - /// older deployments retain the V8 structured-clone default. | |
| 1702 | - pub queue_json_messages: bool, | |
| 1703 | -} | |
| 1704 | - | |
| 1705 | -/// A non-main module the worker's main module may import, tagged by how the | |
| 1706 | -/// runtime materializes it. | |
| 1707 | -pub enum ModuleSource { | |
| 1708 | - /// UTF-8 content served as `export default "<content>"` (wrangler's Text | |
| 1709 | - /// rule), registered under the given specifier verbatim. | |
| 1710 | - Text(String), | |
| 1711 | - /// JS source compiled as a sibling ES module (Worker Loader multi-module | |
| 1712 | - /// bundles), registered under both `name` and `./name`. | |
| 1713 | - EsModule(String), | |
| 1714 | - /// Wasm bytes served as a module whose default export is the compiled | |
| 1715 | - /// `WebAssembly.Module` (Wrangler's `CompiledWasm` rule), registered | |
| 1716 | - /// under both `name` and `./name`. | |
| 1717 | - Wasm(bytes::Bytes), | |
| 1718 | -} | |
| 1719 | - | |
| 1720 | -/// A Workflow binding keeps the three names distinct across deployment | |
| 1721 | -/// loading, environment construction, and runtime class injection. | |
| 1722 | -pub struct WorkflowBinding { | |
| 1723 | - pub environment: String, | |
| 1724 | - pub workflow: String, | |
| 1725 | - pub class: String, | |
| 1726 | -} | |
| 1727 | - | |
| 1728 | -/// One Queue producer binding in a Worker environment. | |
| 1729 | -#[derive(Clone)] | |
| 1730 | -pub struct QueueBinding { | |
| 1731 | - pub environment: String, | |
| 1732 | - pub queue: String, | |
| 1733 | - pub delivery_delay: u32, | |
| 1734 | -} | |
| 1735 | - | |
| 1736 | -/// One queue's push consumer after the owning script has been resolved. | |
| 1737 | -#[derive(Clone)] | |
| 1738 | -pub struct QueueConsumerRegistration { | |
| 1739 | - pub script: String, | |
| 1740 | - pub config: crate::protocol::QueueConsumerConfig, | |
| 1741 | -} | |
| 1742 | - | |
| 1743 | -pub struct WorkerConfig { | |
| 1744 | - src: String, | |
| 1745 | - pub script_name: String, | |
| 1746 | - do_classes: Vec<String>, | |
| 1747 | - bindings: Vec<(String, String)>, | |
| 1748 | - /// `r2_buckets`: (environment name, bucket name). The bucket name is | |
| 1749 | - /// the key space the binding owns inside the fleet bucket; see [[r2]]. | |
| 1750 | - r2_bindings: Vec<(String, String)>, | |
| 1751 | - /// `d1_databases`: (environment name, stable database identity). The | |
| 1752 | - /// identity addresses the cell that holds the database; see [[d1]]. | |
| 1753 | - d1_bindings: Vec<(String, String)>, | |
| 1754 | - /// `kv_namespaces`: (environment name, namespace identity). The identity is | |
| 1755 | - /// the config's `id` verbatim, and it addresses the namespace's cells; see | |
| 1756 | - /// [[kv]]. | |
| 1757 | - kv_bindings: Vec<(String, String)>, | |
| 1758 | - queue_bindings: Vec<QueueBinding>, | |
| 1759 | - queue_consumers: Vec<QueueConsumerRegistration>, | |
| 1760 | - /// This script declared a consumer in its own manifest. The deployment- | |
| 1761 | - /// wide catalog later replaces `queue_consumers` in every isolate, so the | |
| 1762 | - /// catalog cannot answer whether this particular default export can omit | |
| 1763 | - /// `fetch` and provide only `queue`. | |
| 1764 | - declares_queue_consumer: bool, | |
| 1765 | - workflow_bindings: Vec<WorkflowBinding>, | |
| 1766 | - ai_binding: Option<String>, | |
| 1767 | - vars: Vec<(String, String)>, | |
| 1768 | - node: String, | |
| 1769 | - /// The worker's non-main modules, so the main module can import siblings. | |
| 1770 | - modules: Vec<(String, ModuleSource)>, | |
| 1771 | - compat: Compat, | |
| 1772 | - /// `[[services]]`: (binding name, target script, optional entrypoint). | |
| 1773 | - /// The target runs in this process; see [[service-bindings]]. | |
| 1774 | - services: Vec<(String, String, Option<String>)>, | |
| 1775 | - asset_binding: Option<String>, | |
| 1776 | - /// `env` name of the Worker Loader binding, if this Worker may spawn | |
| 1777 | - /// dynamic isolates. | |
| 1778 | - loader_binding: Option<String>, | |
| 1779 | - /// Ambient outbound authority. Loaded workers may be denied. | |
| 1780 | - egress: EgressPolicy, | |
| 1781 | - /// Extra `env` values a loaded worker was handed, as a JSON object string | |
| 1782 | - /// merged onto its `env`. Loader-only; empty for normal workers. | |
| 1783 | - loader_env: Option<String>, | |
| 1784 | - /// `triggers.crons` from the deployment. Empty for a loaded worker and for | |
| 1785 | - /// any script without cron triggers. | |
| 1786 | - pub crons: Vec<String>, | |
| 1787 | - /// The application generation this configuration belongs to. Every | |
| 1788 | - /// isolate built from it carries the value as a slot, so its host calls | |
| 1789 | - /// resolve against the deployment graph it was built with. | |
| 1790 | - pub generation: crate::generation::GenerationId, | |
| 1791 | - /// The external (`node:*`/`cloudflare:*`) imports of `src`. | |
| 1792 | - /// | |
| 1793 | - /// The scan walks the whole bundle, which an esbuild artifact makes | |
| 1794 | - /// megabytes, and its answer depends only on `src` — a field nothing | |
| 1795 | - /// mutates after construction. It used to run inside `load_config`, | |
| 1796 | - /// so a deployment paid it again on every cell wake and on every | |
| 1797 | - /// stateless pool thread. One `Arc<WorkerConfig>` backs all of those | |
| 1798 | - /// isolates, so scanning here pays it once instead. | |
| 1799 | - main_imports: modules::ExternalImports, | |
| 1800 | - /// The same scan for each `ModuleSource::EsModule` sibling, in the order | |
| 1801 | - /// `es_module_sources` yields them. Read through | |
| 1802 | - /// [`WorkerConfig::es_modules`], which hands a module and its scan out | |
| 1803 | - /// together so no caller can pair a module with another module's scan. | |
| 1804 | - module_imports: Vec<modules::ExternalImports>, | |
| 1805 | -} | |
| 1806 | - | |
| 1807 | -/// The `ModuleSource::EsModule` siblings of a worker, as (name, source). | |
| 1808 | -/// | |
| 1809 | -/// The single definition of that order: `WorkerConfig::new` scans in it and | |
| 1810 | -/// `WorkerConfig::es_modules` zips against it, so the two cannot disagree. | |
| 1811 | -fn es_module_sources(modules: &[(String, ModuleSource)]) -> impl Iterator<Item = (&str, &str)> { | |
| 1812 | - modules.iter().filter_map(|(name, source)| match source { | |
| 1813 | - ModuleSource::EsModule(source) => Some((name.as_str(), source.as_str())), | |
| 1814 | - _ => None, | |
| 1815 | - }) | |
| 1816 | -} | |
| 1817 | - | |
| 1818 | -pub struct WorkerConfigOptions { | |
| 1819 | - pub src: String, | |
| 1820 | - pub script_name: String, | |
| 1821 | - pub do_classes: Vec<String>, | |
| 1822 | - pub bindings: Vec<(String, String)>, | |
| 1823 | - pub r2_bindings: Vec<(String, String)>, | |
| 1824 | - pub d1_bindings: Vec<(String, String)>, | |
| 1825 | - pub kv_bindings: Vec<(String, String)>, | |
| 1826 | - pub queue_bindings: Vec<QueueBinding>, | |
| 1827 | - pub queue_consumers: Vec<crate::protocol::QueueConsumerConfig>, | |
| 1828 | - pub workflow_bindings: Vec<WorkflowBinding>, | |
| 1829 | - pub ai_binding: Option<String>, | |
| 1830 | - pub vars: Vec<(String, String)>, | |
| 1831 | - pub node: String, | |
| 1832 | - pub modules: Vec<(String, ModuleSource)>, | |
| 1833 | - pub compat: Compat, | |
| 1834 | -} | |
| 1835 | - | |
| 1836 | -impl WorkerConfig { | |
| 1837 | - pub fn new(options: WorkerConfigOptions) -> Self { | |
| 1838 | - let WorkerConfigOptions { | |
| 1839 | - src, | |
| 1840 | - script_name, | |
| 1841 | - do_classes, | |
| 1842 | - bindings, | |
| 1843 | - r2_bindings, | |
| 1844 | - d1_bindings, | |
| 1845 | - kv_bindings, | |
| 1846 | - queue_bindings, | |
| 1847 | - queue_consumers, | |
| 1848 | - workflow_bindings, | |
| 1849 | - ai_binding, | |
| 1850 | - vars, | |
| 1851 | - node, | |
| 1852 | - modules, | |
| 1853 | - compat, | |
| 1854 | - } = options; | |
| 1855 | - let main_imports = modules::scan_external_imports(&src); | |
| 1856 | - let module_imports = es_module_sources(&modules) | |
| 1857 | - .map(|(_name, source)| modules::scan_external_imports(source)) | |
| 1858 | - .collect(); | |
| 1859 | - let declares_queue_consumer = !queue_consumers.is_empty(); | |
| 1860 | - let queue_consumers = queue_consumers | |
| 1861 | - .into_iter() | |
| 1862 | - .map(|config| QueueConsumerRegistration { | |
| 1863 | - script: script_name.clone(), | |
| 1864 | - config, | |
| 1865 | - }) | |
| 1866 | - .collect(); | |
| 1867 | - Self { | |
| 1868 | - src, | |
| 1869 | - script_name, | |
| 1870 | - do_classes, | |
| 1871 | - bindings, | |
| 1872 | - r2_bindings, | |
| 1873 | - d1_bindings, | |
| 1874 | - kv_bindings, | |
| 1875 | - queue_bindings, | |
| 1876 | - queue_consumers, | |
| 1877 | - declares_queue_consumer, | |
| 1878 | - workflow_bindings, | |
| 1879 | - ai_binding, | |
| 1880 | - vars, | |
| 1881 | - node, | |
| 1882 | - modules, | |
| 1883 | - compat, | |
| 1884 | - services: Vec::new(), | |
| 1885 | - asset_binding: None, | |
| 1886 | - loader_binding: None, | |
| 1887 | - egress: EgressPolicy::Allow, | |
| 1888 | - loader_env: None, | |
| 1889 | - crons: Vec::new(), | |
| 1890 | - generation: 0, | |
| 1891 | - main_imports, | |
| 1892 | - module_imports, | |
| 1893 | - } | |
| 1894 | - } | |
| 1895 | - | |
| 1896 | - /// Stamp this Worker with the application generation it serves. | |
| 1897 | - pub fn with_generation(mut self, generation: crate::generation::GenerationId) -> Self { | |
| 1898 | - self.generation = generation; | |
| 1899 | - self | |
| 1900 | - } | |
| 1901 | - | |
| 1902 | - pub fn with_queue_consumers(mut self, consumers: Vec<QueueConsumerRegistration>) -> Self { | |
| 1903 | - self.queue_consumers = consumers; | |
| 1904 | - self | |
| 1905 | - } | |
| 1906 | - | |
| 1907 | - /// Every `ModuleSource::EsModule` sibling with its name, its source and | |
| 1908 | - /// its scanned external imports. | |
| 1909 | - fn es_modules(&self) -> impl Iterator<Item = (&str, &str, &modules::ExternalImports)> { | |
| 1910 | - // `zip` would truncate silently if the two ever disagreed, and a | |
| 1911 | - // truncated scan means a sibling links against a stub missing its | |
| 1912 | - // names. Both are filled from `es_module_sources` in `new`, so a | |
| 1913 | - // disagreement is a bug in a future mutator, not a reachable state. | |
| 1914 | - debug_assert_eq!( | |
| 1915 | - es_module_sources(&self.modules).count(), | |
| 1916 | - self.module_imports.len(), | |
| 1917 | - "an ES sibling lost its scanned imports", | |
| 1918 | - ); | |
| 1919 | - es_module_sources(&self.modules) | |
| 1920 | - .zip(&self.module_imports) | |
| 1921 | - .map(|((name, source), imports)| (name, source, imports)) | |
| 1922 | - } | |
| 1923 | - | |
| 1924 | - /// Give this Worker the deployment's cron trigger expressions. | |
| 1925 | - pub fn with_crons(mut self, crons: Vec<String>) -> Self { | |
| 1926 | - self.crons = crons; | |
| 1927 | - self | |
| 1928 | - } | |
| 1929 | - | |
| 1930 | - /// Grant this Worker a Worker Loader binding at `env` name `binding`. | |
| 1931 | - pub fn with_loader(mut self, binding: Option<String>) -> Self { | |
| 1932 | - self.loader_binding = binding; | |
| 1933 | - self | |
| 1934 | - } | |
| 1935 | - | |
| 1936 | - /// Set this Worker's ambient outbound authority (loaded workers only). | |
| 1937 | - fn with_egress(mut self, egress: EgressPolicy) -> Self { | |
| 1938 | - self.egress = egress; | |
| 1939 | - self | |
| 1940 | - } | |
| 1941 | - | |
| 1942 | - /// Merge `env` (a JSON object string) onto a loaded worker's `env`. | |
| 1943 | - fn with_loader_env(mut self, env: Option<String>) -> Self { | |
| 1944 | - self.loader_env = env; | |
| 1945 | - self | |
| 1946 | - } | |
| 1947 | - | |
| 1948 | - /// Declare the service bindings this Worker may call. | |
| 1949 | - pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self { | |
| 1950 | - self.services = services; | |
| 1951 | - self | |
| 1952 | - } | |
| 1953 | - | |
| 1954 | - pub fn with_asset_binding(mut self, binding: Option<String>) -> Self { | |
| 1955 | - self.asset_binding = binding; | |
| 1956 | - self | |
| 1957 | - } | |
| 1958 | -} | |
| 1959 | - | |
| 1960 | -/// The storage authority installed when a cell enters an isolate. | |
| 1961 | -/// | |
| 1962 | -/// The path and epoch form one value because opening either one without the | |
| 1963 | -/// other would let later asynchronous work use the wrong ownership epoch. | |
| 1964 | -#[doc(hidden)] | |
| 1965 | -pub struct CellStorage<'a> { | |
| 1966 | - pub path: &'a str, | |
| 1967 | - pub epoch: u64, | |
| 1968 | -} | |
| 1969 | - | |
| 1970 | -pub struct Worker { | |
| 1971 | - inner: Option<WorkerIsolate>, | |
| 1972 | -} | |
| 1973 | - | |
| 1974 | -pub struct WorkerIsolate { | |
| 1975 | - /// Shared rather than owned: under D1 an isolate belongs to no thread, | |
| 1976 | - /// and a worker enters it by taking its `v8::Locker`. | |
| 1977 | - /// | |
| 1978 | - /// Every `lock()` below blocks until the current holder releases. That is | |
| 1979 | - /// only safe because the pool takes an async permit for this isolate | |
| 1980 | - /// first, so the lock is uncontended by construction; a `lock()` reached | |
| 1981 | - /// without that permit would be a blocking call on a tokio worker. | |
| 1982 | - isolate: v8::SharedIsolate, | |
| 1983 | - /// The one realm this isolate has: its context, and the entry `fetch` | |
| 1984 | - /// that lives in it. | |
| 1985 | - /// | |
| 1986 | - /// It was a `HashMap` keyed by cell, on the premise that a cell needs a | |
| 1987 | - /// realm of its own. It does not, and nothing ever put a second one in. | |
| 1988 | - /// The harness already keys instances by scope (`__cell.instances`), and | |
| 1989 | - /// Durable Objects **share** a context per script rather than getting one | |
| 1990 | - /// each — a context per cell would also duplicate the compiled module per | |
| 1991 | - /// cell, which is most of what sharing an isolate saves. | |
| 1992 | - realm: Realm, | |
| 1993 | - original_heap_limit: usize, | |
| 1994 | - compat: Compat, | |
| 1995 | - /// Identity used to reclaim every dynamic Worker this isolate created. | |
| 1996 | - /// Named Worker Loader identity lives in this isolate's JavaScript heap, | |
| 1997 | - /// so no child can remain charged to the registry after its owner is gone. | |
| 1998 | - loader_owner: LoaderOwner, | |
| 1999 | - /// The storage of the cells this isolate hosts. | |
| 2000 | - /// | |
| 2001 | - /// It lives here, and not in a thread-local, because a driven cell's | |
| 2002 | - /// turns run on whatever tokio worker holds the isolate. See | |
| 2003 | - /// `storage::Cells`. | |
| 2004 | - cells: storage::Cells, | |
| 2005 | -} | |
| 2006 | - | |
| 2007 | -/// An isolate's context and the entry `fetch` that lives in it. | |
| 2008 | -/// | |
| 2009 | -/// `fetch` is here rather than beside the isolate because a function is a | |
| 2010 | -/// value in the realm that created it. | |
| 2011 | -struct Realm { | |
| 2012 | - context: v8::Global<v8::Context>, | |
| 2013 | - fetch: v8::Global<v8::Function>, | |
| 2014 | -} | |
| 2015 | - | |
| 2016 | -impl WorkerIsolate { | |
| 2017 | - /// Take the isolate for one turn, and make the cells it hosts reachable | |
| 2018 | - /// while it is held. | |
| 2019 | - /// | |
| 2020 | - /// The two belong together. The lock is what makes this thread the only | |
| 2021 | - /// one that can touch the isolate, and a cell's SQLite handles are part | |
| 2022 | - /// of what it may touch — so a locker taken without installing them | |
| 2023 | - /// would let a turn reach no storage at all, or another isolate's. | |
| 2024 | - /// Pairing them here is why no call site has to remember. | |
| 2025 | - fn lock(&self) -> (v8::Locker<'_>, storage::Installed) { | |
| 2026 | - (self.isolate.lock(), self.cells.install()) | |
| 2027 | - } | |
| 2028 | - | |
| 2029 | - /// Lift condemnation from an isolate whose heap has drained. | |
| 2030 | - /// | |
| 2031 | - /// `near_heap_limit` latches a flag that nothing used to clear, so a cell | |
| 2032 | - /// that reached its limit once stayed condemned until the process | |
| 2033 | - /// restarted. The flag is re-read here, between turns rather than inside | |
| 2034 | - /// one, because a handler must not see the isolate recover halfway | |
| 2035 | - /// through. | |
| 2036 | - /// | |
| 2037 | - /// A heap still over the line buys one `low_memory_notification` and a | |
| 2038 | - /// second reading. V8 stops collecting once it is past the limit, so a | |
| 2039 | - /// drained isolate holds the dead heap until something allocates again — | |
| 2040 | - /// without the forced collection the reading that decides recovery is a | |
| 2041 | - /// reading of garbage. `HEAP_GC_NUDGE_INTERVAL` bounds the cost. | |
| 2042 | - /// | |
| 2043 | - /// Removing the callback with the original limit puts back the limit | |
| 2044 | - /// `near_heap_limit` raised; re-adding it re-arms the guard. | |
| 2045 | - fn recover_heap(&self, locker: &mut v8::Locker<'_>) { | |
| 2046 | - let Some(state) = locker.get_slot::<Arc<HeapLimitState>>().cloned() else { | |
| 2047 | - return; | |
| 2048 | - }; | |
| 2049 | - if !state.excessively_exceeded.load(Ordering::Relaxed) { | |
| 2050 | - return; | |
| 2051 | - } | |
| 2052 | - if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE { | |
| 2053 | - if !state.due_for_gc_nudge() { | |
| 2054 | - return; | |
| 2055 | - } | |
| 2056 | - locker.low_memory_notification(); | |
| 2057 | - if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE { | |
| 2058 | - return; | |
| 2059 | - } | |
| 2060 | - } | |
| 2061 | - state.excessively_exceeded.store(false, Ordering::Relaxed); | |
| 2062 | - let data = Arc::as_ptr(&state) as *mut HeapLimitState as *mut std::ffi::c_void; | |
| 2063 | - locker.remove_near_heap_limit_callback(near_heap_limit, state.limit); | |
| 2064 | - locker.add_near_heap_limit_callback(near_heap_limit, data); | |
| 2065 | - tracing::info!( | |
| 2066 | - event = "isolate_heap_recovered", | |
| 2067 | - limit_bytes = state.limit, | |
| 2068 | - "isolate heap fell back under its limit, so it serves again" | |
| 2069 | - ); | |
| 2070 | - } | |
| 2071 | - | |
| 2072 | - /// Localise the realm for one turn. | |
| 2073 | - /// | |
| 2074 | - /// **Taking the scope is the point.** Reaching a realm means touching | |
| 2075 | - /// `Global` handles, which on a shared isolate is only legal while its | |
| 2076 | - /// `Locker` is held — and there is no scope to pass until the isolate is | |
| 2077 | - /// locked. So the requirement is structural rather than a comment asking | |
| 2078 | - /// callers to remember it. It was a comment, and the one call site that | |
| 2079 | - /// forgot cloned two `Global`s a line too early; the panic happened | |
| 2080 | - /// inside a spawned request task, where tokio swallowed it and it | |
| 2081 | - /// surfaced only as a poisoned mutex on every later request. | |
| 2082 | - fn realm<'s>(&self, hs: &mut v8::PinScope<'s, '_, ()>) -> Entered<'s> { | |
| 2083 | - Entered { | |
| 2084 | - context: v8::Local::new(hs, &self.realm.context), | |
| 2085 | - fetch: v8::Local::new(hs, &self.realm.fetch), | |
| 2086 | - } | |
| 2087 | - } | |
| 2088 | -} | |
| 2089 | - | |
| 2090 | -/// One realm, entered. Valid only for the scope that produced it, which is | |
| 2091 | -/// what ties it to the isolate being locked. | |
| 2092 | -struct Entered<'s> { | |
| 2093 | - context: v8::Local<'s, v8::Context>, | |
| 2094 | - fetch: v8::Local<'s, v8::Function>, | |
| 2095 | -} | |
| 2096 | - | |
| 2097 | -impl std::ops::Deref for Worker { | |
| 2098 | - type Target = WorkerIsolate; | |
| 2099 | - | |
| 2100 | - fn deref(&self) -> &Self::Target { | |
| 2101 | - self.inner.as_ref().expect("Worker isolate unavailable") | |
| 2102 | - } | |
| 2103 | -} | |
| 2104 | - | |
| 2105 | -impl std::ops::DerefMut for Worker { | |
| 2106 | - fn deref_mut(&mut self) -> &mut Self::Target { | |
| 2107 | - self.inner.as_mut().expect("Worker isolate unavailable") | |
| 2108 | - } | |
| 2109 | -} | |
| 2110 | - | |
| 2111 | -const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024; | |
| 2112 | -const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024; | |
| 2113 | - | |
| 2114 | -/// Share of the heap limit past which an isolate takes on no more retained | |
| 2115 | -/// state. It sits below the near-limit callback on purpose: this refuses one | |
| 2116 | -/// hibernatable socket while the isolate still works, where the callback | |
| 2117 | -/// fires once it no longer does. | |
| 2118 | -const HEAP_ADMISSION_SHARE: f64 = 0.9; | |
| 2119 | - | |
| 2120 | -/// Share of the heap limit under which a condemned isolate is condemned no | |
| 2121 | -/// more. Under `HEAP_ADMISSION_SHARE` by enough that recovery does not | |
| 2122 | -/// immediately re-admit into a heap that is about to fail again. | |
| 2123 | -const HEAP_RECOVERY_SHARE: f64 = 0.75; | |
| 2124 | - | |
| 2125 | -/// The shortest gap between two collections forced by `recover_heap`. A full | |
| 2126 | -/// collection of a 128 MB heap costs tens of milliseconds and a loaded cell | |
| 2127 | -/// begins many turns each second, so an unbounded nudge would spend more of a | |
| 2128 | -/// condemned isolate on collecting than on serving. | |
| 2129 | -const HEAP_GC_NUDGE_INTERVAL: Duration = Duration::from_secs(1); | |
| 2130 | - | |
| 2131 | -struct HeapLimitState { | |
| 2132 | - excessively_exceeded: AtomicBool, | |
| 2133 | - /// The limit V8 gave this isolate, before any emergency extension. | |
| 2134 | - /// Recovery measures against this one because `near_heap_limit` raises | |
| 2135 | - /// the current one. | |
| 2136 | - limit: usize, | |
| 2137 | - last_gc_nudge: Mutex<Option<Instant>>, | |
| 2138 | - /// An explicit admission refusal cannot use the condemnation flag because | |
| 2139 | - /// recovery clears that flag at the next turn. | |
| 2140 | - #[cfg(celld_internal_tests)] | |
| 2141 | - forced_admission_refusal: AtomicBool, | |
| 2142 | -} | |
| 2143 | - | |
| 2144 | -impl HeapLimitState { | |
| 2145 | - /// Whether a condemned isolate can pay for another forced collection. | |
| 2146 | - /// | |
| 2147 | - /// Rate-limited rather than once for each condemnation: the load can | |
| 2148 | - /// still be live at the first reading and gone by the second, so a | |
| 2149 | - /// one-shot nudge would leave the cell condemned exactly as before. | |
| 2150 | - fn due_for_gc_nudge(&self) -> bool { | |
| 2151 | - let Ok(mut last) = self.last_gc_nudge.lock() else { | |
| 2152 | - return false; | |
| 2153 | - }; | |
| 2154 | - let now = Instant::now(); | |
| 2155 | - if last.is_some_and(|at| now.duration_since(at) < HEAP_GC_NUDGE_INTERVAL) { | |
| 2156 | - return false; | |
| 2157 | - } | |
| 2158 | - *last = Some(now); | |
| 2159 | - true | |
| 2160 | - } | |
| 2161 | -} | |
| 2162 | - | |
| 2163 | -#[cfg(celld_internal_tests)] | |
| 2164 | -fn admission_refusal_forced(state: &HeapLimitState) -> bool { | |
| 2165 | - state.forced_admission_refusal.load(Ordering::Relaxed) | |
| 2166 | -} | |
| 2167 | - | |
| 2168 | -#[cfg(not(celld_internal_tests))] | |
| 2169 | -fn admission_refusal_forced(_state: &HeapLimitState) -> bool { | |
| 2170 | - false | |
| 2171 | -} | |
| 2172 | - | |
| 2173 | -type SerializedPut = (String, Vec<u8>); | |
| 2174 | -type PendingPuts = HashMap<String, Vec<SerializedPut>>; | |
| 2175 | - | |
| 2176 | -/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a | |
| 2177 | -/// Worker Loader can hand a loaded worker `Deny` (globalOutbound: null) so its | |
| 2178 | -/// global `fetch()` throws and it must reach the world through `env` | |
| 2179 | -/// capabilities. | |
| 2180 | -#[derive(Clone, Copy, Default, PartialEq)] | |
| 2181 | -enum EgressPolicy { | |
| 2182 | - #[default] | |
| 2183 | - Allow, | |
| 2184 | - Deny, | |
| 2185 | -} | |
| 2186 | - | |
| 2187 | -#[derive(Default)] | |
| 2188 | -struct ActorRuntimeState { | |
| 2189 | - promises: std::sync::Mutex<PromiseMap>, | |
| 2190 | - termination: std::sync::Mutex<Option<ExecutionTermination>>, | |
| 2191 | - pending_puts: std::sync::Mutex<PendingPuts>, | |
| 2192 | - io_contexts: std::sync::Mutex<HashMap<u64, Weak<IoContext>>>, | |
| 2193 | - next_io_context_id: AtomicU64, | |
| 2194 | - egress: EgressPolicy, | |
| 2195 | - event_hooks: OnceLock<EventHooks>, | |
| 2196 | -} | |
| 2197 | - | |
| 2198 | -/// The harness functions the host calls on the boundary of every cell event. | |
| 2199 | -/// | |
| 2200 | -/// `harness.js` installs `__beginEvent`, `__endEvent` and | |
| 2201 | -/// `__abortIncomingRequest` on the global once per isolate and never replaces | |
| 2202 | -/// them. Reading each one back by name per event cost a fresh `v8::String` | |
| 2203 | -/// plus a lookup on the global object for a result that cannot change; | |
| 2204 | -/// holding the functions removes the string and the lookup together. | |
| 2205 | -/// | |
| 2206 | -/// The three are resolved together on purpose. A partial resolution would | |
| 2207 | -/// leave one hook still reached by name, so `install_harness` builds all three | |
| 2208 | -/// or the isolate fails to load, and no caller has to remember which of them | |
| 2209 | -/// is cached. | |
| 2210 | -/// | |
| 2211 | -/// A `v8::Global` is only valid in the isolate that created it, which is why | |
| 2212 | -/// this hangs off `ActorRuntimeState` — an isolate slot — and not off a | |
| 2213 | -/// process-wide `static`. `ModuleRegistry` documents the same constraint. | |
| 2214 | -struct EventHooks { | |
| 2215 | - begin_event: v8::Global<v8::Function>, | |
| 2216 | - end_event: v8::Global<v8::Function>, | |
| 2217 | - abort_incoming_request: v8::Global<v8::Function>, | |
| 2218 | -} | |
| 2219 | - | |
| 2220 | -/// One cached hook, opened into `scope`. | |
| 2221 | -/// | |
| 2222 | -/// `pick` names the hook rather than a getter per hook, so the three call | |
| 2223 | -/// sites stay one line each. | |
| 2224 | -fn event_hook<'s>( | |
| 2225 | - scope: &mut v8::PinScope<'s, '_>, | |
| 2226 | - pick: fn(&EventHooks) -> &v8::Global<v8::Function>, | |
| 2227 | -) -> Result<v8::Local<'s, v8::Function>> { | |
| 2228 | - let state = actor_runtime_state(scope); | |
| 2229 | - let hooks = state | |
| 2230 | - .event_hooks | |
| 2231 | - .get() | |
| 2232 | - .ok_or_else(|| anyhow!("event hooks are not installed"))?; | |
| 2233 | - Ok(v8::Local::new(scope, pick(hooks))) | |
| 2234 | -} | |
| 2235 | - | |
| 2236 | -impl ActorRuntimeState { | |
| 2237 | - fn allocate_io_context_id(&self) -> u64 { | |
| 2238 | - self.next_io_context_id | |
| 2239 | - .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| { | |
| 2240 | - current.checked_add(1) | |
| 2241 | - }) | |
| 2242 | - .unwrap_or_else(|_| panic!("the isolate exhausted its IoContext ids")) | |
| 2243 | - + 1 | |
| 2244 | - } | |
| 2245 | - | |
| 2246 | - fn io_context(&self, id: u64) -> Option<Arc<IoContext>> { | |
| 2247 | - let mut contexts = self.io_contexts.lock().unwrap(); | |
| 2248 | - let context = contexts.get(&id)?.upgrade(); | |
| 2249 | - if context.is_none() { | |
| 2250 | - contexts.remove(&id); | |
| 2251 | - } | |
| 2252 | - context | |
| 2253 | - } | |
| 2254 | -} | |
| 2255 | - | |
| 2256 | -struct ExecutionTermination { | |
| 2257 | - error: String, | |
| 2258 | - actor_scope: Option<String>, | |
| 2259 | -} | |
| 2260 | - | |
| 2261 | -fn finish_terminated_actor_event(scope: &mut v8::PinScope, actor_scope: &str) { | |
| 2262 | - // The one exit from a block that runs no JS, so the `finally` in | |
| 2263 | - // harness.js never releases. Leave it and the cell refuses everything | |
| 2264 | - // from here on. | |
| 2265 | - cell_gate_abandon(actor_scope); | |
| 2266 | - let global = scope.get_current_context().global(scope); | |
| 2267 | - let key = v8::String::new(scope, "__endTerminatedActorEvent").unwrap(); | |
| 2268 | - let Some(value) = global.get(scope, key.into()) else { | |
| 2269 | - return; | |
| 2270 | - }; | |
| 2271 | - let Ok(function) = v8::Local::<v8::Function>::try_from(value) else { | |
| 2272 | - return; | |
| 2273 | - }; | |
| 2274 | - let actor_scope = v8::String::new(scope, actor_scope).unwrap(); | |
| 2275 | - let recv = v8::undefined(scope).into(); | |
| 2276 | - let _ = function.call(scope, recv, &[actor_scope.into()]); | |
| 2277 | -} | |
| 2278 | - | |
| 2279 | -/// Compile and run a JS expression that evaluates to a function. | |
| 2280 | -fn compile_fn<'s>( | |
| 2281 | - scope: &mut v8::PinScope<'s, '_>, | |
| 2282 | - src: &str, | |
| 2283 | -) -> Result<v8::Local<'s, v8::Function>> { | |
| 2284 | - let code = v8::String::new(scope, src).unwrap(); | |
| 2285 | - let script = | |
| 2286 | - v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compile shim: {src}"))?; | |
| 2287 | - let value = script | |
| 2288 | - .run(scope) | |
| 2289 | - .ok_or_else(|| anyhow!("run shim: {src}"))?; | |
| 2290 | - value | |
| 2291 | - .try_into() | |
| 2292 | - .map_err(|_| anyhow!("shim is not a function: {src}")) | |
| 2293 | -} | |
| 2294 | - | |
| 2295 | -/// Whether `register_entrypoints` put `name` in the `__cell.<registry>` | |
| 2296 | -/// object (e.g. `entrypoints`, `doExports`). | |
| 2297 | -fn cell_registry_has(scope: &mut v8::PinScope, registry: &str, name: &str) -> Result<bool> { | |
| 2298 | - let context = scope.get_current_context(); | |
| 2299 | - let global = context.global(scope); | |
| 2300 | - let cell_key = static_key(scope, &v8_strings::CELL); | |
| 2301 | - let registry_key = v8::String::new(scope, registry).unwrap(); | |
| 2302 | - let registry_obj = global | |
| 2303 | - .get(scope, cell_key.into()) | |
| 2304 | - .and_then(|value| value.to_object(scope)) | |
| 2305 | - .and_then(|cell| cell.get(scope, registry_key.into())) | |
| 2306 | - .and_then(|value| value.to_object(scope)) | |
| 2307 | - .ok_or_else(|| anyhow!("missing __cell.{registry} registry"))?; | |
| 2308 | - let name_key = v8::String::new(scope, name).unwrap(); | |
| 2309 | - Ok(registry_obj | |
| 2310 | - .has_own_property(scope, name_key.into()) | |
| 2311 | - .unwrap_or(false)) | |
| 2312 | -} | |
| 2313 | - | |
| 2314 | -fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> { | |
| 2315 | - let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned(); | |
| 2316 | - let termination = state.and_then(|state| state.termination.lock().ok()?.take()); | |
| 2317 | - let is_terminating = scope.is_execution_terminating(); | |
| 2318 | - if termination.is_some() || is_terminating { | |
| 2319 | - scope.cancel_terminate_execution(); | |
| 2320 | - } | |
| 2321 | - if let Some(termination) = termination { | |
| 2322 | - if let Some(actor_scope) = termination.actor_scope { | |
| 2323 | - finish_terminated_actor_event(scope, &actor_scope); | |
| 2324 | - } | |
| 2325 | - return Some(anyhow!(termination.error)); | |
| 2326 | - } | |
| 2327 | - is_terminating.then(|| anyhow!("JavaScript execution was terminated")) | |
| 2328 | -} | |
| 2329 | - | |
| 2330 | -extern "C" fn near_heap_limit( | |
| 2331 | - data: *mut std::ffi::c_void, | |
| 2332 | - current_heap_limit: usize, | |
| 2333 | - _initial_heap_limit: usize, | |
| 2334 | -) -> usize { | |
| 2335 | - // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop | |
| 2336 | - // removes this callback before the isolate (and its slots) are destroyed. | |
| 2337 | - let state = unsafe { &*(data as *const HeapLimitState) }; | |
| 2338 | - state.excessively_exceeded.store(true, Ordering::Relaxed); | |
| 2339 | - // V8 fatally aborts the process if a near-limit callback does not extend | |
| 2340 | - // the limit. This reserve lets JS observe condemnation and unwind. | |
| 2341 | - // | |
| 2342 | - // The extension must also cover one allocation as large as the limit | |
| 2343 | - // itself: flattening a 128 MiB cons string asks V8 for a single 128 MiB | |
| 2344 | - // block, and V8 re-invokes this callback across last-resort GC rounds | |
| 2345 | - // only unreliably (under parallel load it often stops after one round | |
| 2346 | - // and aborts the process). Doubling the original limit makes the first | |
| 2347 | - // invocation sufficient on its own; `recover_heap` and `Drop` still | |
| 2348 | - // restore the original limit, so nothing else changes. | |
| 2349 | - current_heap_limit | |
| 2350 | - .saturating_add(V8_HEAP_EMERGENCY_BYTES) | |
| 2351 | - .max(state.limit.saturating_mul(2)) | |
| 2352 | -} | |
| 2353 | - | |
| 2354 | -/// Live heap use, as a share of `limit`. | |
| 2355 | -fn heap_share(isolate: &mut v8::Isolate, limit: usize) -> f64 { | |
| 2356 | - if limit == 0 { | |
| 2357 | - return 0.0; | |
| 2358 | - } | |
| 2359 | - isolate.get_heap_statistics().used_heap_size() as f64 / limit as f64 | |
| 2360 | -} | |
| 2361 | - | |
| 2362 | -fn v8_heap_limit_bytes() -> usize { | |
| 2363 | - crate::env_vars::positive::<usize>("CELLD_V8_HEAP_LIMIT_MB") | |
| 2364 | - .expect("validated CELLD_V8_HEAP_LIMIT_MB") | |
| 2365 | - .map(|megabytes| { | |
| 2366 | - megabytes | |
| 2367 | - .checked_mul(1024 * 1024) | |
| 2368 | - .expect("validated CELLD_V8_HEAP_LIMIT_MB range") | |
| 2369 | - }) | |
| 2370 | - .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES) | |
| 2371 | -} | |
| 2372 | - | |
| 2373 | -impl Drop for WorkerIsolate { | |
| 2374 | - fn drop(&mut self) { | |
| 2375 | - // Detach children while their IDs are still attributable to this | |
| 2376 | - // parent, but do not drop their V8 isolates while this one is entered. | |
| 2377 | - // In-flight child calls hold their own receiver clones and finish | |
| 2378 | - // normally; this removes only the registry's ownership reference. | |
| 2379 | - let loaded_children = take_loader_owner(self.loader_owner); | |
| 2380 | - let limit = self.original_heap_limit; | |
| 2381 | - { | |
| 2382 | - let (mut locker, _cells) = self.lock(); | |
| 2383 | - locker.remove_near_heap_limit_callback(near_heap_limit, limit); | |
| 2384 | - } | |
| 2385 | - drop(loaded_children); | |
| 2386 | - } | |
| 2387 | -} | |
| 2388 | - | |
| 2389 | -/// One in-flight request inside a shared isolate. | |
| 2390 | -/// | |
| 2391 | -/// Owned by the request's own tokio task, which is why every field is | |
| 2392 | -/// `Send`: the task suspends between turns and can resume on any worker, | |
| 2393 | -/// then re-enters the isolate it is affiliated with. | |
| 2394 | -/// Where a finished handler's result goes, and in what shape. | |
| 2395 | -/// | |
| 2396 | -/// A fetch answers an `HttpResponse` and an entrypoint RPC answers bytes. | |
| 2397 | -/// Everything between — the turn loop, the op region, cancellation, the | |
| 2398 | -/// budget — is identical, so the difference lives here rather than in two | |
| 2399 | -/// copies of `drive`. | |
| 2400 | -pub enum Answer { | |
| 2401 | - Fetch(tokio::sync::oneshot::Sender<Result<HttpResponse>>), | |
| 2402 | - Rpc(tokio::sync::oneshot::Sender<Result<Vec<u8>>>), | |
| 2403 | - Queue(tokio::sync::oneshot::Sender<Result<QueueDispatchResult>>), | |
| 2404 | - /// A DO method call, which answers a value rather than a response. | |
| 2405 | - CellRpc(tokio::sync::oneshot::Sender<Result<RpcOutcome>>), | |
| 2406 | - /// A `webSocketMessage`, which answers the frames the output gate held | |
| 2407 | - /// and the write they are gated on. | |
| 2408 | - WsMessage(tokio::sync::oneshot::Sender<Result<WsDispatch>>), | |
| 2409 | - /// An event whose result is that it finished: `webSocketOpen`, | |
| 2410 | - /// `webSocketClose`. | |
| 2411 | - Ack(tokio::sync::oneshot::Sender<Result<()>>), | |
| 2412 | - /// An alarm, which answers whatever alarm the handler left armed. | |
| 2413 | - Alarm(tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>), | |
| 2414 | -} | |
| 2415 | - | |
| 2416 | -impl Answer { | |
| 2417 | - /// Send an error, whichever shape the caller is waiting for. | |
| 2418 | - fn fail(self, error: anyhow::Error) { | |
| 2419 | - let _ = self.fail_with_arm_gates(error, Vec::new()); | |
| 2420 | - } | |
| 2421 | - | |
| 2422 | - fn fail_with_arm_gates( | |
| 2423 | - self, | |
| 2424 | - error: anyhow::Error, | |
| 2425 | - gates: Vec<ArmGateRx>, | |
| 2426 | - ) -> Option<GatedReplyRx> { | |
| 2427 | - match self { | |
| 2428 | - Answer::Fetch(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 2429 | - Answer::Rpc(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 2430 | - Answer::Queue(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 2431 | - Answer::CellRpc(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 2432 | - Answer::WsMessage(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 2433 | - Answer::Ack(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 2434 | - Answer::Alarm(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 2435 | - } | |
| 2436 | - } | |
| 2437 | -} | |
| 2438 | - | |
| 2439 | -async fn await_arm_gates(gates: Vec<ArmGateRx>) -> Result<(), String> { | |
| 2440 | - let mut first_failure = None; | |
| 2441 | - for gate in gates { | |
| 2442 | - let failure = match gate.await { | |
| 2443 | - Ok(Ok(())) => None, | |
| 2444 | - Ok(Err(error)) => Some(error), | |
| 2445 | - Err(_) => Some("wake-entry gate task dropped".into()), | |
| 2446 | - }; | |
| 2447 | - if first_failure.is_none() { | |
| 2448 | - first_failure = failure; | |
| 2449 | - } | |
| 2450 | - } | |
| 2451 | - match first_failure { | |
| 2452 | - Some(failure) => Err(failure), | |
| 2453 | - None => Ok(()), | |
| 2454 | - } | |
| 2455 | -} | |
| 2456 | - | |
| 2457 | -fn send_answer_after_arm_gates<T: Send + 'static>( | |
| 2458 | - mut reply: tokio::sync::oneshot::Sender<Result<T>>, | |
| 2459 | - value: Result<T>, | |
| 2460 | - gates: Vec<ArmGateRx>, | |
| 2461 | -) -> Option<GatedReplyRx> { | |
| 2462 | - if gates.is_empty() { | |
| 2463 | - drop(reply.send(value)); | |
| 2464 | - return None; | |
| 2465 | - } | |
| 2466 | - let (completed, completion) = tokio::sync::oneshot::channel(); | |
| 2467 | - let (cancel, mut cancelled) = tokio::sync::oneshot::channel(); | |
| 2468 | - #[cfg(celld_internal_tests)] | |
| 2469 | - let drop_task = asyncrt::services() | |
| 2470 | - .wake_entry() | |
| 2471 | - .drop_next_gated_reply_task | |
| 2472 | - .swap(false, Ordering::AcqRel); | |
| 2473 | - asyncrt::spawn(async move { | |
| 2474 | - #[cfg(celld_internal_tests)] | |
| 2475 | - if drop_task { | |
| 2476 | - return; | |
| 2477 | - } | |
| 2478 | - enum GateWait { | |
| 2479 | - Completed(Result<(), String>), | |
| 2480 | - CallerClosed, | |
| 2481 | - Cancelled, | |
| 2482 | - DriverDropped, | |
| 2483 | - } | |
| 2484 | - let gate_wait = { | |
| 2485 | - let mut waiting = Box::pin(await_arm_gates(gates)); | |
| 2486 | - let result = asyncrt::select_biased! { | |
| 2487 | - "a completed gate aggregate wins a tie with caller cancellation"; | |
| 2488 | - result = &mut waiting => GateWait::Completed(result), | |
| 2489 | - cancellation = async { | |
| 2490 | - asyncrt::select_biased! { | |
| 2491 | - "a closed caller wins a tie with an explicit cancellation signal"; | |
| 2492 | - _ = reply.closed() => GateWait::CallerClosed, | |
| 2493 | - cancelled = &mut cancelled => match cancelled { | |
| 2494 | - Ok(()) => GateWait::Cancelled, | |
| 2495 | - Err(_) => GateWait::DriverDropped, | |
| 2496 | - }, | |
| 2497 | - } | |
| 2498 | - } => cancellation, | |
| 2499 | - }; | |
| 2500 | - // On either cancellation path this drops every unobserved gate | |
| 2501 | - // receiver before the completion becomes visible to the driver. | |
| 2502 | - drop(waiting); | |
| 2503 | - result | |
| 2504 | - }; | |
| 2505 | - let value = match gate_wait { | |
| 2506 | - GateWait::Completed(gate_result) => match (value, gate_result) { | |
| 2507 | - (value, Ok(())) => value, | |
| 2508 | - (Ok(_), Err(error)) => Err(anyhow!("wake-entry gate: {error}")), | |
| 2509 | - (Err(primary), Err(error)) => { | |
| 2510 | - tracing::error!( | |
| 2511 | - event = "wake_entry_gate_failed_after_handler_error", | |
| 2512 | - handler_error = %primary, | |
| 2513 | - gate_error = %error, | |
| 2514 | - ); | |
| 2515 | - Err(primary.context(format!("wake-entry gate also failed: {error}"))) | |
| 2516 | - } | |
| 2517 | - }, | |
| 2518 | - GateWait::CallerClosed => { | |
| 2519 | - let failure = value | |
| 2520 | - .as_ref() | |
| 2521 | - .err() | |
| 2522 | - .map(|error| crate::telemetry::cap_error(format!("{error:#}"))); | |
| 2523 | - drop(value); | |
| 2524 | - let _ = completed.send(GatedReplyCompletion::CallerClosed { failure }); | |
| 2525 | - return; | |
| 2526 | - } | |
| 2527 | - // The driver observed a request cancellation after the handler | |
| 2528 | - // fixed its reply. Do not enter JavaScript again: the handler is | |
| 2529 | - // already over. A successful answer becomes a disconnect error, | |
| 2530 | - // while an existing handler error remains the primary failure. | |
| 2531 | - GateWait::Cancelled => match value { | |
| 2532 | - Ok(_) => Err(anyhow!("The client has disconnected")), | |
| 2533 | - Err(primary) => Err(primary), | |
| 2534 | - }, | |
| 2535 | - // Dropping the driver drops both halves of its completion handle. | |
| 2536 | - // Release every detached resource, but do not let an abandoned | |
| 2537 | - // driver manufacture a reply that nothing owns any longer. | |
| 2538 | - GateWait::DriverDropped => { | |
| 2539 | - drop(value); | |
| 2540 | - return; | |
| 2541 | - } | |
| 2542 | - }; | |
| 2543 | - let failure = value | |
| 2544 | - .as_ref() | |
| 2545 | - .err() | |
| 2546 | - .map(|error| crate::telemetry::cap_error(format!("{error:#}"))); | |
| 2547 | - let completion = match reply.send(value) { | |
| 2548 | - Ok(()) => GatedReplyCompletion::Sent { failure }, | |
| 2549 | - Err(value) => { | |
| 2550 | - drop(value); | |
| 2551 | - GatedReplyCompletion::CallerClosed { failure } | |
| 2552 | - } | |
| 2553 | - }; | |
| 2554 | - let _ = completed.send(completion); | |
| 2555 | - }) | |
| 2556 | - .detach(); | |
| 2557 | - Some(GatedReplyRx { | |
| 2558 | - completion, | |
| 2559 | - cancel: Some(cancel), | |
| 2560 | - }) | |
| 2561 | -} | |
| 2562 | - | |
| 2563 | -pub(crate) enum GatedReplyCompletion { | |
| 2564 | - /// The final reply value is now visible to the receiver. | |
| 2565 | - Sent { failure: Option<String> }, | |
| 2566 | - /// The receiver disappeared, so no reply remains to deliver. | |
| 2567 | - CallerClosed { failure: Option<String> }, | |
| 2568 | -} | |
| 2569 | - | |
| 2570 | -pub(crate) struct GatedReplyRx { | |
| 2571 | - completion: tokio::sync::oneshot::Receiver<GatedReplyCompletion>, | |
| 2572 | - cancel: Option<tokio::sync::oneshot::Sender<()>>, | |
| 2573 | -} | |
| 2574 | - | |
| 2575 | -impl GatedReplyRx { | |
| 2576 | - /// Stop waiting on event gates after a request cancellation. The detached | |
| 2577 | - /// task owns the reply value and gate receivers, so it performs their | |
| 2578 | - /// ordered cleanup and reports completion back to the driver. | |
| 2579 | - pub(crate) fn cancel(&mut self) { | |
| 2580 | - if let Some(cancel) = self.cancel.take() { | |
| 2581 | - let _ = cancel.send(()); | |
| 2582 | - } | |
| 2583 | - } | |
| 2584 | -} | |
| 2585 | - | |
| 2586 | -impl std::future::Future for GatedReplyRx { | |
| 2587 | - type Output = Result<GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>; | |
| 2588 | - | |
| 2589 | - fn poll( | |
| 2590 | - self: Pin<&mut Self>, | |
| 2591 | - context: &mut std::task::Context<'_>, | |
| 2592 | - ) -> std::task::Poll<Self::Output> { | |
| 2593 | - Pin::new(&mut self.get_mut().completion).poll(context) | |
| 2594 | - } | |
| 2595 | -} | |
| 2596 | - | |
| 2597 | -#[cfg(celld_internal_tests)] | |
| 2598 | -#[doc(hidden)] | |
| 2599 | -pub async fn await_arm_gates_for_test( | |
| 2600 | - gates: Vec<tokio::sync::oneshot::Receiver<Result<(), String>>>, | |
| 2601 | -) -> Result<(), String> { | |
| 2602 | - await_arm_gates(gates).await | |
| 2603 | -} | |
| 2604 | - | |
| 2605 | -#[cfg(celld_internal_tests)] | |
| 2606 | -#[doc(hidden)] | |
| 2607 | -pub enum GatedReplyCompletionForTest { | |
| 2608 | - Sent { failure: Option<String> }, | |
| 2609 | - CallerClosed { failure: Option<String> }, | |
| 2610 | -} | |
| 2611 | - | |
| 2612 | -#[cfg(celld_internal_tests)] | |
| 2613 | -#[doc(hidden)] | |
| 2614 | -pub struct GatedReplyForTest(GatedReplyRx); | |
| 2615 | - | |
| 2616 | -#[cfg(celld_internal_tests)] | |
| 2617 | -impl std::future::Future for GatedReplyForTest { | |
| 2618 | - type Output = Result<GatedReplyCompletionForTest, tokio::sync::oneshot::error::RecvError>; | |
| 2619 | - | |
| 2620 | - fn poll( | |
| 2621 | - self: Pin<&mut Self>, | |
| 2622 | - context: &mut std::task::Context<'_>, | |
| 2623 | - ) -> std::task::Poll<Self::Output> { | |
| 2624 | - Pin::new(&mut self.get_mut().0).poll(context).map(|result| { | |
| 2625 | - result.map(|completion| match completion { | |
| 2626 | - GatedReplyCompletion::Sent { failure } => { | |
| 2627 | - GatedReplyCompletionForTest::Sent { failure } | |
| 2628 | - } | |
| 2629 | - GatedReplyCompletion::CallerClosed { failure } => { | |
| 2630 | - GatedReplyCompletionForTest::CallerClosed { failure } | |
| 2631 | - } | |
| 2632 | - }) | |
| 2633 | - }) | |
| 2634 | - } | |
| 2635 | -} | |
| 2636 | - | |
| 2637 | -#[cfg(celld_internal_tests)] | |
| 2638 | -#[doc(hidden)] | |
| 2639 | -pub fn send_answer_after_arm_gates_for_test<T: Send + 'static>( | |
| 2640 | - reply: tokio::sync::oneshot::Sender<Result<T>>, | |
| 2641 | - value: Result<T>, | |
| 2642 | - gates: Vec<tokio::sync::oneshot::Receiver<Result<(), String>>>, | |
| 2643 | -) -> Option<GatedReplyForTest> { | |
| 2644 | - send_answer_after_arm_gates(reply, value, gates).map(GatedReplyForTest) | |
| 2645 | -} | |
| 2646 | - | |
| 2647 | -#[cfg(celld_internal_tests)] | |
| 2648 | -#[doc(hidden)] | |
| 2649 | -pub fn drop_next_gated_reply_task_for_test() { | |
| 2650 | - asyncrt::services() | |
| 2651 | - .wake_entry() | |
| 2652 | - .drop_next_gated_reply_task | |
| 2653 | - .store(true, Ordering::Release); | |
| 2654 | -} | |
| 2655 | - | |
| 2656 | -pub struct InFlight { | |
| 2657 | - /// The handler's promise. A `Global` because it outlives the turn that | |
| 2658 | - /// created it: Locals never cross a turn, exactly as workerd's | |
| 2659 | - /// `Worker::Lock` never does. | |
| 2660 | - promise: v8::Global<v8::Promise>, | |
| 2661 | - context: Arc<IoContext>, | |
| 2662 | - /// The cell this event belongs to, and `None` for stateless work. | |
| 2663 | - /// | |
| 2664 | - /// It is what the storage-shaped parts of settling — the durability | |
| 2665 | - /// position, a fatal SQL error — are read against. | |
| 2666 | - scope: Option<String>, | |
| 2667 | - /// The cell's committed-write position before the handler ran. | |
| 2668 | - /// | |
| 2669 | - /// The answer carries a write position only if the handler advanced it, | |
| 2670 | - /// so the output gate sees a write this event made and ignores celld's | |
| 2671 | - /// own activation writes (the actor name, alarm bookkeeping). | |
| 2672 | - writes_before: Option<u64>, | |
| 2673 | - request_id: Option<RequestId>, | |
| 2674 | - active_request_id: Option<RequestId>, | |
| 2675 | - reply: Option<Answer>, | |
| 2676 | - gated_reply: Option<GatedReplyRx>, | |
| 2677 | - /// `waitUntil` work still running after the response was sent. The | |
| 2678 | - /// request stays in flight until it settles, as the single-request loop | |
| 2679 | - /// keeps driving it. | |
| 2680 | - background: Option<v8::Global<v8::Promise>>, | |
| 2681 | - /// Ops this request is waiting on, so a completion can be attributed to | |
| 2682 | - /// the request whose context must be current while its continuation runs. | |
| 2683 | - ops: std::collections::HashSet<u64>, | |
| 2684 | - /// The alarm bookkeeping this entry still owes, if it is one. | |
| 2685 | - alarm: Option<AlarmClaim>, | |
| 2686 | - started: Instant, | |
| 2687 | - /// The sampled trace this entry records into, `None` when telemetry | |
| 2688 | - /// is off or the trace was not sampled. Installed into the isolate's | |
| 2689 | - /// CPED slot for every turn, so promise continuations carry it. | |
| 2690 | - trace: Option<crate::telemetry::TraceIds>, | |
| 2691 | - /// Why the event failed, captured for the span's `error` so a query sees | |
| 2692 | - /// the reason, not only that it failed. This also records an output-gate | |
| 2693 | - /// failure after a successful handler. | |
| 2694 | - failure: Option<String>, | |
| 2695 | - /// The isolate this entry's ops belong to, so `abandon` can drop their | |
| 2696 | - /// resolvers without a scope to reach the isolate through. | |
| 2697 | - runtime_state: Arc<ActorRuntimeState>, | |
| 2698 | -} | |
| 2699 | - | |
| 2700 | -impl InFlight { | |
| 2701 | - /// Read the handler's settled value in the shape this entry answers, end | |
| 2702 | - /// the event, and reply. | |
| 2703 | - /// | |
| 2704 | - /// Every shape ends the event exactly once, whether it produced a value | |
| 2705 | - /// or an error — ending it is what yields the `waitUntil` work the entry | |
| 2706 | - /// keeps driving afterwards, and a shape that skipped it on the error | |
| 2707 | - /// path would leave the context open. | |
| 2708 | - fn answer_settled<'s>( | |
| 2709 | - &mut self, | |
| 2710 | - tc: &mut v8::PinScope<'s, '_>, | |
| 2711 | - value: v8::Local<'s, v8::Value>, | |
| 2712 | - ) { | |
| 2713 | - let Some(reply) = self.reply.take() else { | |
| 2714 | - return; | |
| 2715 | - }; | |
| 2716 | - // A cell whose SQL failed fatally cannot answer whatever the handler | |
| 2717 | - // returned: the storage the handler read may not be what the cell | |
| 2718 | - // has. | |
| 2719 | - if let Some(error) = self.scope.as_deref().and_then(storage::sql_critical_error) { | |
| 2720 | - let _ = end_event_context(tc); | |
| 2721 | - if self.trace.is_some() { | |
| 2722 | - self.failure = Some(crate::telemetry::cap_error(error.to_string())); | |
| 2723 | - } | |
| 2724 | - self.gated_reply = | |
| 2725 | - reply.fail_with_arm_gates(anyhow!(error), self.context.take_arm_gates()); | |
| 2726 | - return; | |
| 2727 | - } | |
| 2728 | - let (background, gated_reply) = match reply { | |
| 2729 | - Answer::Fetch(reply) => { | |
| 2730 | - let read = read_response(tc, value).map(|mut response| { | |
| 2731 | - response.write_position = self.write_delta(); | |
| 2732 | - response | |
| 2733 | - }); | |
| 2734 | - send_and_end(tc, &self.context, reply, read) | |
| 2735 | - } | |
| 2736 | - Answer::Rpc(reply) => { | |
| 2737 | - let read = | |
| 2738 | - view_bytes(value).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes")); | |
| 2739 | - send_and_end(tc, &self.context, reply, read) | |
| 2740 | - } | |
| 2741 | - Answer::Queue(reply) => { | |
| 2742 | - let read = read_queue_result(tc, value); | |
| 2743 | - if let Ok(result) = &read { | |
| 2744 | - if result.outcome == QueueOutcome::Exception && self.trace.is_some() { | |
| 2745 | - self.failure = Some(crate::telemetry::cap_error( | |
| 2746 | - result | |
| 2747 | - .error | |
| 2748 | - .clone() | |
| 2749 | - .unwrap_or_else(|| "queue handler rejected".to_string()), | |
| 2750 | - )); | |
| 2751 | - } | |
| 2752 | - } | |
| 2753 | - send_and_end(tc, &self.context, reply, read) | |
| 2754 | - } | |
| 2755 | - Answer::CellRpc(reply) => { | |
| 2756 | - let outcome = RpcOutcome { | |
| 2757 | - data: rpc_data_ret(tc, value), | |
| 2758 | - write_position: self.write_delta(), | |
| 2759 | - }; | |
| 2760 | - send_and_end(tc, &self.context, reply, Ok(outcome)) | |
| 2761 | - } | |
| 2762 | - Answer::WsMessage(reply) => { | |
| 2763 | - let dispatch = WsDispatch { | |
| 2764 | - frames: ws_capture_take(), | |
| 2765 | - write_position: self.write_delta(), | |
| 2766 | - }; | |
| 2767 | - send_and_end(tc, &self.context, reply, Ok(dispatch)) | |
| 2768 | - } | |
| 2769 | - Answer::Ack(reply) => send_and_end(tc, &self.context, reply, Ok(())), | |
| 2770 | - Answer::Alarm(reply) => { | |
| 2771 | - // The handler ran and returned, so close the claim as a | |
| 2772 | - // success. This is the only path that does: every other | |
| 2773 | - // `settle_alarm` call site records a failure, and without | |
| 2774 | - // this one a *successful* alarm was recorded as one to | |
| 2775 | - // retry — which re-armed it forever, kept the cell busy, | |
| 2776 | - // and meant an eviction waiting for the cell to go quiet | |
| 2777 | - // never got its turn. | |
| 2778 | - self.settle_alarm(true, false); | |
| 2779 | - // Read what stands *after* that cleanup, and take the delta | |
| 2780 | - // last so it covers the cleanup's own commit — which is the | |
| 2781 | - // write the core must prove durable before it settles the | |
| 2782 | - // alarm. | |
| 2783 | - let alarm = self | |
| 2784 | - .scope | |
| 2785 | - .as_deref() | |
| 2786 | - .map(storage::get_alarm) | |
| 2787 | - .unwrap_or(None); | |
| 2788 | - send_and_end(tc, &self.context, reply, Ok((alarm, self.write_delta()))) | |
| 2789 | - } | |
| 2790 | - }; | |
| 2791 | - self.background = background; | |
| 2792 | - self.gated_reply = gated_reply; | |
| 2793 | - } | |
| 2794 | - | |
| 2795 | - /// The write position to gate this answer on: `None` unless the handler | |
| 2796 | - /// advanced the cell's committed writes past where they were. | |
| 2797 | - fn write_delta(&self) -> Option<u64> { | |
| 2798 | - write_delta( | |
| 2799 | - self.writes_before, | |
| 2800 | - self.scope.as_deref().and_then(storage::write_position), | |
| 2801 | - ) | |
| 2802 | - } | |
| 2803 | - | |
| 2804 | - /// Fail whichever shape is waiting, without knowing which. | |
| 2805 | - /// | |
| 2806 | - /// This must not touch cell storage: a budget overrun and a stuck | |
| 2807 | - /// handler are found on the driving task, between turns, where the | |
| 2808 | - /// storage thread-local is null — settling the alarm claim here | |
| 2809 | - /// panicked the node (denoland/celld#170). The claim stays put, and | |
| 2810 | - /// the drive loop's `owes_alarm` turn records it as not counting | |
| 2811 | - /// against the retry limit, because a failure here is not the | |
| 2812 | - /// handler's. A handler that threw is recorded by `settle`, which | |
| 2813 | - /// knows that it did, before it reaches this. | |
| 2814 | - fn fail(&mut self, error: anyhow::Error) { | |
| 2815 | - if let Some(reply) = self.reply.take() { | |
| 2816 | - if self.trace.is_some() { | |
| 2817 | - self.failure = Some(crate::telemetry::cap_error(error.to_string())); | |
| 2818 | - } | |
| 2819 | - self.gated_reply = reply.fail_with_arm_gates(error, self.context.take_arm_gates()); | |
| 2820 | - } | |
| 2821 | - } | |
| 2822 | - | |
| 2823 | - /// Record how a claimed alarm ended. Runs once; later calls do nothing. | |
| 2824 | - fn settle_alarm(&mut self, ok: bool, counts_against_limit: bool) { | |
| 2825 | - let (Some(scope), Some(claim)) = (self.scope.as_deref(), self.alarm.take()) else { | |
| 2826 | - return; | |
| 2827 | - }; | |
| 2828 | - if ok { | |
| 2829 | - storage::finish_alarm_handler(scope, true, claim.now_ms); | |
| 2830 | - } else { | |
| 2831 | - storage::finish_alarm_handler_with_retry_policy( | |
| 2832 | - scope, | |
| 2833 | - false, | |
| 2834 | - claim.now_ms, | |
| 2835 | - counts_against_limit, | |
| 2836 | - ); | |
| 2837 | - } | |
| 2838 | - } | |
| 2839 | - | |
| 2840 | - /// Whether a claimed alarm's outcome is still unrecorded. True only | |
| 2841 | - /// where the event ended without ever entering the isolate again. | |
| 2842 | - pub fn owes_alarm(&self) -> bool { | |
| 2843 | - self.alarm.is_some() | |
| 2844 | - } | |
| 2845 | - | |
| 2846 | - /// Done when the response has been sent and nothing is left running. | |
| 2847 | - pub fn finished(&self) -> bool { | |
| 2848 | - self.retired() && self.ops.is_empty() | |
| 2849 | - } | |
| 2850 | - | |
| 2851 | - /// The gate waiter that still owns this event's reply, if any. | |
| 2852 | - pub(crate) fn gated_reply(&mut self) -> Option<&mut GatedReplyRx> { | |
| 2853 | - self.gated_reply.as_mut() | |
| 2854 | - } | |
| 2855 | - | |
| 2856 | - #[cfg(celld_internal_tests)] | |
| 2857 | - #[doc(hidden)] | |
| 2858 | - pub fn has_gated_reply_for_test(&self) -> bool { | |
| 2859 | - self.gated_reply.is_some() | |
| 2860 | - } | |
| 2861 | - | |
| 2862 | - #[cfg(celld_internal_tests)] | |
| 2863 | - #[doc(hidden)] | |
| 2864 | - pub async fn finish_gated_reply_for_test(&mut self) -> bool { | |
| 2865 | - let Some(gated_reply) = self.gated_reply.as_mut() else { | |
| 2866 | - return false; | |
| 2867 | - }; | |
| 2868 | - let completion = gated_reply.await; | |
| 2869 | - self.finish_gated_reply(completion); | |
| 2870 | - true | |
| 2871 | - } | |
| 2872 | - | |
| 2873 | - /// Ask the detached gate owner to release every event gate and finish the | |
| 2874 | - /// reply edge. The driver waits for its completion before it retires the | |
| 2875 | - /// event, so response resources cannot outlive that cleanup. | |
| 2876 | - pub(crate) fn cancel_gated_reply(&mut self) { | |
| 2877 | - if let Some(gated_reply) = &mut self.gated_reply { | |
| 2878 | - gated_reply.cancel(); | |
| 2879 | - } | |
| 2880 | - } | |
| 2881 | - | |
| 2882 | - /// Retire a gate waiter after it sent the reply or observed caller-close. | |
| 2883 | - /// | |
| 2884 | - /// This method also closes request sockets when the completion makes the | |
| 2885 | - /// entry retire. `finish_turn` cannot do that earlier because the reply | |
| 2886 | - /// value can still own response resources while the gate is pending. | |
| 2887 | - pub(crate) fn finish_gated_reply( | |
| 2888 | - &mut self, | |
| 2889 | - completion: Result<GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>, | |
| 2890 | - ) { | |
| 2891 | - self.gated_reply = None; | |
| 2892 | - if self.trace.is_some() { | |
| 2893 | - match completion { | |
| 2894 | - Ok(GatedReplyCompletion::Sent { | |
| 2895 | - failure: Some(failure), | |
| 2896 | - }) | |
| 2897 | - | Ok(GatedReplyCompletion::CallerClosed { | |
| 2898 | - failure: Some(failure), | |
| 2899 | - }) => self.failure = Some(failure), | |
| 2900 | - Ok(GatedReplyCompletion::Sent { failure: None }) => {} | |
| 2901 | - Ok(GatedReplyCompletion::CallerClosed { failure: None }) => { | |
| 2902 | - if self.failure.is_none() { | |
| 2903 | - self.failure = Some("The client has disconnected".to_string()); | |
| 2904 | - } | |
| 2905 | - } | |
| 2906 | - Err(_) => { | |
| 2907 | - if self.failure.is_none() { | |
| 2908 | - self.failure = Some("wake-entry reply gate task dropped".to_string()); | |
| 2909 | - } | |
| 2910 | - } | |
| 2911 | - } | |
| 2912 | - } | |
| 2913 | - if self.retired() { | |
| 2914 | - self.context.close_sockets(); | |
| 2915 | - } | |
| 2916 | - } | |
| 2917 | - | |
| 2918 | - /// The request has answered and its `waitUntil` work has settled. | |
| 2919 | - /// | |
| 2920 | - /// An isolate-polled WebSocket can still own an op after this point. The | |
| 2921 | - /// request closes that socket when it retires, so the op can finish and | |
| 2922 | - /// the request can leave the drive loop. | |
| 2923 | - fn retired(&self) -> bool { | |
| 2924 | - self.reply.is_none() && self.gated_reply.is_none() && self.background.is_none() | |
| 2925 | - } | |
| 2926 | - | |
| 2927 | - /// Why the event failed, when a sampled trace captured it. | |
| 2928 | - pub fn failure(&self) -> Option<&str> { | |
| 2929 | - self.failure.as_deref() | |
| 2930 | - } | |
| 2931 | - | |
| 2932 | - /// How long this handler may still run, or `None` once it has answered. | |
| 2933 | - /// | |
| 2934 | - /// The budget bounds the *response*, not the request: `waitUntil` work | |
| 2935 | - /// continues after the client has been served and is not charged for the | |
| 2936 | - /// time the handler already spent. | |
| 2937 | - pub fn remaining(&self, budget: Duration) -> Option<Duration> { | |
| 2938 | - self.reply | |
| 2939 | - .is_some() | |
| 2940 | - .then(|| budget.saturating_sub(self.started.elapsed())) | |
| 2941 | - } | |
| 2942 | - | |
| 2943 | - /// Give up on a handler that will not settle. | |
| 2944 | - pub fn time_out(&mut self, budget: Duration) { | |
| 2945 | - self.fail(anyhow!("handler exceeded {}s budget", budget.as_secs())); | |
| 2946 | - } | |
| 2947 | - | |
| 2948 | - /// Nothing this request awaits can move it, so it will never settle on | |
| 2949 | - /// its own. Reachable when a handler awaits a promise only some *other* | |
| 2950 | - /// request could resolve — which the pump concealed, because it settled | |
| 2951 | - /// every entry on every turn whoever the turn belonged to. | |
| 2952 | - pub fn stuck(&mut self) { | |
| 2953 | - self.fail(anyhow!("handler is waiting on nothing")); | |
| 2954 | - self.background = None; | |
| 2955 | - } | |
| 2956 | - | |
| 2957 | - /// Has the client been answered? `waitUntil` work can still be running. | |
| 2958 | - pub fn answered(&self) -> bool { | |
| 2959 | - self.reply.is_none() && self.gated_reply.is_none() | |
| 2960 | - } | |
| 2961 | - | |
| 2962 | - /// Whether a native operation can still resume JavaScript for this event. | |
| 2963 | - /// | |
| 2964 | - /// A detached reply gate is host work. It cannot keep handler operations | |
| 2965 | - /// alive after the handler ends, but explicit `waitUntil` work can. | |
| 2966 | - pub(crate) fn keeps_native_ops(&self) -> bool { | |
| 2967 | - self.reply.is_some() || self.background.is_some() | |
| 2968 | - } | |
| 2969 | - | |
| 2970 | - /// Whether a client can still disconnect from this request. A request | |
| 2971 | - /// with no id is internal and has no client to hang up. | |
| 2972 | - pub fn cancellable(&self) -> bool { | |
| 2973 | - self.reply.is_some() && self.request_id.is_some() | |
| 2974 | - } | |
| 2975 | - | |
| 2976 | - pub fn request_id(&self) -> Option<RequestId> { | |
| 2977 | - self.request_id | |
| 2978 | - } | |
| 2979 | - | |
| 2980 | - /// The request is over and its remaining ops are being dropped. Purge | |
| 2981 | - /// their resolvers. | |
| 2982 | - /// | |
| 2983 | - /// An op that never completes would otherwise leave its | |
| 2984 | - /// `Global<PromiseResolver>` in the isolate's map for as long as the | |
| 2985 | - /// isolate lives. A request that drives itself has to purge them on its | |
| 2986 | - /// own way out. | |
| 2987 | - pub fn abandon(&mut self) { | |
| 2988 | - if self.ops.is_empty() { | |
| 2989 | - return; | |
| 2990 | - } | |
| 2991 | - let mut promises = self.runtime_state.promises.lock().unwrap(); | |
| 2992 | - for id in self.ops.drain() { | |
| 2993 | - promises.remove(&id); | |
| 2994 | - } | |
| 2995 | - } | |
| 2996 | -} | |
| 2997 | - | |
| 2998 | -/// The CPED slot carries three riders in one immutable record: the | |
| 2999 | -/// harness's async-context frame (`__als_get`/`__als_set` — ALS and | |
| 3000 | -/// request-context confinement), telemetry's trace context, and the native | |
| 3001 | -/// `IoContext` token. Each write builds a fresh three-element array preserving | |
| 3002 | -/// the other riders, so V8's per-reaction snapshots restore them atomically. | |
| 3003 | -/// Telemetry once took the whole slot and exposed this collision. | |
| 3004 | -/// | |
| 3005 | -/// When all three riders are absent, the slot stays undefined and V8 can use | |
| 3006 | -/// its empty-state fast path. Stateless code can retain that path. A cell | |
| 3007 | -/// event intentionally installs the native token even when telemetry is off. | |
| 3008 | -fn cped_parts<'s>( | |
| 3009 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3010 | -) -> ( | |
| 3011 | - v8::Local<'s, v8::Value>, | |
| 3012 | - v8::Local<'s, v8::Value>, | |
| 3013 | - v8::Local<'s, v8::Value>, | |
| 3014 | -) { | |
| 3015 | - let data = scope.get_continuation_preserved_embedder_data(); | |
| 3016 | - if let Ok(record) = v8::Local::<v8::Array>::try_from(data) { | |
| 3017 | - if record.length() == 3 { | |
| 3018 | - let undefined = v8::undefined(scope).into(); | |
| 3019 | - return ( | |
| 3020 | - record.get_index(scope, 0).unwrap_or(undefined), | |
| 3021 | - record.get_index(scope, 1).unwrap_or(undefined), | |
| 3022 | - record.get_index(scope, 2).unwrap_or(undefined), | |
| 3023 | - ); | |
| 3024 | - } | |
| 3025 | - // Accept snapshots created by the former two-rider layout. They can | |
| 3026 | - // still be live while an isolate upgrades across this code boundary. | |
| 3027 | - if record.length() == 2 { | |
| 3028 | - let undefined = v8::undefined(scope).into(); | |
| 3029 | - return ( | |
| 3030 | - record.get_index(scope, 0).unwrap_or(undefined), | |
| 3031 | - record.get_index(scope, 1).unwrap_or(undefined), | |
| 3032 | - undefined, | |
| 3033 | - ); | |
| 3034 | - } | |
| 3035 | - } | |
| 3036 | - // Any non-record value is a bare frame from before this scheme, or | |
| 3037 | - // the empty slot. | |
| 3038 | - ( | |
| 3039 | - data, | |
| 3040 | - v8::undefined(scope).into(), | |
| 3041 | - v8::undefined(scope).into(), | |
| 3042 | - ) | |
| 3043 | -} | |
| 3044 | - | |
| 3045 | -fn cped_frame<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { | |
| 3046 | - cped_parts(scope).0 | |
| 3047 | -} | |
| 3048 | - | |
| 3049 | -fn cped_trace<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { | |
| 3050 | - cped_parts(scope).1 | |
| 3051 | -} | |
| 3052 | - | |
| 3053 | -fn cped_io_context<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { | |
| 3054 | - cped_parts(scope).2 | |
| 3055 | -} | |
| 3056 | - | |
| 3057 | -fn set_cped( | |
| 3058 | - scope: &mut v8::PinScope, | |
| 3059 | - frame: v8::Local<v8::Value>, | |
| 3060 | - trace: v8::Local<v8::Value>, | |
| 3061 | - io_context: v8::Local<v8::Value>, | |
| 3062 | -) { | |
| 3063 | - if frame.is_undefined() && trace.is_undefined() && io_context.is_undefined() { | |
| 3064 | - let undefined = v8::undefined(scope).into(); | |
| 3065 | - scope.set_continuation_preserved_embedder_data(undefined); | |
| 3066 | - return; | |
| 3067 | - } | |
| 3068 | - let record = v8::Array::new(scope, 3); | |
| 3069 | - record.set_index(scope, 0, frame); | |
| 3070 | - record.set_index(scope, 1, trace); | |
| 3071 | - record.set_index(scope, 2, io_context); | |
| 3072 | - scope.set_continuation_preserved_embedder_data(record.into()); | |
| 3073 | -} | |
| 3074 | - | |
| 3075 | -/// Install a trace context into the isolate's CPED slot for one turn. | |
| 3076 | -/// | |
| 3077 | -/// V8 snapshots continuation-preserved embedder data when a promise | |
| 3078 | -/// reaction is registered and restores it while the reaction runs. That | |
| 3079 | -/// is the exactness `console.log` correlation needs: a continuation | |
| 3080 | -/// belonging to a *different* entry that runs during this turn's | |
| 3081 | -/// microtask checkpoint carries its own context, not this turn's. The | |
| 3082 | -/// layout is 16 trace-id bytes then 8 span-id bytes in one 24-byte | |
| 3083 | -/// ArrayBuffer, fresh per turn — cheap at sampled rates, and nothing | |
| 3084 | -/// outlives V8's own snapshots. | |
| 3085 | -/// | |
| 3086 | -/// Returns the previous slot value *only when a trace was installed*; the | |
| 3087 | -/// caller restores it before releasing the isolate. An untraced turn does not | |
| 3088 | -/// install the trace rider. A cell event separately installs its `IoContext` | |
| 3089 | -/// token, so V8 can attribute a continuation that runs during another event's | |
| 3090 | -/// checkpoint. | |
| 3091 | -fn install_trace<'s>( | |
| 3092 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3093 | - trace: Option<&crate::telemetry::TraceIds>, | |
| 3094 | -) -> Option<v8::Local<'s, v8::Value>> { | |
| 3095 | - let ids = trace?; | |
| 3096 | - let previous = scope.get_continuation_preserved_embedder_data(); | |
| 3097 | - let buffer = v8::ArrayBuffer::new(scope, 24); | |
| 3098 | - let data = buffer.get_backing_store().data()?; | |
| 3099 | - let bytes = data.as_ptr() as *mut u8; | |
| 3100 | - // SAFETY: a freshly created 24-byte buffer, written before any JS | |
| 3101 | - // can see it. | |
| 3102 | - unsafe { | |
| 3103 | - std::ptr::copy_nonoverlapping(ids.trace_id.as_ptr(), bytes, 16); | |
| 3104 | - std::ptr::copy_nonoverlapping(ids.span_id.as_ptr(), bytes.add(16), 8); | |
| 3105 | - } | |
| 3106 | - let frame = cped_frame(scope); | |
| 3107 | - let io_context = cped_io_context(scope); | |
| 3108 | - set_cped(scope, frame, buffer.into(), io_context); | |
| 3109 | - Some(previous) | |
| 3110 | -} | |
| 3111 | - | |
| 3112 | -fn restore_trace(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) { | |
| 3113 | - if let Some(previous) = previous { | |
| 3114 | - scope.set_continuation_preserved_embedder_data(previous); | |
| 3115 | - } | |
| 3116 | -} | |
| 3117 | - | |
| 3118 | -/// Install the current cell event's native context in CPED. V8 restores this | |
| 3119 | -/// token for each reaction, including a reaction that runs during another | |
| 3120 | -/// event's microtask checkpoint. | |
| 3121 | -fn install_io_context<'s>( | |
| 3122 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3123 | - context: &IoContext, | |
| 3124 | -) -> Option<v8::Local<'s, v8::Value>> { | |
| 3125 | - let (id, _) = context.continuation.as_ref()?; | |
| 3126 | - let previous = scope.get_continuation_preserved_embedder_data(); | |
| 3127 | - let frame = cped_frame(scope); | |
| 3128 | - let trace = cped_trace(scope); | |
| 3129 | - let token: v8::Local<v8::Value> = v8::BigInt::new_from_u64(scope, *id).into(); | |
| 3130 | - set_cped(scope, frame, trace, token); | |
| 3131 | - Some(previous) | |
| 3132 | -} | |
| 3133 | - | |
| 3134 | -fn restore_io_context(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) { | |
| 3135 | - if let Some(previous) = previous { | |
| 3136 | - scope.set_continuation_preserved_embedder_data(previous); | |
| 3137 | - } | |
| 3138 | -} | |
| 3139 | - | |
| 3140 | -fn current_reaction_io_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> { | |
| 3141 | - let token = v8::Local::<v8::BigInt>::try_from(cped_io_context(scope)).ok()?; | |
| 3142 | - let (id, lossless) = token.u64_value(); | |
| 3143 | - lossless | |
| 3144 | - .then(|| actor_runtime_state(scope).io_context(id)) | |
| 3145 | - .flatten() | |
| 3146 | -} | |
| 3147 | - | |
| 3148 | -/// The trace context current at this exact point of JS execution, read | |
| 3149 | -/// from CPED — the running turn's, or the running continuation's if V8 | |
| 3150 | -/// restored one. `None` when telemetry is off, the trace was unsampled, | |
| 3151 | -/// or execution is outside any entry. | |
| 3152 | -pub(crate) fn current_trace_ids(scope: &mut v8::PinScope) -> Option<crate::telemetry::TraceIds> { | |
| 3153 | - if !crate::telemetry::active() { | |
| 3154 | - return None; | |
| 3155 | - } | |
| 3156 | - let data = cped_trace(scope); | |
| 3157 | - let buffer = v8::Local::<v8::ArrayBuffer>::try_from(data).ok()?; | |
| 3158 | - if buffer.byte_length() != 24 { | |
| 3159 | - return None; | |
| 3160 | - } | |
| 3161 | - let data = buffer.get_backing_store().data()?; | |
| 3162 | - let bytes = data.as_ptr() as *const u8; | |
| 3163 | - let mut trace_id = [0u8; 16]; | |
| 3164 | - let mut span_id = [0u8; 8]; | |
| 3165 | - // SAFETY: length checked; the buffer is alive for this scope. | |
| 3166 | - unsafe { | |
| 3167 | - std::ptr::copy_nonoverlapping(bytes, trace_id.as_mut_ptr(), 16); | |
| 3168 | - std::ptr::copy_nonoverlapping(bytes.add(16), span_id.as_mut_ptr(), 8); | |
| 3169 | - } | |
| 3170 | - Some(crate::telemetry::TraceIds { trace_id, span_id }) | |
| 3171 | -} | |
| 3172 | - | |
| 3173 | -/// The isolate, entered for one turn. Everything a request does to a shared | |
| 3174 | -/// isolate goes through one of these, and none of them may be held across an | |
| 3175 | -/// await: the caller takes the pool's async permit first, runs a turn, and | |
| 3176 | -/// leaves. | |
| 3177 | -impl Worker { | |
| 3178 | - /// Run a request's first turn. | |
| 3179 | - /// | |
| 3180 | - /// Returns what is now in flight — `None` when nothing is, the reply | |
| 3181 | - /// already carrying the error — and the ops the handler enqueued, which | |
| 3182 | - /// the caller awaits with no isolate held. | |
| 3183 | - pub fn turn_begin( | |
| 3184 | - &mut self, | |
| 3185 | - job: crate::WorkerJob, | |
| 3186 | - trace: Option<crate::telemetry::TraceIds>, | |
| 3187 | - ) -> (Option<InFlight>, Vec<Op>) { | |
| 3188 | - let Some(inner) = self.inner.as_mut() else { | |
| 3189 | - return (None, Vec::new()); | |
| 3190 | - }; | |
| 3191 | - let (mut locker, _cells) = inner.lock(); | |
| 3192 | - inner.recover_heap(&mut locker); | |
| 3193 | - v8::scope!(let hs, &mut *locker); | |
| 3194 | - let realm = inner.realm(hs); | |
| 3195 | - let context = realm.context; | |
| 3196 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 3197 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 3198 | - let tc = &mut tc.init(); | |
| 3199 | - | |
| 3200 | - let previous = install_trace(tc, trace.as_ref()); | |
| 3201 | - let out = match begin(tc, realm.fetch, job) { | |
| 3202 | - Begun::Running(mut entry) => { | |
| 3203 | - entry.trace = trace; | |
| 3204 | - // A handler that returned an already-resolved promise is | |
| 3205 | - // finished before it ever suspends, and must not wait for an | |
| 3206 | - // op it will never start. | |
| 3207 | - let ops = finish_turn(tc, &mut entry); | |
| 3208 | - (Some(*entry), ops) | |
| 3209 | - } | |
| 3210 | - Begun::Threw(answer) => { | |
| 3211 | - answer.fail(anyhow!("fetch threw: {}", exc!(tc))); | |
| 3212 | - (None, Vec::new()) | |
| 3213 | - } | |
| 3214 | - Begun::Nothing => (None, Vec::new()), | |
| 3215 | - }; | |
| 3216 | - restore_trace(tc, previous); | |
| 3217 | - out | |
| 3218 | - } | |
| 3219 | - | |
| 3220 | - /// Enter the isolate solely to end a request whose client has hung up. | |
| 3221 | - /// | |
| 3222 | - /// A suspended request notices the disconnect without any isolate — the | |
| 3223 | - /// flag is host state — so this is reached only when it has actually | |
| 3224 | - /// fired, rather than on a timer as the blocking run loop did. | |
| 3225 | - pub fn turn_cancel(&mut self, entry: &mut InFlight) -> Vec<Op> { | |
| 3226 | - let Some(inner) = self.inner.as_mut() else { | |
| 3227 | - return Vec::new(); | |
| 3228 | - }; | |
| 3229 | - let (mut locker, _cells) = inner.lock(); | |
| 3230 | - v8::scope!(let hs, &mut *locker); | |
| 3231 | - let realm = inner.realm(hs); | |
| 3232 | - let context = realm.context; | |
| 3233 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 3234 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 3235 | - let tc = &mut tc.init(); | |
| 3236 | - | |
| 3237 | - let previous_io_context = install_io_context(tc, &entry.context); | |
| 3238 | - let previous = install_trace(tc, entry.trace.as_ref()); | |
| 3239 | - cancel(tc, entry); | |
| 3240 | - let ops = finish_turn(tc, entry); | |
| 3241 | - restore_trace(tc, previous); | |
| 3242 | - restore_io_context(tc, previous_io_context); | |
| 3243 | - ops | |
| 3244 | - } | |
| 3245 | - | |
| 3246 | - /// Run a later turn: resolve one of this request's ops, drain the | |
| 3247 | - /// microtasks that follow, and answer if the handler settled. | |
| 3248 | - pub fn turn_deliver( | |
| 3249 | - &mut self, | |
| 3250 | - entry: &mut InFlight, | |
| 3251 | - op: u64, | |
| 3252 | - res: Result<asyncrt::OpOut, String>, | |
| 3253 | - ) -> Vec<Op> { | |
| 3254 | - let Some(inner) = self.inner.as_mut() else { | |
| 3255 | - return Vec::new(); | |
| 3256 | - }; | |
| 3257 | - let (mut locker, _cells) = inner.lock(); | |
| 3258 | - v8::scope!(let hs, &mut *locker); | |
| 3259 | - let realm = inner.realm(hs); | |
| 3260 | - let context = realm.context; | |
| 3261 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 3262 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 3263 | - let tc = &mut tc.init(); | |
| 3264 | - | |
| 3265 | - let previous_io_context = install_io_context(tc, &entry.context); | |
| 3266 | - let previous = install_trace(tc, entry.trace.as_ref()); | |
| 3267 | - deliver(tc, entry, op, res); | |
| 3268 | - cancelled(tc, entry); | |
| 3269 | - let ops = finish_turn(tc, entry); | |
| 3270 | - restore_trace(tc, previous); | |
| 3271 | - restore_io_context(tc, previous_io_context); | |
| 3272 | - ops | |
| 3273 | - } | |
| 3274 | -} | |
| 3275 | - | |
| 3276 | -/// Close a turn, whatever the turn did. | |
| 3277 | -/// | |
| 3278 | -/// Every step earns its place and the order is the whole point: | |
| 3279 | -/// | |
| 3280 | -/// 1. **settle** — the handler's promise may have resolved, so marshal the | |
| 3281 | -/// response and answer. Marshalling can start a JS-to-host body pump and | |
| 3282 | -/// register it with `waitUntil`. | |
| 3283 | -/// 2. **checkpoint** — that pump's native ops exist only once the microtasks | |
| 3284 | -/// which create them run. | |
| 3285 | -/// 3. **settle again** — the checkpoint may itself have settled the promise, | |
| 3286 | -/// or the `waitUntil` aggregate. | |
| 3287 | -/// 4. **adopt** — only now is the set of ops this request waits on complete. | |
| 3288 | -/// | |
| 3289 | -/// Draining before step 2 is the bug that made a streaming handler answer | |
| 3290 | -/// with nothing outstanding and conclude it was waiting on nothing. | |
| 3291 | -/// The checkpoint before adoption is what makes response-body pumps visible. | |
| 3292 | -/// | |
| 3293 | -/// Step 5 exists because `finished()` also waits for the op set to empty, | |
| 3294 | -/// and an isolate-polled WebSocket keeps one op outstanding for as long as | |
| 3295 | -/// the socket lives. The drive loop therefore never reached its own exit for | |
| 3296 | -/// such a request: it parked on `ops.next()` forever, holding the request's | |
| 3297 | -/// affiliation and its context, so nothing that runs *after* the loop could | |
| 3298 | -/// ever close the socket. Closing at the moment the request retires is what | |
| 3299 | -/// lets the pump's op resolve, which is what lets the loop finish. | |
| 3300 | -/// | |
| 3301 | -/// "Retired" is deliberately not "answered": a streaming response body is a | |
| 3302 | -/// pump `send_and_end` registers with `waitUntil`, so the client is still | |
| 3303 | -/// being served while `background` is set, and a socket the handler opened | |
| 3304 | -/// stays open for as long as that body is still going out. | |
| 3305 | -fn finish_turn(tc: &mut v8::PinScope, entry: &mut InFlight) -> Vec<Op> { | |
| 3306 | - settle(tc, entry); | |
| 3307 | - tc.perform_microtask_checkpoint(); | |
| 3308 | - // `abort()` and `process.exit()` terminate execution without settling | |
| 3309 | - // the handler's promise, so an entry that only watched the promise would | |
| 3310 | - // wait on it forever and then report that it was waiting on nothing. | |
| 3311 | - // The blocking loop broke out of its loop here; an entry fails here. | |
| 3312 | - if let Some(error) = take_execution_termination(tc) { | |
| 3313 | - entry.fail(error); | |
| 3314 | - entry.background = None; | |
| 3315 | - entry.abandon(); | |
| 3316 | - return Vec::new(); | |
| 3317 | - } | |
| 3318 | - settle(tc, entry); | |
| 3319 | - // 5. **close the request's sockets** — see above. | |
| 3320 | - if entry.retired() { | |
| 3321 | - entry.context.close_sockets(); | |
| 3322 | - } | |
| 3323 | - adopt(entry) | |
| 3324 | -} | |
| 3325 | - | |
| 3326 | -/// An op the JS enqueued, and the id whose promise it resolves. | |
| 3327 | -pub type Op = (u64, asyncrt::OpFuture); | |
| 3328 | - | |
| 3329 | -/// Take the ops this turn enqueued, recording them as the request's own. | |
| 3330 | -/// | |
| 3331 | -/// Drained after `settle`, not before: ending an event runs JS, and anything | |
| 3332 | -/// that starts there belongs to this request too. The pump drained first and | |
| 3333 | -/// so could attribute those to whichever entry it settled next. | |
| 3334 | -fn adopt(entry: &mut InFlight) -> Vec<Op> { | |
| 3335 | - let spawns = asyncrt::drain_spawns(); | |
| 3336 | - for (id, _) in &spawns { | |
| 3337 | - entry.ops.insert(*id); | |
| 3338 | - } | |
| 3339 | - spawns | |
| 3340 | -} | |
| 3341 | - | |
| 3342 | -/// What starting a request produced. | |
| 3343 | -enum Begun { | |
| 3344 | - /// In flight. Its ops must be adopted and its promise driven. | |
| 3345 | - Running(Box<InFlight>), | |
| 3346 | - /// The handler threw before it could suspend, so nothing is in flight. | |
| 3347 | - /// The exception belongs to the caller's `TryCatch` — an unnameable type | |
| 3348 | - /// no signature here can take — so the caller reads it and answers. | |
| 3349 | - Threw(Answer), | |
| 3350 | - /// Nothing started: the job was not a fetch, or the reply already | |
| 3351 | - /// carries the error. | |
| 3352 | - Nothing, | |
| 3353 | -} | |
| 3354 | - | |
| 3355 | -/// Start a request: build it, call the Worker's `fetch`, and hand back what | |
| 3356 | -/// is now in flight. | |
| 3357 | -/// | |
| 3358 | -/// The half of a turn that runs *before* anything can suspend. | |
| 3359 | -fn begin<'s>( | |
| 3360 | - tc: &mut v8::PinScope<'s, '_>, | |
| 3361 | - fetch: v8::Local<'s, v8::Function>, | |
| 3362 | - job: crate::WorkerJob, | |
| 3363 | -) -> Begun { | |
| 3364 | - let job = match job { | |
| 3365 | - crate::WorkerJob::Rpc { | |
| 3366 | - entrypoint, | |
| 3367 | - method, | |
| 3368 | - args, | |
| 3369 | - reply, | |
| 3370 | - } => return begin_entrypoint_rpc(tc, &entrypoint, &method, args, reply), | |
| 3371 | - crate::WorkerJob::Queue { batch, reply, .. } => { | |
| 3372 | - return begin_queue(tc, batch, reply); | |
| 3373 | - } | |
| 3374 | - job => job, | |
| 3375 | - }; | |
| 3376 | - let crate::WorkerJob::Fetch { | |
| 3377 | - url, | |
| 3378 | - method, | |
| 3379 | - body, | |
| 3380 | - headers, | |
| 3381 | - request_id, | |
| 3382 | - reply, | |
| 3383 | - .. | |
| 3384 | - } = job | |
| 3385 | - else { | |
| 3386 | - return Begun::Nothing; | |
| 3387 | - }; | |
| 3388 | - let context = IoContext::new(); | |
| 3389 | - if let Some(stream_id) = body.stream_id() { | |
| 3390 | - context.own_body_stream(stream_id); | |
| 3391 | - } | |
| 3392 | - let guard = CurrentGuard::enter(context.clone()); | |
| 3393 | - let started = start_fetch(tc, fetch, &url, &method, body, &headers, request_id); | |
| 3394 | - let promise = match started { | |
| 3395 | - Ok(Started::Running(ret, active)) => match ret.try_cast::<v8::Promise>() { | |
| 3396 | - Ok(promise) => Ok((promise, active)), | |
| 3397 | - Err(_) => resolved_promise(tc, ret).map(|promise| (promise, active)), | |
| 3398 | - }, | |
| 3399 | - Ok(Started::Threw) => { | |
| 3400 | - drop(guard); | |
| 3401 | - return Begun::Threw(Answer::Fetch(reply)); | |
| 3402 | - } | |
| 3403 | - Err(error) => Err(error), | |
| 3404 | - }; | |
| 3405 | - match promise { | |
| 3406 | - Ok((promise, active_request_id)) => { | |
| 3407 | - tc.perform_microtask_checkpoint(); | |
| 3408 | - let entry = InFlight { | |
| 3409 | - runtime_state: actor_runtime_state(tc), | |
| 3410 | - promise: v8::Global::new(tc, promise), | |
| 3411 | - context, | |
| 3412 | - scope: None, | |
| 3413 | - writes_before: None, | |
| 3414 | - request_id, | |
| 3415 | - active_request_id, | |
| 3416 | - reply: Some(Answer::Fetch(reply)), | |
| 3417 | - gated_reply: None, | |
| 3418 | - background: None, | |
| 3419 | - ops: std::collections::HashSet::new(), | |
| 3420 | - alarm: None, | |
| 3421 | - started: Instant::now(), | |
| 3422 | - trace: None, | |
| 3423 | - failure: None, | |
| 3424 | - }; | |
| 3425 | - drop(guard); | |
| 3426 | - Begun::Running(Box::new(entry)) | |
| 3427 | - } | |
| 3428 | - Err(error) => { | |
| 3429 | - drop(guard); | |
| 3430 | - let _ = reply.send(Err(error)); | |
| 3431 | - Begun::Nothing | |
| 3432 | - } | |
| 3433 | - } | |
| 3434 | -} | |
| 3435 | - | |
| 3436 | -/// Start an entrypoint RPC's first turn. | |
| 3437 | -/// | |
| 3438 | -/// The same shape as a fetch and deliberately so: call the handler, keep the | |
| 3439 | -/// promise, and let `drive` pump it with no isolate held across the awaits. | |
| 3440 | -/// The old dispatcher blocked until the promise settled, which is why RPC | |
| 3441 | -/// needed a thread of its own and why `WorkerPool` outlived the fetch path. | |
| 3442 | -fn begin_entrypoint_rpc( | |
| 3443 | - tc: &mut v8::PinScope, | |
| 3444 | - entrypoint: &str, | |
| 3445 | - method: &str, | |
| 3446 | - args: Vec<u8>, | |
| 3447 | - reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>, | |
| 3448 | -) -> Begun { | |
| 3449 | - let context = IoContext::new(); | |
| 3450 | - let guard = CurrentGuard::enter(context.clone()); | |
| 3451 | - let global = tc.get_current_context().global(tc); | |
| 3452 | - let started = (|| { | |
| 3453 | - let key = v8::String::new(tc, "__dispatchEntrypointRpc").unwrap(); | |
| 3454 | - let f: v8::Local<v8::Function> = global | |
| 3455 | - .get(tc, key.into()) | |
| 3456 | - .ok_or_else(|| anyhow!("no __dispatchEntrypointRpc"))? | |
| 3457 | - .try_into() | |
| 3458 | - .map_err(|_| anyhow!("__dispatchEntrypointRpc is not a function"))?; | |
| 3459 | - let entrypoint = v8::String::new(tc, entrypoint).unwrap(); | |
| 3460 | - let method = v8::String::new(tc, method).unwrap(); | |
| 3461 | - let args = bytes_value(tc, args); | |
| 3462 | - let recv = v8::undefined(tc).into(); | |
| 3463 | - begin_event_context(tc)?; | |
| 3464 | - let ret = f | |
| 3465 | - .call(tc, recv, &[entrypoint.into(), method.into(), args]) | |
| 3466 | - .ok_or_else(|| anyhow!("entrypoint RPC threw"))?; | |
| 3467 | - match ret.try_cast::<v8::Promise>() { | |
| 3468 | - Ok(promise) => Ok(promise), | |
| 3469 | - Err(_) => resolved_promise(tc, ret), | |
| 3470 | - } | |
| 3471 | - })(); | |
| 3472 | - let event_started = Instant::now(); | |
| 3473 | - match started { | |
| 3474 | - Ok(promise) => { | |
| 3475 | - tc.perform_microtask_checkpoint(); | |
| 3476 | - let entry = InFlight { | |
| 3477 | - runtime_state: actor_runtime_state(tc), | |
| 3478 | - promise: v8::Global::new(tc, promise), | |
| 3479 | - context, | |
| 3480 | - scope: None, | |
| 3481 | - writes_before: None, | |
| 3482 | - request_id: None, | |
| 3483 | - active_request_id: None, | |
| 3484 | - reply: Some(Answer::Rpc(reply)), | |
| 3485 | - gated_reply: None, | |
| 3486 | - background: None, | |
| 3487 | - ops: std::collections::HashSet::new(), | |
| 3488 | - alarm: None, | |
| 3489 | - started: event_started, | |
| 3490 | - trace: None, | |
| 3491 | - failure: None, | |
| 3492 | - }; | |
| 3493 | - drop(guard); | |
| 3494 | - Begun::Running(Box::new(entry)) | |
| 3495 | - } | |
| 3496 | - Err(error) => { | |
| 3497 | - let _ = end_event_context(tc); | |
| 3498 | - drop(guard); | |
| 3499 | - let _ = reply.send(Err(error)); | |
| 3500 | - Begun::Nothing | |
| 3501 | - } | |
| 3502 | - } | |
| 3503 | -} | |
| 3504 | - | |
| 3505 | -fn queue_property<'s>( | |
| 3506 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3507 | - object: v8::Local<'s, v8::Object>, | |
| 3508 | - name: &str, | |
| 3509 | -) -> Result<v8::Local<'s, v8::Value>> { | |
| 3510 | - let key = v8::String::new(scope, name).unwrap(); | |
| 3511 | - object | |
| 3512 | - .get(scope, key.into()) | |
| 3513 | - .ok_or_else(|| anyhow!("queue result has no {name}")) | |
| 3514 | -} | |
| 3515 | - | |
| 3516 | -fn queue_bool<'s>( | |
| 3517 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3518 | - object: v8::Local<'s, v8::Object>, | |
| 3519 | - name: &str, | |
| 3520 | -) -> Result<bool> { | |
| 3521 | - let value = queue_property(scope, object, name)?; | |
| 3522 | - anyhow::ensure!(value.is_boolean(), "queue result {name} is not a boolean"); | |
| 3523 | - Ok(value.boolean_value(scope)) | |
| 3524 | -} | |
| 3525 | - | |
| 3526 | -fn queue_delay<'s>( | |
| 3527 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3528 | - object: v8::Local<'s, v8::Object>, | |
| 3529 | -) -> Result<Option<i32>> { | |
| 3530 | - let value = queue_property(scope, object, "delaySeconds")?; | |
| 3531 | - if value.is_undefined() { | |
| 3532 | - return Ok(None); | |
| 3533 | - } | |
| 3534 | - value | |
| 3535 | - .int32_value(scope) | |
| 3536 | - .map(Some) | |
| 3537 | - .ok_or_else(|| anyhow!("queue retry delaySeconds is not a 32-bit integer")) | |
| 3538 | -} | |
| 3539 | - | |
| 3540 | -fn queue_string_array<'s>( | |
| 3541 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3542 | - object: v8::Local<'s, v8::Object>, | |
| 3543 | - name: &str, | |
| 3544 | -) -> Result<Vec<String>> { | |
| 3545 | - let value = queue_property(scope, object, name)?; | |
| 3546 | - let array: v8::Local<v8::Array> = value | |
| 3547 | - .try_into() | |
| 3548 | - .map_err(|_| anyhow!("queue result {name} is not an array"))?; | |
| 3549 | - (0..array.length()) | |
| 3550 | - .map(|index| { | |
| 3551 | - let value = array | |
| 3552 | - .get_index(scope, index) | |
| 3553 | - .ok_or_else(|| anyhow!("queue result {name}[{index}] is missing"))?; | |
| 3554 | - anyhow::ensure!( | |
| 3555 | - value.is_string(), | |
| 3556 | - "queue result {name}[{index}] is not a string" | |
| 3557 | - ); | |
| 3558 | - Ok(value.to_rust_string_lossy(scope)) | |
| 3559 | - }) | |
| 3560 | - .collect() | |
| 3561 | -} | |
| 3562 | - | |
| 3563 | -fn read_queue_result<'s>( | |
| 3564 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3565 | - value: v8::Local<'s, v8::Value>, | |
| 3566 | -) -> Result<QueueDispatchResult> { | |
| 3567 | - let object: v8::Local<v8::Object> = value | |
| 3568 | - .try_into() | |
| 3569 | - .map_err(|_| anyhow!("queue handler answered a non-object"))?; | |
| 3570 | - let outcome = queue_property(scope, object, "outcome")?; | |
| 3571 | - anyhow::ensure!(outcome.is_string(), "queue result outcome is not a string"); | |
| 3572 | - let outcome = match outcome.to_rust_string_lossy(scope).as_str() { | |
| 3573 | - "ok" => QueueOutcome::Ok, | |
| 3574 | - "exception" => QueueOutcome::Exception, | |
| 3575 | - outcome => return Err(anyhow!("unknown queue result outcome {outcome}")), | |
| 3576 | - }; | |
| 3577 | - let error = queue_property(scope, object, "error")?; | |
| 3578 | - let error = if error.is_undefined() { | |
| 3579 | - None | |
| 3580 | - } else { | |
| 3581 | - anyhow::ensure!(error.is_string(), "queue result error is not a string"); | |
| 3582 | - Some(error.to_rust_string_lossy(scope)) | |
| 3583 | - }; | |
| 3584 | - let retry_batch: v8::Local<v8::Object> = queue_property(scope, object, "retryBatch")? | |
| 3585 | - .try_into() | |
| 3586 | - .map_err(|_| anyhow!("queue result retryBatch is not an object"))?; | |
| 3587 | - let retries = queue_property(scope, object, "retryMessages")?; | |
| 3588 | - let retries: v8::Local<v8::Array> = retries | |
| 3589 | - .try_into() | |
| 3590 | - .map_err(|_| anyhow!("queue result retryMessages is not an array"))?; | |
| 3591 | - let mut retry_messages = Vec::with_capacity(retries.length() as usize); | |
| 3592 | - for index in 0..retries.length() { | |
| 3593 | - let retry: v8::Local<v8::Object> = retries | |
| 3594 | - .get_index(scope, index) | |
| 3595 | - .ok_or_else(|| anyhow!("queue result retryMessages[{index}] is missing"))? | |
| 3596 | - .try_into() | |
| 3597 | - .map_err(|_| anyhow!("queue result retryMessages[{index}] is not an object"))?; | |
| 3598 | - let msg_id = queue_property(scope, retry, "msgId")?; | |
| 3599 | - anyhow::ensure!( | |
| 3600 | - msg_id.is_string(), | |
| 3601 | - "queue result retryMessages[{index}].msgId is not a string" | |
| 3602 | - ); | |
| 3603 | - retry_messages.push(QueueRetryMessage { | |
| 3604 | - msg_id: msg_id.to_rust_string_lossy(scope), | |
| 3605 | - delay_seconds: queue_delay(scope, retry)?, | |
| 3606 | - }); | |
| 3607 | - } | |
| 3608 | - Ok(QueueDispatchResult { | |
| 3609 | - outcome, | |
| 3610 | - error, | |
| 3611 | - ack_all: queue_bool(scope, object, "ackAll")?, | |
| 3612 | - retry_batch: QueueRetryBatch { | |
| 3613 | - retry: queue_bool(scope, retry_batch, "retry")?, | |
| 3614 | - delay_seconds: queue_delay(scope, retry_batch)?, | |
| 3615 | - }, | |
| 3616 | - explicit_acks: queue_string_array(scope, object, "explicitAcks")?, | |
| 3617 | - retry_messages, | |
| 3618 | - }) | |
| 3619 | -} | |
| 3620 | - | |
| 3621 | -fn set_queue_property<'s>( | |
| 3622 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3623 | - object: v8::Local<'s, v8::Object>, | |
| 3624 | - name: &str, | |
| 3625 | - value: v8::Local<'s, v8::Value>, | |
| 3626 | -) -> Result<()> { | |
| 3627 | - let key = v8::String::new(scope, name).unwrap(); | |
| 3628 | - anyhow::ensure!( | |
| 3629 | - object.create_data_property(scope, key.into(), value) == Some(true), | |
| 3630 | - "could not construct queue batch field {name}" | |
| 3631 | - ); | |
| 3632 | - Ok(()) | |
| 3633 | -} | |
| 3634 | - | |
| 3635 | -fn queue_batch_value<'s>( | |
| 3636 | - scope: &mut v8::PinScope<'s, '_>, | |
| 3637 | - batch: QueueBatch, | |
| 3638 | -) -> Result<v8::Local<'s, v8::Value>> { | |
| 3639 | - let QueueBatch { | |
| 3640 | - queue, | |
| 3641 | - messages, | |
| 3642 | - metrics, | |
| 3643 | - } = batch; | |
| 3644 | - let mut message_values = Vec::with_capacity(messages.len()); | |
| 3645 | - for message in messages { | |
| 3646 | - let object = v8::Object::new(scope); | |
| 3647 | - let id = v8::String::new(scope, &message.id).unwrap(); | |
| 3648 | - set_queue_property(scope, object, "id", id.into())?; | |
| 3649 | - let timestamp = v8::Number::new(scope, message.timestamp_ms as f64); | |
| 3650 | - set_queue_property(scope, object, "timestamp", timestamp.into())?; | |
| 3651 | - let body = bytes_value(scope, message.body); | |
| 3652 | - set_queue_property(scope, object, "body", body)?; | |
| 3653 | - let content_type = v8::String::new(scope, message.content_type.as_str()).unwrap(); | |
| 3654 | - set_queue_property(scope, object, "contentType", content_type.into())?; | |
| 3655 | - let attempts = v8::Integer::new_from_unsigned(scope, u32::from(message.attempts)); | |
| 3656 | - set_queue_property(scope, object, "attempts", attempts.into())?; | |
| 3657 | - message_values.push(object.into()); | |
| 3658 | - } | |
| 3659 | - | |
| 3660 | - let metrics_value = v8::Object::new(scope); | |
| 3661 | - let count = v8::Number::new(scope, metrics.backlog_count); | |
| 3662 | - set_queue_property(scope, metrics_value, "backlogCount", count.into())?; | |
| 3663 | - let bytes = v8::Number::new(scope, metrics.backlog_bytes); | |
| 3664 | - set_queue_property(scope, metrics_value, "backlogBytes", bytes.into())?; | |
| 3665 | - let oldest = match metrics.oldest_message_timestamp_ms { | |
| 3666 | - Some(timestamp) => v8::Number::new(scope, timestamp as f64).into(), | |
| 3667 | - None => v8::undefined(scope).into(), | |
| 3668 | - }; | |
| 3669 | - set_queue_property(scope, metrics_value, "oldestMessageTimestamp", oldest)?; | |
| 3670 | - | |
| 3671 | - let value = v8::Object::new(scope); | |
| 3672 | - let queue = v8::String::new(scope, &queue).unwrap(); | |
| 3673 | - set_queue_property(scope, value, "queue", queue.into())?; | |
| 3674 | - let messages = v8::Array::new_with_elements(scope, &message_values); | |
| 3675 | - set_queue_property(scope, value, "messages", messages.into())?; | |
| 3676 | - set_queue_property(scope, value, "metrics", metrics_value.into())?; | |
| 3677 | - Ok(value.into()) | |
| 3678 | -} | |
| 3679 | - | |
| 3680 | -/// Start a queue consumer's first turn. The batch body bytes move directly | |
| 3681 | -/// into V8, and only the small settlement record crosses back out. | |
| 3682 | -fn begin_queue( | |
| 3683 | - tc: &mut v8::PinScope, | |
| 3684 | - batch: QueueBatch, | |
| 3685 | - reply: tokio::sync::oneshot::Sender<Result<QueueDispatchResult>>, | |
| 3686 | -) -> Begun { | |
| 3687 | - let context = IoContext::new(); | |
| 3688 | - let guard = CurrentGuard::enter(context.clone()); | |
| 3689 | - let started = (|| { | |
| 3690 | - let dispatch = dispatcher(tc, "__dispatchEntrypointQueue")?; | |
| 3691 | - let batch = queue_batch_value(tc, batch)?; | |
| 3692 | - let entrypoint = v8::String::new(tc, "default").unwrap(); | |
| 3693 | - let recv = v8::undefined(tc).into(); | |
| 3694 | - begin_event_context(tc)?; | |
| 3695 | - let ret = dispatch | |
| 3696 | - .call(tc, recv, &[entrypoint.into(), batch]) | |
| 3697 | - .ok_or_else(|| anyhow!("queue dispatch threw"))?; | |
| 3698 | - match ret.try_cast::<v8::Promise>() { | |
| 3699 | - Ok(promise) => Ok(promise), | |
| 3700 | - Err(_) => resolved_promise(tc, ret), | |
| 3701 | - } | |
| 3702 | - })(); | |
| 3703 | - match started { | |
| 3704 | - Ok(promise) => { | |
| 3705 | - tc.perform_microtask_checkpoint(); | |
| 3706 | - let entry = InFlight { | |
| 3707 | - runtime_state: actor_runtime_state(tc), | |
| 3708 | - promise: v8::Global::new(tc, promise), | |
| 3709 | - context, | |
| 3710 | - scope: None, | |
| 3711 | - writes_before: None, | |
| 3712 | - request_id: None, | |
| 3713 | - active_request_id: None, | |
| 3714 | - reply: Some(Answer::Queue(reply)), | |
| 3715 | - gated_reply: None, | |
| 3716 | - background: None, | |
| 3717 | - ops: std::collections::HashSet::new(), | |
| 3718 | - alarm: None, | |
| 3719 | - started: Instant::now(), | |
| 3720 | - trace: None, | |
| 3721 | - failure: None, | |
| 3722 | - }; | |
| 3723 | - drop(guard); | |
| 3724 | - Begun::Running(Box::new(entry)) | |
| 3725 | - } | |
| 3726 | - Err(error) => { | |
| 3727 | - let _ = end_event_context(tc); | |
| 3728 | - drop(guard); | |
| 3729 | - let _ = reply.send(Err(error)); | |
| 3730 | - Begun::Nothing | |
| 3731 | - } | |
| 3732 | - } | |
| 3733 | -} | |
| 3734 | - | |
| 3735 | -/// for the JSON flavor, a `Uint8Array` for structured clone. | |
| 3736 | -fn rpc_data_value<'s>(scope: &mut v8::PinScope<'s, '_>, data: RpcData) -> v8::Local<'s, v8::Value> { | |
| 3737 | - match data { | |
| 3738 | - RpcData::Json(json) => v8::String::new(scope, &json).unwrap().into(), | |
| 3739 | - RpcData::V8(bytes) => bytes_value(scope, bytes.into()), | |
| 3740 | - } | |
| 3741 | -} | |
| 3742 | - | |
| 3743 | -/// The inverse: `__dispatchRpc` answers in the flavor it was asked in. | |
| 3744 | -fn rpc_data_ret(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> RpcData { | |
| 3745 | - match view_bytes(ret) { | |
| 3746 | - Some(bytes) => RpcData::V8(bytes.into()), | |
| 3747 | - None => RpcData::Json(ret.to_rust_string_lossy(scope)), | |
| 3748 | - } | |
| 3749 | -} | |
| 3750 | - | |
| 3751 | -fn unix_now_ms() -> i64 { | |
| 3752 | - std::time::SystemTime::now() | |
| 3753 | - .duration_since(std::time::UNIX_EPOCH) | |
| 3754 | - .unwrap_or_default() | |
| 3755 | - .as_millis() | |
| 3756 | - .min(i64::MAX as u128) as i64 | |
| 3757 | -} | |
| 3758 | - | |
| 3759 | -/// End the event, then answer with what the handler produced. | |
| 3760 | -/// | |
| 3761 | -/// Ending it is what yields the `waitUntil` aggregate the entry keeps | |
| 3762 | -/// driving after the caller has been served, so it happens for every answer | |
| 3763 | -/// shape and on the error path too. | |
| 3764 | -fn send_and_end<T>( | |
| 3765 | - tc: &mut v8::PinScope, | |
| 3766 | - context: &IoContext, | |
| 3767 | - reply: tokio::sync::oneshot::Sender<Result<T>>, | |
| 3768 | - value: Result<T>, | |
| 3769 | -) -> (Option<v8::Global<v8::Promise>>, Option<GatedReplyRx>) | |
| 3770 | -where | |
| 3771 | - T: Send + 'static, | |
| 3772 | -{ | |
| 3773 | - let background = end_event_context(tc).ok().flatten(); | |
| 3774 | - let gated_reply = send_answer_after_arm_gates(reply, value, context.take_arm_gates()); | |
| 3775 | - ( | |
| 3776 | - background.map(|promise| v8::Global::new(tc, promise)), | |
| 3777 | - gated_reply, | |
| 3778 | - ) | |
| 3779 | -} | |
| 3780 | - | |
| 3781 | -/// A committed-write position only counts when the handler advanced it; celld's | |
| 3782 | -/// own activation writes are already below `before`. | |
| 3783 | -pub(crate) fn write_delta(before: Option<u64>, after: Option<u64>) -> Option<u64> { | |
| 3784 | - match (before, after) { | |
| 3785 | - (Some(before), Some(after)) if after > before => Some(after), | |
| 3786 | - _ => None, | |
| 3787 | - } | |
| 3788 | -} | |
| 3789 | - | |
| 3790 | -/// What a Durable Object RPC method returned, plus the position its writes | |
| 3791 | -/// reached, so the caller can hold the reply behind durability. | |
| 3792 | -pub struct RpcOutcome { | |
| 3793 | - pub data: RpcData, | |
| 3794 | - pub write_position: Option<u64>, | |
| 3795 | -} | |
| 3796 | - | |
| 3797 | -/// What a claimed alarm still owes its bookkeeping. | |
| 3798 | -/// | |
| 3799 | -/// `finish_alarm_handler` must run exactly once however the event ends, and | |
| 3800 | -/// an event can now end without running JS at all — a budget overrun, a | |
| 3801 | -/// handler waiting on nothing — so the entry carries the claim rather than | |
| 3802 | -/// the caller that made it. | |
| 3803 | -struct AlarmClaim { | |
| 3804 | - /// The instant the dispatch was judged due against, so the outcome is | |
| 3805 | - /// recorded against the same one. | |
| 3806 | - now_ms: i64, | |
| 3807 | -} | |
| 3808 | - | |
| 3809 | -/// Start one cell event: the half that runs before the handler can suspend. | |
| 3810 | -/// | |
| 3811 | -/// Every cell event does the same four things — name the cell it belongs to, | |
| 3812 | -/// sample the writes its answer will be gated on, open an event context, and | |
| 3813 | -/// keep the promise the dispatcher returned. Only the call and the shape of | |
| 3814 | -/// the answer differ, which is what the arguments say. | |
| 3815 | -fn start_cell_event<'s>( | |
| 3816 | - tc: &mut v8::PinScope<'s, '_>, | |
| 3817 | - scope: &str, | |
| 3818 | - answer: Answer, | |
| 3819 | - request_id: Option<RequestId>, | |
| 3820 | - body_stream_id: Option<u64>, | |
| 3821 | - capture_frames: bool, | |
| 3822 | - call: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>>, | |
| 3823 | -) -> Begun { | |
| 3824 | - let runtime_state = actor_runtime_state(tc); | |
| 3825 | - let context = IoContext::tracked(&runtime_state); | |
| 3826 | - if let Some(stream_id) = body_stream_id { | |
| 3827 | - context.own_body_stream(stream_id); | |
| 3828 | - } | |
| 3829 | - let guard = CurrentGuard::enter(context.clone()); | |
| 3830 | - let previous_io_context = install_io_context(tc, &context); | |
| 3831 | - // Sampled before the handler runs so the output gate can tell a write | |
| 3832 | - // this event made from celld's own activation writes. | |
| 3833 | - let writes_before = storage::write_position(scope); | |
| 3834 | - // No guard: this frame is the context's outermost one and the context | |
| 3835 | - // ends with the event, so there is nothing to pop it before. | |
| 3836 | - context | |
| 3837 | - .egress | |
| 3838 | - .lock() | |
| 3839 | - .unwrap() | |
| 3840 | - .push((scope.to_string(), writes_before.unwrap_or(0))); | |
| 3841 | - if capture_frames { | |
| 3842 | - ws_capture_begin(); | |
| 3843 | - } | |
| 3844 | - let event_started = Instant::now(); | |
| 3845 | - let started = (|| { | |
| 3846 | - begin_event_context(tc)?; | |
| 3847 | - let ret = call(tc)?; | |
| 3848 | - match ret.try_cast::<v8::Promise>() { | |
| 3849 | - Ok(promise) => Ok(promise), | |
| 3850 | - Err(_) => resolved_promise(tc, ret), | |
| 3851 | - } | |
| 3852 | - })(); | |
| 3853 | - match started { | |
| 3854 | - Ok(promise) => { | |
| 3855 | - tc.perform_microtask_checkpoint(); | |
| 3856 | - let entry = InFlight { | |
| 3857 | - runtime_state: runtime_state.clone(), | |
| 3858 | - promise: v8::Global::new(tc, promise), | |
| 3859 | - context, | |
| 3860 | - scope: Some(scope.to_string()), | |
| 3861 | - writes_before, | |
| 3862 | - request_id, | |
| 3863 | - // A cell's dispatcher registers the incoming request itself, | |
| 3864 | - // so there is nothing for the shell to finish; `cancel` | |
| 3865 | - // aborts by the job's own id. | |
| 3866 | - active_request_id: None, | |
| 3867 | - reply: Some(answer), | |
| 3868 | - gated_reply: None, | |
| 3869 | - background: None, | |
| 3870 | - ops: std::collections::HashSet::new(), | |
| 3871 | - alarm: None, | |
| 3872 | - started: event_started, | |
| 3873 | - trace: None, | |
| 3874 | - failure: None, | |
| 3875 | - }; | |
| 3876 | - restore_io_context(tc, previous_io_context); | |
| 3877 | - drop(guard); | |
| 3878 | - Begun::Running(Box::new(entry)) | |
| 3879 | - } | |
| 3880 | - Err(error) => { | |
| 3881 | - // A V8 termination has a concrete stored cause. The dispatcher | |
| 3882 | - // wrapper can only report that its call returned no value, so do | |
| 3883 | - // not replace process.exit or actor-abort with that generic seam. | |
| 3884 | - let error = take_execution_termination(tc).unwrap_or(error); | |
| 3885 | - let background = end_event_context(tc) | |
| 3886 | - .ok() | |
| 3887 | - .flatten() | |
| 3888 | - .map(|promise| v8::Global::new(tc, promise)); | |
| 3889 | - let failure = crate::telemetry::cap_error(format!("{error:#}")); | |
| 3890 | - let gated_reply = answer.fail_with_arm_gates(error, context.take_arm_gates()); | |
| 3891 | - let begun = if gated_reply.is_none() && background.is_none() { | |
| 3892 | - Begun::Nothing | |
| 3893 | - } else { | |
| 3894 | - let undefined = v8::undefined(tc).into(); | |
| 3895 | - let promise = resolved_promise(tc, undefined) | |
| 3896 | - .expect("a finishing cell event can create a resolved promise"); | |
| 3897 | - Begun::Running(Box::new(InFlight { | |
| 3898 | - runtime_state, | |
| 3899 | - promise: v8::Global::new(tc, promise), | |
| 3900 | - context, | |
| 3901 | - scope: Some(scope.to_string()), | |
| 3902 | - writes_before, | |
| 3903 | - request_id, | |
| 3904 | - active_request_id: None, | |
| 3905 | - reply: None, | |
| 3906 | - gated_reply, | |
| 3907 | - background, | |
| 3908 | - ops: std::collections::HashSet::new(), | |
| 3909 | - alarm: None, | |
| 3910 | - started: event_started, | |
| 3911 | - trace: None, | |
| 3912 | - failure: Some(failure), | |
| 3913 | - })) | |
| 3914 | - }; | |
| 3915 | - restore_io_context(tc, previous_io_context); | |
| 3916 | - drop(guard); | |
| 3917 | - begun | |
| 3918 | - } | |
| 3919 | - } | |
| 3920 | -} | |
| 3921 | - | |
| 3922 | -/// Look one of the harness dispatchers up on the current realm's global. | |
| 3923 | -fn dispatcher<'s>( | |
| 3924 | - tc: &mut v8::PinScope<'s, '_>, | |
| 3925 | - name: &str, | |
| 3926 | -) -> Result<v8::Local<'s, v8::Function>> { | |
| 3927 | - let global = tc.get_current_context().global(tc); | |
| 3928 | - let key = v8::String::new(tc, name).unwrap(); | |
| 3929 | - global | |
| 3930 | - .get(tc, key.into()) | |
| 3931 | - .ok_or_else(|| anyhow!("no {name}"))? | |
| 3932 | - .try_into() | |
| 3933 | - .map_err(|_| anyhow!("{name} is not a function")) | |
| 3934 | -} | |
| 3935 | - | |
| 3936 | -/// Start a cell event's first turn. | |
| 3937 | -/// | |
| 3938 | -/// The counterpart of `begin` for the events a cell receives. Where the | |
| 3939 | -/// blocking loop ran each of these to completion inside one call — and | |
| 3940 | -/// serviced other cells' events inside *that* — each is now an entry a tokio | |
| 3941 | -/// task drives, so two events of one cell interleave by suspending rather | |
| 3942 | -/// than by nesting. | |
| 3943 | -fn begin_cell(tc: &mut v8::PinScope, job: CellJob) -> Begun { | |
| 3944 | - match job { | |
| 3945 | - CellJob::Fetch { | |
| 3946 | - request_id, | |
| 3947 | - scope, | |
| 3948 | - name, | |
| 3949 | - url, | |
| 3950 | - method, | |
| 3951 | - body, | |
| 3952 | - headers, | |
| 3953 | - reply, | |
| 3954 | - order: _, | |
| 3955 | - } => { | |
| 3956 | - if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) { | |
| 3957 | - let _ = reply.send(Err(error)); | |
| 3958 | - return Begun::Nothing; | |
| 3959 | - } | |
| 3960 | - let body_stream_id = body.stream_id(); | |
| 3961 | - start_cell_event( | |
| 3962 | - tc, | |
| 3963 | - &scope, | |
| 3964 | - Answer::Fetch(reply), | |
| 3965 | - request_id, | |
| 3966 | - body_stream_id, | |
| 3967 | - false, | |
| 3968 | - |tc| { | |
| 3969 | - let f = dispatcher(tc, "__dispatchTo")?; | |
| 3970 | - // A held body crosses as its bytes; a streamed body crosses as | |
| 3971 | - // its host stream id, so the handler reads it in parts instead | |
| 3972 | - // of the routing seam collecting it first. | |
| 3973 | - let (body_value, stream_id) = match body { | |
| 3974 | - RequestBody::Bytes(bytes) => { | |
| 3975 | - (bytes_value(tc, bytes.into()), v8::null(tc).into()) | |
| 3976 | - } | |
| 3977 | - RequestBody::Stream(id) => ( | |
| 3978 | - v8::undefined(tc).into(), | |
| 3979 | - v8::Number::new(tc, id as f64).into(), | |
| 3980 | - ), | |
| 3981 | - }; | |
| 3982 | - let arguments = [ | |
| 3983 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 3984 | - v8::String::new(tc, &url).unwrap().into(), | |
| 3985 | - v8::String::new(tc, &method).unwrap().into(), | |
| 3986 | - body_value, | |
| 3987 | - v8::String::new(tc, &serde_json::to_string(&headers)?) | |
| 3988 | - .unwrap() | |
| 3989 | - .into(), | |
| 3990 | - match request_id { | |
| 3991 | - Some(id) => v8::String::new(tc, &request_id_string(id)).unwrap().into(), | |
| 3992 | - None => v8::null(tc).into(), | |
| 3993 | - }, | |
| 3994 | - stream_id, | |
| 3995 | - ]; | |
| 3996 | - let recv = v8::undefined(tc).into(); | |
| 3997 | - f.call(tc, recv, &arguments) | |
| 3998 | - .ok_or_else(|| anyhow!("dispatchTo threw")) | |
| 3999 | - }, | |
| 4000 | - ) | |
| 4001 | - } | |
| 4002 | - CellJob::Rpc { | |
| 4003 | - scope, | |
| 4004 | - name, | |
| 4005 | - method, | |
| 4006 | - args, | |
| 4007 | - reply, | |
| 4008 | - } => { | |
| 4009 | - if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) { | |
| 4010 | - let _ = reply.send(Err(error)); | |
| 4011 | - return Begun::Nothing; | |
| 4012 | - } | |
| 4013 | - start_cell_event( | |
| 4014 | - tc, | |
| 4015 | - &scope, | |
| 4016 | - Answer::CellRpc(reply), | |
| 4017 | - None, | |
| 4018 | - None, | |
| 4019 | - false, | |
| 4020 | - |tc| { | |
| 4021 | - let f = dispatcher(tc, "__dispatchRpc")?; | |
| 4022 | - let arguments = [ | |
| 4023 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 4024 | - v8::String::new(tc, &method).unwrap().into(), | |
| 4025 | - rpc_data_value(tc, args), | |
| 4026 | - ]; | |
| 4027 | - let recv = v8::undefined(tc).into(); | |
| 4028 | - f.call(tc, recv, &arguments) | |
| 4029 | - .ok_or_else(|| anyhow!("dispatchRpc threw")) | |
| 4030 | - }, | |
| 4031 | - ) | |
| 4032 | - } | |
| 4033 | - CellJob::WsOpen { | |
| 4034 | - scope, | |
| 4035 | - ws_id, | |
| 4036 | - protocol, | |
| 4037 | - reply, | |
| 4038 | - } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| { | |
| 4039 | - let f = dispatcher(tc, "__wsOpen")?; | |
| 4040 | - let arguments = [ | |
| 4041 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 4042 | - v8::Number::new(tc, ws_id as f64).into(), | |
| 4043 | - v8::String::new(tc, &protocol).unwrap().into(), | |
| 4044 | - ]; | |
| 4045 | - let recv = v8::undefined(tc).into(); | |
| 4046 | - f.call(tc, recv, &arguments) | |
| 4047 | - .ok_or_else(|| anyhow!("wsOpen threw")) | |
| 4048 | - }), | |
| 4049 | - CellJob::WsMessage { | |
| 4050 | - scope, | |
| 4051 | - ws_id, | |
| 4052 | - data, | |
| 4053 | - reply, | |
| 4054 | - } => start_cell_event( | |
| 4055 | - tc, | |
| 4056 | - &scope, | |
| 4057 | - Answer::WsMessage(reply), | |
| 4058 | - None, | |
| 4059 | - None, | |
| 4060 | - true, | |
| 4061 | - |tc| { | |
| 4062 | - let (name, data) = match data { | |
| 4063 | - WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()), | |
| 4064 | - WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)), | |
| 4065 | - }; | |
| 4066 | - let f = dispatcher(tc, name)?; | |
| 4067 | - let arguments = [ | |
| 4068 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 4069 | - v8::Number::new(tc, ws_id as f64).into(), | |
| 4070 | - data, | |
| 4071 | - ]; | |
| 4072 | - let recv = v8::undefined(tc).into(); | |
| 4073 | - f.call(tc, recv, &arguments) | |
| 4074 | - .ok_or_else(|| anyhow!("WebSocket message dispatch threw")) | |
| 4075 | - }, | |
| 4076 | - ), | |
| 4077 | - CellJob::WsClosed { | |
| 4078 | - scope, | |
| 4079 | - ws_id, | |
| 4080 | - code, | |
| 4081 | - reason, | |
| 4082 | - was_clean, | |
| 4083 | - reply, | |
| 4084 | - } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| { | |
| 4085 | - let f = dispatcher(tc, "__wsClosed")?; | |
| 4086 | - let arguments = [ | |
| 4087 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 4088 | - v8::Number::new(tc, ws_id as f64).into(), | |
| 4089 | - v8::Number::new(tc, f64::from(code)).into(), | |
| 4090 | - v8::String::new(tc, &reason).unwrap().into(), | |
| 4091 | - v8::Boolean::new(tc, was_clean).into(), | |
| 4092 | - ]; | |
| 4093 | - let recv = v8::undefined(tc).into(); | |
| 4094 | - f.call(tc, recv, &arguments) | |
| 4095 | - .ok_or_else(|| anyhow!("wsClosed threw")) | |
| 4096 | - }), | |
| 4097 | - CellJob::Alarm { | |
| 4098 | - scope, | |
| 4099 | - scheduled_ms, | |
| 4100 | - claim, | |
| 4101 | - reply, | |
| 4102 | - } => begin_alarm(tc, &scope, scheduled_ms, claim, reply), | |
| 4103 | - #[cfg(celld_internal_tests)] | |
| 4104 | - CellJob::SyncErrorForTest { | |
| 4105 | - scope, | |
| 4106 | - gate, | |
| 4107 | - socket_id, | |
| 4108 | - terminate, | |
| 4109 | - reply, | |
| 4110 | - } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| { | |
| 4111 | - register_arm_gate_with_current_event(gate, installed_context()); | |
| 4112 | - if let Some(socket_id) = socket_id { | |
| 4113 | - current_context().sockets.lock().unwrap().push(socket_id); | |
| 4114 | - } | |
| 4115 | - if terminate { | |
| 4116 | - let state = actor_runtime_state(tc); | |
| 4117 | - *state.termination.lock().expect("termination lock poisoned") = | |
| 4118 | - Some(ExecutionTermination { | |
| 4119 | - error: "synchronous V8 termination sentinel".to_string(), | |
| 4120 | - actor_scope: None, | |
| 4121 | - }); | |
| 4122 | - tc.terminate_execution(); | |
| 4123 | - Err(anyhow!("generic synchronous dispatch failure")) | |
| 4124 | - } else { | |
| 4125 | - Err(anyhow!("synchronous cell dispatch sentinel")) | |
| 4126 | - } | |
| 4127 | - }), | |
| 4128 | - } | |
| 4129 | -} | |
| 4130 | - | |
| 4131 | -/// Start an alarm, claiming the due entry so nothing else fires it. | |
| 4132 | -/// | |
| 4133 | -/// The claim is recorded on the entry rather than closed here, because the | |
| 4134 | -/// handler has not run yet: the outcome is known only when the event ends, | |
| 4135 | -/// which is now many turns away. | |
| 4136 | -fn begin_alarm( | |
| 4137 | - tc: &mut v8::PinScope, | |
| 4138 | - scope: &str, | |
| 4139 | - scheduled_ms: i64, | |
| 4140 | - claim: AlarmDispatch, | |
| 4141 | - reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 4142 | -) -> Begun { | |
| 4143 | - let now = unix_now_ms(); | |
| 4144 | - if now < scheduled_ms { | |
| 4145 | - let _ = reply.send(Err(anyhow!("alarm dispatched before its deadline"))); | |
| 4146 | - return Begun::Nothing; | |
| 4147 | - } | |
| 4148 | - #[cfg(celld_internal_tests)] | |
| 4149 | - if let AlarmDispatch::Claimed(retry) = claim { | |
| 4150 | - let Some(scheduled_at) = storage::active_alarm_scheduled_time(scope) else { | |
| 4151 | - let _ = reply.send(Err(anyhow!("alarm dispatched without a claim"))); | |
| 4152 | - return Begun::Nothing; | |
| 4153 | - }; | |
| 4154 | - return fire_alarm_handler(tc, scope, scheduled_at, retry, None, reply); | |
| 4155 | - } | |
| 4156 | - let due_by = match claim { | |
| 4157 | - #[cfg(celld_internal_tests)] | |
| 4158 | - AlarmDispatch::Armed => i64::MAX, | |
| 4159 | - AlarmDispatch::Due => now, | |
| 4160 | - #[cfg(celld_internal_tests)] | |
| 4161 | - AlarmDispatch::Claimed(_) => unreachable!("claimed alarms return above"), | |
| 4162 | - }; | |
| 4163 | - let Some((scheduled_at, retry)) = storage::due_alarm_entry(scope, due_by) else { | |
| 4164 | - // Nothing is due: another dispatch already ran it, or the handler | |
| 4165 | - // that armed it cleared it. Answer what stands now, with no delta — | |
| 4166 | - // no handler ran, so there is nothing written to prove. | |
| 4167 | - let _ = reply.send(Ok((storage::get_alarm(scope), None))); | |
| 4168 | - return Begun::Nothing; | |
| 4169 | - }; | |
| 4170 | - storage::begin_alarm_handler(scope, scheduled_at); | |
| 4171 | - fire_alarm_handler( | |
| 4172 | - tc, | |
| 4173 | - scope, | |
| 4174 | - scheduled_at, | |
| 4175 | - retry, | |
| 4176 | - Some(AlarmClaim { now_ms: now }), | |
| 4177 | - reply, | |
| 4178 | - ) | |
| 4179 | -} | |
| 4180 | - | |
| 4181 | -/// Call `alarm()`, carrying whatever claim its outcome must close. | |
| 4182 | -fn fire_alarm_handler( | |
| 4183 | - tc: &mut v8::PinScope, | |
| 4184 | - scope: &str, | |
| 4185 | - scheduled_at: i64, | |
| 4186 | - retry: i64, | |
| 4187 | - claim: Option<AlarmClaim>, | |
| 4188 | - reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 4189 | -) -> Begun { | |
| 4190 | - let begun = start_cell_event(tc, scope, Answer::Alarm(reply), None, None, false, |tc| { | |
| 4191 | - let f = dispatcher(tc, "__fireAlarm")?; | |
| 4192 | - let arguments = [ | |
| 4193 | - v8::String::new(tc, scope).unwrap().into(), | |
| 4194 | - v8::Number::new(tc, scheduled_at as f64).into(), | |
| 4195 | - v8::Number::new(tc, retry as f64).into(), | |
| 4196 | - ]; | |
| 4197 | - let recv = v8::undefined(tc).into(); | |
| 4198 | - f.call(tc, recv, &arguments) | |
| 4199 | - .ok_or_else(|| anyhow!("alarm threw")) | |
| 4200 | - }); | |
| 4201 | - match begun { | |
| 4202 | - Begun::Running(mut entry) => { | |
| 4203 | - entry.alarm = claim; | |
| 4204 | - Begun::Running(entry) | |
| 4205 | - } | |
| 4206 | - // The dispatcher never ran, so nothing can have changed the alarm. | |
| 4207 | - // Give the claim back as a failure that does not count against the | |
| 4208 | - // retry limit: the handler is not what failed. | |
| 4209 | - begun => { | |
| 4210 | - if let Some(claim) = claim { | |
| 4211 | - storage::finish_alarm_handler_with_retry_policy(scope, false, claim.now_ms, false); | |
| 4212 | - } | |
| 4213 | - begun | |
| 4214 | - } | |
| 4215 | - } | |
| 4216 | -} | |
| 4217 | - | |
| 4218 | -/// Resolve one completed op and run the microtasks that follow, with the | |
| 4219 | -/// owning request's context current. | |
| 4220 | -/// | |
| 4221 | -/// The half of a turn that resumes a suspended request. It knows nothing | |
| 4222 | -/// about any other request: the caller has already established that this op | |
| 4223 | -/// is `entry`'s. | |
| 4224 | -fn deliver( | |
| 4225 | - tc: &mut v8::PinScope, | |
| 4226 | - entry: &mut InFlight, | |
| 4227 | - op: u64, | |
| 4228 | - res: Result<asyncrt::OpOut, String>, | |
| 4229 | -) { | |
| 4230 | - entry.ops.remove(&op); | |
| 4231 | - let guard = CurrentGuard::enter(entry.context.clone()); | |
| 4232 | - resolve_res(tc, op, res); | |
| 4233 | - tc.perform_microtask_checkpoint(); | |
| 4234 | - drop(guard); | |
| 4235 | -} | |
| 4236 | - | |
| 4237 | -/// End a request whose client has hung up, so its handler stops running. | |
| 4238 | -fn cancelled(tc: &mut v8::PinScope, entry: &mut InFlight) { | |
| 4239 | - if entry.reply.is_none() || !take_request_cancellation(entry.request_id) { | |
| 4240 | - return; | |
| 4241 | - } | |
| 4242 | - cancel(tc, entry); | |
| 4243 | -} | |
| 4244 | - | |
| 4245 | -/// End a request whose cancellation has already been taken. | |
| 4246 | -/// | |
| 4247 | -/// Split from [`cancelled`] because a suspended request observes the | |
| 4248 | -/// cancellation *outside* the isolate — the flag is host state and costs no | |
| 4249 | -/// V8 — and only then enters to act on it. | |
| 4250 | -fn cancel(tc: &mut v8::PinScope, entry: &mut InFlight) { | |
| 4251 | - let guard = CurrentGuard::enter(entry.context.clone()); | |
| 4252 | - // The id that names this request to the JS side. A stateless handler is | |
| 4253 | - // registered by the shell, and only once it suspends, so the shell holds | |
| 4254 | - // the id; a cell's dispatcher registers the request itself, so the job's | |
| 4255 | - // own id is the one to abort. Aborting the wrong one — or neither — | |
| 4256 | - // leaves the target's `request.signal` unfired while the caller is told | |
| 4257 | - // the client has gone. | |
| 4258 | - if let Some(id) = entry.active_request_id.or(entry.request_id) { | |
| 4259 | - let _ = abort_incoming_request(tc, id); | |
| 4260 | - } | |
| 4261 | - // Finishing is the shell's to undo only where the shell registered. | |
| 4262 | - if let Some(id) = entry.active_request_id { | |
| 4263 | - finish_incoming_request(tc, id); | |
| 4264 | - } | |
| 4265 | - let background = end_event_context(tc).ok().flatten(); | |
| 4266 | - entry.background = background.map(|promise| v8::Global::new(tc, promise)); | |
| 4267 | - drop(guard); | |
| 4268 | - entry.fail(anyhow!("The client has disconnected")); | |
| 4269 | - // A cancelled handler with no waitUntil work has nothing left to drive. | |
| 4270 | - // Drop its host ops now, so their guards cancel routed work. Explicit | |
| 4271 | - // waitUntil work keeps its ops and continues after the client disconnects. | |
| 4272 | - if entry.background.is_none() { | |
| 4273 | - entry.abandon(); | |
| 4274 | - } | |
| 4275 | -} | |
| 4276 | - | |
| 4277 | -/// Answer a request whose handler promise has settled, and retire its | |
| 4278 | -/// `waitUntil` work once that settles too. | |
| 4279 | -fn settle(tc: &mut v8::PinScope, entry: &mut InFlight) { | |
| 4280 | - if entry.reply.is_some() { | |
| 4281 | - let promise = v8::Local::new(tc, &entry.promise); | |
| 4282 | - match promise.state() { | |
| 4283 | - v8::PromiseState::Pending => {} | |
| 4284 | - v8::PromiseState::Fulfilled => { | |
| 4285 | - let guard = CurrentGuard::enter(entry.context.clone()); | |
| 4286 | - let value = promise.result(tc); | |
| 4287 | - entry.answer_settled(tc, value); | |
| 4288 | - if let Some(request_id) = entry.active_request_id { | |
| 4289 | - finish_incoming_request(tc, request_id); | |
| 4290 | - } | |
| 4291 | - drop(guard); | |
| 4292 | - } | |
| 4293 | - v8::PromiseState::Rejected => { | |
| 4294 | - let guard = CurrentGuard::enter(entry.context.clone()); | |
| 4295 | - let reason = reject_reason(tc, promise); | |
| 4296 | - // The handler is what failed, so an alarm's failure here | |
| 4297 | - // counts against its retry limit — unlike a budget overrun | |
| 4298 | - // or a disconnect, which `fail` records as not counting. | |
| 4299 | - entry.settle_alarm(false, true); | |
| 4300 | - let _ = end_event_context(tc); | |
| 4301 | - if let Some(request_id) = entry.active_request_id { | |
| 4302 | - finish_incoming_request(tc, request_id); | |
| 4303 | - } | |
| 4304 | - drop(guard); | |
| 4305 | - entry.fail(anyhow!("rejected: {reason}")); | |
| 4306 | - } | |
| 4307 | - } | |
| 4308 | - } | |
| 4309 | - if let Some(background) = &entry.background { | |
| 4310 | - let promise = v8::Local::new(tc, background); | |
| 4311 | - if !matches!(promise.state(), v8::PromiseState::Pending) { | |
| 4312 | - entry.background = None; | |
| 4313 | - } | |
| 4314 | - } | |
| 4315 | -} | |
| 4316 | - | |
| 4317 | -/// Begin a stateless request: build it, call the Worker's `fetch`, and hand | |
| 4318 | -/// back the promise it returned. | |
| 4319 | -/// | |
| 4320 | -/// The half of a request that runs *before* it can suspend. Split out from | |
| 4321 | -/// driving it to completion so a caller can start several and drive them | |
| 4322 | -/// together; the single-request path starts one and drives it immediately, | |
| 4323 | -/// which is what it always did. | |
| 4324 | -/// | |
| 4325 | -/// The caller owns the `IoContext` and must have it current: `__beginEvent` | |
| 4326 | -/// runs here, and the frame it pushes belongs to this request. | |
| 4327 | -fn start_fetch<'s>( | |
| 4328 | - tc: &mut v8::PinScope<'s, '_>, | |
| 4329 | - fetch: v8::Local<'s, v8::Function>, | |
| 4330 | - url: &str, | |
| 4331 | - method: &str, | |
| 4332 | - body: RequestBody, | |
| 4333 | - headers: &[(String, String)], | |
| 4334 | - request_id: Option<RequestId>, | |
| 4335 | -) -> Result<Started<'s>> { | |
| 4336 | - let req = match request_id { | |
| 4337 | - Some(_) => make_incoming_request(tc, url, method, body, headers), | |
| 4338 | - None => make_request(tc, url, method, body, headers), | |
| 4339 | - }?; | |
| 4340 | - let env = harness_env(tc)?; | |
| 4341 | - let recv = v8::undefined(tc).into(); | |
| 4342 | - let f = fetch; | |
| 4343 | - let execution_ctx = begin_event_context(tc)?; | |
| 4344 | - let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else { | |
| 4345 | - // The handler threw synchronously. Termination carries its own error; | |
| 4346 | - // otherwise the pending exception is on the caller's TryCatch, which | |
| 4347 | - // is the only scope that can read it, so it formats the message. | |
| 4348 | - let error = take_execution_termination(tc); | |
| 4349 | - let _ = end_event_context(tc); | |
| 4350 | - return match error { | |
| 4351 | - Some(error) => Err(error), | |
| 4352 | - None => Ok(Started::Threw), | |
| 4353 | - }; | |
| 4354 | - }; | |
| 4355 | - // A handler that suspends must be reachable by an abort: register it as an | |
| 4356 | - // incoming request so a client disconnect can cancel it. One that already | |
| 4357 | - // settled cannot be cancelled, so its registration is cleared instead. | |
| 4358 | - let active_request_id = match request_id { | |
| 4359 | - Some(request_id) | |
| 4360 | - if ret | |
| 4361 | - .try_cast::<v8::Promise>() | |
| 4362 | - .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) => | |
| 4363 | - { | |
| 4364 | - if let Err(error) = register_incoming_request(tc, request_id, req) { | |
| 4365 | - clear_request_cancellation(request_id); | |
| 4366 | - let _ = end_event_context(tc); | |
| 4367 | - return Err(error); | |
| 4368 | - } | |
| 4369 | - Some(request_id) | |
| 4370 | - } | |
| 4371 | - Some(request_id) => { | |
| 4372 | - clear_request_cancellation(request_id); | |
| 4373 | - None | |
| 4374 | - } | |
| 4375 | - None => None, | |
| 4376 | - }; | |
| 4377 | - Ok(Started::Running(ret, active_request_id)) | |
| 4378 | -} | |
| 4379 | - | |
| 4380 | -/// What `start_fetch` produced: a running handler, or a synchronous throw | |
| 4381 | -/// whose exception only the caller's `TryCatch` can read. | |
| 4382 | -enum Started<'s> { | |
| 4383 | - Running(v8::Local<'s, v8::Value>, Option<RequestId>), | |
| 4384 | - Threw, | |
| 4385 | -} | |
| 4386 | - | |
| 4387 | -impl Worker { | |
| 4388 | - /// Compile the worker module, wire the DO harness, and extract the entry | |
| 4389 | - /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding | |
| 4390 | - /// name to a DO class name (from wrangler metadata). | |
| 4391 | - /// | |
| 4392 | - /// The runtime builds a `WorkerConfig` directly. This cfg-gated helper | |
| 4393 | - /// constructs the same value from individual options. | |
| 4394 | - #[cfg(celld_internal_tests)] | |
| 4395 | - pub fn load(options: WorkerConfigOptions) -> Result<Worker> { | |
| 4396 | - Self::load_config(Arc::new(WorkerConfig::new(options))) | |
| 4397 | - } | |
| 4398 | - | |
| 4399 | - pub fn load_config(config: Arc<WorkerConfig>) -> Result<Worker> { | |
| 4400 | - let src = config.src.as_str(); | |
| 4401 | - let script_name = config.script_name.as_str(); | |
| 4402 | - let do_classes = config.do_classes.as_slice(); | |
| 4403 | - let node = config.node.as_str(); | |
| 4404 | - let compat = config.compat; | |
| 4405 | - let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes()); | |
| 4406 | - let mut isolate = v8::Isolate::new(params); | |
| 4407 | - // Dynamic `import()` of builtin specifiers; per-import()-call only. | |
| 4408 | - isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically); | |
| 4409 | - let original_heap_limit = isolate.get_heap_statistics().heap_size_limit(); | |
| 4410 | - let heap_limit_state = Arc::new(HeapLimitState { | |
| 4411 | - excessively_exceeded: AtomicBool::new(false), | |
| 4412 | - limit: original_heap_limit, | |
| 4413 | - last_gc_nudge: Mutex::new(None), | |
| 4414 | - #[cfg(celld_internal_tests)] | |
| 4415 | - forced_admission_refusal: AtomicBool::new(false), | |
| 4416 | - }); | |
| 4417 | - let runtime_state = Arc::new(ActorRuntimeState { | |
| 4418 | - promises: std::sync::Mutex::new(PromiseMap::new()), | |
| 4419 | - egress: config.egress, | |
| 4420 | - ..Default::default() | |
| 4421 | - }); | |
| 4422 | - let loader_owner = LoaderOwner::fresh(); | |
| 4423 | - let heap_limit_state_ptr = | |
| 4424 | - Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void; | |
| 4425 | - isolate.set_slot(heap_limit_state); | |
| 4426 | - isolate.set_slot(runtime_state.clone()); | |
| 4427 | - isolate.set_slot(Arc::new(ModuleRegistry::default())); | |
| 4428 | - isolate.set_slot(loader_owner); | |
| 4429 | - isolate.set_slot(crate::generation::GenerationTag(config.generation)); | |
| 4430 | - isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr); | |
| 4431 | - let (context, fetch) = { | |
| 4432 | - v8::scope!(let hs, &mut isolate); | |
| 4433 | - let context = v8::Context::new(hs, Default::default()); | |
| 4434 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 4435 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 4436 | - let scope = &mut tc.init(); | |
| 4437 | - | |
| 4438 | - install_ops(scope, context); | |
| 4439 | - install_prelude(scope)?; // Web Platform APIs | |
| 4440 | - install_harness(scope)?; // DO object model + minimal Response | |
| 4441 | - install_lazy_globals(scope)?; | |
| 4442 | - // A global, so it must exist before the module evaluates: bundles | |
| 4443 | - // read Cloudflare.compatibilityFlags at module scope. | |
| 4444 | - inject_compatibility_flags(scope, compat)?; | |
| 4445 | - inject_storage_compatibility(scope, compat)?; | |
| 4446 | - | |
| 4447 | - let module = match compile_module(scope, "worker.js", src) { | |
| 4448 | - Some(m) => m, | |
| 4449 | - None => return Err(anyhow!("compile: {}", exc!(scope))), | |
| 4450 | - }; | |
| 4451 | - register_stubs(scope, &config); // cloudflare:*/node:* + text modules | |
| 4452 | - register_wasm_modules(scope, &config.modules); | |
| 4453 | - register_loader_modules(scope, &config); | |
| 4454 | - module | |
| 4455 | - .instantiate_module(scope, resolve_external) | |
| 4456 | - .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?; | |
| 4457 | - let ev = match module.evaluate(scope) { | |
| 4458 | - Some(value) => value, | |
| 4459 | - None => { | |
| 4460 | - if let Some(error) = take_execution_termination(scope) { | |
| 4461 | - return Err(error); | |
| 4462 | - } | |
| 4463 | - return Err(anyhow!("evaluate: {}", exc!(scope))); | |
| 4464 | - } | |
| 4465 | - }; | |
| 4466 | - if let Some(error) = take_execution_termination(scope) { | |
| 4467 | - return Err(error); | |
| 4468 | - } | |
| 4469 | - if let Ok(p) = ev.try_cast::<v8::Promise>() { | |
| 4470 | - if p.state() == v8::PromiseState::Rejected { | |
| 4471 | - let r = p.result(scope); | |
| 4472 | - let stk = r | |
| 4473 | - .to_object(scope) | |
| 4474 | - .and_then(|o| { | |
| 4475 | - let k = v8::String::new(scope, "stack")?; | |
| 4476 | - o.get(scope, k.into()) | |
| 4477 | - }) | |
| 4478 | - .map(|s| s.to_rust_string_lossy(scope)) | |
| 4479 | - .unwrap_or_default(); | |
| 4480 | - return Err(anyhow!( | |
| 4481 | - "top-level rejected: {} | {}", | |
| 4482 | - r.to_rust_string_lossy(scope), | |
| 4483 | - stk.lines().take(4).collect::<Vec<_>>().join(" <- ") | |
| 4484 | - )); | |
| 4485 | - } | |
| 4486 | - } | |
| 4487 | - | |
| 4488 | - let ns = module | |
| 4489 | - .get_module_namespace() | |
| 4490 | - .to_object(scope) | |
| 4491 | - .ok_or_else(|| anyhow!("ns"))?; | |
| 4492 | - | |
| 4493 | - // register each exported DO class into the harness registry | |
| 4494 | - for cn in do_classes { | |
| 4495 | - // The D1 class is the runtime's own and is never a worker | |
| 4496 | - // export. It is in `do_classes` so that it gets a namespace | |
| 4497 | - // key; reading it off the module namespace would find | |
| 4498 | - // `undefined` and overwrite the harness's registration. | |
| 4499 | - if crate::deploy::is_reserved_class(cn) { | |
| 4500 | - continue; | |
| 4501 | - } | |
| 4502 | - let key = v8::String::new(scope, cn).unwrap(); | |
| 4503 | - let cls = ns | |
| 4504 | - .get(scope, key.into()) | |
| 4505 | - .ok_or_else(|| anyhow!("DO class {cn} not exported"))?; | |
| 4506 | - register_class(scope, cn, cls)?; | |
| 4507 | - } | |
| 4508 | - inject_namespace_keys(scope, script_name, do_classes)?; | |
| 4509 | - inject_crons(scope, &config.crons)?; | |
| 4510 | - inject_workflows(scope, script_name, &config.workflow_bindings)?; | |
| 4511 | - inject_kv_limits(scope)?; | |
| 4512 | - inject_queue_config(scope, &config)?; | |
| 4513 | - populate_cf_exports(scope, ns, do_classes)?; | |
| 4514 | - register_entrypoints(scope, ns)?; | |
| 4515 | - validate_workflow_classes(scope, ns, &config.workflow_bindings)?; | |
| 4516 | - // build env from bindings and stash it in the harness | |
| 4517 | - build_env(scope, &config)?; | |
| 4518 | - // tell the harness which cells are local (route the rest cross-node) | |
| 4519 | - inject_routing(scope, node)?; | |
| 4520 | - | |
| 4521 | - // entry fetch | |
| 4522 | - let dk = v8::String::new(scope, "default").unwrap(); | |
| 4523 | - let default = ns | |
| 4524 | - .get(scope, dk.into()) | |
| 4525 | - .ok_or_else(|| anyhow!("no default export"))? | |
| 4526 | - .to_object(scope) | |
| 4527 | - .ok_or_else(|| anyhow!("default not object"))?; | |
| 4528 | - let fk = v8::String::new(scope, "fetch").unwrap(); | |
| 4529 | - let fetch_value = default | |
| 4530 | - .get(scope, fk.into()) | |
| 4531 | - .ok_or_else(|| anyhow!("no fetch"))?; | |
| 4532 | - let default_is_entrypoint = | |
| 4533 | - default.is_function() && cell_registry_has(scope, "entrypoints", "default")?; | |
| 4534 | - let class_fetch = default_is_entrypoint | |
| 4535 | - && default | |
| 4536 | - .get(scope, v8::String::new(scope, "prototype").unwrap().into()) | |
| 4537 | - .and_then(|prototype| prototype.to_object(scope)) | |
| 4538 | - .and_then(|prototype| prototype.get(scope, fk.into())) | |
| 4539 | - .is_some_and(|handler| handler.is_function()); | |
| 4540 | - let qk = v8::String::new(scope, "queue").unwrap(); | |
| 4541 | - let own_queue = default | |
| 4542 | - .get(scope, qk.into()) | |
| 4543 | - .is_some_and(|handler| handler.is_function()); | |
| 4544 | - let class_queue = default_is_entrypoint | |
| 4545 | - && default | |
| 4546 | - .get(scope, v8::String::new(scope, "prototype").unwrap().into()) | |
| 4547 | - .and_then(|prototype| prototype.to_object(scope)) | |
| 4548 | - .and_then(|prototype| prototype.get(scope, qk.into())) | |
| 4549 | - .is_some_and(|handler| handler.is_function()); | |
| 4550 | - let has_queue_handler = own_queue || class_queue; | |
| 4551 | - anyhow::ensure!( | |
| 4552 | - !config.declares_queue_consumer || has_queue_handler, | |
| 4553 | - "queue consumer has no queue handler" | |
| 4554 | - ); | |
| 4555 | - let f: v8::Local<v8::Function> = if fetch_value.is_function() { | |
| 4556 | - fetch_value.try_into().expect("function casts to Function") | |
| 4557 | - } else if default_is_entrypoint && class_fetch { | |
| 4558 | - // A class-based default entrypoint (extends WorkerEntrypoint) | |
| 4559 | - // keeps fetch on the prototype, so route through the | |
| 4560 | - // harness's cached instance like a named entrypoint. Only a | |
| 4561 | - // registered entrypoint dispatches that way — any other | |
| 4562 | - // callable would load fine and then 500 on every request. | |
| 4563 | - compile_fn( | |
| 4564 | - scope, | |
| 4565 | - "(req) => globalThis.__dispatchEntrypointFetch('default', req)", | |
| 4566 | - )? | |
| 4567 | - } else if default.is_function() && cell_registry_has(scope, "doExports", "default")? { | |
| 4568 | - return Err(anyhow!( | |
| 4569 | - "the default export is a Durable Object class; export a fetch \ | |
| 4570 | - handler or a WorkerEntrypoint class as the default" | |
| 4571 | - )); | |
| 4572 | - } else if config.declares_queue_consumer { | |
| 4573 | - // A push-consumer Worker needs no HTTP handler. Keep the | |
| 4574 | - // stateless pool's fetch slot total, but fail closed if this | |
| 4575 | - // deployment becomes the fleet's HTTP entry point. Test the | |
| 4576 | - // prototype above before the entrypoint fallback below: a | |
| 4577 | - // queue-only class is still a registered entrypoint, but | |
| 4578 | - // routing fetch through it throws instead of returning 404. | |
| 4579 | - compile_fn(scope, "() => new Response('Not found', { status: 404 })")? | |
| 4580 | - } else if default_is_entrypoint { | |
| 4581 | - // Preserve an RPC-only default entrypoint. Its HTTP path | |
| 4582 | - // reports the harness's specific missing-fetch error, while | |
| 4583 | - // its named methods remain callable through RPC. | |
| 4584 | - compile_fn( | |
| 4585 | - scope, | |
| 4586 | - "(req) => globalThis.__dispatchEntrypointFetch('default', req)", | |
| 4587 | - )? | |
| 4588 | - } else { | |
| 4589 | - return Err(anyhow!("fetch not fn")); | |
| 4590 | - }; | |
| 4591 | - | |
| 4592 | - // Lets a self-targeted service binding invoke the handler in | |
| 4593 | - // this isolate instead of crossing to a pool thread. | |
| 4594 | - { | |
| 4595 | - let cell_key = static_key(scope, &v8_strings::CELL); | |
| 4596 | - if let Some(cell) = context | |
| 4597 | - .global(scope) | |
| 4598 | - .get(scope, cell_key.into()) | |
| 4599 | - .and_then(|value| value.to_object(scope)) | |
| 4600 | - { | |
| 4601 | - let key = v8::String::new(scope, "selfFetch").unwrap(); | |
| 4602 | - cell.set(scope, key.into(), f.into()); | |
| 4603 | - // Optional scheduled handler, reached by a self-targeted | |
| 4604 | - // service binding's scheduled(). | |
| 4605 | - let sk = v8::String::new(scope, "scheduled").unwrap(); | |
| 4606 | - let key_ = v8::String::new(scope, "selfScheduled").unwrap(); | |
| 4607 | - let own = default | |
| 4608 | - .get(scope, sk.into()) | |
| 4609 | - .filter(|handler| handler.is_function()); | |
| 4610 | - if let Some(handler) = own { | |
| 4611 | - cell.set(scope, key_.into(), handler); | |
| 4612 | - } else if default_is_entrypoint { | |
| 4613 | - // A class-based default entrypoint keeps scheduled on | |
| 4614 | - // the prototype; dispatch through the cached instance | |
| 4615 | - // like fetch above. | |
| 4616 | - let pk = v8::String::new(scope, "prototype").unwrap(); | |
| 4617 | - let proto_scheduled = default | |
| 4618 | - .get(scope, pk.into()) | |
| 4619 | - .and_then(|proto| proto.to_object(scope)) | |
| 4620 | - .and_then(|proto| proto.get(scope, sk.into())); | |
| 4621 | - if proto_scheduled.is_some_and(|handler| handler.is_function()) { | |
| 4622 | - let shim = compile_fn( | |
| 4623 | - scope, | |
| 4624 | - "(ctrl) => globalThis.__dispatchEntrypointScheduled('default', ctrl)", | |
| 4625 | - )?; | |
| 4626 | - cell.set(scope, key_.into(), shim.into()); | |
| 4627 | - } | |
| 4628 | - } | |
| 4629 | - } | |
| 4630 | - } | |
| 4631 | - (v8::Global::new(scope, context), v8::Global::new(scope, f)) | |
| 4632 | - }; | |
| 4633 | - Ok(Worker { | |
| 4634 | - inner: Some(WorkerIsolate { | |
| 4635 | - // Every setup scope above has closed, so nothing is entered | |
| 4636 | - // on top of this isolate and it can be handed over. | |
| 4637 | - // SAFETY: `into_shared` requires every piece of embedder | |
| 4638 | - // state hanging off this isolate to be `Send`, because it | |
| 4639 | - // migrates between threads and is dropped on whichever one | |
| 4640 | - // holds the lock last. This isolate carries exactly: | |
| 4641 | - // | |
| 4642 | - // - four slots, whose types the assertion below pins as | |
| 4643 | - // `Send + Sync`; | |
| 4644 | - // - `near_heap_limit`, a bare fn pointer whose only captured | |
| 4645 | - // state is a raw pointer into the `HeapLimitState` above; | |
| 4646 | - // - `host_import_module_dynamically`, a bare fn pointer that | |
| 4647 | - // captures nothing; | |
| 4648 | - // - a default `CreateParams` allocator, owned by V8. | |
| 4649 | - // | |
| 4650 | - // Nothing else is attached, and the assertion fails the build | |
| 4651 | - // if a slot type ever stops being thread-safe. | |
| 4652 | - // | |
| 4653 | - // 152.1.0 made this fallible. None of the four refusals can | |
| 4654 | - // hold here — this isolate is entered, is not a snapshot | |
| 4655 | - // creator, has no C++ heap, and has taken no weak handles — | |
| 4656 | - // so a refusal is a bug in the setup above, not a condition | |
| 4657 | - // to recover from. It panics with the reason named. | |
| 4658 | - isolate: unsafe { isolate.try_into_shared() } | |
| 4659 | - .unwrap_or_else(|error| panic!("cell isolate cannot be shared: {error}")), | |
| 4660 | - realm: Realm { context, fetch }, | |
| 4661 | - original_heap_limit, | |
| 4662 | - compat, | |
| 4663 | - loader_owner, | |
| 4664 | - cells: storage::Cells::default(), | |
| 4665 | - }), | |
| 4666 | - }) | |
| 4667 | - } | |
| 4668 | - | |
| 4669 | - /// Restore an idFromName() actor's human-readable identity before its | |
| 4670 | - /// constructor runs. The host calls this on activation and before a named | |
| 4671 | - /// request is dispatched. | |
| 4672 | - /// Take a cell into this isolate or give it back. | |
| 4673 | - /// | |
| 4674 | - /// Taking it opens the cell's SQLite -- which the isolate owns, not the | |
| 4675 | - /// caller -- and restores the persisted id name. Giving it back releases | |
| 4676 | - /// what the isolate holds for the residency and closes the database, so | |
| 4677 | - /// state cannot span two epochs. | |
| 4678 | - /// | |
| 4679 | - /// Dispatch does not depend on this: every cell call goes out through the | |
| 4680 | - /// host whichever isolate hosts the target. | |
| 4681 | - pub fn own_cell( | |
| 4682 | - &mut self, | |
| 4683 | - cell: &str, | |
| 4684 | - storage: Option<CellStorage<'_>>, | |
| 4685 | - ) -> Result<Option<i64>> { | |
| 4686 | - let compat = self.inner.as_ref().expect("live worker isolate").compat; | |
| 4687 | - let (mut locker, _cells) = self.lock(); | |
| 4688 | - v8::scope!(let hs, &mut *locker); | |
| 4689 | - let realm = self.realm(hs); | |
| 4690 | - let context = realm.context; | |
| 4691 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 4692 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 4693 | - adopt_cell(&mut tc.init(), cell, storage, compat) | |
| 4694 | - } | |
| 4695 | - | |
| 4696 | - /// Drain the alarm moves the last turn committed in this isolate. | |
| 4697 | - /// | |
| 4698 | - /// An alarm move is a turn output, exactly like the ops a turn starts: | |
| 4699 | - /// the drive that ran the turn reports it to the host, so a handler | |
| 4700 | - /// that arms an alarm and then awaits it is schedulable immediately, | |
| 4701 | - /// not when the request ends. A separate call rather than part of the | |
| 4702 | - /// turn methods' return because stateless turns cannot move an alarm | |
| 4703 | - /// and never pay for it. | |
| 4704 | - pub fn take_alarm_moves(&mut self) -> Vec<(String, i64)> { | |
| 4705 | - let Some(inner) = self.inner.as_mut() else { | |
| 4706 | - return Vec::new(); | |
| 4707 | - }; | |
| 4708 | - let (_locker, _cells) = inner.lock(); | |
| 4709 | - storage::take_alarm_moves() | |
| 4710 | - } | |
| 4711 | - | |
| 4712 | - pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> { | |
| 4713 | - let (mut locker, _cells) = self.lock(); | |
| 4714 | - v8::scope!(let hs, &mut *locker); | |
| 4715 | - let realm = self.realm(hs); | |
| 4716 | - let context = realm.context; | |
| 4717 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 4718 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 4719 | - register_actor_name(&mut tc.init(), scope, Some(name)) | |
| 4720 | - } | |
| 4721 | - | |
| 4722 | - /// Start a cell event's first turn. | |
| 4723 | - /// | |
| 4724 | - /// The cell counterpart of `turn_begin`: it hands back what is now in | |
| 4725 | - /// flight for `runtime::drive_cell` to pump. | |
| 4726 | - pub fn turn_begin_cell( | |
| 4727 | - &mut self, | |
| 4728 | - job: CellJob, | |
| 4729 | - trace: Option<crate::telemetry::TraceIds>, | |
| 4730 | - ) -> (Option<InFlight>, Vec<Op>) { | |
| 4731 | - let Some(inner) = self.inner.as_mut() else { | |
| 4732 | - return (None, Vec::new()); | |
| 4733 | - }; | |
| 4734 | - let (mut locker, _cells) = inner.lock(); | |
| 4735 | - inner.recover_heap(&mut locker); | |
| 4736 | - v8::scope!(let hs, &mut *locker); | |
| 4737 | - let realm = inner.realm(hs); | |
| 4738 | - let context = realm.context; | |
| 4739 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 4740 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 4741 | - let tc = &mut tc.init(); | |
| 4742 | - | |
| 4743 | - let previous = install_trace(tc, trace.as_ref()); | |
| 4744 | - let out = match begin_cell(tc, job) { | |
| 4745 | - Begun::Running(mut entry) => { | |
| 4746 | - entry.trace = trace; | |
| 4747 | - let previous_io_context = install_io_context(tc, &entry.context); | |
| 4748 | - let ops = finish_turn(tc, &mut entry); | |
| 4749 | - restore_io_context(tc, previous_io_context); | |
| 4750 | - (Some(*entry), ops) | |
| 4751 | - } | |
| 4752 | - Begun::Threw(answer) => { | |
| 4753 | - answer.fail(anyhow!("cell event threw: {}", exc!(tc))); | |
| 4754 | - (None, Vec::new()) | |
| 4755 | - } | |
| 4756 | - Begun::Nothing => (None, Vec::new()), | |
| 4757 | - }; | |
| 4758 | - restore_trace(tc, previous); | |
| 4759 | - out | |
| 4760 | - } | |
| 4761 | - | |
| 4762 | - /// Enter the isolate solely to see whether another event settled this | |
| 4763 | - /// one's promise. | |
| 4764 | - /// | |
| 4765 | - /// A promise resolved by a different entry has no waker pointing here, | |
| 4766 | - /// so the driving task cannot be told and has to look. That is why this | |
| 4767 | - /// is a poll and not an event, and it is the same reason the blocking | |
| 4768 | - /// loop woke every 10 ms. | |
| 4769 | - pub fn turn_poll(&mut self, entry: &mut InFlight) -> Vec<Op> { | |
| 4770 | - let Some(inner) = self.inner.as_mut() else { | |
| 4771 | - return Vec::new(); | |
| 4772 | - }; | |
| 4773 | - let (mut locker, _cells) = inner.lock(); | |
| 4774 | - v8::scope!(let hs, &mut *locker); | |
| 4775 | - let realm = inner.realm(hs); | |
| 4776 | - let context = realm.context; | |
| 4777 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 4778 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 4779 | - let tc = &mut tc.init(); | |
| 4780 | - | |
| 4781 | - let previous_io_context = install_io_context(tc, &entry.context); | |
| 4782 | - let previous = install_trace(tc, entry.trace.as_ref()); | |
| 4783 | - let ops = finish_turn(tc, entry); | |
| 4784 | - restore_trace(tc, previous); | |
| 4785 | - restore_io_context(tc, previous_io_context); | |
| 4786 | - ops | |
| 4787 | - } | |
| 4788 | - | |
| 4789 | - /// Enter the isolate solely to record how a claimed alarm ended. | |
| 4790 | - /// | |
| 4791 | - /// Reached only when the event ended without running JS again — a budget | |
| 4792 | - /// overrun, or a handler waiting on nothing. The bookkeeping is storage | |
| 4793 | - /// the isolate owns, so it cannot be done from the driving task. | |
| 4794 | - pub fn turn_finish_alarm(&mut self, entry: &mut InFlight) { | |
| 4795 | - let Some(inner) = self.inner.as_mut() else { | |
| 4796 | - return; | |
| 4797 | - }; | |
| 4798 | - let (_locker, _cells) = inner.lock(); | |
| 4799 | - entry.settle_alarm(false, false); | |
| 4800 | - } | |
| 4801 | -} | |
| 4802 | - | |
| 4803 | -// ---- native ops exposed to JS ---- | |
| 4804 | - | |
| 4805 | -/// Host ops, defined non-enumerable. They are runtime internals: a bundle | |
| 4806 | -/// walking `globalThis` must not find them, let alone `new` one — `for (const | |
| 4807 | -/// k in globalThis) new globalThis[k]()` used to reach `__actor_abort` and | |
| 4808 | -/// kill the actor. | |
| 4809 | -macro_rules! ops { | |
| 4810 | - ($scope:expr, $global:expr, $($name:literal => $op:path),* $(,)?) => { | |
| 4811 | - $({ | |
| 4812 | - let f = v8::Function::new($scope, $op).unwrap(); | |
| 4813 | - let k = v8::String::new($scope, $name).unwrap(); | |
| 4814 | - $global.define_own_property( | |
| 4815 | - $scope, k.into(), f.into(), v8::PropertyAttribute::DONT_ENUM); | |
| 4816 | - })* | |
| 4817 | - }; | |
| 4818 | -} | |
| 4819 | - | |
| 4820 | -fn install_ops(scope: &mut v8::PinScope, context: v8::Local<v8::Context>) { | |
| 4821 | - let global = context.global(scope); | |
| 4822 | - ops! { scope, global, | |
| 4823 | - "__heap_limit_excessively_exceeded" => | |
| 4824 | - op_heap_limit_excessively_exceeded, | |
| 4825 | - "__heap_over_admission_share" => op_heap_over_admission_share, | |
| 4826 | - "__ws_send" => websocket::op_ws_send, | |
| 4827 | - "__ws_send_binary" => websocket::op_ws_send_binary, | |
| 4828 | - "__ws_close" => websocket::op_ws_close, | |
| 4829 | - "__ws_alloc" => websocket::op_ws_alloc, | |
| 4830 | - "__ws_prepare_worker_handoff" => websocket::op_ws_prepare_worker_handoff, | |
| 4831 | - "__ws_accept" => websocket::op_ws_accept, | |
| 4832 | - "__ws_accept_regular" => websocket::op_ws_accept_regular, | |
| 4833 | - "__ws_list" => websocket::op_ws_list, | |
| 4834 | - "__ws_attachment_set" => websocket::op_ws_attachment_set, | |
| 4835 | - "__ws_auto_response_set" => websocket::op_ws_auto_response_set, | |
| 4836 | - "__ws_auto_response_get" => websocket::op_ws_auto_response_get, | |
| 4837 | - "__ws_auto_response_ts" => websocket::op_ws_auto_response_ts, | |
| 4838 | - "__ws_connect" => websocket::op_ws_connect, | |
| 4839 | - "__ws_bind_target" => websocket::op_ws_bind_target, | |
| 4840 | - "__ws_next" => websocket::op_ws_next, | |
| 4841 | - "__ws_upgrade" => websocket::op_ws_upgrade, | |
| 4842 | - "__storage_get" => storage_ops::op_storage_get, | |
| 4843 | - "__storage_get_many" => storage_ops::op_storage_get_many, | |
| 4844 | - "__sql_ingest" => storage_ops::op_sql_ingest, | |
| 4845 | - "__sql_cursor_start" => storage_ops::op_sql_cursor_start, | |
| 4846 | - "__sql_cursor_next" => storage_ops::op_sql_cursor_next, | |
| 4847 | - "__sql_cursor_close" => storage_ops::op_sql_cursor_close, | |
| 4848 | - "__sql_database_size" => storage_ops::op_sql_database_size, | |
| 4849 | - "__d1_run" => storage_ops::op_d1_run, | |
| 4850 | - "__storage_transaction_control" => storage_ops::op_storage_transaction_control, | |
| 4851 | - "__log" => op_log, | |
| 4852 | - "__storage_put" => storage_ops::op_storage_put, | |
| 4853 | - "__storage_put_many" => storage_ops::op_storage_put_many, | |
| 4854 | - "__storage_queue_put" => storage_ops::op_storage_queue_put, | |
| 4855 | - "__storage_queue_put_many" => storage_ops::op_storage_queue_put_many, | |
| 4856 | - "__storage_put_serialized" => storage_ops::op_storage_put_serialized, | |
| 4857 | - "__storage_queue_put_serialized" => storage_ops::op_storage_queue_put_serialized, | |
| 4858 | - "__storage_flush_pending_puts" => storage_ops::op_storage_flush_pending_puts, | |
| 4859 | - "__storage_cancel_pending_puts" => storage_ops::op_storage_cancel_pending_puts, | |
| 4860 | - "__actor_abort" => op_actor_abort, | |
| 4861 | - "__cron_plan" => op_cron_plan, | |
| 4862 | - "__kv_blob" => op_kv_blob, | |
| 4863 | - "__process_exit" => op_process_exit, | |
| 4864 | - "__storage_delete" => storage_ops::op_storage_delete, | |
| 4865 | - "__storage_delete_many" => storage_ops::op_storage_delete_many, | |
| 4866 | - "__storage_list" => storage_ops::op_storage_list, | |
| 4867 | - "__storage_sync_list_start" => storage_ops::op_storage_sync_list_start, | |
| 4868 | - "__storage_sync_list_next" => storage_ops::op_storage_sync_list_next, | |
| 4869 | - "__storage_delete_all" => storage_ops::op_storage_delete_all, | |
| 4870 | - "$$urlParse" => op_url_parse, | |
| 4871 | - "$$urlPatternParse" => op_urlpattern_parse, | |
| 4872 | - "$$urlPatternMatchInput" => op_urlpattern_match_input, | |
| 4873 | - "$$atob" => op_atob, | |
| 4874 | - "$$btoa" => op_btoa, | |
| 4875 | - "$$textDecoderLabel" => op_text_decoder_label, | |
| 4876 | - "$$textDecoderNew" => op_text_decoder_new, | |
| 4877 | - "$$textDecoderDecode" => op_text_decoder_decode, | |
| 4878 | - "$$textDecoderDecodeOnce" => op_text_decoder_decode_once, | |
| 4879 | - "$$textDecoderFree" => op_text_decoder_free, | |
| 4880 | - "__alarm_set" => op_alarm_set, | |
| 4881 | - "__alarm_get" => op_alarm_get, | |
| 4882 | - "__alarm_delete" => op_alarm_delete, | |
| 4883 | - "__loader_load" => op_loader_load, | |
| 4884 | - "__loader_fetch" => op_loader_fetch, | |
| 4885 | - "__loader_rpc" => op_loader_rpc, | |
| 4886 | - "__loader_drop" => op_loader_drop, | |
| 4887 | - "__do_call" => op_do_call, | |
| 4888 | - "__svc_call" => op_svc_call, | |
| 4889 | - "__svc_call_cancellable" => op_svc_call_cancellable, | |
| 4890 | - "__svc_rpc" => op_svc_rpc, | |
| 4891 | - "__queue_dispatch" => op_queue_dispatch, | |
| 4892 | - "__queue_policy" => op_queue_policy, | |
| 4893 | - "__do_call_cancellable" => op_do_call_cancellable, | |
| 4894 | - "__do_call_cancel" => op_do_call_cancel, | |
| 4895 | - "__do_id" => op_do_id, | |
| 4896 | - "__rpc_call" => op_rpc_call, | |
| 4897 | - "__sc_encode" => storage_ops::op_sc_encode, | |
| 4898 | - "__sc_decode" => storage_ops::op_sc_decode, | |
| 4899 | - "__op_fetch" => op_fetch, | |
| 4900 | - "__r2_head" => r2_ops::op_r2_head, | |
| 4901 | - "__r2_get" => r2_ops::op_r2_get, | |
| 4902 | - "__r2_put" => r2_ops::op_r2_put, | |
| 4903 | - "__r2_put_begin" => r2_ops::op_r2_put_begin, | |
| 4904 | - "__r2_put_chunk" => r2_ops::op_r2_put_chunk, | |
| 4905 | - "__r2_put_end" => r2_ops::op_r2_put_end, | |
| 4906 | - "__r2_delete" => r2_ops::op_r2_delete, | |
| 4907 | - "__r2_list" => r2_ops::op_r2_list, | |
| 4908 | - "__r2_mp_begin" => r2_ops::op_r2_mp_begin, | |
| 4909 | - "__r2_mp_resume" => r2_ops::op_r2_mp_resume, | |
| 4910 | - "__r2_mp_part" => r2_ops::op_r2_mp_part, | |
| 4911 | - "__r2_mp_complete" => r2_ops::op_r2_mp_complete, | |
| 4912 | - "__r2_mp_abort" => r2_ops::op_r2_mp_abort, | |
| 4913 | - "__asset_fetch" => op_asset_fetch, | |
| 4914 | - "__http_stream_read" => op_http_stream_read, | |
| 4915 | - "__http_stream_cancel" => op_http_stream_cancel, | |
| 4916 | - "__http_stream_tee" => op_http_stream_tee, | |
| 4917 | - "__response_stream_create" => op_response_stream_create, | |
| 4918 | - "__response_stream_write" => op_response_stream_write, | |
| 4919 | - "__response_stream_closed" => op_response_stream_closed, | |
| 4920 | - "__response_stream_close" => op_response_stream_close, | |
| 4921 | - "__op_timer" => op_timer, | |
| 4922 | - "__timer_alloc" => op_timer_alloc, | |
| 4923 | - "__gate_acquire" => op_gate_acquire, | |
| 4924 | - "__gate_wait" => op_gate_wait, | |
| 4925 | - "__gate_release" => op_gate_release, | |
| 4926 | - "__timer_cancel" => op_timer_cancel, | |
| 4927 | - "__crypto_operation" => crypto::op_crypto_operation, | |
| 4928 | - "$$randomValues" => crypto::op_webcrypto_random, | |
| 4929 | - "$$digest" => crypto::op_webcrypto_digest, | |
| 4930 | - "$$hmacSign" => crypto::op_webcrypto_hmac_sign, | |
| 4931 | - "$$hmacVerify" => crypto::op_webcrypto_hmac_verify, | |
| 4932 | - "$$aesEncrypt" => crypto::op_webcrypto_aes_encrypt, | |
| 4933 | - "$$aesDecrypt" => crypto::op_webcrypto_aes_decrypt, | |
| 4934 | - "$$pbkdf2" => crypto::op_node_pbkdf2, | |
| 4935 | - "$$hkdf" => crypto::op_node_hkdf, | |
| 4936 | - "$$timingSafeEqual" => crypto::op_timing_safe_equal, | |
| 4937 | - "__event_begin" => op_event_begin, | |
| 4938 | - "__event_end" => op_event_end, | |
| 4939 | - "__wait_until" => op_wait_until, | |
| 4940 | - "__event_depth" => op_event_depth, | |
| 4941 | - "__als_get" => op_als_get, | |
| 4942 | - "__als_set" => op_als_set, | |
| 4943 | - "__util_type_flags" => op_util_type_flags, | |
| 4944 | - "__util_constructor_name" => op_util_constructor_name, | |
| 4945 | - "__util_proxy_details" => op_util_proxy_details, | |
| 4946 | - "__util_promise_details" => op_util_promise_details, | |
| 4947 | - "__util_preview_entries" => op_util_preview_entries, | |
| 4948 | - "__builtin_module" => op_builtin_module, | |
| 4949 | - "__zlib" => zlib::op_zlib, | |
| 4950 | - "__zlib_stream_new" => zlib::op_zlib_stream_new, | |
| 4951 | - "__zlib_stream_push" => zlib::op_zlib_stream_push, | |
| 4952 | - "__zlib_stream_end" => zlib::op_zlib_stream_end, | |
| 4953 | - "__zlib_stream_drop" => zlib::op_zlib_stream_drop, | |
| 4954 | - } | |
| 4955 | - #[cfg(celld_internal_tests)] | |
| 4956 | - ops! { scope, global, | |
| 4957 | - "__test_gc" => op_test_gc, | |
| 4958 | - "__loader_count" => op_loader_count, | |
| 4959 | - "__test_set_heap_limit_excessively_exceeded" => | |
| 4960 | - op_test_set_heap_limit_excessively_exceeded, | |
| 4961 | - "__test_force_heap_admission_refusal" => | |
| 4962 | - op_test_force_heap_admission_refusal, | |
| 4963 | - "__test_heap_share" => op_test_heap_share, | |
| 4964 | - "__test_external_memory" => op_test_external_memory, | |
| 4965 | - "__test_workflow_event_consumed" => op_test_workflow_event_consumed, | |
| 4966 | - "__test_workflow_meta_created" => op_test_workflow_meta_created, | |
| 4967 | - "__test_workflow_alarm_deleted" => op_test_workflow_alarm_deleted, | |
| 4968 | - "__test_queue_dlq_accepted" => op_test_queue_dlq_accepted, | |
| 4969 | - "__test_queue_metrics_materialized" => op_test_queue_metrics_materialized, | |
| 4970 | - "__test_queue_rearm_bounded" => op_test_queue_rearm_bounded, | |
| 4971 | - "__test_queue_lease_lookup_plan" => op_test_queue_lease_lookup_plan, | |
| 4972 | - "__sql_set_max_page_count_for_test" => | |
| 4973 | - storage_ops::op_sql_set_max_page_count_for_test, | |
| 4974 | - "__sql_set_write_fault_for_test" => storage_ops::op_sql_set_write_fault_for_test, | |
| 4975 | - "__sql_set_cache_size_for_test" => storage_ops::op_sql_set_cache_size_for_test, | |
| 4976 | - "__sql_set_interrupt_fault_for_test" => | |
| 4977 | - storage_ops::op_sql_set_interrupt_fault_for_test, | |
| 4978 | - "__sql_register_nomem_function_for_test" => | |
| 4979 | - storage_ops::op_sql_register_nomem_function_for_test, | |
| 4980 | - } | |
| 4981 | -} | |
| 4982 | - | |
| 4983 | -/// `__kv_blob(requestJson, bytes?)` -> Promise<string | Uint8Array>. | |
| 4984 | -/// | |
| 4985 | -/// One op for the whole large-value path, following `__d1_run` rather than | |
| 4986 | -/// exposing get, put and sweep as three. A put copies one typed view into Rust, | |
| 4987 | -/// and a successful get resolves directly to a `Uint8Array`. JSON arrays would | |
| 4988 | -/// turn a valid 25 MiB value into millions of heap objects and crash the | |
| 4989 | -/// isolate before the bucket I/O began. | |
| 4990 | -/// | |
| 4991 | -/// JSON remains the control envelope for an absent get and a swept count. The | |
| 4992 | -/// cell scope is host-derived, so JavaScript cannot read or collect another | |
| 4993 | -/// namespace's objects by changing the request. | |
| 4994 | -fn op_kv_blob( | |
| 4995 | - scope: &mut v8::PinScope, | |
| 4996 | - args: v8::FunctionCallbackArguments, | |
| 4997 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4998 | -) { | |
| 4999 | - let request = args.get(0).to_rust_string_lossy(scope); | |
| 5000 | - let value = view_bytes(args.get(1)); | |
| 5001 | - // Bucket I/O is egress, so it waits on the same gate a service call does | |
| 5002 | - // rather than escaping the shed the node applies under pressure. | |
| 5003 | - let gate = egress_gate_request(celld_logic::Channel::Service); | |
| 5004 | - // Blob authority follows the storage installed for this exact cell | |
| 5005 | - // activation. Capturing it before enqueue prevents a later ownership | |
| 5006 | - // lookup from lending a deposed collector the new owner's epoch. | |
| 5007 | - let authority = gate | |
| 5008 | - .cell_scope() | |
| 5009 | - .and_then(|cell| storage::activation_epoch(cell).map(|epoch| (cell.to_string(), epoch))); | |
| 5010 | - let id = asyncrt::enqueue(async move { | |
| 5011 | - let (cell, activation_epoch) = | |
| 5012 | - authority.ok_or_else(|| "KV blob I/O requires active cell storage".to_string())?; | |
| 5013 | - let request: serde_json::Value = | |
| 5014 | - serde_json::from_str(&request).map_err(|error| format!("invalid request: {error}"))?; | |
| 5015 | - let field = |name: &str| -> std::result::Result<String, String> { | |
| 5016 | - request | |
| 5017 | - .get(name) | |
| 5018 | - .and_then(serde_json::Value::as_str) | |
| 5019 | - .map(str::to_string) | |
| 5020 | - .ok_or_else(|| format!("request has no {name}")) | |
| 5021 | - }; | |
| 5022 | - let mode = field("mode")?; | |
| 5023 | - await_egress_gate(gate).await?; | |
| 5024 | - let reply = match mode.as_str() { | |
| 5025 | - "prepare" => { | |
| 5026 | - let digest = field("digest")?; | |
| 5027 | - let reference = celld_logic::kv::BlobRef::v2(activation_epoch, &digest) | |
| 5028 | - .map_err(|error| error.to_string())? | |
| 5029 | - .encode(); | |
| 5030 | - serde_json::json!({ "reference": reference }) | |
| 5031 | - } | |
| 5032 | - "get" => { | |
| 5033 | - let reference = field("reference")?; | |
| 5034 | - let reference = celld_logic::kv::BlobRef::parse(&reference) | |
| 5035 | - .map_err(|error| error.to_string())?; | |
| 5036 | - if !reference.readable_by(activation_epoch) { | |
| 5037 | - return Err("a KV row references a later ownership epoch".to_string()); | |
| 5038 | - } | |
| 5039 | - let key = reference.object_key(&cell); | |
| 5040 | - match kv_blob_store()? | |
| 5041 | - .get(&key) | |
| 5042 | - .await | |
| 5043 | - .map_err(|error| error.to_string())? | |
| 5044 | - { | |
| 5045 | - Some((bytes, _etag)) => { | |
| 5046 | - return Ok(asyncrt::OpOut::Bytes(bytes.to_vec())); | |
| 5047 | - } | |
| 5048 | - None => serde_json::json!({ "found": false }), | |
| 5049 | - } | |
| 5050 | - } | |
| 5051 | - "put" => { | |
| 5052 | - let bytes = value.ok_or_else(|| "request has no byte view".to_string())?; | |
| 5053 | - let reference = field("reference")?; | |
| 5054 | - let reference = celld_logic::kv::BlobRef::parse(&reference) | |
| 5055 | - .map_err(|error| error.to_string())?; | |
| 5056 | - if !reference.writable_by(activation_epoch) { | |
| 5057 | - return Err("a new KV blob must use the active ownership epoch".to_string()); | |
| 5058 | - } | |
| 5059 | - let key = reference.object_key(&cell); | |
| 5060 | - kv_blob_store()? | |
| 5061 | - .put(&key, bytes) | |
| 5062 | - .await | |
| 5063 | - .map_err(|error| error.to_string())?; | |
| 5064 | - serde_json::json!({ "ok": true }) | |
| 5065 | - } | |
| 5066 | - "sweep" => { | |
| 5067 | - let values = request | |
| 5068 | - .get("live") | |
| 5069 | - .and_then(serde_json::Value::as_array) | |
| 5070 | - .ok_or_else(|| "request has no live blob reference list".to_string())?; | |
| 5071 | - let mut live = HashSet::new(); | |
| 5072 | - for value in values { | |
| 5073 | - let reference = value.as_str().ok_or_else(|| { | |
| 5074 | - "the live blob reference list contains a non-string".to_string() | |
| 5075 | - })?; | |
| 5076 | - let reference = celld_logic::kv::BlobRef::parse(reference) | |
| 5077 | - .map_err(|error| error.to_string())?; | |
| 5078 | - if !reference.readable_by(activation_epoch) { | |
| 5079 | - return Err( | |
| 5080 | - "the live blob reference list contains a later epoch".to_string() | |
| 5081 | - ); | |
| 5082 | - } | |
| 5083 | - if matches!(reference, celld_logic::kv::BlobRef::V2 { .. }) { | |
| 5084 | - live.insert(reference.encode()); | |
| 5085 | - } | |
| 5086 | - } | |
| 5087 | - // Mark and sweep, and the model says why it is not a refcount: | |
| 5088 | - // a crash between the blob write and the row commit leaves | |
| 5089 | - // bytes no count ever counted. The caller includes its pending | |
| 5090 | - // references because this end only needs "do not delete these". | |
| 5091 | - // Legacy blobs live outside this prefix and remain retained as | |
| 5092 | - // the safe migration cost. | |
| 5093 | - let prefix = celld_logic::kv::BlobRef::v2_object_prefix(&cell); | |
| 5094 | - let listed = kv_blob_store()? | |
| 5095 | - .list(&prefix) | |
| 5096 | - .await | |
| 5097 | - .map_err(|error| error.to_string())?; | |
| 5098 | - // Validate the complete listing before issuing one delete. A | |
| 5099 | - // malformed key must fail closed instead of turning a parsing | |
| 5100 | - // error into partial collection. | |
| 5101 | - let mut doomed = Vec::new(); | |
| 5102 | - for object in listed { | |
| 5103 | - let key = object.location.as_ref().to_string(); | |
| 5104 | - let suffix = key.strip_prefix(&prefix).ok_or_else(|| { | |
| 5105 | - "the KV blob listing returned a key outside its prefix".to_string() | |
| 5106 | - })?; | |
| 5107 | - let reference = celld_logic::kv::BlobRef::parse_object_suffix(suffix) | |
| 5108 | - .map_err(|error| error.to_string())?; | |
| 5109 | - if reference.collectable_by(activation_epoch) | |
| 5110 | - && !live.contains(&reference.encode()) | |
| 5111 | - { | |
| 5112 | - doomed.push(key); | |
| 5113 | - } | |
| 5114 | - } | |
| 5115 | - let gone = kv_blob_store()?.delete_many(&doomed).await; | |
| 5116 | - if gone.len() != doomed.len() { | |
| 5117 | - return Err(format!( | |
| 5118 | - "{} blob(s) refused deletion", | |
| 5119 | - doomed.len().saturating_sub(gone.len()) | |
| 5120 | - )); | |
| 5121 | - } | |
| 5122 | - serde_json::json!({ "removed": gone.len() }) | |
| 5123 | - } | |
| 5124 | - other => return Err(format!("unknown mode {other}")), | |
| 5125 | - }; | |
| 5126 | - Ok(asyncrt::OpOut::Str(reply.to_string())) | |
| 5127 | - }); | |
| 5128 | - rv.set(promise_for(scope, id)); | |
| 5129 | -} | |
| 5130 | - | |
| 5131 | -/// Create a JS promise for an async op `id` and return it to JS. | |
| 5132 | -fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> { | |
| 5133 | - let resolver = v8::PromiseResolver::new(scope).unwrap(); | |
| 5134 | - let promise = resolver.get_promise(scope); | |
| 5135 | - promise_store(scope, id, v8::Global::new(scope, resolver)); | |
| 5136 | - promise.into() | |
| 5137 | -} | |
| 5138 | - | |
| 5139 | -#[derive(serde::Deserialize)] | |
| 5140 | -#[serde(rename_all = "camelCase")] | |
| 5141 | -struct QueueDispatchEnvelope { | |
| 5142 | - lease_id: String, | |
| 5143 | - leases: Vec<QueueLeaseRef>, | |
| 5144 | - messages: Vec<QueueWireMessage>, | |
| 5145 | - metrics: QueueWireMetrics, | |
| 5146 | -} | |
| 5147 | - | |
| 5148 | -#[derive(serde::Deserialize)] | |
| 5149 | -#[serde(rename_all = "camelCase")] | |
| 5150 | -struct QueueWireMessage { | |
| 5151 | - id: String, | |
| 5152 | - timestamp_ms: i64, | |
| 5153 | - body_base64: String, | |
| 5154 | - content_type: String, | |
| 5155 | - attempts: u16, | |
| 5156 | -} | |
| 5157 | - | |
| 5158 | -#[derive(serde::Deserialize)] | |
| 5159 | -#[serde(rename_all = "camelCase")] | |
| 5160 | -struct QueueWireMetrics { | |
| 5161 | - backlog_count: f64, | |
| 5162 | - backlog_bytes: f64, | |
| 5163 | - oldest_message_timestamp_ms: Option<i64>, | |
| 5164 | -} | |
| 5165 | - | |
| 5166 | -/// `__queue_dispatch(script, queue, envelopeJson)` persists no state itself. | |
| 5167 | -/// The Queue cell has already installed each lease; this op gates that write, | |
| 5168 | -/// then hands the batch to the host and returns. Settlement comes back as a | |
| 5169 | -/// new call to the broker, so the alarm event does not spend the consumer's | |
| 5170 | -/// admission or handler budget and several leases can run concurrently. | |
| 5171 | -fn op_queue_dispatch( | |
| 5172 | - scope: &mut v8::PinScope, | |
| 5173 | - args: v8::FunctionCallbackArguments, | |
| 5174 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5175 | -) { | |
| 5176 | - let script = args.get(0).to_rust_string_lossy(scope); | |
| 5177 | - let queue = args.get(1).to_rust_string_lossy(scope); | |
| 5178 | - let envelope: QueueDispatchEnvelope = | |
| 5179 | - match serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)) { | |
| 5180 | - Ok(envelope) => envelope, | |
| 5181 | - Err(error) => { | |
| 5182 | - return loader_throw(scope, &format!("invalid Queue dispatch envelope: {error}")) | |
| 5183 | - } | |
| 5184 | - }; | |
| 5185 | - let gate = egress_gate_request(celld_logic::Channel::Queue); | |
| 5186 | - let cell = gate.cell_scope().map(str::to_string); | |
| 5187 | - let mut messages = Vec::with_capacity(envelope.messages.len()); | |
| 5188 | - for message in envelope.messages { | |
| 5189 | - let content_type = match message.content_type.as_str() { | |
| 5190 | - "text" => QueueContentType::Text, | |
| 5191 | - "bytes" => QueueContentType::Bytes, | |
| 5192 | - "json" => QueueContentType::Json, | |
| 5193 | - "v8" => QueueContentType::V8, | |
| 5194 | - other => return loader_throw(scope, &format!("invalid Queue content type {other:?}")), | |
| 5195 | - }; | |
| 5196 | - let body = match base64::engine::general_purpose::STANDARD.decode(&message.body_base64) { | |
| 5197 | - Ok(body) => body, | |
| 5198 | - Err(error) => { | |
| 5199 | - return loader_throw(scope, &format!("invalid Queue message body: {error}")) | |
| 5200 | - } | |
| 5201 | - }; | |
| 5202 | - messages.push(QueueMessage { | |
| 5203 | - id: message.id, | |
| 5204 | - timestamp_ms: message.timestamp_ms, | |
| 5205 | - body, | |
| 5206 | - content_type, | |
| 5207 | - attempts: message.attempts, | |
| 5208 | - }); | |
| 5209 | - } | |
| 5210 | - if messages.len() != envelope.leases.len() | |
| 5211 | - || messages | |
| 5212 | - .iter() | |
| 5213 | - .zip(&envelope.leases) | |
| 5214 | - .any(|(message, lease)| message.id != lease.message_id) | |
| 5215 | - { | |
| 5216 | - return loader_throw( | |
| 5217 | - scope, | |
| 5218 | - "a Queue dispatch must carry one matching lease per message", | |
| 5219 | - ); | |
| 5220 | - } | |
| 5221 | - let request = QueueDispatchReq { | |
| 5222 | - generation: current_generation(scope), | |
| 5223 | - scope: cell.unwrap_or_default(), | |
| 5224 | - script, | |
| 5225 | - lease_id: envelope.lease_id, | |
| 5226 | - leases: envelope.leases, | |
| 5227 | - batch: QueueBatch { | |
| 5228 | - queue, | |
| 5229 | - messages, | |
| 5230 | - metrics: QueueMetrics { | |
| 5231 | - backlog_count: envelope.metrics.backlog_count, | |
| 5232 | - backlog_bytes: envelope.metrics.backlog_bytes, | |
| 5233 | - oldest_message_timestamp_ms: envelope.metrics.oldest_message_timestamp_ms, | |
| 5234 | - }, | |
| 5235 | - }, | |
| 5236 | - }; | |
| 5237 | - let id = asyncrt::enqueue(async move { | |
| 5238 | - if request.scope.is_empty() { | |
| 5239 | - return Err("Queue dispatch requires a cell event".to_string()); | |
| 5240 | - } | |
| 5241 | - gated_channel_send( | |
| 5242 | - gate, | |
| 5243 | - &QUEUE_DISPATCH_TX, | |
| 5244 | - request, | |
| 5245 | - "no Queue dispatch channel", | |
| 5246 | - ) | |
| 5247 | - .await?; | |
| 5248 | - Ok(asyncrt::OpOut::Str(String::new())) | |
| 5249 | - }); | |
| 5250 | - rv.set(promise_for(scope, id)); | |
| 5251 | -} | |
| 5252 | - | |
| 5253 | -/// One synchronous boundary for Queue policy owned by `celld-logic`. | |
| 5254 | -/// | |
| 5255 | -/// The JavaScript cell owns SQL and presentation. It sends row facts here so | |
| 5256 | -/// alarm selection, concurrency admission, generation advancement, settlement | |
| 5257 | -/// fencing, purge classification, retry precedence, and exhaustion have one | |
| 5258 | -/// production implementation rather than a tested Rust copy beside a different | |
| 5259 | -/// shipped JavaScript copy. | |
| 5260 | -fn op_queue_policy( | |
| 5261 | - scope: &mut v8::PinScope, | |
| 5262 | - args: v8::FunctionCallbackArguments, | |
| 5263 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5264 | -) { | |
| 5265 | - let request: serde_json::Value = | |
| 5266 | - match serde_json::from_str(&args.get(0).to_rust_string_lossy(scope)) { | |
| 5267 | - Ok(request) => request, | |
| 5268 | - Err(error) => { | |
| 5269 | - return loader_throw(scope, &format!("invalid Queue policy input: {error}")) | |
| 5270 | - } | |
| 5271 | - }; | |
| 5272 | - let integer = |object: &serde_json::Value, name: &str| -> Result<i64> { | |
| 5273 | - object | |
| 5274 | - .get(name) | |
| 5275 | - .and_then(serde_json::Value::as_i64) | |
| 5276 | - .ok_or_else(|| anyhow!("Queue policy input has no integer {name}")) | |
| 5277 | - }; | |
| 5278 | - let optional_integer = |object: &serde_json::Value, name: &str| -> Result<Option<i64>> { | |
| 5279 | - match object.get(name) { | |
| 5280 | - None | Some(serde_json::Value::Null) => Ok(None), | |
| 5281 | - Some(value) => value | |
| 5282 | - .as_i64() | |
| 5283 | - .map(Some) | |
| 5284 | - .ok_or_else(|| anyhow!("Queue policy input {name} is not an integer")), | |
| 5285 | - } | |
| 5286 | - }; | |
| 5287 | - let result = (|| -> Result<serde_json::Value> { | |
| 5288 | - match request.get("op").and_then(serde_json::Value::as_str) { | |
| 5289 | - Some("rearm") => Ok(serde_json::json!(celld_logic::queue::rearm( | |
| 5290 | - integer(&request, "now")?, | |
| 5291 | - optional_integer(&request, "batchDeadline")?, | |
| 5292 | - optional_integer(&request, "earliestVisible")?, | |
| 5293 | - optional_integer(&request, "earliestLeaseExpiry")?, | |
| 5294 | - optional_integer(&request, "nextSweep")?, | |
| 5295 | - ))), | |
| 5296 | - Some("capacity") => { | |
| 5297 | - let active = usize::try_from(integer(&request, "active")?) | |
| 5298 | - .map_err(|_| anyhow!("Queue active concurrency is out of range"))?; | |
| 5299 | - let maximum = u16::try_from(integer(&request, "maximum")?) | |
| 5300 | - .map_err(|_| anyhow!("Queue max concurrency is out of range"))?; | |
| 5301 | - Ok(serde_json::json!(celld_logic::queue::can_install_lease( | |
| 5302 | - active, maximum, | |
| 5303 | - ))) | |
| 5304 | - } | |
| 5305 | - Some("retries") => { | |
| 5306 | - let now = integer(&request, "now")?; | |
| 5307 | - let entries = request | |
| 5308 | - .get("entries") | |
| 5309 | - .and_then(serde_json::Value::as_array) | |
| 5310 | - .ok_or_else(|| anyhow!("Queue retry policy has no entries"))?; | |
| 5311 | - let mut results = Vec::with_capacity(entries.len()); | |
| 5312 | - for entry in entries { | |
| 5313 | - let seconds = |name: &str| -> Result<Option<u32>> { | |
| 5314 | - optional_integer(entry, name)? | |
| 5315 | - .map(|value| { | |
| 5316 | - u32::try_from(value) | |
| 5317 | - .map_err(|_| anyhow!("Queue retry {name} is out of range")) | |
| 5318 | - }) | |
| 5319 | - .transpose() | |
| 5320 | - }; | |
| 5321 | - let attempt = u16::try_from(integer(entry, "attempt")?) | |
| 5322 | - .map_err(|_| anyhow!("Queue retry attempt is out of range"))?; | |
| 5323 | - let max_retries = u16::try_from(integer(entry, "maxRetries")?) | |
| 5324 | - .map_err(|_| anyhow!("Queue maxRetries is out of range"))?; | |
| 5325 | - results.push(serde_json::json!({ | |
| 5326 | - "at": celld_logic::queue::retry_at( | |
| 5327 | - now, | |
| 5328 | - seconds("explicitSeconds")?, | |
| 5329 | - seconds("configuredSeconds")?, | |
| 5330 | - ), | |
| 5331 | - "exhausted": celld_logic::queue::exhausted(attempt, max_retries), | |
| 5332 | - })); | |
| 5333 | - } | |
| 5334 | - Ok(serde_json::Value::Array(results)) | |
| 5335 | - } | |
| 5336 | - Some("expiry") => { | |
| 5337 | - let now = integer(&request, "now")?; | |
| 5338 | - let entries = request | |
| 5339 | - .get("entries") | |
| 5340 | - .and_then(serde_json::Value::as_array) | |
| 5341 | - .ok_or_else(|| anyhow!("Queue expiry policy has no entries"))?; | |
| 5342 | - let mut results = Vec::with_capacity(entries.len()); | |
| 5343 | - for entry in entries { | |
| 5344 | - let prior_failures = u16::try_from(integer(entry, "priorFailures")?) | |
| 5345 | - .map_err(|_| anyhow!("Queue priorFailures is out of range"))?; | |
| 5346 | - let max_retries = u16::try_from(integer(entry, "maxRetries")?) | |
| 5347 | - .map_err(|_| anyhow!("Queue maxRetries is out of range"))?; | |
| 5348 | - let configured = optional_integer(entry, "configuredSeconds")? | |
| 5349 | - .map(|value| { | |
| 5350 | - u32::try_from(value) | |
| 5351 | - .map_err(|_| anyhow!("Queue retry delay is out of range")) | |
| 5352 | - }) | |
| 5353 | - .transpose()?; | |
| 5354 | - let purge = entry | |
| 5355 | - .get("purgeOnSettle") | |
| 5356 | - .and_then(serde_json::Value::as_bool) | |
| 5357 | - .ok_or_else(|| anyhow!("Queue expiry has no purgeOnSettle"))?; | |
| 5358 | - let expired = celld_logic::queue::expire_lease( | |
| 5359 | - now, | |
| 5360 | - prior_failures, | |
| 5361 | - max_retries, | |
| 5362 | - configured, | |
| 5363 | - purge, | |
| 5364 | - ); | |
| 5365 | - let action = match expired.action { | |
| 5366 | - celld_logic::queue::ExpiredLeaseAction::RetryAt(at) => { | |
| 5367 | - serde_json::json!({ "kind": "retry", "at": at }) | |
| 5368 | - } | |
| 5369 | - celld_logic::queue::ExpiredLeaseAction::Exhausted => { | |
| 5370 | - serde_json::json!({ "kind": "exhausted" }) | |
| 5371 | - } | |
| 5372 | - celld_logic::queue::ExpiredLeaseAction::DeletePurged => { | |
| 5373 | - serde_json::json!({ "kind": "delete-purged" }) | |
| 5374 | - } | |
| 5375 | - }; | |
| 5376 | - results.push(serde_json::json!({ | |
| 5377 | - "attempt": expired.attempt, | |
| 5378 | - "action": action, | |
| 5379 | - })); | |
| 5380 | - } | |
| 5381 | - Ok(serde_json::Value::Array(results)) | |
| 5382 | - } | |
| 5383 | - Some("batch") => { | |
| 5384 | - let now = integer(&request, "now")?; | |
| 5385 | - let max_batch_size = usize::try_from(integer(&request, "maxBatchSize")?) | |
| 5386 | - .map_err(|_| anyhow!("Queue maxBatchSize is out of range"))?; | |
| 5387 | - let rows = request | |
| 5388 | - .get("rows") | |
| 5389 | - .and_then(serde_json::Value::as_array) | |
| 5390 | - .ok_or_else(|| anyhow!("Queue batch policy has no rows"))?; | |
| 5391 | - let rows = rows | |
| 5392 | - .iter() | |
| 5393 | - .map(|row| { | |
| 5394 | - let generation = row | |
| 5395 | - .get("leaseGeneration") | |
| 5396 | - .and_then(serde_json::Value::as_str) | |
| 5397 | - .ok_or_else(|| anyhow!("Queue row has no leaseGeneration"))? | |
| 5398 | - .parse::<u64>() | |
| 5399 | - .context("Queue leaseGeneration is invalid")?; | |
| 5400 | - Ok(celld_logic::queue::BatchRow { | |
| 5401 | - seq: integer(row, "seq")?, | |
| 5402 | - visible_at: integer(row, "visibleAt")?, | |
| 5403 | - lease_generation: generation, | |
| 5404 | - leased_until: optional_integer(row, "leasedUntil")?, | |
| 5405 | - purge_on_settle: row | |
| 5406 | - .get("purgeOnSettle") | |
| 5407 | - .and_then(serde_json::Value::as_bool) | |
| 5408 | - .ok_or_else(|| anyhow!("Queue row has no purgeOnSettle"))?, | |
| 5409 | - }) | |
| 5410 | - }) | |
| 5411 | - .collect::<Result<Vec<_>>>()?; | |
| 5412 | - let plan = celld_logic::queue::batch_plan(now, &rows, max_batch_size)?; | |
| 5413 | - Ok(serde_json::json!({ | |
| 5414 | - "leases": plan.leases.into_iter().map(|lease| serde_json::json!({ | |
| 5415 | - "seq": lease.seq, | |
| 5416 | - "generation": lease.generation.to_string(), | |
| 5417 | - "reclaimed": lease.reclaimed, | |
| 5418 | - })).collect::<Vec<_>>(), | |
| 5419 | - "deletePurged": plan.delete_purged, | |
| 5420 | - })) | |
| 5421 | - } | |
| 5422 | - Some("settlement") => { | |
| 5423 | - #[cfg(celld_internal_tests)] | |
| 5424 | - QUEUE_SETTLEMENT_POLICY_OBSERVED.with(|observed| observed.set(true)); | |
| 5425 | - | |
| 5426 | - let members = |name: &str| -> Result<Vec<celld_logic::queue::LeaseMember<'_>>> { | |
| 5427 | - request | |
| 5428 | - .get(name) | |
| 5429 | - .and_then(serde_json::Value::as_array) | |
| 5430 | - .ok_or_else(|| anyhow!("Queue settlement policy has no {name}"))? | |
| 5431 | - .iter() | |
| 5432 | - .map(|member| { | |
| 5433 | - let string = |field: &str| -> Result<&str> { | |
| 5434 | - member | |
| 5435 | - .get(field) | |
| 5436 | - .and_then(serde_json::Value::as_str) | |
| 5437 | - .ok_or_else(|| { | |
| 5438 | - anyhow!("Queue settlement member has no {field}") | |
| 5439 | - }) | |
| 5440 | - }; | |
| 5441 | - Ok(celld_logic::queue::LeaseMember { | |
| 5442 | - seq: string("seq")? | |
| 5443 | - .parse::<i64>() | |
| 5444 | - .context("Queue settlement sequence is invalid")?, | |
| 5445 | - message_id: string("messageId")?, | |
| 5446 | - generation: string("generation")? | |
| 5447 | - .parse::<u64>() | |
| 5448 | - .context("Queue settlement generation is invalid")?, | |
| 5449 | - }) | |
| 5450 | - }) | |
| 5451 | - .collect() | |
| 5452 | - }; | |
| 5453 | - let current = members("current")?; | |
| 5454 | - let submitted = members("submitted")?; | |
| 5455 | - Ok(serde_json::json!(celld_logic::queue::settlement_matches( | |
| 5456 | - ¤t, &submitted, | |
| 5457 | - ))) | |
| 5458 | - } | |
| 5459 | - Some("purge") => { | |
| 5460 | - let now = integer(&request, "now")?; | |
| 5461 | - let rows = request | |
| 5462 | - .get("rows") | |
| 5463 | - .and_then(serde_json::Value::as_array) | |
| 5464 | - .ok_or_else(|| anyhow!("Queue purge policy has no rows"))? | |
| 5465 | - .iter() | |
| 5466 | - .map(|row| { | |
| 5467 | - Ok(celld_logic::queue::PurgeRow { | |
| 5468 | - seq: row | |
| 5469 | - .get("seq") | |
| 5470 | - .and_then(serde_json::Value::as_str) | |
| 5471 | - .ok_or_else(|| anyhow!("Queue purge row has no sequence"))? | |
| 5472 | - .parse::<i64>() | |
| 5473 | - .context("Queue purge sequence is invalid")?, | |
| 5474 | - lease_id_present: row | |
| 5475 | - .get("leaseIdPresent") | |
| 5476 | - .and_then(serde_json::Value::as_bool) | |
| 5477 | - .ok_or_else(|| anyhow!("Queue purge row has no lease state"))?, | |
| 5478 | - leased_until: optional_integer(row, "leasedUntil")?, | |
| 5479 | - }) | |
| 5480 | - }) | |
| 5481 | - .collect::<Result<Vec<_>>>()?; | |
| 5482 | - let plan = celld_logic::queue::purge_plan(now, &rows); | |
| 5483 | - Ok(serde_json::json!({ | |
| 5484 | - "delete": plan.delete.into_iter().map(|seq| seq.to_string()).collect::<Vec<_>>(), | |
| 5485 | - "markForSettle": plan.mark_for_settle.into_iter().map(|seq| seq.to_string()).collect::<Vec<_>>(), | |
| 5486 | - })) | |
| 5487 | - } | |
| 5488 | - Some(other) => Err(anyhow!("unknown Queue policy operation {other:?}")), | |
| 5489 | - None => Err(anyhow!("Queue policy input has no op")), | |
| 5490 | - } | |
| 5491 | - })(); | |
| 5492 | - match result { | |
| 5493 | - Ok(value) => { | |
| 5494 | - let value = v8::String::new(scope, &value.to_string()).unwrap(); | |
| 5495 | - rv.set(value.into()); | |
| 5496 | - } | |
| 5497 | - Err(error) => loader_throw(scope, &error.to_string()), | |
| 5498 | - } | |
| 5499 | -} | |
| 5500 | - | |
| 5501 | -/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await | |
| 5502 | -/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON | |
| 5503 | -/// `{status, body, headers}` string the harness turns back into a Response. | |
| 5504 | -/// `__svc_rpc(script, entrypoint, method, argsSc)` -> Promise<Uint8Array>; | |
| 5505 | -/// arguments and result are V8 structured-clone bytes. | |
| 5506 | -/// The application generation the calling isolate was built for, from the | |
| 5507 | -/// slot `load_config` installs. Zero for an isolate built outside any | |
| 5508 | -/// generation, which the runtime resolves as the current one. | |
| 5509 | -fn current_generation(scope: &mut v8::PinScope) -> crate::generation::GenerationId { | |
| 5510 | - scope | |
| 5511 | - .get_slot::<crate::generation::GenerationTag>() | |
| 5512 | - .map(|tag| tag.0) | |
| 5513 | - .unwrap_or(0) | |
| 5514 | -} | |
| 5515 | - | |
| 5516 | -fn op_svc_rpc( | |
| 5517 | - scope: &mut v8::PinScope, | |
| 5518 | - args: v8::FunctionCallbackArguments, | |
| 5519 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5520 | -) { | |
| 5521 | - let script = args.get(0).to_rust_string_lossy(scope); | |
| 5522 | - let entrypoint = args.get(1).to_rust_string_lossy(scope); | |
| 5523 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 5524 | - let call_args = view_bytes(args.get(3)).unwrap_or_default(); | |
| 5525 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 5526 | - let gate = egress_gate_request(celld_logic::Channel::Service); | |
| 5527 | - let request = SvcRpcReq { | |
| 5528 | - generation: current_generation(scope), | |
| 5529 | - script, | |
| 5530 | - entrypoint, | |
| 5531 | - method, | |
| 5532 | - args: call_args, | |
| 5533 | - reply: tx, | |
| 5534 | - }; | |
| 5535 | - let id = asyncrt::enqueue(async move { | |
| 5536 | - gated_channel_send(gate, &SVC_RPC_TX, request, "no service binding channel").await?; | |
| 5537 | - match rx.await { | |
| 5538 | - Ok(Ok(result)) => Ok(result), | |
| 5539 | - Ok(Err(error)) => Err(format!("{error}")), | |
| 5540 | - Err(error) => Err(format!("service dropped: {error}")), | |
| 5541 | - } | |
| 5542 | - }); | |
| 5543 | - rv.set(promise_for(scope, id)); | |
| 5544 | -} | |
| 5545 | - | |
| 5546 | -/// `__svc_call(script, url, method, body, headersJson)` -> Promise<json>. | |
| 5547 | -/// The service-binding equivalent of `__do_call`: no scope to resolve and no | |
| 5548 | -/// cancellation token, just a handoff to the target script's pool. | |
| 5549 | -fn op_svc_call( | |
| 5550 | - scope: &mut v8::PinScope, | |
| 5551 | - args: v8::FunctionCallbackArguments, | |
| 5552 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5553 | -) { | |
| 5554 | - op_svc_call_impl(scope, args, &mut rv, false); | |
| 5555 | -} | |
| 5556 | - | |
| 5557 | -fn op_svc_call_cancellable( | |
| 5558 | - scope: &mut v8::PinScope, | |
| 5559 | - args: v8::FunctionCallbackArguments, | |
| 5560 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5561 | -) { | |
| 5562 | - op_svc_call_impl(scope, args, &mut rv, true); | |
| 5563 | -} | |
| 5564 | - | |
| 5565 | -fn op_svc_call_impl( | |
| 5566 | - scope: &mut v8::PinScope, | |
| 5567 | - args: v8::FunctionCallbackArguments, | |
| 5568 | - rv: &mut v8::ReturnValue<v8::Value>, | |
| 5569 | - cancellable: bool, | |
| 5570 | -) { | |
| 5571 | - let script = args.get(0).to_rust_string_lossy(scope); | |
| 5572 | - let url = args.get(1).to_rust_string_lossy(scope); | |
| 5573 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 5574 | - let stream_arg = args.get(5); | |
| 5575 | - let body = if stream_arg.is_number() { | |
| 5576 | - RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64) | |
| 5577 | - } else { | |
| 5578 | - let Some(bytes) = view_bytes(args.get(3)) else { | |
| 5579 | - return loader_throw( | |
| 5580 | - scope, | |
| 5581 | - "service binding: the request body is not a typed array", | |
| 5582 | - ); | |
| 5583 | - }; | |
| 5584 | - RequestBody::Bytes(bytes.into()) | |
| 5585 | - }; | |
| 5586 | - let headers: Vec<(String, String)> = | |
| 5587 | - match serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)) { | |
| 5588 | - Ok(headers) => headers, | |
| 5589 | - Err(error) => { | |
| 5590 | - return loader_throw( | |
| 5591 | - scope, | |
| 5592 | - &format!( | |
| 5593 | - "service binding: the request headers are not a name/value list: {error}" | |
| 5594 | - ), | |
| 5595 | - ) | |
| 5596 | - } | |
| 5597 | - }; | |
| 5598 | - let body_guard = match body.stream_id() { | |
| 5599 | - Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 5600 | - Some(guard) => guard, | |
| 5601 | - None => return loader_throw(scope, "service binding: the body stream is not owned"), | |
| 5602 | - }, | |
| 5603 | - None => RequestBodyGuard::of(&body), | |
| 5604 | - }; | |
| 5605 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 5606 | - // Shares the Durable Object cancel registry and the id encoding | |
| 5607 | - // `attach_cancel_id` writes, so `__do_call_cancel` works unchanged for a | |
| 5608 | - // service call. Only a cancellable call registers: a caller with no | |
| 5609 | - // AbortSignal has nothing that can cancel it, and the router already ends | |
| 5610 | - // the call when the reply sender drops. | |
| 5611 | - let (request_id, cancel, cancel_guard) = if cancellable { | |
| 5612 | - let request_id = next_do_request_id(); | |
| 5613 | - let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel(); | |
| 5614 | - do_call_cancels() | |
| 5615 | - .lock() | |
| 5616 | - .unwrap() | |
| 5617 | - .insert(request_id, cancel_sender); | |
| 5618 | - ( | |
| 5619 | - Some(request_id), | |
| 5620 | - Some(cancel_receiver), | |
| 5621 | - Some(DoCallCancelGuard::new(request_id)), | |
| 5622 | - ) | |
| 5623 | - } else { | |
| 5624 | - (None, None, None) | |
| 5625 | - }; | |
| 5626 | - let gate = egress_gate_request(celld_logic::Channel::Service); | |
| 5627 | - let request = SvcCallReq { | |
| 5628 | - cancel, | |
| 5629 | - generation: current_generation(scope), | |
| 5630 | - script, | |
| 5631 | - url, | |
| 5632 | - method, | |
| 5633 | - body, | |
| 5634 | - body_guard, | |
| 5635 | - headers, | |
| 5636 | - reply: tx, | |
| 5637 | - }; | |
| 5638 | - let id = asyncrt::enqueue(async move { | |
| 5639 | - let mut cancel_guard = cancel_guard; | |
| 5640 | - gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?; | |
| 5641 | - let result = match rx.await { | |
| 5642 | - Ok(Ok(response)) => Ok(encode_http_response(response, true)), | |
| 5643 | - Ok(Err(error)) => Err(format!("{error}")), | |
| 5644 | - Err(error) => Err(format!("service dropped: {error}")), | |
| 5645 | - }; | |
| 5646 | - if let Some(cancel_guard) = cancel_guard.as_mut() { | |
| 5647 | - cancel_guard.disarm(); | |
| 5648 | - } | |
| 5649 | - result | |
| 5650 | - }); | |
| 5651 | - let promise = promise_for(scope, id); | |
| 5652 | - if let Some(request_id) = request_id { | |
| 5653 | - attach_cancel_id(scope, promise, request_id); | |
| 5654 | - } | |
| 5655 | - rv.set(promise); | |
| 5656 | -} | |
| 5657 | - | |
| 5658 | -// --- Worker Loader: dynamic isolates for Code Mode --- | |
| 5659 | -// A running Worker creates a fresh isolate from code it supplies at runtime | |
| 5660 | -// and invokes it. The loaded isolate uses the same turn driver as every | |
| 5661 | -// stateless Worker, so an awaited operation holds no thread or isolate. | |
| 5662 | - | |
| 5663 | -// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total | |
| 5664 | -// module bytes, 1 MiB env. Messages match so the conformance cases pass. | |
| 5665 | -const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024; | |
| 5666 | -const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024; | |
| 5667 | - | |
| 5668 | -#[derive(Clone)] | |
| 5669 | -enum LoaderState { | |
| 5670 | - Loading, | |
| 5671 | - Ready(Arc<crate::pool::Slot>), | |
| 5672 | - Failed(Arc<str>), | |
| 5673 | -} | |
| 5674 | - | |
| 5675 | -#[derive(Clone, Copy, Eq, PartialEq)] | |
| 5676 | -struct LoaderOwner(u64); | |
| 5677 | - | |
| 5678 | -impl LoaderOwner { | |
| 5679 | - fn fresh() -> Self { | |
| 5680 | - Self(LOADER_NEXT_OWNER.fetch_add(1, Ordering::Relaxed)) | |
| 5681 | - } | |
| 5682 | -} | |
| 5683 | - | |
| 5684 | -#[doc(hidden)] | |
| 5685 | -pub struct LoaderEntry { | |
| 5686 | - owner: LoaderOwner, | |
| 5687 | - state: tokio::sync::watch::Receiver<LoaderState>, | |
| 5688 | -} | |
| 5689 | - | |
| 5690 | -type LoaderRegistry = HashMap<u64, LoaderEntry>; | |
| 5691 | -static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new(); | |
| 5692 | -static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1); | |
| 5693 | -static LOADER_NEXT_OWNER: AtomicU64 = AtomicU64::new(1); | |
| 5694 | - | |
| 5695 | -#[doc(hidden)] | |
| 5696 | -pub fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> { | |
| 5697 | - LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 5698 | -} | |
| 5699 | - | |
| 5700 | -/// Remove the registry references for every child of `owner`. The caller | |
| 5701 | -/// chooses when to drop the returned states, because they can own V8 isolates | |
| 5702 | -/// and no other isolate can be entered on that thread at destruction time. | |
| 5703 | -fn take_loader_owner(owner: LoaderOwner) -> Vec<tokio::sync::watch::Receiver<LoaderState>> { | |
| 5704 | - let mut registry = loader_registry().lock().unwrap(); | |
| 5705 | - let ids: Vec<u64> = registry | |
| 5706 | - .iter() | |
| 5707 | - .filter_map(|(id, entry)| (entry.owner == owner).then_some(*id)) | |
| 5708 | - .collect(); | |
| 5709 | - ids.into_iter() | |
| 5710 | - .filter_map(|id| registry.remove(&id).map(|entry| entry.state)) | |
| 5711 | - .collect() | |
| 5712 | -} | |
| 5713 | - | |
| 5714 | -fn loader_throw(scope: &mut v8::PinScope, message: &str) { | |
| 5715 | - let message = v8::String::new(scope, message).unwrap(); | |
| 5716 | - let exception = v8::Exception::error(scope, message); | |
| 5717 | - scope.throw_exception(exception); | |
| 5718 | -} | |
| 5719 | - | |
| 5720 | -async fn loaded_worker_slot( | |
| 5721 | - mut state: tokio::sync::watch::Receiver<LoaderState>, | |
| 5722 | -) -> Result<Arc<crate::pool::Slot>, String> { | |
| 5723 | - loop { | |
| 5724 | - match state.borrow().clone() { | |
| 5725 | - LoaderState::Ready(slot) => return Ok(slot), | |
| 5726 | - LoaderState::Failed(error) => return Err(error.to_string()), | |
| 5727 | - LoaderState::Loading => {} | |
| 5728 | - } | |
| 5729 | - state | |
| 5730 | - .changed() | |
| 5731 | - .await | |
| 5732 | - .map_err(|_| "worker loader: load task dropped".to_string())?; | |
| 5733 | - } | |
| 5734 | -} | |
| 5735 | - | |
| 5736 | -/// `__loader_load(codeJson)` -> stub id. Builds a WorkerConfig from the | |
| 5737 | -/// supplied modules and registers its asynchronous load state. Compilation | |
| 5738 | -/// runs on Tokio's blocking pool. Calls wait for that result and then use the | |
| 5739 | -/// normal stateless turn driver. | |
| 5740 | -fn op_loader_load( | |
| 5741 | - scope: &mut v8::PinScope, | |
| 5742 | - args: v8::FunctionCallbackArguments, | |
| 5743 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5744 | -) { | |
| 5745 | - let code_json = args.get(0).to_rust_string_lossy(scope); | |
| 5746 | - let code: serde_json::Value = match serde_json::from_str(&code_json) { | |
| 5747 | - Ok(code) => code, | |
| 5748 | - Err(e) => return loader_throw(scope, &format!("worker loader: {e}")), | |
| 5749 | - }; | |
| 5750 | - let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else { | |
| 5751 | - return loader_throw(scope, "worker loader: missing mainModule"); | |
| 5752 | - }; | |
| 5753 | - let Some(src) = code | |
| 5754 | - .get("modules") | |
| 5755 | - .and_then(|m| m.get(main)) | |
| 5756 | - .and_then(|v| v.as_str()) | |
| 5757 | - .map(str::to_string) | |
| 5758 | - else { | |
| 5759 | - return loader_throw( | |
| 5760 | - scope, | |
| 5761 | - &format!("worker loader: module {main:?} missing or not a string"), | |
| 5762 | - ); | |
| 5763 | - }; | |
| 5764 | - // Every module other than the main one is a sibling the main module may | |
| 5765 | - // import. JS modules arrive in the JSON as strings; anything else there is | |
| 5766 | - // rejected — JSON.stringify would already have mangled it, and dropping it | |
| 5767 | - // silently leaves the loaded worker failing instantiation with an | |
| 5768 | - // unresolved specifier that never names the cause. Wasm modules arrive | |
| 5769 | - // out of band as the second argument, an array of `[name, Uint8Array]` | |
| 5770 | - // pairs, which keeps the blobs out of the JSON payload entirely. | |
| 5771 | - let mut modules: Vec<(String, ModuleSource)> = Vec::new(); | |
| 5772 | - if let Some(map) = code.get("modules").and_then(|m| m.as_object()) { | |
| 5773 | - for (name, value) in map.iter().filter(|(name, _)| name.as_str() != main) { | |
| 5774 | - let Some(source) = value.as_str() else { | |
| 5775 | - return loader_throw( | |
| 5776 | - scope, | |
| 5777 | - &format!("worker loader: module {name:?} must be a string or wasm bytes"), | |
| 5778 | - ); | |
| 5779 | - }; | |
| 5780 | - modules.push((name.clone(), ModuleSource::EsModule(source.to_string()))); | |
| 5781 | - } | |
| 5782 | - } | |
| 5783 | - let sideband = args.get(1); | |
| 5784 | - if !sideband.is_undefined() { | |
| 5785 | - let Ok(entries) = v8::Local::<v8::Array>::try_from(sideband) else { | |
| 5786 | - return loader_throw(scope, "worker loader: wasm modules must be an array"); | |
| 5787 | - }; | |
| 5788 | - for index in 0..entries.length() { | |
| 5789 | - let entry = entries | |
| 5790 | - .get_index(scope, index) | |
| 5791 | - .and_then(|entry| v8::Local::<v8::Array>::try_from(entry).ok()) | |
| 5792 | - .and_then(|pair| Some((pair.get_index(scope, 0)?, pair.get_index(scope, 1)?))) | |
| 5793 | - .filter(|(name, _)| name.is_string()) | |
| 5794 | - .and_then(|(name, value)| { | |
| 5795 | - let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?; | |
| 5796 | - Some((name.to_rust_string_lossy(scope), view)) | |
| 5797 | - }); | |
| 5798 | - let Some((name, view)) = entry else { | |
| 5799 | - return loader_throw(scope, "worker loader: malformed wasm module entry"); | |
| 5800 | - }; | |
| 5801 | - // A name carried by both the JSON map and the side-band would | |
| 5802 | - // silently shadow one module with the other in the registry; | |
| 5803 | - // refuse it the way a non-string JSON module is refused. | |
| 5804 | - if name == main || modules.iter().any(|(existing, _)| *existing == name) { | |
| 5805 | - return loader_throw( | |
| 5806 | - scope, | |
| 5807 | - &format!("worker loader: duplicate module name {name:?}"), | |
| 5808 | - ); | |
| 5809 | - } | |
| 5810 | - let mut bytes = vec![0u8; view.byte_length()]; | |
| 5811 | - view.copy_contents(&mut bytes); | |
| 5812 | - modules.push((name, ModuleSource::Wasm(bytes.into()))); | |
| 5813 | - } | |
| 5814 | - } | |
| 5815 | - // Total module bytes, checked before compiling anything (the oversized | |
| 5816 | - // module is never parsed) — the extra modules are not yet loaded but do | |
| 5817 | - // count against the ceiling, as upstream. | |
| 5818 | - let code_size: usize = src.len() | |
| 5819 | - + modules | |
| 5820 | - .iter() | |
| 5821 | - .map(|(_, source)| match source { | |
| 5822 | - ModuleSource::Text(source) | ModuleSource::EsModule(source) => source.len(), | |
| 5823 | - ModuleSource::Wasm(bytes) => bytes.len(), | |
| 5824 | - }) | |
| 5825 | - .sum::<usize>(); | |
| 5826 | - if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE { | |
| 5827 | - return loader_throw( | |
| 5828 | - scope, | |
| 5829 | - &format!( | |
| 5830 | - "Dynamic Worker code size ({code_size} bytes) exceeds the \ | |
| 5831 | - maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes." | |
| 5832 | - ), | |
| 5833 | - ); | |
| 5834 | - } | |
| 5835 | - // Plain JSON `env` values merge onto the loaded worker's env; capability | |
| 5836 | - // stubs are not yet supported and would fail to serialize upstream in JS. | |
| 5837 | - let loader_env = code | |
| 5838 | - .get("env") | |
| 5839 | - .filter(|v| !v.is_null()) | |
| 5840 | - .map(|v| v.to_string()); | |
| 5841 | - if let Some(env) = &loader_env { | |
| 5842 | - if env.len() > MAX_DYNAMIC_WORKER_ENV_SIZE { | |
| 5843 | - return loader_throw( | |
| 5844 | - scope, | |
| 5845 | - &format!( | |
| 5846 | - "Dynamic Worker env size ({} bytes) exceeds the maximum \ | |
| 5847 | - allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.", | |
| 5848 | - env.len() | |
| 5849 | - ), | |
| 5850 | - ); | |
| 5851 | - } | |
| 5852 | - } | |
| 5853 | - // globalOutbound: absent inherits the caller's authority, null denies | |
| 5854 | - // ambient egress, a Fetcher (broker) is not implemented yet. | |
| 5855 | - let egress = match code.get("globalOutbound") { | |
| 5856 | - None => actor_runtime_state(scope).egress, | |
| 5857 | - Some(v) if v.is_null() => EgressPolicy::Deny, | |
| 5858 | - Some(_) => { | |
| 5859 | - return loader_throw( | |
| 5860 | - scope, | |
| 5861 | - "worker loader: globalOutbound broker is not implemented yet", | |
| 5862 | - ); | |
| 5863 | - } | |
| 5864 | - }; | |
| 5865 | - let owner = *scope | |
| 5866 | - .get_slot::<LoaderOwner>() | |
| 5867 | - .expect("Worker isolate has a Loader owner"); | |
| 5868 | - // Bound live loaded workers so a runaway agent loop cannot exhaust | |
| 5869 | - // isolates. Evicted workers (dropped stubs) free their slot. | |
| 5870 | - let max = crate::env_vars::positive_or("CELLD_MAX_LOADED_WORKERS", 256) | |
| 5871 | - .expect("validated CELLD_MAX_LOADED_WORKERS"); | |
| 5872 | - if loader_registry().lock().unwrap().len() >= max { | |
| 5873 | - return loader_throw( | |
| 5874 | - scope, | |
| 5875 | - &format!("worker loader: too many loaded workers (limit {max})"), | |
| 5876 | - ); | |
| 5877 | - } | |
| 5878 | - // Honor the WorkerCode's declared compatibility (workerd worker_compat | |
| 5879 | - // reads snake_case keys); Code Mode workers keep RPC on regardless. | |
| 5880 | - let mut compat = crate::worker_compat(&serde_json::json!({ | |
| 5881 | - "compatibility_date": code.get("compatibilityDate"), | |
| 5882 | - "compatibility_flags": code.get("compatibilityFlags"), | |
| 5883 | - })); | |
| 5884 | - compat.js_rpc = true; | |
| 5885 | - let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed); | |
| 5886 | - let config = Arc::new( | |
| 5887 | - WorkerConfig::new(WorkerConfigOptions { | |
| 5888 | - src, | |
| 5889 | - script_name: format!("__loader:{id}"), | |
| 5890 | - do_classes: Vec::new(), | |
| 5891 | - bindings: Vec::new(), | |
| 5892 | - r2_bindings: Vec::new(), | |
| 5893 | - // A loaded worker reaches D1 only if its parent injects a stub; | |
| 5894 | - // ambient bindings are exactly what Code Mode withholds. | |
| 5895 | - d1_bindings: Vec::new(), | |
| 5896 | - kv_bindings: Vec::new(), | |
| 5897 | - queue_bindings: Vec::new(), | |
| 5898 | - queue_consumers: Vec::new(), | |
| 5899 | - workflow_bindings: Vec::new(), | |
| 5900 | - ai_binding: None, | |
| 5901 | - vars: Vec::new(), | |
| 5902 | - node: String::new(), | |
| 5903 | - modules, | |
| 5904 | - compat, | |
| 5905 | - }) | |
| 5906 | - .with_egress(egress) | |
| 5907 | - .with_loader_env(loader_env), | |
| 5908 | - ); | |
| 5909 | - let handle = match tokio::runtime::Handle::try_current() { | |
| 5910 | - Ok(handle) => handle, | |
| 5911 | - Err(error) => return loader_throw(scope, &format!("worker loader: {error}")), | |
| 5912 | - }; | |
| 5913 | - let (loaded, state) = tokio::sync::watch::channel(LoaderState::Loading); | |
| 5914 | - loader_registry() | |
| 5915 | - .lock() | |
| 5916 | - .unwrap() | |
| 5917 | - .insert(id, LoaderEntry { owner, state }); | |
| 5918 | - handle.spawn(async move { | |
| 5919 | - let state = match tokio::task::spawn_blocking(move || Worker::load_config(config)).await { | |
| 5920 | - Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::standalone(worker)), | |
| 5921 | - Ok(Err(error)) => LoaderState::Failed(Arc::from(format!("{error}"))), | |
| 5922 | - Err(error) => LoaderState::Failed(Arc::from(format!( | |
| 5923 | - "worker loader: load task failed: {error}" | |
| 5924 | - ))), | |
| 5925 | - }; | |
| 5926 | - loaded.send_replace(state); | |
| 5927 | - }); | |
| 5928 | - rv.set(v8::Number::new(scope, id as f64).into()); | |
| 5929 | -} | |
| 5930 | - | |
| 5931 | -/// `__loader_fetch(id, url, method, body, headersJson)` -> Promise<json>. The | |
| 5932 | -/// loaded-worker analog of `__svc_call`: encodes the response the same way. | |
| 5933 | -fn op_loader_fetch( | |
| 5934 | - scope: &mut v8::PinScope, | |
| 5935 | - args: v8::FunctionCallbackArguments, | |
| 5936 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5937 | -) { | |
| 5938 | - let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 5939 | - let url = args.get(1).to_rust_string_lossy(scope); | |
| 5940 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 5941 | - let stream_arg = args.get(5); | |
| 5942 | - let body = if stream_arg.is_number() { | |
| 5943 | - RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64) | |
| 5944 | - } else { | |
| 5945 | - let Some(bytes) = view_bytes(args.get(3)) else { | |
| 5946 | - return loader_throw( | |
| 5947 | - scope, | |
| 5948 | - "worker loader: the request body is not a typed array", | |
| 5949 | - ); | |
| 5950 | - }; | |
| 5951 | - RequestBody::Bytes(bytes.into()) | |
| 5952 | - }; | |
| 5953 | - let headers: Vec<(String, String)> = | |
| 5954 | - match serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)) { | |
| 5955 | - Ok(headers) => headers, | |
| 5956 | - Err(error) => { | |
| 5957 | - return loader_throw( | |
| 5958 | - scope, | |
| 5959 | - &format!( | |
| 5960 | - "worker loader: the request headers are not a name/value list: {error}" | |
| 5961 | - ), | |
| 5962 | - ) | |
| 5963 | - } | |
| 5964 | - }; | |
| 5965 | - let mut body_guard = match body.stream_id() { | |
| 5966 | - Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 5967 | - Some(guard) => guard, | |
| 5968 | - None => return loader_throw(scope, "worker loader: the body stream is not owned"), | |
| 5969 | - }, | |
| 5970 | - None => RequestBodyGuard::of(&body), | |
| 5971 | - }; | |
| 5972 | - let loaded = loader_registry() | |
| 5973 | - .lock() | |
| 5974 | - .unwrap() | |
| 5975 | - .get(&id) | |
| 5976 | - .map(|entry| entry.state.clone()); | |
| 5977 | - let async_id = asyncrt::enqueue(async move { | |
| 5978 | - let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 5979 | - let slot = loaded_worker_slot(state).await?; | |
| 5980 | - let (reply, receive) = tokio::sync::oneshot::channel(); | |
| 5981 | - let job = crate::WorkerJob::Fetch { | |
| 5982 | - queued_at: Instant::now(), | |
| 5983 | - url, | |
| 5984 | - method, | |
| 5985 | - body, | |
| 5986 | - headers, | |
| 5987 | - // A loaded Worker receives an incoming request like a service | |
| 5988 | - // target does. The id selects the stream-aware construction path | |
| 5989 | - // and gives an abandoned request a lifecycle owner. | |
| 5990 | - request_id: Some(next_request_id()), | |
| 5991 | - reply, | |
| 5992 | - }; | |
| 5993 | - let driving = tokio::spawn(crate::runtime::drive(slot, job, None)); | |
| 5994 | - match receive.await { | |
| 5995 | - Ok(Ok(response)) => { | |
| 5996 | - // The response proves that the loaded Worker installed its | |
| 5997 | - // request context. That context owns an unread body tail | |
| 5998 | - // through its waitUntil work. | |
| 5999 | - body_guard.disarm(); | |
| 6000 | - Ok(encode_http_response(response, false)) | |
| 6001 | - } | |
| 6002 | - Ok(Err(error)) => Err(format!("{error}")), | |
| 6003 | - Err(_) => match driving.await { | |
| 6004 | - Err(error) => Err(format!("loaded worker task died: {error}")), | |
| 6005 | - Ok(()) => Err("loaded worker dropped response".to_string()), | |
| 6006 | - }, | |
| 6007 | - } | |
| 6008 | - }); | |
| 6009 | - rv.set(promise_for(scope, async_id)); | |
| 6010 | -} | |
| 6011 | - | |
| 6012 | -/// Reclaims a streamed request body if a host dispatch fails before the | |
| 6013 | -/// target installs a request context. A successful dispatch disarms this | |
| 6014 | -/// fallback because the target context then owns the unread tail. | |
| 6015 | -pub struct RequestBodyGuard(Option<u64>); | |
| 6016 | - | |
| 6017 | -impl RequestBodyGuard { | |
| 6018 | - pub fn of(body: &RequestBody) -> Self { | |
| 6019 | - let stream_id = body.stream_id().filter(|id| claim_http_stream(*id)); | |
| 6020 | - Self(stream_id) | |
| 6021 | - } | |
| 6022 | - | |
| 6023 | - fn transferred(stream_id: u64) -> Self { | |
| 6024 | - Self(Some(stream_id)) | |
| 6025 | - } | |
| 6026 | - | |
| 6027 | - pub fn disarm(&mut self) { | |
| 6028 | - if let Some(stream_id) = self.0.take() { | |
| 6029 | - release_http_stream(stream_id); | |
| 6030 | - } | |
| 6031 | - } | |
| 6032 | -} | |
| 6033 | - | |
| 6034 | -impl Drop for RequestBodyGuard { | |
| 6035 | - fn drop(&mut self) { | |
| 6036 | - if let Some(stream_id) = self.0.take() { | |
| 6037 | - release_http_stream(stream_id); | |
| 6038 | - } | |
| 6039 | - } | |
| 6040 | -} | |
| 6041 | - | |
| 6042 | -/// `__loader_rpc(id, entrypoint, method, argsSc)` -> Promise<Uint8Array>. The | |
| 6043 | -/// loaded-worker analog of `__svc_rpc`: a named-entrypoint method call whose | |
| 6044 | -/// args and result are V8 structured-clone bytes. | |
| 6045 | -fn op_loader_rpc( | |
| 6046 | - scope: &mut v8::PinScope, | |
| 6047 | - args: v8::FunctionCallbackArguments, | |
| 6048 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6049 | -) { | |
| 6050 | - let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6051 | - let entrypoint = args.get(1).to_rust_string_lossy(scope); | |
| 6052 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 6053 | - let call_args = view_bytes(args.get(3)).unwrap_or_default(); | |
| 6054 | - let loaded = loader_registry() | |
| 6055 | - .lock() | |
| 6056 | - .unwrap() | |
| 6057 | - .get(&id) | |
| 6058 | - .map(|entry| entry.state.clone()); | |
| 6059 | - let async_id = asyncrt::enqueue(async move { | |
| 6060 | - let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 6061 | - let slot = loaded_worker_slot(state).await?; | |
| 6062 | - let (reply, receive) = tokio::sync::oneshot::channel(); | |
| 6063 | - let job = crate::WorkerJob::Rpc { | |
| 6064 | - entrypoint, | |
| 6065 | - method, | |
| 6066 | - args: call_args, | |
| 6067 | - reply, | |
| 6068 | - }; | |
| 6069 | - let driving = tokio::spawn(crate::runtime::drive(slot, job, None)); | |
| 6070 | - match receive.await { | |
| 6071 | - Ok(Ok(result)) => Ok(result), | |
| 6072 | - Ok(Err(error)) => Err(format!("{error}")), | |
| 6073 | - Err(_) => match driving.await { | |
| 6074 | - Err(error) => Err(format!("loaded worker task died: {error}")), | |
| 6075 | - Ok(()) => Err("loaded worker dropped RPC result".to_string()), | |
| 6076 | - }, | |
| 6077 | - } | |
| 6078 | - }); | |
| 6079 | - rv.set(promise_for(scope, async_id)); | |
| 6080 | -} | |
| 6081 | - | |
| 6082 | -/// `__loader_drop(id)` — evict a loaded worker. Called from a | |
| 6083 | -/// FinalizationRegistry when its stub is GC'd. Removing the registry entry | |
| 6084 | -/// drops the isolate after any calls that already cloned its load state end. | |
| 6085 | -fn op_loader_drop( | |
| 6086 | - scope: &mut v8::PinScope, | |
| 6087 | - args: v8::FunctionCallbackArguments, | |
| 6088 | - _rv: v8::ReturnValue<v8::Value>, | |
| 6089 | -) { | |
| 6090 | - let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6091 | - if let Some(entry) = loader_registry().lock().unwrap().remove(&id) { | |
| 6092 | - // This op runs while the parent isolate is entered. The load state can | |
| 6093 | - // own the loaded isolate, and V8 forbids dropping one isolate while a | |
| 6094 | - // different isolate is entered on the same thread. Hand the final | |
| 6095 | - // reference to the host scheduler so destruction happens after this | |
| 6096 | - // turn has left V8. | |
| 6097 | - asyncrt::op_handle().spawn(async move { drop(entry.state) }); | |
| 6098 | - } | |
| 6099 | -} | |
| 6100 | - | |
| 6101 | -fn op_do_call( | |
| 6102 | - scope: &mut v8::PinScope, | |
| 6103 | - args: v8::FunctionCallbackArguments, | |
| 6104 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6105 | -) { | |
| 6106 | - op_do_call_impl(scope, args, &mut rv, false); | |
| 6107 | -} | |
| 6108 | - | |
| 6109 | -fn op_do_call_cancellable( | |
| 6110 | - scope: &mut v8::PinScope, | |
| 6111 | - args: v8::FunctionCallbackArguments, | |
| 6112 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6113 | -) { | |
| 6114 | - op_do_call_impl(scope, args, &mut rv, true); | |
| 6115 | -} | |
| 6116 | - | |
| 6117 | -fn op_do_call_impl( | |
| 6118 | - scope: &mut v8::PinScope, | |
| 6119 | - args: v8::FunctionCallbackArguments, | |
| 6120 | - rv: &mut v8::ReturnValue<v8::Value>, | |
| 6121 | - cancellable: bool, | |
| 6122 | -) { | |
| 6123 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 6124 | - let name_value = args.get(1); | |
| 6125 | - let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope)); | |
| 6126 | - let url = args.get(2).to_rust_string_lossy(scope); | |
| 6127 | - let method = args.get(3).to_rust_string_lossy(scope); | |
| 6128 | - // arg 4 is the held bytes; arg 6, when a number, is a host stream id for a | |
| 6129 | - // body that must not be collected here (a large or unbounded upload). The | |
| 6130 | - // owning cell reads that stream directly; only a cross-node hop collects it. | |
| 6131 | - let stream_arg = args.get(6); | |
| 6132 | - let body = if stream_arg.is_number() { | |
| 6133 | - RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64) | |
| 6134 | - } else { | |
| 6135 | - let Some(bytes) = view_bytes(args.get(4)) else { | |
| 6136 | - return loader_throw( | |
| 6137 | - scope, | |
| 6138 | - "durable object: the request body is not a typed array", | |
| 6139 | - ); | |
| 6140 | - }; | |
| 6141 | - RequestBody::Bytes(bytes.into()) | |
| 6142 | - }; | |
| 6143 | - let headers: Vec<(String, String)> = | |
| 6144 | - match serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)) { | |
| 6145 | - Ok(headers) => headers, | |
| 6146 | - Err(error) => { | |
| 6147 | - return loader_throw( | |
| 6148 | - scope, | |
| 6149 | - &format!( | |
| 6150 | - "durable object: the request headers are not a name/value list: {error}" | |
| 6151 | - ), | |
| 6152 | - ) | |
| 6153 | - } | |
| 6154 | - }; | |
| 6155 | - let body_guard = match body.stream_id() { | |
| 6156 | - Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 6157 | - Some(guard) => guard, | |
| 6158 | - None => return loader_throw(scope, "durable object: the body stream is not owned"), | |
| 6159 | - }, | |
| 6160 | - None => RequestBodyGuard::of(&body), | |
| 6161 | - }; | |
| 6162 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 6163 | - // Taken here and nowhere later: this is the last point that still runs | |
| 6164 | - // in the order the script made the calls. | |
| 6165 | - let order = Some(enter_call_order(current_context(), &cell)); | |
| 6166 | - // Every host op needs an internal cancellation channel. A caller without | |
| 6167 | - // an AbortSignal cannot cancel from JavaScript, but its enclosing Worker | |
| 6168 | - // can still disappear and drop this op before routing completes. | |
| 6169 | - let request_id = next_do_request_id(); | |
| 6170 | - let (cancel_sender, cancel) = tokio::sync::oneshot::channel(); | |
| 6171 | - do_call_cancels() | |
| 6172 | - .lock() | |
| 6173 | - .unwrap() | |
| 6174 | - .insert(request_id, cancel_sender); | |
| 6175 | - let mut cancel_guard = DoCallCancelGuard::new(request_id); | |
| 6176 | - let gate = egress_gate_request(celld_logic::Channel::CellRpc); | |
| 6177 | - let request = DoCallReq { | |
| 6178 | - request_id: Some(request_id), | |
| 6179 | - cancel: Some(cancel), | |
| 6180 | - deliver_abort_to_handler: cancellable, | |
| 6181 | - scope: cell, | |
| 6182 | - name, | |
| 6183 | - url, | |
| 6184 | - method, | |
| 6185 | - body, | |
| 6186 | - body_guard, | |
| 6187 | - headers, | |
| 6188 | - reply: tx, | |
| 6189 | - order, | |
| 6190 | - parent: current_trace_ids(scope), | |
| 6191 | - }; | |
| 6192 | - let id = asyncrt::enqueue(async move { | |
| 6193 | - gated_channel_send(gate, &DO_CALL_TX, request, "no proxy channel").await?; | |
| 6194 | - let result = match rx.await { | |
| 6195 | - Ok(Ok(response)) => Ok(encode_http_response(response, true)), | |
| 6196 | - Ok(Err(e)) => Err(format!("{e}")), | |
| 6197 | - Err(e) => Err(format!("proxy dropped: {e}")), | |
| 6198 | - }; | |
| 6199 | - cancel_guard.disarm(); | |
| 6200 | - result | |
| 6201 | - }); | |
| 6202 | - let p = promise_for(scope, id); | |
| 6203 | - if cancellable { | |
| 6204 | - attach_cancel_id(scope, p, request_id); | |
| 6205 | - } | |
| 6206 | - rv.set(p); | |
| 6207 | -} | |
| 6208 | - | |
| 6209 | -fn op_do_call_cancel( | |
| 6210 | - scope: &mut v8::PinScope, | |
| 6211 | - args: v8::FunctionCallbackArguments, | |
| 6212 | - _rv: v8::ReturnValue<v8::Value>, | |
| 6213 | -) { | |
| 6214 | - let request_id = args.get(0).to_rust_string_lossy(scope); | |
| 6215 | - let Some(request_id) = parse_request_id(&request_id) else { | |
| 6216 | - return; | |
| 6217 | - }; | |
| 6218 | - if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) { | |
| 6219 | - let _ = cancel.send(()); | |
| 6220 | - } | |
| 6221 | -} | |
| 6222 | - | |
| 6223 | -/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>; | |
| 6224 | -/// arguments and result are V8 structured-clone bytes. | |
| 6225 | -fn op_rpc_call( | |
| 6226 | - scope: &mut v8::PinScope, | |
| 6227 | - args: v8::FunctionCallbackArguments, | |
| 6228 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6229 | -) { | |
| 6230 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 6231 | - let name_value = args.get(1); | |
| 6232 | - let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope)); | |
| 6233 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 6234 | - let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default().into()); | |
| 6235 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 6236 | - let gate = egress_gate_request(celld_logic::Channel::CellRpc); | |
| 6237 | - let request = RpcCallReq { | |
| 6238 | - scope: cell, | |
| 6239 | - name, | |
| 6240 | - method, | |
| 6241 | - args, | |
| 6242 | - reply: tx, | |
| 6243 | - }; | |
| 6244 | - let id = asyncrt::enqueue(async move { | |
| 6245 | - gated_channel_send(gate, &RPC_CALL_TX, request, "no RPC channel").await?; | |
| 6246 | - match rx.await { | |
| 6247 | - Ok(Ok(RpcData::V8(bytes))) => Ok(Vec::<u8>::from(bytes)), | |
| 6248 | - Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()), | |
| 6249 | - Ok(Err(e)) => Err(format!("{e}")), | |
| 6250 | - Err(e) => Err(format!("RPC proxy dropped: {e}")), | |
| 6251 | - } | |
| 6252 | - }); | |
| 6253 | - let p = promise_for(scope, id); | |
| 6254 | - rv.set(p); | |
| 6255 | -} | |
| 6256 | - | |
| 6257 | -/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON | |
| 6258 | -/// `{status, body, headers}` string. | |
| 6259 | -fn op_fetch( | |
| 6260 | - scope: &mut v8::PinScope, | |
| 6261 | - args: v8::FunctionCallbackArguments, | |
| 6262 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6263 | -) { | |
| 6264 | - // A loaded worker with globalOutbound: null has no ambient egress: it must | |
| 6265 | - // reach the world through `env` capabilities. Message matches workerd. | |
| 6266 | - if actor_runtime_state(scope).egress == EgressPolicy::Deny { | |
| 6267 | - return loader_throw( | |
| 6268 | - scope, | |
| 6269 | - "This worker is not permitted to access the internet via global \ | |
| 6270 | - functions like fetch(). It must use capabilities (such as \ | |
| 6271 | - bindings in 'env') to talk to the outside world.", | |
| 6272 | - ); | |
| 6273 | - } | |
| 6274 | - let method = args.get(0).to_rust_string_lossy(scope); | |
| 6275 | - let url = args.get(1).to_rust_string_lossy(scope); | |
| 6276 | - // A body is a typed array, as it is for `__svc_call`, `__do_call` and | |
| 6277 | - // `__loader_fetch`. `None` and an empty body are different requests — one | |
| 6278 | - // carries no `Content-Length` — so the absent case stays distinct. | |
| 6279 | - let body_arg = args.get(2); | |
| 6280 | - let stream_arg = args.get(5); | |
| 6281 | - let body: Option<RequestBody> = if body_arg.is_undefined() || body_arg.is_null() { | |
| 6282 | - None | |
| 6283 | - } else if stream_arg.is_number() { | |
| 6284 | - Some(RequestBody::Stream( | |
| 6285 | - stream_arg.number_value(scope).unwrap_or(0.0) as u64, | |
| 6286 | - )) | |
| 6287 | - } else { | |
| 6288 | - match view_bytes(body_arg) { | |
| 6289 | - Some(bytes) => Some(RequestBody::Bytes(bytes.into())), | |
| 6290 | - // Answering an unreadable argument with `None` sent the request | |
| 6291 | - // with no body at all: the peer saw something the Worker never | |
| 6292 | - // asked for, and nothing threw and nothing was logged. | |
| 6293 | - None => return loader_throw(scope, "fetch: the request body is not a typed array"), | |
| 6294 | - } | |
| 6295 | - }; | |
| 6296 | - let raw_headers = args.get(3).to_rust_string_lossy(scope); | |
| 6297 | - let mut headers: Vec<(String, String)> = match serde_json::from_str(&raw_headers) { | |
| 6298 | - Ok(headers) => headers, | |
| 6299 | - // Same failure as the body: dropping the headers silently sent an | |
| 6300 | - // unauthenticated, unrouted request in place of the real one. | |
| 6301 | - Err(error) => { | |
| 6302 | - return loader_throw( | |
| 6303 | - scope, | |
| 6304 | - &format!("fetch: the request headers are not a name/value list: {error}"), | |
| 6305 | - ) | |
| 6306 | - } | |
| 6307 | - }; | |
| 6308 | - let redirect = args.get(4).to_rust_string_lossy(scope); | |
| 6309 | - let mut body_guard = match body.as_ref().and_then(RequestBody::stream_id) { | |
| 6310 | - Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 6311 | - Some(guard) => guard, | |
| 6312 | - None => return loader_throw(scope, "fetch: the body stream is not owned"), | |
| 6313 | - }, | |
| 6314 | - None => RequestBodyGuard(None), | |
| 6315 | - }; | |
| 6316 | - let client = if redirect == "manual" { | |
| 6317 | - HTTP_MANUAL.with(|client| client.clone()) | |
| 6318 | - } else { | |
| 6319 | - HTTP.with(|client| client.clone()) | |
| 6320 | - }; | |
| 6321 | - // The creating context, read here while JS is still running: the op | |
| 6322 | - // future resolves on whatever worker polls it, far from any CPED. | |
| 6323 | - let trace = current_trace_ids(scope); | |
| 6324 | - // The child's ids are minted before the request leaves so the | |
| 6325 | - // traceparent header carries them: whatever this fetch reaches can | |
| 6326 | - // join the trace celld is part of. | |
| 6327 | - let child = trace.as_ref().map(crate::telemetry::child_ids); | |
| 6328 | - if let Some(child) = child.as_ref() { | |
| 6329 | - if !headers | |
| 6330 | - .iter() | |
| 6331 | - .any(|(name, _)| name.eq_ignore_ascii_case("traceparent")) | |
| 6332 | - { | |
| 6333 | - headers.push(("traceparent".into(), crate::telemetry::traceparent(child))); | |
| 6334 | - } | |
| 6335 | - } | |
| 6336 | - let span_url = trace.as_ref().map(|_| url.clone()); | |
| 6337 | - // Whatever this request can reveal must be durable before it leaves: a | |
| 6338 | - // third party that has acted on a write celld then loses cannot be told to | |
| 6339 | - // un-act. That covers a write this handler made and a value it only read, | |
| 6340 | - // because the third party cannot tell the two apart. | |
| 6341 | - let gate = egress_gate_request(celld_logic::Channel::Fetch); | |
| 6342 | - let id = asyncrt::enqueue(async move { | |
| 6343 | - let span_started = trace.as_ref().map(|_| crate::telemetry::now_unix_us()); | |
| 6344 | - let mut span = trace.as_ref().zip(child).map(|(parent, child)| { | |
| 6345 | - let mut span = | |
| 6346 | - crate::telemetry::Span::new(child, "fetch", crate::telemetry::KIND_CLIENT); | |
| 6347 | - span.parent_span_id = Some(parent.span_id); | |
| 6348 | - span.parent_remote = Some(false); | |
| 6349 | - span.url = span_url; | |
| 6350 | - span | |
| 6351 | - }); | |
| 6352 | - let mut finish = |ok: bool, status: Option<u16>, error: Option<String>| { | |
| 6353 | - if let Some(mut span) = span.take() { | |
| 6354 | - span.start_unix_us = span_started.unwrap_or_default(); | |
| 6355 | - span.duration_us = crate::telemetry::now_unix_us() - span.start_unix_us; | |
| 6356 | - span.ok = ok; | |
| 6357 | - span.http_status = status; | |
| 6358 | - span.error = error; | |
| 6359 | - crate::telemetry::record(span); | |
| 6360 | - } | |
| 6361 | - }; | |
| 6362 | - await_egress_gate(gate).await.inspect_err(|error| { | |
| 6363 | - finish(false, None, Some(error.clone())); | |
| 6364 | - })?; | |
| 6365 | - let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET); | |
| 6366 | - // a timeout bounds a black-hole host: the future settles (Err) instead | |
| 6367 | - // of parking run_loop forever — the hang the Drop guard can't catch. | |
| 6368 | - let fetch_timeout = crate::env_vars::positive_or("CELLD_FETCH_TIMEOUT_S", 120) | |
| 6369 | - .expect("validated CELLD_FETCH_TIMEOUT_S"); | |
| 6370 | - let mut rb = client | |
| 6371 | - .request(m, &url) | |
| 6372 | - .timeout(std::time::Duration::from_secs(fetch_timeout)); | |
| 6373 | - // reqwest omits Content-Length for an empty Vec, which collapses the | |
| 6374 | - // wire representation of `Some([])` into the representation of | |
| 6375 | - // `None`. Install the zero length here unless the Worker supplied a | |
| 6376 | - // framing header, so the body distinction survives the HTTP client. | |
| 6377 | - let empty_body_needs_length = body | |
| 6378 | - .as_ref() | |
| 6379 | - .is_some_and(|body| matches!(body, RequestBody::Bytes(bytes) if bytes.is_empty())) | |
| 6380 | - && !headers.iter().any(|(name, _)| { | |
| 6381 | - name.eq_ignore_ascii_case("content-length") | |
| 6382 | - || name.eq_ignore_ascii_case("transfer-encoding") | |
| 6383 | - }); | |
| 6384 | - for (name, value) in headers { | |
| 6385 | - rb = rb.header(name, value); | |
| 6386 | - } | |
| 6387 | - if let Some(body) = body { | |
| 6388 | - rb = match body { | |
| 6389 | - RequestBody::Bytes(bytes) => rb.body(bytes), | |
| 6390 | - RequestBody::Stream(stream_id) => match take_body_stream(stream_id) { | |
| 6391 | - Ok(stream) => { | |
| 6392 | - body_guard.disarm(); | |
| 6393 | - rb.body(reqwest::Body::wrap_stream(stream)) | |
| 6394 | - } | |
| 6395 | - Err(error) => { | |
| 6396 | - finish(false, None, Some(error.clone())); | |
| 6397 | - return Err(error); | |
| 6398 | - } | |
| 6399 | - }, | |
| 6400 | - }; | |
| 6401 | - } | |
| 6402 | - if empty_body_needs_length { | |
| 6403 | - rb = rb.header(reqwest::header::CONTENT_LENGTH, 0); | |
| 6404 | - } | |
| 6405 | - match rb.send().await { | |
| 6406 | - Ok(resp) => { | |
| 6407 | - let status = resp.status().as_u16(); | |
| 6408 | - finish(true, Some(status), None); | |
| 6409 | - let headers = resp | |
| 6410 | - .headers() | |
| 6411 | - .iter() | |
| 6412 | - .map(|(name, value)| { | |
| 6413 | - ( | |
| 6414 | - name.as_str().to_string(), | |
| 6415 | - value.to_str().unwrap_or_default().to_string(), | |
| 6416 | - ) | |
| 6417 | - }) | |
| 6418 | - .collect::<Vec<_>>(); | |
| 6419 | - let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 6420 | - register_http_stream(stream_id, HttpStreamSource::Response(resp)); | |
| 6421 | - Ok(serde_json::json!({ | |
| 6422 | - "status": status, "streamId": stream_id, "headers": headers, | |
| 6423 | - }) | |
| 6424 | - .to_string()) | |
| 6425 | - } | |
| 6426 | - Err(e) => { | |
| 6427 | - finish(false, None, Some(format!("fetch: {e}"))); | |
| 6428 | - Err(format!("fetch: {e}")) | |
| 6429 | - } | |
| 6430 | - } | |
| 6431 | - }); | |
| 6432 | - let p = promise_for(scope, id); | |
| 6433 | - rv.set(p); | |
| 6434 | -} | |
| 6435 | - | |
| 6436 | -fn op_asset_fetch( | |
| 6437 | - scope: &mut v8::PinScope, | |
| 6438 | - args: v8::FunctionCallbackArguments, | |
| 6439 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6440 | -) { | |
| 6441 | - let script = args.get(0).to_rust_string_lossy(scope); | |
| 6442 | - let method = args.get(1).to_rust_string_lossy(scope); | |
| 6443 | - let url = args.get(2).to_rust_string_lossy(scope); | |
| 6444 | - let headers: Vec<(String, String)> = | |
| 6445 | - match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) { | |
| 6446 | - Ok(headers) => headers, | |
| 6447 | - Err(error) => { | |
| 6448 | - return loader_throw( | |
| 6449 | - scope, | |
| 6450 | - &format!("assets: the request headers are not a name/value list: {error}"), | |
| 6451 | - ) | |
| 6452 | - } | |
| 6453 | - }; | |
| 6454 | - let generation = current_generation(scope); | |
| 6455 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 6456 | - let sent = ASSET_CALL_TX.get().is_some_and(|sender| { | |
| 6457 | - sender | |
| 6458 | - .send(AssetCallReq { | |
| 6459 | - generation, | |
| 6460 | - script, | |
| 6461 | - url, | |
| 6462 | - method, | |
| 6463 | - headers, | |
| 6464 | - reply: tx, | |
| 6465 | - }) | |
| 6466 | - .is_ok() | |
| 6467 | - }); | |
| 6468 | - let id = asyncrt::enqueue(async move { | |
| 6469 | - if !sent { | |
| 6470 | - return Err("no asset resolver channel".to_string()); | |
| 6471 | - } | |
| 6472 | - match rx.await { | |
| 6473 | - Ok(Ok(response)) => Ok(encode_http_response(response, false)), | |
| 6474 | - Ok(Err(error)) => Err(format!("asset fetch: {error}")), | |
| 6475 | - Err(error) => Err(format!("asset resolver dropped: {error}")), | |
| 6476 | - } | |
| 6477 | - }); | |
| 6478 | - rv.set(promise_for(scope, id)); | |
| 6479 | -} | |
| 6480 | - | |
| 6481 | -/// Take exclusive ownership of a registered request source. | |
| 6482 | -/// | |
| 6483 | -/// The returned stream removes the registry hop, so its eventual consumer | |
| 6484 | -/// supplies the backpressure and dropping that consumer cancels the source. | |
| 6485 | -pub fn take_body_stream(stream_id: u64) -> Result<HttpChunkStream, String> { | |
| 6486 | - match http_streams().lock().unwrap().remove(&stream_id) { | |
| 6487 | - Some(entry) => entry | |
| 6488 | - .source | |
| 6489 | - .map(http_chunk_stream) | |
| 6490 | - .ok_or_else(|| format!("body stream {stream_id} source is checked out")), | |
| 6491 | - None => Err(format!("body stream {stream_id} is not registered")), | |
| 6492 | - } | |
| 6493 | -} | |
| 6494 | - | |
| 6495 | -async fn next_http_stream_chunk(source: &mut HttpStreamSource) -> Result<Option<Vec<u8>>, String> { | |
| 6496 | - match source { | |
| 6497 | - HttpStreamSource::Response(response) => response | |
| 6498 | - .chunk() | |
| 6499 | - .await | |
| 6500 | - .map(|chunk| chunk.map(|bytes| bytes.to_vec())) | |
| 6501 | - .map_err(|error| format!("response stream: {error}")), | |
| 6502 | - HttpStreamSource::Receiver(receiver) => match receiver.recv().await { | |
| 6503 | - Some(Ok(bytes)) => Ok(Some(bytes)), | |
| 6504 | - Some(Err(error)) => Err(error), | |
| 6505 | - None => Ok(None), | |
| 6506 | - }, | |
| 6507 | - HttpStreamSource::Stream(stream) => stream.next().await.transpose(), | |
| 6508 | - } | |
| 6509 | -} | |
| 6510 | - | |
| 6511 | -/// Move a host response source into a directly-polled stream. No pump task is | |
| 6512 | -/// needed: the eventual HTTP or JS consumer supplies the backpressure. | |
| 6513 | -fn http_chunk_stream(source: HttpStreamSource) -> HttpChunkStream { | |
| 6514 | - match source { | |
| 6515 | - HttpStreamSource::Response(response) => Box::pin(response.bytes_stream().map(|chunk| { | |
| 6516 | - chunk | |
| 6517 | - .map(|bytes| bytes.to_vec()) | |
| 6518 | - .map_err(|error| format!("response stream: {error}")) | |
| 6519 | - })), | |
| 6520 | - HttpStreamSource::Receiver(receiver) => { | |
| 6521 | - Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver)) | |
| 6522 | - } | |
| 6523 | - HttpStreamSource::Stream(stream) => stream, | |
| 6524 | - } | |
| 6525 | -} | |
| 6526 | - | |
| 6527 | -/// Host-native tee for an outbound response. Both branches are represented by | |
| 6528 | -/// stream IDs, so one can be returned through Axum while JS independently | |
| 6529 | -/// scans the other for observability or usage accounting. | |
| 6530 | -fn tee_http_stream(mut source: HttpStreamSource) -> (u64, u64) { | |
| 6531 | - let (tx1, rx1) = tokio::sync::mpsc::channel(16); | |
| 6532 | - let (tx2, rx2) = tokio::sync::mpsc::channel(16); | |
| 6533 | - let id1 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 6534 | - let id2 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 6535 | - register_http_stream(id1, HttpStreamSource::Receiver(rx1)); | |
| 6536 | - register_http_stream(id2, HttpStreamSource::Receiver(rx2)); | |
| 6537 | - asyncrt::op_handle().spawn(async move { | |
| 6538 | - loop { | |
| 6539 | - match next_http_stream_chunk(&mut source).await { | |
| 6540 | - Ok(Some(bytes)) => { | |
| 6541 | - let first = tx1.send(Ok(bytes.clone())).await.is_ok(); | |
| 6542 | - let second = tx2.send(Ok(bytes)).await.is_ok(); | |
| 6543 | - if !first && !second { | |
| 6544 | - break; | |
| 6545 | - } | |
| 6546 | - } | |
| 6547 | - Ok(None) => break, | |
| 6548 | - Err(error) => { | |
| 6549 | - let _ = tx1.send(Err(error.clone())).await; | |
| 6550 | - let _ = tx2.send(Err(error)).await; | |
| 6551 | - break; | |
| 6552 | - } | |
| 6553 | - } | |
| 6554 | - } | |
| 6555 | - }); | |
| 6556 | - (id1, id2) | |
| 6557 | -} | |
| 6558 | - | |
| 6559 | -fn op_http_stream_read( | |
| 6560 | - scope: &mut v8::PinScope, | |
| 6561 | - args: v8::FunctionCallbackArguments, | |
| 6562 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6563 | -) { | |
| 6564 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6565 | - let source = http_streams() | |
| 6566 | - .lock() | |
| 6567 | - .unwrap() | |
| 6568 | - .get_mut(&stream_id) | |
| 6569 | - .and_then(|stream| { | |
| 6570 | - stream | |
| 6571 | - .source | |
| 6572 | - .take() | |
| 6573 | - .map(|source| (source, stream.cancelled.subscribe())) | |
| 6574 | - }); | |
| 6575 | - let id = asyncrt::enqueue(async move { | |
| 6576 | - let Some((mut source, mut cancelled)) = source else { | |
| 6577 | - return Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())); | |
| 6578 | - }; | |
| 6579 | - let next = crate::asyncrt::select! { | |
| 6580 | - result = next_http_stream_chunk(&mut source) => Some(result), | |
| 6581 | - _ = cancelled.changed() => None, | |
| 6582 | - }; | |
| 6583 | - match next { | |
| 6584 | - None => Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())), | |
| 6585 | - Some(Ok(Some(bytes))) => { | |
| 6586 | - if let Some(stream) = http_streams().lock().unwrap().get_mut(&stream_id) { | |
| 6587 | - stream.created = Instant::now(); | |
| 6588 | - stream.source = Some(source); | |
| 6589 | - } | |
| 6590 | - Ok(asyncrt::OpOut::Bytes(bytes)) | |
| 6591 | - } | |
| 6592 | - Some(Ok(None)) => { | |
| 6593 | - http_streams().lock().unwrap().remove(&stream_id); | |
| 6594 | - Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())) | |
| 6595 | - } | |
| 6596 | - Some(Err(error)) => { | |
| 6597 | - http_streams().lock().unwrap().remove(&stream_id); | |
| 6598 | - Err(error) | |
| 6599 | - } | |
| 6600 | - } | |
| 6601 | - }); | |
| 6602 | - rv.set(promise_for(scope, id)); | |
| 6603 | -} | |
| 6604 | - | |
| 6605 | -fn op_http_stream_tee( | |
| 6606 | - scope: &mut v8::PinScope, | |
| 6607 | - args: v8::FunctionCallbackArguments, | |
| 6608 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6609 | -) { | |
| 6610 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6611 | - let source = http_streams() | |
| 6612 | - .lock() | |
| 6613 | - .unwrap() | |
| 6614 | - .remove(&stream_id) | |
| 6615 | - .and_then(|stream| stream.source); | |
| 6616 | - let Some(source) = source else { | |
| 6617 | - let message = v8::String::new(scope, "response stream is no longer available").unwrap(); | |
| 6618 | - let exception = v8::Exception::type_error(scope, message); | |
| 6619 | - scope.throw_exception(exception); | |
| 6620 | - return; | |
| 6621 | - }; | |
| 6622 | - let ids = tee_http_stream(source); | |
| 6623 | - current_context().replace_body_stream(stream_id, ids); | |
| 6624 | - let json = serde_json::to_string(&ids).unwrap(); | |
| 6625 | - rv.set(v8::String::new(scope, &json).unwrap().into()); | |
| 6626 | -} | |
| 6627 | - | |
| 6628 | -fn op_http_stream_cancel( | |
| 6629 | - scope: &mut v8::PinScope, | |
| 6630 | - args: v8::FunctionCallbackArguments, | |
| 6631 | - _rv: v8::ReturnValue<v8::Value>, | |
| 6632 | -) { | |
| 6633 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6634 | - if let Some(stream) = http_streams().lock().unwrap().remove(&stream_id) { | |
| 6635 | - let _ = stream.cancelled.send(true); | |
| 6636 | - } | |
| 6637 | -} | |
| 6638 | - | |
| 6639 | -fn op_response_stream_create( | |
| 6640 | - scope: &mut v8::PinScope, | |
| 6641 | - _args: v8::FunctionCallbackArguments, | |
| 6642 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6643 | -) { | |
| 6644 | - let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 6645 | - let (writer, receiver) = tokio::sync::mpsc::channel(1); | |
| 6646 | - let (finished, _) = tokio::sync::watch::channel(false); | |
| 6647 | - let now = Instant::now(); | |
| 6648 | - register_http_stream(stream_id, HttpStreamSource::Receiver(receiver)); | |
| 6649 | - let mut writers = response_stream_writers().lock().unwrap(); | |
| 6650 | - writers.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60)); | |
| 6651 | - writers.insert( | |
| 6652 | - stream_id, | |
| 6653 | - ResponseStreamWriter { | |
| 6654 | - created: now, | |
| 6655 | - writer, | |
| 6656 | - finished, | |
| 6657 | - }, | |
| 6658 | - ); | |
| 6659 | - rv.set(v8::Number::new(scope, stream_id as f64).into()); | |
| 6660 | -} | |
| 6661 | - | |
| 6662 | -fn op_response_stream_write( | |
| 6663 | - scope: &mut v8::PinScope, | |
| 6664 | - args: v8::FunctionCallbackArguments, | |
| 6665 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6666 | -) { | |
| 6667 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6668 | - let bytes = args | |
| 6669 | - .get(1) | |
| 6670 | - .try_cast::<v8::ArrayBufferView>() | |
| 6671 | - .ok() | |
| 6672 | - .map(|view| { | |
| 6673 | - let mut bytes = vec![0; view.byte_length()]; | |
| 6674 | - view.copy_contents(&mut bytes); | |
| 6675 | - bytes | |
| 6676 | - }); | |
| 6677 | - let writer = response_stream_writers() | |
| 6678 | - .lock() | |
| 6679 | - .unwrap() | |
| 6680 | - .get_mut(&stream_id) | |
| 6681 | - .map(|stream| { | |
| 6682 | - stream.created = Instant::now(); | |
| 6683 | - stream.writer.clone() | |
| 6684 | - }); | |
| 6685 | - let id = asyncrt::enqueue(async move { | |
| 6686 | - let Some(bytes) = bytes else { | |
| 6687 | - return Err("response stream chunks must be ArrayBuffer views".into()); | |
| 6688 | - }; | |
| 6689 | - let Some(writer) = writer else { | |
| 6690 | - return Err("response stream consumer canceled".into()); | |
| 6691 | - }; | |
| 6692 | - if writer.send(Ok(bytes)).await.is_err() { | |
| 6693 | - response_stream_writers().lock().unwrap().remove(&stream_id); | |
| 6694 | - return Err("response stream consumer canceled".into()); | |
| 6695 | - } | |
| 6696 | - Ok(String::new()) | |
| 6697 | - }); | |
| 6698 | - rv.set(promise_for(scope, id)); | |
| 6699 | -} | |
| 6700 | - | |
| 6701 | -fn op_response_stream_closed( | |
| 6702 | - scope: &mut v8::PinScope, | |
| 6703 | - args: v8::FunctionCallbackArguments, | |
| 6704 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6705 | -) { | |
| 6706 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6707 | - let (writer, mut finished) = response_stream_writers() | |
| 6708 | - .lock() | |
| 6709 | - .unwrap() | |
| 6710 | - .get(&stream_id) | |
| 6711 | - .map(|stream| (stream.writer.clone(), stream.finished.subscribe())) | |
| 6712 | - .unzip(); | |
| 6713 | - let id = asyncrt::enqueue(async move { | |
| 6714 | - let cancelled = match (writer, finished.as_mut()) { | |
| 6715 | - (Some(writer), Some(finished)) => crate::asyncrt::select_biased! { | |
| 6716 | - "stream completion wins a tie so a completed response is not reported as cancelled"; | |
| 6717 | - result = finished.changed() => result.is_err(), | |
| 6718 | - _ = writer.closed() => true, | |
| 6719 | - }, | |
| 6720 | - _ => false, | |
| 6721 | - }; | |
| 6722 | - Ok(String::from(if cancelled { | |
| 6723 | - "cancelled" | |
| 6724 | - } else { | |
| 6725 | - "finished" | |
| 6726 | - })) | |
| 6727 | - }); | |
| 6728 | - rv.set(promise_for(scope, id)); | |
| 6729 | -} | |
| 6730 | - | |
| 6731 | -fn op_response_stream_close( | |
| 6732 | - scope: &mut v8::PinScope, | |
| 6733 | - args: v8::FunctionCallbackArguments, | |
| 6734 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6735 | -) { | |
| 6736 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6737 | - let error = args.get(1).to_rust_string_lossy(scope); | |
| 6738 | - let stream = response_stream_writers().lock().unwrap().remove(&stream_id); | |
| 6739 | - let id = asyncrt::enqueue(async move { | |
| 6740 | - if let Some(stream) = stream { | |
| 6741 | - let _ = stream.finished.send(true); | |
| 6742 | - if !error.is_empty() { | |
| 6743 | - let _ = stream.writer.send(Err(error)).await; | |
| 6744 | - } | |
| 6745 | - } | |
| 6746 | - Ok(String::new()) | |
| 6747 | - }); | |
| 6748 | - rv.set(promise_for(scope, id)); | |
| 6749 | -} | |
| 6750 | - | |
| 6751 | -/// Hand a request body to the isolate as a stream rather than as bytes. | |
| 6752 | -/// The returned id names the stream for `__http_stream_read`, so the | |
| 6753 | -/// Worker pulls each chunk off the socket as it asks for it and the host | |
| 6754 | -/// never holds the whole body. | |
| 6755 | -pub fn register_body_stream(stream: HttpChunkStream) -> u64 { | |
| 6756 | - let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 6757 | - register_http_stream(stream_id, HttpStreamSource::Stream(stream)); | |
| 6758 | - stream_id | |
| 6759 | -} | |
| 6760 | - | |
| 6761 | -/// How an incoming request body reaches the isolate. | |
| 6762 | -/// | |
| 6763 | -/// A small body crosses as bytes. This costs one copy and no asynchronous | |
| 6764 | -/// operations, so a common request pays nothing for a stream that it does | |
| 6765 | -/// not need. A large body, or a body of unknown length, crosses as a | |
| 6766 | -/// stream id. The peak cost of that body is one chunk, not its length. | |
| 6767 | -pub enum RequestBody { | |
| 6768 | - Bytes(bytes::Bytes), | |
| 6769 | - Stream(u64), | |
| 6770 | -} | |
| 6771 | - | |
| 6772 | -impl RequestBody { | |
| 6773 | - /// The bytes already in hand, for the paths that hold a whole body. | |
| 6774 | - pub fn bytes(&self) -> &[u8] { | |
| 6775 | - match self { | |
| 6776 | - Self::Bytes(bytes) => bytes, | |
| 6777 | - Self::Stream(_) => &[], | |
| 6778 | - } | |
| 6779 | - } | |
| 6780 | - | |
| 6781 | - pub fn stream_id(&self) -> Option<u64> { | |
| 6782 | - match self { | |
| 6783 | - Self::Bytes(_) => None, | |
| 6784 | - Self::Stream(id) => Some(*id), | |
| 6785 | - } | |
| 6786 | - } | |
| 6787 | - | |
| 6788 | - fn into_held_bytes(self) -> Option<Vec<u8>> { | |
| 6789 | - match self { | |
| 6790 | - Self::Bytes(bytes) => Some(bytes.into()), | |
| 6791 | - Self::Stream(_) => None, | |
| 6792 | - } | |
| 6793 | - } | |
| 6794 | -} | |
| 6795 | - | |
| 6796 | -impl From<Vec<u8>> for RequestBody { | |
| 6797 | - fn from(bytes: Vec<u8>) -> Self { | |
| 6798 | - Self::Bytes(bytes.into()) | |
| 6799 | - } | |
| 6800 | -} | |
| 6801 | - | |
| 6802 | -/// Timer op behind `setTimeout`: a promise resolving after `ms`. | |
| 6803 | -fn op_timer( | |
| 6804 | - scope: &mut v8::PinScope, | |
| 6805 | - args: v8::FunctionCallbackArguments, | |
| 6806 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6807 | -) { | |
| 6808 | - let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6809 | - let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64; | |
| 6810 | - let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel(); | |
| 6811 | - timer_cancels().lock().unwrap().insert(timer_id, cancel_tx); | |
| 6812 | - let id = asyncrt::enqueue(async move { | |
| 6813 | - crate::asyncrt::select! { | |
| 6814 | - _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {} | |
| 6815 | - _ = &mut cancel_rx => {} | |
| 6816 | - } | |
| 6817 | - timer_cancels().lock().unwrap().remove(&timer_id); | |
| 6818 | - Ok(String::new()) | |
| 6819 | - }); | |
| 6820 | - let p = promise_for(scope, id); | |
| 6821 | - rv.set(p); | |
| 6822 | -} | |
| 6823 | - | |
| 6824 | -/// `__gate_acquire(scope)` — take the cell's input gate for a | |
| 6825 | -/// `blockConcurrencyWhile`, waiting if another block holds it. | |
| 6826 | -/// | |
| 6827 | -/// Answers a promise of the event id, not the id itself. It was synchronous, | |
| 6828 | -/// and that was right while a cell's events came off one channel: only one | |
| 6829 | -/// ran at a time, a delivery point had already found the gate open, and | |
| 6830 | -/// yielding even one microtask reopened a window in which a nested delivery | |
| 6831 | -/// could wait on a gate nothing would release. Neither half holds now — | |
| 6832 | -/// events are independent tasks, several run at once, and nothing nests — | |
| 6833 | -/// so two blocks can meet and the second must queue. | |
| 6834 | -fn op_gate_acquire( | |
| 6835 | - scope: &mut v8::PinScope, | |
| 6836 | - args: v8::FunctionCallbackArguments, | |
| 6837 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6838 | -) { | |
| 6839 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 6840 | - let event = NEXT_GATE_EVENT.fetch_add(1, Ordering::Relaxed); | |
| 6841 | - // Taken under the gates lock so the observation and the take are one step: a | |
| 6842 | - // release landing between them would leave this block queued behind a | |
| 6843 | - // gate that is already open. | |
| 6844 | - let taken = cell_gates() | |
| 6845 | - .lock() | |
| 6846 | - .unwrap() | |
| 6847 | - .entry(cell.clone()) | |
| 6848 | - .or_default() | |
| 6849 | - .acquire(event); | |
| 6850 | - if taken { | |
| 6851 | - let id = asyncrt::enqueue(async move { Ok(event.to_string()) }); | |
| 6852 | - rv.set(promise_for(scope, id)); | |
| 6853 | - return; | |
| 6854 | - } | |
| 6855 | - let id = asyncrt::enqueue(async move { | |
| 6856 | - loop { | |
| 6857 | - // Ask for a ticket first: `cell_gate_wait` tests and enqueues | |
| 6858 | - // under the gates lock, so a release landing between the two | |
| 6859 | - // cannot leave this waiter behind an open gate. | |
| 6860 | - let waiting = cell_gate_wait(&cell); | |
| 6861 | - let taken = cell_gates() | |
| 6862 | - .lock() | |
| 6863 | - .unwrap() | |
| 6864 | - .entry(cell.clone()) | |
| 6865 | - .or_default() | |
| 6866 | - .acquire(event); | |
| 6867 | - if taken { | |
| 6868 | - return Ok(event.to_string()); | |
| 6869 | - } | |
| 6870 | - match waiting { | |
| 6871 | - Some(open) => match open.await { | |
| 6872 | - Ok(Ok(())) => {} | |
| 6873 | - // The block ahead of this one failed and reset the cell, | |
| 6874 | - // so this block has nothing left to guard. | |
| 6875 | - Ok(Err(failure)) => return Err(failure), | |
| 6876 | - Err(_) => { | |
| 6877 | - return Err("cell stopped while waiting for its input gate".to_string()) | |
| 6878 | - } | |
| 6879 | - }, | |
| 6880 | - // The gate was open when we asked and shut before we took | |
| 6881 | - // it: another block won the race. Yield rather than spin — | |
| 6882 | - // this runs on a tokio worker, and a bare `continue` here | |
| 6883 | - // starved the runtime. | |
| 6884 | - None => tokio::task::yield_now().await, | |
| 6885 | - } | |
| 6886 | - } | |
| 6887 | - }); | |
| 6888 | - rv.set(promise_for(scope, id)); | |
| 6889 | -} | |
| 6890 | - | |
| 6891 | -/// `__gate_wait(scope)` — settle when the cell's input gate is open. | |
| 6892 | -/// | |
| 6893 | -/// The gate's other side. `op_gate_acquire` is for something that wants to | |
| 6894 | -/// *hold* the gate; this is for something that only has to arrive after it, | |
| 6895 | -/// which is every event the gate exists to hold back. A drive does this in | |
| 6896 | -/// Rust before it begins a turn; an RPC stub op does it here, because it is | |
| 6897 | -/// dispatched inside the isolate and never becomes a drive. | |
| 6898 | -/// | |
| 6899 | -/// Rejecting matters as much as resolving: a critical section that failed | |
| 6900 | -/// reset the cell, so what waited behind it is refused with the reason | |
| 6901 | -/// rather than run against state that no longer exists. | |
| 6902 | -fn op_gate_wait( | |
| 6903 | - scope: &mut v8::PinScope, | |
| 6904 | - args: v8::FunctionCallbackArguments, | |
| 6905 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6906 | -) { | |
| 6907 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 6908 | - let id = asyncrt::enqueue(async move { | |
| 6909 | - loop { | |
| 6910 | - match cell_gate_wait(&cell) { | |
| 6911 | - None => return Ok(String::new()), | |
| 6912 | - Some(open) => match open.await { | |
| 6913 | - Ok(Ok(())) => {} | |
| 6914 | - Ok(Err(failure)) => return Err(failure), | |
| 6915 | - Err(_) => { | |
| 6916 | - return Err("cell stopped while waiting for its input gate".to_string()) | |
| 6917 | - } | |
| 6918 | - }, | |
| 6919 | - } | |
| 6920 | - } | |
| 6921 | - }); | |
| 6922 | - rv.set(promise_for(scope, id)); | |
| 6923 | -} | |
| 6924 | - | |
| 6925 | -/// `__gate_release(scope, event)` — the block is over. The next delivery | |
| 6926 | -/// point to run takes whatever queued behind it. | |
| 6927 | -fn op_gate_release( | |
| 6928 | - scope: &mut v8::PinScope, | |
| 6929 | - args: v8::FunctionCallbackArguments, | |
| 6930 | - _rv: v8::ReturnValue<v8::Value>, | |
| 6931 | -) { | |
| 6932 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 6933 | - let event = args.get(1).number_value(scope).unwrap_or_default() as celld_logic::gate::EventId; | |
| 6934 | - // A third argument means the block failed and the actor was reset, so | |
| 6935 | - // what queued behind it is refused with that reason rather than | |
| 6936 | - // delivered to a cell whose state is gone. | |
| 6937 | - let failure = args.get(2); | |
| 6938 | - let outcome = if failure.is_null_or_undefined() { | |
| 6939 | - Ok(()) | |
| 6940 | - } else { | |
| 6941 | - Err(failure.to_rust_string_lossy(scope)) | |
| 6942 | - }; | |
| 6943 | - if let Some(gate) = cell_gates().lock().unwrap().get_mut(&cell) { | |
| 6944 | - gate.release(event); | |
| 6945 | - } | |
| 6946 | - wake_gate_waiters(&cell, outcome); | |
| 6947 | -} | |
| 6948 | - | |
| 6949 | -fn op_timer_alloc( | |
| 6950 | - scope: &mut v8::PinScope, | |
| 6951 | - _args: v8::FunctionCallbackArguments, | |
| 6952 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 6953 | -) { | |
| 6954 | - let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64); | |
| 6955 | - rv.set(id.into()); | |
| 6956 | -} | |
| 6957 | - | |
| 6958 | -fn op_timer_cancel( | |
| 6959 | - scope: &mut v8::PinScope, | |
| 6960 | - args: v8::FunctionCallbackArguments, | |
| 6961 | - _rv: v8::ReturnValue<v8::Value>, | |
| 6962 | -) { | |
| 6963 | - let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 6964 | - if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) { | |
| 6965 | - let _ = cancel.send(()); | |
| 6966 | - } | |
| 6967 | -} | |
| 6968 | - | |
| 6969 | -fn durable_object_id_key(namespace_key: &str) -> [u8; 32] { | |
| 6970 | - DO_ID_KEYS.with(|keys| { | |
| 6971 | - if let Some(key) = keys.borrow().get(namespace_key) { | |
| 6972 | - return *key; | |
| 6973 | - } | |
| 6974 | - use sha2::Digest; | |
| 6975 | - let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into(); | |
| 6976 | - keys.borrow_mut().insert(namespace_key.to_string(), key); | |
| 6977 | - key | |
| 6978 | - }) | |
| 6979 | -} | |
| 6980 | - | |
| 6981 | -fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> { | |
| 6982 | - use hmac::Mac; | |
| 6983 | - let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key) | |
| 6984 | - .expect("SHA-256 accepts any HMAC key"); | |
| 6985 | - mac.update(input); | |
| 6986 | - mac | |
| 6987 | -} | |
| 6988 | - | |
| 6989 | -/// Ids already derived on this thread, keyed by namespace and name. | |
| 6990 | -/// | |
| 6991 | -/// `getByName` costs two HMAC-SHA256 rounds, and a profile of `/c/hello` | |
| 6992 | -/// found them among the largest terms the stateless path does not have — | |
| 6993 | -/// the same name resolving to the same id, recomputed on every request. | |
| 6994 | -/// | |
| 6995 | -/// Per thread and unsynchronised, which is sound because the derivation is | |
| 6996 | -/// a pure function of its inputs: a worker that has not seen a name pays | |
| 6997 | -/// for it once, and no answer can differ between threads. Bounded because | |
| 6998 | -/// names come from the application, and cleared wholesale at the cap rather | |
| 6999 | -/// than evicted one at a time — a cache this cheap to refill does not earn | |
| 7000 | -/// an LRU. | |
| 7001 | -const DO_ID_CACHE_MAX: usize = 4096; | |
| 7002 | - | |
| 7003 | -fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] { | |
| 7004 | - use hmac::Mac; | |
| 7005 | - | |
| 7006 | - thread_local! { | |
| 7007 | - static IDS: RefCell<HashMap<(String, String), [u8; 32]>> = | |
| 7008 | - RefCell::new(HashMap::new()); | |
| 7009 | - } | |
| 7010 | - let cached = IDS.with(|ids| { | |
| 7011 | - ids.borrow() | |
| 7012 | - .get(&(namespace_key.to_string(), name.to_string())) | |
| 7013 | - .copied() | |
| 7014 | - }); | |
| 7015 | - if let Some(id) = cached { | |
| 7016 | - return id; | |
| 7017 | - } | |
| 7018 | - | |
| 7019 | - let key = durable_object_id_key(namespace_key); | |
| 7020 | - let mut id = [0_u8; 32]; | |
| 7021 | - let digest = durable_object_id_hmac(&key, name.as_bytes()) | |
| 7022 | - .finalize() | |
| 7023 | - .into_bytes(); | |
| 7024 | - id[..16].copy_from_slice(&digest[..16]); | |
| 7025 | - let digest = durable_object_id_hmac(&key, &id[..16]) | |
| 7026 | - .finalize() | |
| 7027 | - .into_bytes(); | |
| 7028 | - id[16..].copy_from_slice(&digest[..16]); | |
| 7029 | - | |
| 7030 | - IDS.with(|ids| { | |
| 7031 | - let mut ids = ids.borrow_mut(); | |
| 7032 | - if ids.len() >= DO_ID_CACHE_MAX { | |
| 7033 | - ids.clear(); | |
| 7034 | - } | |
| 7035 | - ids.insert((namespace_key.to_string(), name.to_string()), id); | |
| 7036 | - }); | |
| 7037 | - id | |
| 7038 | -} | |
| 7039 | - | |
| 7040 | -/// The key a Durable Object namespace derives its IDs from. D1 uses one | |
| 7041 | -/// fleet-wide namespace because the database is a resource that several | |
| 7042 | -/// Workers can bind, and a Worker rename must not rename that database. | |
| 7043 | -const D1_NAMESPACE_KEY: &str = "cells:v1:d1:__D1Database"; | |
| 7044 | - | |
| 7045 | -/// The same, for a KV namespace, and for the same reason: several Workers can | |
| 7046 | -/// bind one namespace, and they must reach one set of cells. | |
| 7047 | -/// | |
| 7048 | -/// Written out rather than derived from the class name, because these two | |
| 7049 | -/// strings are addresses. A scheme that computed them would be free to change, | |
| 7050 | -/// and changing one renames every cell it ever addressed. | |
| 7051 | -const KV_NAMESPACE_KEY: &str = "cells:v1:kv:__KvNamespace"; | |
| 7052 | - | |
| 7053 | -/// The fleet-wide namespace for Queue broker cells. The queue name is the | |
| 7054 | -/// durable resource identity, so a producer and a consumer in different | |
| 7055 | -/// scripts must derive the same cell id. | |
| 7056 | -const QUEUE_NAMESPACE_KEY: &str = "cells:v1:queue:__Queue"; | |
| 7057 | - | |
| 7058 | -/// A shared reserved class addresses one set of cells for the whole fleet; every | |
| 7059 | -/// other class, reserved or not, is scoped to the script that exports it. | |
| 7060 | -/// | |
| 7061 | -/// The question is asked once, through `deploy::is_shared_reserved_class`, and | |
| 7062 | -/// not as a chain of `==` against class names. A reserved class declared shared | |
| 7063 | -/// there and script-scoped here would silently give each script its own copy of | |
| 7064 | -/// a resource the configuration says they share -- which is what happened to KV | |
| 7065 | -/// between its manifest landing and this line being written. | |
| 7066 | -fn shared_namespace_key(class_name: &str) -> Option<&'static str> { | |
| 7067 | - match class_name { | |
| 7068 | - crate::deploy::D1_CLASS => Some(D1_NAMESPACE_KEY), | |
| 7069 | - crate::deploy::KV_CLASS => Some(KV_NAMESPACE_KEY), | |
| 7070 | - crate::deploy::QUEUE_CLASS => Some(QUEUE_NAMESPACE_KEY), | |
| 7071 | - _ => { | |
| 7072 | - debug_assert!( | |
| 7073 | - !crate::deploy::is_shared_reserved_class(class_name), | |
| 7074 | - "a shared reserved class needs a fleet-wide namespace key: {class_name}" | |
| 7075 | - ); | |
| 7076 | - None | |
| 7077 | - } | |
| 7078 | - } | |
| 7079 | -} | |
| 7080 | - | |
| 7081 | -pub(crate) fn namespace_key(script_name: &str, class_name: &str) -> String { | |
| 7082 | - match shared_namespace_key(class_name) { | |
| 7083 | - Some(shared) => shared.to_string(), | |
| 7084 | - None => format!("cells:v1:{}:{script_name}:{class_name}", script_name.len()), | |
| 7085 | - } | |
| 7086 | -} | |
| 7087 | - | |
| 7088 | -/// The cell scope a D1 database lives at, for a caller outside any isolate. | |
| 7089 | -/// `celld d1` addresses a database over the operator route, which takes a | |
| 7090 | -/// scope, so this derives what `getByName` derives in the harness, from the | |
| 7091 | -/// same key and the same HMAC. | |
| 7092 | -pub fn d1_cell_scope(database_identity: &str) -> String { | |
| 7093 | - let id = durable_object_id_for_name(D1_NAMESPACE_KEY, database_identity); | |
| 7094 | - format!("{}:{}", crate::deploy::D1_CLASS, durable_object_id_hex(&id)) | |
| 7095 | -} | |
| 7096 | - | |
| 7097 | -/// The cell scope one shard of a KV namespace lives at, for a caller outside | |
| 7098 | -/// any isolate. `celld kv` addresses a namespace over the operator route, and | |
| 7099 | -/// this derives what `getByName` derives in the harness -- from the same key, | |
| 7100 | -/// the same name, and the same HMAC. | |
| 7101 | -/// | |
| 7102 | -/// The name comes from `celld_logic::kv::cell_name`, which is also what the | |
| 7103 | -/// binding is handed at `build_env`. Neither side formats it, because a | |
| 7104 | -/// formatting disagreement here does not fail: it silently addresses a second, | |
| 7105 | -/// empty namespace. | |
| 7106 | -pub fn kv_cell_scope(namespace_id: &str, shard: u32) -> String { | |
| 7107 | - let name = celld_logic::kv::cell_name(namespace_id, shard); | |
| 7108 | - let id = durable_object_id_for_name(KV_NAMESPACE_KEY, &name); | |
| 7109 | - format!("{}:{}", crate::deploy::KV_CLASS, durable_object_id_hex(&id)) | |
| 7110 | -} | |
| 7111 | - | |
| 7112 | -/// The Queue broker scope for callers outside a Worker isolate. | |
| 7113 | -pub fn queue_cell_scope(queue: &str) -> String { | |
| 7114 | - let name = celld_logic::queue::cell_name(queue); | |
| 7115 | - let id = durable_object_id_for_name(QUEUE_NAMESPACE_KEY, name); | |
| 7116 | - format!( | |
| 7117 | - "{}:{}", | |
| 7118 | - crate::deploy::QUEUE_CLASS, | |
| 7119 | - durable_object_id_hex(&id) | |
| 7120 | - ) | |
| 7121 | -} | |
| 7122 | - | |
| 7123 | -#[cfg(celld_internal_tests)] | |
| 7124 | -#[doc(hidden)] | |
| 7125 | -pub fn workflow_cell_scope_for_test( | |
| 7126 | - script_name: &str, | |
| 7127 | - workflow_name: &str, | |
| 7128 | - instance_id: &str, | |
| 7129 | -) -> String { | |
| 7130 | - let class = crate::deploy::workflow_class(script_name); | |
| 7131 | - let namespace = namespace_key(script_name, &class); | |
| 7132 | - let name = format!("{workflow_name}/{instance_id}"); | |
| 7133 | - let id = durable_object_id_for_name(&namespace, &name); | |
| 7134 | - format!("{class}:{}", durable_object_id_hex(&id)) | |
| 7135 | -} | |
| 7136 | - | |
| 7137 | -fn durable_object_id_hex(bytes: &[u8; 32]) -> String { | |
| 7138 | - const HEX: &[u8; 16] = b"0123456789abcdef"; | |
| 7139 | - let mut output = String::with_capacity(64); | |
| 7140 | - for byte in bytes { | |
| 7141 | - output.push(HEX[(byte >> 4) as usize] as char); | |
| 7142 | - output.push(HEX[(byte & 0x0f) as usize] as char); | |
| 7143 | - } | |
| 7144 | - output | |
| 7145 | -} | |
| 7146 | - | |
| 7147 | -fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> { | |
| 7148 | - if value.len() != 64 { | |
| 7149 | - return None; | |
| 7150 | - } | |
| 7151 | - let mut output = [0_u8; 32]; | |
| 7152 | - for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() { | |
| 7153 | - let nibble = |byte| match byte { | |
| 7154 | - b'0'..=b'9' => Some(byte - b'0'), | |
| 7155 | - b'a'..=b'f' => Some(byte - b'a' + 10), | |
| 7156 | - b'A'..=b'F' => Some(byte - b'A' + 10), | |
| 7157 | - _ => None, | |
| 7158 | - }; | |
| 7159 | - output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?; | |
| 7160 | - } | |
| 7161 | - Some(output) | |
| 7162 | -} | |
| 7163 | - | |
| 7164 | -fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) { | |
| 7165 | - let message = v8::String::new(scope, message).unwrap(); | |
| 7166 | - let exception = v8::Exception::type_error(scope, message); | |
| 7167 | - scope.throw_exception(exception); | |
| 7168 | -} | |
| 7169 | - | |
| 7170 | -fn register_actor_name( | |
| 7171 | - scope: &mut v8::PinScope, | |
| 7172 | - actor_scope: &str, | |
| 7173 | - name: Option<&str>, | |
| 7174 | -) -> Result<()> { | |
| 7175 | - let Some(name) = name else { | |
| 7176 | - return Ok(()); | |
| 7177 | - }; | |
| 7178 | - let context = scope.get_current_context(); | |
| 7179 | - let global = context.global(scope); | |
| 7180 | - let cell_key = static_key(scope, &v8_strings::CELL); | |
| 7181 | - let cell = global | |
| 7182 | - .get(scope, cell_key.into()) | |
| 7183 | - .and_then(|value| value.to_object(scope)) | |
| 7184 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 7185 | - let names_key = v8::String::new(scope, "idNames").unwrap(); | |
| 7186 | - let names = cell | |
| 7187 | - .get(scope, names_key.into()) | |
| 7188 | - .and_then(|value| value.to_object(scope)) | |
| 7189 | - .ok_or_else(|| anyhow!("missing Durable Object name registry"))?; | |
| 7190 | - let actor_scope_key = v8::String::new(scope, actor_scope).unwrap(); | |
| 7191 | - if let Some(existing) = names.get(scope, actor_scope_key.into()) { | |
| 7192 | - if !existing.is_undefined() { | |
| 7193 | - if existing.to_rust_string_lossy(scope) == name { | |
| 7194 | - return Ok(()); | |
| 7195 | - } | |
| 7196 | - anyhow::bail!("actor name conflicts with active identity for {actor_scope}"); | |
| 7197 | - } | |
| 7198 | - } | |
| 7199 | - | |
| 7200 | - let (class_name, id) = actor_scope | |
| 7201 | - .split_once(':') | |
| 7202 | - .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?; | |
| 7203 | - let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap(); | |
| 7204 | - let namespace_keys = cell | |
| 7205 | - .get(scope, namespace_keys_key.into()) | |
| 7206 | - .and_then(|value| value.to_object(scope)) | |
| 7207 | - .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?; | |
| 7208 | - let class_name_key = v8::String::new(scope, class_name).unwrap(); | |
| 7209 | - let namespace_key = namespace_keys | |
| 7210 | - .get(scope, class_name_key.into()) | |
| 7211 | - .filter(|value| value.is_string()) | |
| 7212 | - .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))? | |
| 7213 | - .to_rust_string_lossy(scope); | |
| 7214 | - let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name)); | |
| 7215 | - if id != expected { | |
| 7216 | - anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}"); | |
| 7217 | - } | |
| 7218 | - storage::set_actor_name(actor_scope, name)?; | |
| 7219 | - | |
| 7220 | - let name_value = v8::String::new(scope, name).unwrap(); | |
| 7221 | - if !names | |
| 7222 | - .set(scope, actor_scope_key.into(), name_value.into()) | |
| 7223 | - .unwrap_or(false) | |
| 7224 | - { | |
| 7225 | - anyhow::bail!("could not register Durable Object name"); | |
| 7226 | - } | |
| 7227 | - Ok(()) | |
| 7228 | -} | |
| 7229 | - | |
| 7230 | -fn op_do_id( | |
| 7231 | - scope: &mut v8::PinScope, | |
| 7232 | - args: v8::FunctionCallbackArguments, | |
| 7233 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 7234 | -) { | |
| 7235 | - use hmac::Mac; | |
| 7236 | - | |
| 7237 | - let namespace_key = args.get(0).to_rust_string_lossy(scope); | |
| 7238 | - let operation = args.get(1).to_rust_string_lossy(scope); | |
| 7239 | - let input = args.get(2).to_rust_string_lossy(scope); | |
| 7240 | - let key = durable_object_id_key(&namespace_key); | |
| 7241 | - let mut id = [0_u8; 32]; | |
| 7242 | - | |
| 7243 | - match operation.as_str() { | |
| 7244 | - "name" => { | |
| 7245 | - id = durable_object_id_for_name(&namespace_key, &input); | |
| 7246 | - rv.set( | |
| 7247 | - v8::String::new(scope, &durable_object_id_hex(&id)) | |
| 7248 | - .unwrap() | |
| 7249 | - .into(), | |
| 7250 | - ); | |
| 7251 | - return; | |
| 7252 | - } | |
| 7253 | - "unique" => { | |
| 7254 | - if getrandom::fill(&mut id[..16]).is_err() { | |
| 7255 | - throw_durable_object_id_error(scope, "secure random generation failed"); | |
| 7256 | - return; | |
| 7257 | - } | |
| 7258 | - } | |
| 7259 | - "validate" => { | |
| 7260 | - let Some(decoded) = decode_durable_object_id(&input) else { | |
| 7261 | - throw_durable_object_id_error( | |
| 7262 | - scope, | |
| 7263 | - "Invalid Durable Object ID: must be 64 hex digits", | |
| 7264 | - ); | |
| 7265 | - return; | |
| 7266 | - }; | |
| 7267 | - if durable_object_id_hmac(&key, &decoded[..16]) | |
| 7268 | - .verify_truncated_left(&decoded[16..]) | |
| 7269 | - .is_err() | |
| 7270 | - { | |
| 7271 | - throw_durable_object_id_error( | |
| 7272 | - scope, | |
| 7273 | - "Durable Object ID is not valid for this namespace", | |
| 7274 | - ); | |
| 7275 | - return; | |
| 7276 | - } | |
| 7277 | - rv.set( | |
| 7278 | - v8::String::new(scope, &input.to_ascii_lowercase()) | |
| 7279 | - .unwrap() | |
| 7280 | - .into(), | |
| 7281 | - ); | |
| 7282 | - return; | |
| 7283 | - } | |
| 7284 | - _ => { | |
| 7285 | - throw_durable_object_id_error(scope, "unknown Durable Object ID operation"); | |
| 7286 | - return; | |
| 7287 | - } | |
| 7288 | - } | |
| 7289 | - | |
| 7290 | - let digest = durable_object_id_hmac(&key, &id[..16]) | |
| 7291 | - .finalize() | |
| 7292 | - .into_bytes(); | |
| 7293 | - id[16..].copy_from_slice(&digest[..16]); | |
| 7294 | - rv.set( | |
| 7295 | - v8::String::new(scope, &durable_object_id_hex(&id)) | |
| 7296 | - .unwrap() | |
| 7297 | - .into(), | |
| 7298 | - ); | |
| 7299 | -} | |
| 7300 | - | |
| 7301 | -fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> { | |
| 7302 | - let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?; | |
| 7303 | - let mut bytes = vec![0_u8; view.byte_length()]; | |
| 7304 | - view.copy_contents(&mut bytes); | |
| 7305 | - Some(bytes) | |
| 7306 | -} | |
| 7307 | - | |
| 7308 | -fn webcrypto_return_bytes( | |
| 7309 | - scope: &mut v8::PinScope, | |
| 7310 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 7311 | - bytes: &[u8], | |
| 7312 | -) { | |
| 7313 | - let buffer = v8::ArrayBuffer::new(scope, bytes.len()); | |
| 7314 | - if !bytes.is_empty() { | |
| 7315 | - let store = buffer.get_backing_store(); | |
| 7316 | - let destination = unsafe { | |
| 7317 | - std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len()) | |
| 7318 | - }; | |
| 7319 | - destination.copy_from_slice(bytes); | |
| 7320 | - } | |
| 7321 | - let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap(); | |
| 7322 | - rv.set(view.into()); | |
| 7323 | -} | |
| 7324 | - | |
| 7325 | -mod crypto; | |
| 7326 | -mod zlib; | |
| 7327 | - | |
| 7328 | -fn op_actor_abort( | |
| 7329 | - scope: &mut v8::PinScope, | |
| 7330 | - args: v8::FunctionCallbackArguments, | |
| 7331 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7332 | -) { | |
| 7333 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 7334 | - let reason = args.get(1).to_rust_string_lossy(scope); | |
| 7335 | - let state = actor_runtime_state(scope); | |
| 7336 | - state | |
| 7337 | - .pending_puts | |
| 7338 | - .lock() | |
| 7339 | - .expect("pending puts lock poisoned") | |
| 7340 | - .remove(&cell); | |
| 7341 | - *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination { | |
| 7342 | - error: format!("__CELLD_ACTOR_ABORT__:{reason}"), | |
| 7343 | - actor_scope: Some(cell), | |
| 7344 | - }); | |
| 7345 | - scope.terminate_execution(); | |
| 7346 | -} | |
| 7347 | - | |
| 7348 | -fn op_process_exit( | |
| 7349 | - scope: &mut v8::PinScope, | |
| 7350 | - args: v8::FunctionCallbackArguments, | |
| 7351 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7352 | -) { | |
| 7353 | - let code = args.get(0).integer_value(scope).unwrap_or(0); | |
| 7354 | - if current_context().depth() == 0 { | |
| 7355 | - tracing::warn!( | |
| 7356 | - code, | |
| 7357 | - "process.exit called without an active request; ignoring" | |
| 7358 | - ); | |
| 7359 | - return; | |
| 7360 | - } | |
| 7361 | - let actor_scope = args.get(1).to_rust_string_lossy(scope); | |
| 7362 | - let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope); | |
| 7363 | - let state = actor_runtime_state(scope); | |
| 7364 | - if let Some(actor_scope) = actor_scope.as_deref() { | |
| 7365 | - state | |
| 7366 | - .pending_puts | |
| 7367 | - .lock() | |
| 7368 | - .expect("pending puts lock poisoned") | |
| 7369 | - .remove(actor_scope); | |
| 7370 | - } | |
| 7371 | - *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination { | |
| 7372 | - error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."), | |
| 7373 | - actor_scope, | |
| 7374 | - }); | |
| 7375 | - scope.terminate_execution(); | |
| 7376 | -} | |
| 7377 | - | |
| 7378 | -fn op_log( | |
| 7379 | - scope: &mut v8::PinScope, | |
| 7380 | - args: v8::FunctionCallbackArguments, | |
| 7381 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7382 | -) { | |
| 7383 | - let msg: Vec<String> = (0..args.length()) | |
| 7384 | - .map(|i| args.get(i).to_rust_string_lossy(scope)) | |
| 7385 | - .collect(); | |
| 7386 | - let body = msg.join(" "); | |
| 7387 | - // Correlated by CPED, so a continuation logging after an await — or | |
| 7388 | - // another entry's continuation running in this turn's checkpoint — | |
| 7389 | - // lands on the trace that owns it, not on whoever holds the isolate. | |
| 7390 | - if crate::telemetry::active() { | |
| 7391 | - let ids = current_trace_ids(scope); | |
| 7392 | - crate::telemetry::record_log(crate::telemetry::Log { | |
| 7393 | - trace_id: ids.as_ref().map(|ids| ids.trace_id), | |
| 7394 | - span_id: ids.as_ref().map(|ids| ids.span_id), | |
| 7395 | - time_unix_us: crate::telemetry::now_unix_us(), | |
| 7396 | - body: body.clone(), | |
| 7397 | - }); | |
| 7398 | - } | |
| 7399 | - tracing::info!(target: "cell_console", "{}", body); | |
| 7400 | -} | |
| 7401 | -fn op_heap_limit_excessively_exceeded( | |
| 7402 | - scope: &mut v8::PinScope, | |
| 7403 | - _args: v8::FunctionCallbackArguments, | |
| 7404 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 7405 | -) { | |
| 7406 | - let exceeded = scope | |
| 7407 | - .get_slot::<Arc<HeapLimitState>>() | |
| 7408 | - .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed)); | |
| 7409 | - rv.set(v8::Boolean::new(scope, exceeded).into()); | |
| 7410 | -} | |
| 7411 | -/// Whether this isolate is too close to its heap limit to retain more state. | |
| 7412 | -fn op_heap_over_admission_share( | |
| 7413 | - scope: &mut v8::PinScope, | |
| 7414 | - _args: v8::FunctionCallbackArguments, | |
| 7415 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 7416 | -) { | |
| 7417 | - let state = scope.get_slot::<Arc<HeapLimitState>>().cloned(); | |
| 7418 | - let over = match state { | |
| 7419 | - // A condemned isolate admits nothing, whatever the heap now reads. | |
| 7420 | - Some(state) | |
| 7421 | - if state.excessively_exceeded.load(Ordering::Relaxed) | |
| 7422 | - || admission_refusal_forced(&state) => | |
| 7423 | - { | |
| 7424 | - true | |
| 7425 | - } | |
| 7426 | - Some(state) => heap_share(scope, state.limit) >= HEAP_ADMISSION_SHARE, | |
| 7427 | - None => false, | |
| 7428 | - }; | |
| 7429 | - rv.set(v8::Boolean::new(scope, over).into()); | |
| 7430 | -} | |
| 7431 | -#[cfg(celld_internal_tests)] | |
| 7432 | -fn op_test_set_heap_limit_excessively_exceeded( | |
| 7433 | - scope: &mut v8::PinScope, | |
| 7434 | - args: v8::FunctionCallbackArguments, | |
| 7435 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7436 | -) { | |
| 7437 | - if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() { | |
| 7438 | - state | |
| 7439 | - .excessively_exceeded | |
| 7440 | - .store(args.get(0).boolean_value(scope), Ordering::Relaxed); | |
| 7441 | - } | |
| 7442 | -} | |
| 7443 | -#[cfg(celld_internal_tests)] | |
| 7444 | -fn op_test_force_heap_admission_refusal( | |
| 7445 | - scope: &mut v8::PinScope, | |
| 7446 | - args: v8::FunctionCallbackArguments, | |
| 7447 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7448 | -) { | |
| 7449 | - if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() { | |
| 7450 | - state | |
| 7451 | - .forced_admission_refusal | |
| 7452 | - .store(args.get(0).boolean_value(scope), Ordering::Relaxed); | |
| 7453 | - } | |
| 7454 | -} | |
| 7455 | -#[cfg(celld_internal_tests)] | |
| 7456 | -fn op_test_gc( | |
| 7457 | - scope: &mut v8::PinScope, | |
| 7458 | - _args: v8::FunctionCallbackArguments, | |
| 7459 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7460 | -) { | |
| 7461 | - scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full); | |
| 7462 | -} | |
| 7463 | - | |
| 7464 | -#[cfg(celld_internal_tests)] | |
| 7465 | -thread_local! { | |
| 7466 | - static FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION: std::cell::Cell<bool> = const { | |
| 7467 | - std::cell::Cell::new(false) | |
| 7468 | - }; | |
| 7469 | - static FAIL_NEXT_WORKFLOW_META_CREATION: std::cell::Cell<bool> = const { | |
| 7470 | - std::cell::Cell::new(false) | |
| 7471 | - }; | |
| 7472 | - static FAIL_NEXT_WORKFLOW_ALARM_DELETION: std::cell::Cell<bool> = const { | |
| 7473 | - std::cell::Cell::new(false) | |
| 7474 | - }; | |
| 7475 | - static FAIL_NEXT_QUEUE_DLQ_ACCEPT: std::cell::Cell<bool> = const { | |
| 7476 | - std::cell::Cell::new(false) | |
| 7477 | - }; | |
| 7478 | - static QUEUE_DLQ_ACCEPT_CALLS: std::cell::Cell<usize> = const { | |
| 7479 | - std::cell::Cell::new(0) | |
| 7480 | - }; | |
| 7481 | - static QUEUE_METRICS_MATERIALIZED: std::cell::Cell<bool> = const { | |
| 7482 | - std::cell::Cell::new(false) | |
| 7483 | - }; | |
| 7484 | - static QUEUE_REARM_OBSERVED: std::cell::Cell<bool> = const { | |
| 7485 | - std::cell::Cell::new(false) | |
| 7486 | - }; | |
| 7487 | - static QUEUE_REARM_POSITIVE: std::cell::Cell<bool> = const { | |
| 7488 | - std::cell::Cell::new(false) | |
| 7489 | - }; | |
| 7490 | - static QUEUE_REARM_BOUND_VIOLATED: std::cell::Cell<bool> = const { | |
| 7491 | - std::cell::Cell::new(false) | |
| 7492 | - }; | |
| 7493 | - static QUEUE_SETTLEMENT_POLICY_OBSERVED: std::cell::Cell<bool> = const { | |
| 7494 | - std::cell::Cell::new(false) | |
| 7495 | - }; | |
| 7496 | - static QUEUE_LEASE_LOOKUP_PLANS: std::cell::RefCell<Vec<String>> = const { | |
| 7497 | - std::cell::RefCell::new(Vec::new()) | |
| 7498 | - }; | |
| 7499 | -} | |
| 7500 | - | |
| 7501 | -#[cfg(celld_internal_tests)] | |
| 7502 | -#[doc(hidden)] | |
| 7503 | -pub fn fail_next_workflow_event_consumption_for_test() { | |
| 7504 | - FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION.with(|fail| fail.set(true)); | |
| 7505 | -} | |
| 7506 | - | |
| 7507 | -#[cfg(celld_internal_tests)] | |
| 7508 | -#[doc(hidden)] | |
| 7509 | -pub fn fail_next_workflow_meta_creation_for_test() { | |
| 7510 | - FAIL_NEXT_WORKFLOW_META_CREATION.with(|fail| fail.set(true)); | |
| 7511 | -} | |
| 7512 | - | |
| 7513 | -#[cfg(celld_internal_tests)] | |
| 7514 | -#[doc(hidden)] | |
| 7515 | -pub fn fail_next_workflow_alarm_deletion_for_test() { | |
| 7516 | - FAIL_NEXT_WORKFLOW_ALARM_DELETION.with(|fail| fail.set(true)); | |
| 7517 | -} | |
| 7518 | - | |
| 7519 | -#[cfg(celld_internal_tests)] | |
| 7520 | -#[doc(hidden)] | |
| 7521 | -pub fn fail_next_queue_dlq_accept_for_test() { | |
| 7522 | - FAIL_NEXT_QUEUE_DLQ_ACCEPT.with(|fail| fail.set(true)); | |
| 7523 | -} | |
| 7524 | - | |
| 7525 | -#[cfg(celld_internal_tests)] | |
| 7526 | -pub fn reset_queue_dlq_accept_calls_for_test() { | |
| 7527 | - QUEUE_DLQ_ACCEPT_CALLS.with(|calls| calls.set(0)); | |
| 7528 | -} | |
| 7529 | - | |
| 7530 | -#[cfg(celld_internal_tests)] | |
| 7531 | -#[doc(hidden)] | |
| 7532 | -pub fn queue_dlq_accept_calls_for_test() -> usize { | |
| 7533 | - QUEUE_DLQ_ACCEPT_CALLS.with(std::cell::Cell::get) | |
| 7534 | -} | |
| 7535 | - | |
| 7536 | -#[cfg(celld_internal_tests)] | |
| 7537 | -pub fn reset_queue_hot_path_observations_for_test() { | |
| 7538 | - QUEUE_METRICS_MATERIALIZED.with(|observed| observed.set(false)); | |
| 7539 | - QUEUE_REARM_OBSERVED.with(|observed| observed.set(false)); | |
| 7540 | - QUEUE_REARM_POSITIVE.with(|observed| observed.set(false)); | |
| 7541 | - QUEUE_REARM_BOUND_VIOLATED.with(|violated| violated.set(false)); | |
| 7542 | -} | |
| 7543 | - | |
| 7544 | -#[cfg(celld_internal_tests)] | |
| 7545 | -#[doc(hidden)] | |
| 7546 | -pub fn queue_hot_path_observations_for_test() -> (bool, bool, bool) { | |
| 7547 | - let materialized = QUEUE_METRICS_MATERIALIZED.with(std::cell::Cell::get); | |
| 7548 | - let bounded = QUEUE_REARM_OBSERVED.with(std::cell::Cell::get) | |
| 7549 | - && QUEUE_REARM_POSITIVE.with(std::cell::Cell::get) | |
| 7550 | - && !QUEUE_REARM_BOUND_VIOLATED.with(std::cell::Cell::get); | |
| 7551 | - let violated = QUEUE_REARM_BOUND_VIOLATED.with(std::cell::Cell::get); | |
| 7552 | - (materialized, bounded, violated) | |
| 7553 | -} | |
| 7554 | - | |
| 7555 | -#[cfg(celld_internal_tests)] | |
| 7556 | -#[doc(hidden)] | |
| 7557 | -pub fn reset_queue_lease_lookup_plans_for_test() { | |
| 7558 | - QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow_mut().clear()); | |
| 7559 | -} | |
| 7560 | - | |
| 7561 | -#[cfg(celld_internal_tests)] | |
| 7562 | -#[doc(hidden)] | |
| 7563 | -pub fn queue_lease_lookup_plans_for_test() -> Vec<String> { | |
| 7564 | - QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow().clone()) | |
| 7565 | -} | |
| 7566 | - | |
| 7567 | -#[cfg(celld_internal_tests)] | |
| 7568 | -#[doc(hidden)] | |
| 7569 | -pub fn reset_queue_settlement_policy_observation_for_test() { | |
| 7570 | - QUEUE_SETTLEMENT_POLICY_OBSERVED.with(|observed| observed.set(false)); | |
| 7571 | -} | |
| 7572 | - | |
| 7573 | -#[cfg(celld_internal_tests)] | |
| 7574 | -#[doc(hidden)] | |
| 7575 | -pub fn queue_settlement_policy_observed_for_test() -> bool { | |
| 7576 | - QUEUE_SETTLEMENT_POLICY_OBSERVED.with(std::cell::Cell::get) | |
| 7577 | -} | |
| 7578 | - | |
| 7579 | -#[cfg(celld_internal_tests)] | |
| 7580 | -fn op_test_workflow_event_consumed( | |
| 7581 | - scope: &mut v8::PinScope, | |
| 7582 | - _args: v8::FunctionCallbackArguments, | |
| 7583 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7584 | -) { | |
| 7585 | - let fail = FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION.with(|fail| fail.replace(false)); | |
| 7586 | - if fail { | |
| 7587 | - throw_storage_error( | |
| 7588 | - scope, | |
| 7589 | - "workflow event consumption", | |
| 7590 | - "injected failure after workflow event delete", | |
| 7591 | - ); | |
| 7592 | - } | |
| 7593 | -} | |
| 7594 | - | |
| 7595 | -#[cfg(celld_internal_tests)] | |
| 7596 | -fn op_test_workflow_meta_created( | |
| 7597 | - scope: &mut v8::PinScope, | |
| 7598 | - _args: v8::FunctionCallbackArguments, | |
| 7599 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7600 | -) { | |
| 7601 | - let fail = FAIL_NEXT_WORKFLOW_META_CREATION.with(|fail| fail.replace(false)); | |
| 7602 | - if fail { | |
| 7603 | - throw_storage_error( | |
| 7604 | - scope, | |
| 7605 | - "workflow creation", | |
| 7606 | - "injected failure after workflow metadata write", | |
| 7607 | - ); | |
| 7608 | - } | |
| 7609 | -} | |
| 7610 | - | |
| 7611 | -#[cfg(celld_internal_tests)] | |
| 7612 | -fn op_test_workflow_alarm_deleted( | |
| 7613 | - scope: &mut v8::PinScope, | |
| 7614 | - _args: v8::FunctionCallbackArguments, | |
| 7615 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7616 | -) { | |
| 7617 | - let fail = FAIL_NEXT_WORKFLOW_ALARM_DELETION.with(|fail| fail.replace(false)); | |
| 7618 | - if fail { | |
| 7619 | - throw_storage_error( | |
| 7620 | - scope, | |
| 7621 | - "workflow alarm deletion", | |
| 7622 | - "injected failure after workflow alarm delete", | |
| 7623 | - ); | |
| 7624 | - } | |
| 7625 | -} | |
| 7626 | - | |
| 7627 | -#[cfg(celld_internal_tests)] | |
| 7628 | -fn op_test_queue_dlq_accepted( | |
| 7629 | - scope: &mut v8::PinScope, | |
| 7630 | - _args: v8::FunctionCallbackArguments, | |
| 7631 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7632 | -) { | |
| 7633 | - QUEUE_DLQ_ACCEPT_CALLS.with(|calls| calls.set(calls.get() + 1)); | |
| 7634 | - let fail = FAIL_NEXT_QUEUE_DLQ_ACCEPT.with(|fail| fail.replace(false)); | |
| 7635 | - if fail { | |
| 7636 | - throw_storage_error( | |
| 7637 | - scope, | |
| 7638 | - "Queue DLQ transfer", | |
| 7639 | - "injected failure after the target accepted the message", | |
| 7640 | - ); | |
| 7641 | - } | |
| 7642 | -} | |
| 7643 | - | |
| 7644 | -#[cfg(celld_internal_tests)] | |
| 7645 | -fn op_test_queue_metrics_materialized( | |
| 7646 | - _scope: &mut v8::PinScope, | |
| 7647 | - _args: v8::FunctionCallbackArguments, | |
| 7648 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7649 | -) { | |
| 7650 | - QUEUE_METRICS_MATERIALIZED.with(|observed| observed.set(true)); | |
| 7651 | -} | |
| 7652 | - | |
| 7653 | -#[cfg(celld_internal_tests)] | |
| 7654 | -fn op_test_queue_lease_lookup_plan( | |
| 7655 | - scope: &mut v8::PinScope, | |
| 7656 | - args: v8::FunctionCallbackArguments, | |
| 7657 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7658 | -) { | |
| 7659 | - let plan = args.get(0).to_rust_string_lossy(scope); | |
| 7660 | - QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow_mut().push(plan)); | |
| 7661 | -} | |
| 7662 | - | |
| 7663 | -#[cfg(celld_internal_tests)] | |
| 7664 | -fn op_test_queue_rearm_bounded( | |
| 7665 | - scope: &mut v8::PinScope, | |
| 7666 | - args: v8::FunctionCallbackArguments, | |
| 7667 | - _rv: v8::ReturnValue<v8::Value>, | |
| 7668 | -) { | |
| 7669 | - QUEUE_REARM_OBSERVED.with(|observed| observed.set(true)); | |
| 7670 | - QUEUE_REARM_POSITIVE.with(|observed| observed.set(observed.get() || args.get(1).is_true())); | |
| 7671 | - if !args.get(0).boolean_value(scope) { | |
| 7672 | - QUEUE_REARM_BOUND_VIOLATED.with(|violated| violated.set(true)); | |
| 7673 | - } | |
| 7674 | -} | |
| 7675 | -mod r2_ops; | |
| 7676 | -mod storage_ops; | |
| 7677 | -use storage_ops::{actor_runtime_state, throw_storage_error}; | |
| 7678 | - | |
| 7679 | -/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href} | |
| 7680 | -/// Backed by the WHATWG-conformant `url` crate. | |
| 7681 | -fn op_url_parse( | |
| 7682 | - scope: &mut v8::PinScope, | |
| 7683 | - args: v8::FunctionCallbackArguments, | |
| 7684 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 7685 | -) { | |
| 7686 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 7687 | - let base = args.get(1); | |
| 7688 | - let parsed = if base.is_undefined() { | |
| 7689 | - url::Url::parse(&input) | |
| 7690 | - } else { | |
| 7691 | - url::Url::options() | |
| 7692 | - .base_url( | |
| 7693 | - url::Url::parse(&base.to_rust_string_lossy(scope)) | |
| 7694 | - .ok() | |
| 7695 | - .as_ref(), | |
| 7696 | - ) | |
| 7697 | - .parse(&input) | |
| 7698 | - }; | |
| 7699 | - let u = match parsed { | |
| 7700 | - Ok(u) => u, | |
| 7701 | - Err(e) => { | |
| 7702 | - let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap(); | |
| 7703 | - let exc = v8::Exception::type_error(scope, msg); | |
| 7704 | - scope.throw_exception(exc); | |
| 7705 | - return; | |
| 7706 | - } | |
| 7707 | - }; | |
| 7708 | - let o = v8::Object::new(scope); | |
| 7709 | - // The nine keys are fixed, so they come from the constant table rather | |
| 7710 | - // than from nine fresh `v8::String`s per `new URL(...)`. | |
| 7711 | - // | |
| 7712 | - // A set can still fail — a throwing setter on `Object.prototype` reaches | |
| 7713 | - // this plain object — and a URL record missing a component is worse than | |
| 7714 | - // no record at all, so the first refusal stops the build. | |
| 7715 | - let port = u.port().map(|p| p.to_string()).unwrap_or_default(); | |
| 7716 | - let fields: [(&'static v8::OneByteConst, &str); 9] = [ | |
| 7717 | - (&v8_strings::URL_PROTOCOL, u.scheme()), | |
| 7718 | - (&v8_strings::URL_USERNAME, u.username()), | |
| 7719 | - (&v8_strings::URL_PASSWORD, u.password().unwrap_or("")), | |
| 7720 | - (&v8_strings::URL_HOST, u.host_str().unwrap_or("")), | |
| 7721 | - (&v8_strings::URL_PORT, &port), | |
| 7722 | - (&v8_strings::URL_PATHNAME, u.path()), | |
| 7723 | - (&v8_strings::URL_SEARCH, u.query().unwrap_or("")), | |
| 7724 | - (&v8_strings::URL_HASH, u.fragment().unwrap_or("")), | |
| 7725 | - (&v8_strings::URL_HREF, u.as_str()), | |
| 7726 | - ]; | |
| 7727 | - for (k, v) in fields { | |
| 7728 | - let key = static_key(scope, k); | |
| 7729 | - let val = v8::String::new(scope, v).unwrap(); | |
| 7730 | - match o.set(scope, key.into(), val.into()) { | |
| 7731 | - Some(true) => {} | |
| 7732 | - // The setter threw. Its exception is already pending, and it names | |
| 7733 | - // the real cause, so it propagates unchanged. Throwing a generic | |
| 7734 | - // TypeError here would overwrite it and hide that cause. | |
| 7735 | - None => return, | |
| 7736 | - // A refusal that does not throw — a non-writable inherited data | |
| 7737 | - // property, in sloppy mode — leaves no pending exception, so this | |
| 7738 | - // path has to raise one of its own. | |
| 7739 | - Some(false) => { | |
| 7740 | - let name = key.to_rust_string_lossy(scope); | |
| 7741 | - let msg = v8::String::new( | |
| 7742 | - scope, | |
| 7743 | - &format!("Invalid URL: the {name} property of the URL record was refused"), | |
| 7744 | - ) | |
| 7745 | - .unwrap(); | |
| 7746 | - let exc = v8::Exception::type_error(scope, msg); | |
| 7747 | - scope.throw_exception(exc); | |
| 7748 | - return; | |
| 7749 | - } | |
| 7750 | - } | |
| 7751 | - } | |
| 7752 | - rv.set(o.into()); | |
| 7753 | -} | |
| 7754 | - | |
| 7755 | -// URLPattern host seam, split like Deno's: pattern parsing and match-input | |
| 7756 | -// canonicalization run in Rust via the `urlpattern` crate; per-match regex | |
| 7757 | -// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the | |
| 7758 | -// boundary — both ops run at construct/match-canonicalize time only. | |
| 7759 | - | |
| 7760 | -/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a | |
| 7761 | -/// pattern string or an init object of string components. Returns | |
| 7762 | -/// per-component `{ patternString, regexpString, groupNameList }` plus | |
| 7763 | -/// `hasRegexpGroups`. Throws TypeError on an invalid pattern. | |
| 7764 | -fn op_urlpattern_parse( | |
| 7765 | - scope: &mut v8::PinScope, | |
| 7766 | - args: v8::FunctionCallbackArguments, | |
| 7767 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 7768 | -) { | |
| 7769 | - use urlpattern::quirks; | |
| 7770 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 7771 | - let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap(); | |
| 7772 | - let base = args.get(1); | |
| 7773 | - let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope)); | |
| 7774 | - let options = urlpattern::UrlPatternOptions { | |
| 7775 | - ignore_case: args.get(2).boolean_value(scope), | |
| 7776 | - }; | |
| 7777 | - let pattern = quirks::process_construct_pattern_input(input, base.as_deref()) | |
| 7778 | - .and_then(|init| quirks::parse_pattern(init, options)); | |
| 7779 | - let p = match pattern { | |
| 7780 | - Ok(p) => p, | |
| 7781 | - Err(e) => { | |
| 7782 | - let msg = v8::String::new(scope, &e.to_string()).unwrap(); | |
| 7783 | - let exc = v8::Exception::type_error(scope, msg); | |
| 7784 | - scope.throw_exception(exc); | |
| 7785 | - return; | |
| 7786 | - } | |
| 7787 | - }; | |
| 7788 | - let component = |c: &quirks::UrlPatternComponent| { | |
| 7789 | - serde_json::json!({ | |
| 7790 | - "patternString": c.pattern_string, | |
| 7791 | - "regexpString": c.regexp_string, | |
| 7792 | - "groupNameList": c.group_name_list, | |
| 7793 | - }) | |
| 7794 | - }; | |
| 7795 | - let out = serde_json::json!({ | |
| 7796 | - "protocol": component(&p.protocol), | |
| 7797 | - "username": component(&p.username), | |
| 7798 | - "password": component(&p.password), | |
| 7799 | - "hostname": component(&p.hostname), | |
| 7800 | - "port": component(&p.port), | |
| 7801 | - "pathname": component(&p.pathname), | |
| 7802 | - "search": component(&p.search), | |
| 7803 | - "hash": component(&p.hash), | |
| 7804 | - "hasRegexpGroups": p.has_regexp_groups, | |
| 7805 | - }); | |
| 7806 | - rv.set(v8::String::new(scope, &out.to_string()).unwrap().into()); | |
| 7807 | -} | |
| 7808 | - | |
| 7809 | -/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in | |
| 7810 | -/// component order (protocol..hash), or `null` when the input does not parse | |
| 7811 | -/// as a URL. Throws TypeError for an init combined with a baseURL argument. | |
| 7812 | -fn op_urlpattern_match_input( | |
| 7813 | - scope: &mut v8::PinScope, | |
| 7814 | - args: v8::FunctionCallbackArguments, | |
| 7815 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 7816 | -) { | |
| 7817 | - use urlpattern::quirks; | |
| 7818 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 7819 | - let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap(); | |
| 7820 | - let base = args.get(1); | |
| 7821 | - let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope)); | |
| 7822 | - let null = v8::null(scope).into(); | |
| 7823 | - let m = match quirks::process_match_input(input, base.as_deref()) { | |
| 7824 | - Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) { | |
| 7825 | - Some(m) => m, | |
| 7826 | - None => return rv.set(null), | |
| 7827 | - }, | |
| 7828 | - Ok(None) => return rv.set(null), | |
| 7829 | - Err(e) => { | |
| 7830 | - let msg = v8::String::new(scope, &e.to_string()).unwrap(); | |
| 7831 | - let exc = v8::Exception::type_error(scope, msg); | |
| 7832 | - scope.throw_exception(exc); | |
| 7833 | - return; | |
| 7834 | - } | |
| 7835 | - }; | |
| 7836 | - let out = serde_json::json!([ | |
| 7837 | - m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash, | |
| 7838 | - ]); | |
| 7839 | - rv.set(v8::String::new(scope, &out.to_string()).unwrap().into()); | |
| 7840 | -} | |
| 7841 | - | |
| 7842 | -fn op_atob( | |
| 7843 | - scope: &mut v8::PinScope, | |
| 7844 | - args: v8::FunctionCallbackArguments, | |
| 7845 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 7846 | -) { | |
| 7847 | - use base64::Engine; | |
| 7848 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 7849 | - let cleaned: String = input.chars().filter(|c| !c.is_whitespace()).collect(); | |
| 7850 | - match base64::engine::general_purpose::STANDARD.decode(cleaned) { | |
| 7851 | - Ok(bytes) => { | |
| 7852 | - // The public `atob()` wrapper omits this argument and keeps the | |
| 7853 | - // required binary-string result. The KV operator protocol asks | |
| 7854 | - // for a typed view, so a 25 MiB value does not become 25 million | |
| 7855 | - // JavaScript numbers before the cell can store it. | |
| 7856 | - if args.get(1).boolean_value(scope) { | |
| 7857 | - rv.set(bytes_value(scope, bytes)); | |
| 7858 | - return; | |
| 7859 | - } | |
| 7860 | - // atob returns a binary string (latin1) | |
| 7861 | - let s: String = bytes.iter().map(|&b| b as char).collect(); | |
| 7862 | - rv.set(v8::String::new(scope, &s).unwrap().into()); | |
| 7863 | - } | |
| 7864 | - Err(_) => { | |
| 7865 | - let msg = v8::String::new(scope, "Invalid base64").unwrap(); | |
| 7866 | - let exc = v8::Exception::error(scope, msg); | |
| 7867 | - scope.throw_exception(exc); | |
| 7868 | - } | |
| 7869 | - } | |
| 7870 | -} | |
| 7871 | - | |
| 7872 | -// node:util introspection seam: V8-level queries that JS cannot perform, | |
| 7873 | -// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy | |
| 7874 | -// node:async_hooks prelude calls these. The value is V8's | |
| 7875 | -// continuation-preserved embedder data — the primitive Workerd's | |
| 7876 | -// AsyncContextFrame rides — which V8 itself captures and restores | |
| 7877 | -// around every promise reaction. No promise hooks are installed. A stateless | |
| 7878 | -// isolate that never touches AsyncLocalStorage leaves the frame absent; a cell | |
| 7879 | -// event still carries the separate native context token described below. | |
| 7880 | - | |
| 7881 | -#[derive(Default)] | |
| 7882 | -struct IoEventFrame { | |
| 7883 | - wait_until: Vec<v8::Global<v8::Promise>>, | |
| 7884 | - arm_gates: Vec<ArmGateRx>, | |
| 7885 | -} | |
| 7886 | - | |
| 7887 | -#[derive(Default)] | |
| 7888 | -struct IoEventState { | |
| 7889 | - frames: Vec<IoEventFrame>, | |
| 7890 | - ended_arm_gates: Vec<ArmGateRx>, | |
| 7891 | - arm_gates_sealed: bool, | |
| 7892 | -} | |
| 7893 | - | |
| 7894 | -/// The per-request context: everything a request owns while it is in flight. | |
| 7895 | -/// | |
| 7896 | -/// Modelled on workerd's `IoContext`. The host owns it, not JS: a request's | |
| 7897 | -/// event frames and the `waitUntil` promises inside them live here, and JS | |
| 7898 | -/// reaches them only through ops that ask for the *current* context. That | |
| 7899 | -/// inversion is the point. While an isolate serves one request at a time, | |
| 7900 | -/// JS-side per-request state is indistinguishable from isolate-side state, | |
| 7901 | -/// and the two silently diverge the moment requests interleave — one | |
| 7902 | -/// request's `__endEvent` popping another's event, its `waitUntil` work | |
| 7903 | -/// attributed to a request that never asked for it. | |
| 7904 | -/// | |
| 7905 | -/// `current()` is a thread-local the host installs for the duration of a | |
| 7906 | -/// turn and restores on the way out, exactly as `threadLocalRequest` is set | |
| 7907 | -/// in `IoContext::runInContextScope` and restored by `SuppressIoContextScope`. | |
| 7908 | -/// An op that needs a context and finds none is a bug in the host, not in | |
| 7909 | -/// the script, so it says so rather than inventing one. | |
| 7910 | -/// | |
| 7911 | -/// **It is `Send + Sync`, and that is load-bearing.** Under D1 a request is | |
| 7912 | -/// a tokio task that suspends between turns and can resume on any worker, so | |
| 7913 | -/// the context it carries has to cross threads with it. `Rc` and `RefCell` | |
| 7914 | -/// would forbid that. The isolate keeps one narrow weak lookup from a CPED | |
| 7915 | -/// continuation token to this context, because a reaction can run during a | |
| 7916 | -/// different event's checkpoint. That lookup owns no context, operation, or | |
| 7917 | -/// resolver, and `IoContext::drop` removes it. It therefore attributes the | |
| 7918 | -/// running reaction without rebuilding the pump's lifetime-owning `idmap`. | |
| 7919 | -/// The interiors are `Mutex`; only the isolate's holder reaches them. | |
| 7920 | -pub struct IoContext { | |
| 7921 | - /// A per-isolate identity captured by V8 with each promise reaction. | |
| 7922 | - /// The registry holds only a `Weak`, so a continuation cannot extend the | |
| 7923 | - /// request lifetime after its `InFlight` owner retires. | |
| 7924 | - continuation: Option<(u64, Weak<ActorRuntimeState>)>, | |
| 7925 | - /// This caller's delivery order for each cell it has called. See | |
| 7926 | - /// `CallOrder` — it is here rather than in a process-wide map because | |
| 7927 | - /// nothing outside this caller ever reads it. | |
| 7928 | - pub call_chains: Mutex<CallChains>, | |
| 7929 | - /// Event frames, innermost last. A frame collects the `waitUntil` | |
| 7930 | - /// promises registered while it is the innermost one. | |
| 7931 | - /// | |
| 7932 | - /// Nesting is per-request and strictly LIFO — a service-binding | |
| 7933 | - /// dispatch, an RPC entry, or a DO construction pushes its own frame so | |
| 7934 | - /// its `waitUntil` binds to that dispatch, matching workerd. | |
| 7935 | - events: Mutex<IoEventState>, | |
| 7936 | - /// Isolate-polled sockets this request opened. Dropping the request's | |
| 7937 | - /// pending ops aborts everything the isolate is waiting on, but a socket | |
| 7938 | - /// is a host-side resource that abort cannot reach: its connector task | |
| 7939 | - /// exits only when the isolate stops reading. So the request closes its | |
| 7940 | - /// own sockets, and [`IoContext::drop`] is what makes that unforgettable. | |
| 7941 | - /// | |
| 7942 | - /// Flat rather than a stack. Only sockets that belong to no cell land | |
| 7943 | - /// here, and one `IoContext` is one request, so there is nothing to nest: | |
| 7944 | - /// a service-binding dispatch or a Durable Object call gets a context of | |
| 7945 | - /// its own rather than a frame inside this one. | |
| 7946 | - sockets: Mutex<Vec<u64>>, | |
| 7947 | - /// Host-backed request bodies this handler owns. A subrequest transfers | |
| 7948 | - /// an id out before its target takes ownership, so only one request can | |
| 7949 | - /// reclaim an unread tail. | |
| 7950 | - body_streams: Mutex<std::collections::HashSet<u64>>, | |
| 7951 | - /// Output-gate capture. While a `webSocketMessage` runs, the frames it | |
| 7952 | - /// sends are collected here instead of reaching the wire, so the shell | |
| 7953 | - /// can hold them until the message's write is durable. A stack, so a | |
| 7954 | - /// nested dispatch keeps its frames apart from the outer one's. | |
| 7955 | - /// | |
| 7956 | - /// On the event and not on the thread, because an event outlives the | |
| 7957 | - /// turn that began it: capture starts in one turn and is taken in a | |
| 7958 | - /// later one, which tokio may run on a different worker. | |
| 7959 | - ws_capture: Mutex<Vec<Vec<(u64, WsOut)>>>, | |
| 7960 | - /// Which cell an event belongs to, and the committed-write position it | |
| 7961 | - /// started at, innermost last. An outbound effect raised during the | |
| 7962 | - /// event consults this: if the handler has advanced the position, the | |
| 7963 | - /// effect waits for the output gate before it leaves the process. | |
| 7964 | - /// | |
| 7965 | - /// Empty for stateless Worker code, which owns no cell and gates | |
| 7966 | - /// nothing. | |
| 7967 | - egress: Mutex<Vec<(String, u64)>>, | |
| 7968 | -} | |
| 7969 | - | |
| 7970 | -impl IoContext { | |
| 7971 | - #[allow(clippy::new_ret_no_self, clippy::new_without_default)] | |
| 7972 | - #[doc(hidden)] | |
| 7973 | - pub fn new() -> Arc<Self> { | |
| 7974 | - Arc::new(Self { | |
| 7975 | - continuation: None, | |
| 7976 | - call_chains: Mutex::new(CallChains::default()), | |
| 7977 | - events: Mutex::new(IoEventState::default()), | |
| 7978 | - sockets: Mutex::new(Vec::new()), | |
| 7979 | - body_streams: Mutex::new(std::collections::HashSet::new()), | |
| 7980 | - ws_capture: Mutex::new(Vec::new()), | |
| 7981 | - egress: Mutex::new(Vec::new()), | |
| 7982 | - }) | |
| 7983 | - } | |
| 7984 | - | |
| 7985 | - fn tracked(runtime_state: &Arc<ActorRuntimeState>) -> Arc<Self> { | |
| 7986 | - let id = runtime_state.allocate_io_context_id(); | |
| 7987 | - let context = Arc::new(Self { | |
| 7988 | - continuation: Some((id, Arc::downgrade(runtime_state))), | |
| 7989 | - call_chains: Mutex::new(CallChains::default()), | |
| 7990 | - events: Mutex::new(IoEventState::default()), | |
| 7991 | - sockets: Mutex::new(Vec::new()), | |
| 7992 | - body_streams: Mutex::new(std::collections::HashSet::new()), | |
| 7993 | - ws_capture: Mutex::new(Vec::new()), | |
| 7994 | - egress: Mutex::new(Vec::new()), | |
| 7995 | - }); | |
| 7996 | - runtime_state | |
| 7997 | - .io_contexts | |
| 7998 | - .lock() | |
| 7999 | - .unwrap() | |
| 8000 | - .insert(id, Arc::downgrade(&context)); | |
| 8001 | - context | |
| 8002 | - } | |
| 8003 | - | |
| 8004 | - fn begin_event(&self) { | |
| 8005 | - self.events | |
| 8006 | - .lock() | |
| 8007 | - .unwrap() | |
| 8008 | - .frames | |
| 8009 | - .push(IoEventFrame::default()); | |
| 8010 | - } | |
| 8011 | - | |
| 8012 | - /// Pop the innermost frame and hand back what it collected. `None` when | |
| 8013 | - /// there is no frame, which is a script calling `waitUntil` outside any | |
| 8014 | - /// event; the harness turns that into workerd's global-scope error. | |
| 8015 | - fn end_event(&self) -> Option<Vec<v8::Global<v8::Promise>>> { | |
| 8016 | - let mut events = self.events.lock().unwrap(); | |
| 8017 | - let mut frame = events.frames.pop()?; | |
| 8018 | - if events.arm_gates_sealed { | |
| 8019 | - drop(frame.arm_gates); | |
| 8020 | - } else if let Some(parent) = events.frames.last_mut() { | |
| 8021 | - parent.arm_gates.append(&mut frame.arm_gates); | |
| 8022 | - } else { | |
| 8023 | - events.ended_arm_gates.append(&mut frame.arm_gates); | |
| 8024 | - } | |
| 8025 | - Some(frame.wait_until) | |
| 8026 | - } | |
| 8027 | - | |
| 8028 | - fn register_wait_until(&self, promise: v8::Global<v8::Promise>) { | |
| 8029 | - if let Some(frame) = self.events.lock().unwrap().frames.last_mut() { | |
| 8030 | - frame.wait_until.push(promise); | |
| 8031 | - } | |
| 8032 | - } | |
| 8033 | - | |
| 8034 | - fn register_arm_gate(&self, gate: ArmGateRx) -> Result<(), ArmGateRx> { | |
| 8035 | - let mut events = self.events.lock().unwrap(); | |
| 8036 | - if events.arm_gates_sealed { | |
| 8037 | - return Err(gate); | |
| 8038 | - } | |
| 8039 | - if let Some(frame) = events.frames.last_mut() { | |
| 8040 | - frame.arm_gates.push(gate); | |
| 8041 | - } else { | |
| 8042 | - // `op_event_end` pops the final frame before `Promise.allSettled` | |
| 8043 | - // can invoke a user-defined `then`. A gate created during that | |
| 8044 | - // call still belongs to this event until `take_arm_gates` seals | |
| 8045 | - // the response boundary. | |
| 8046 | - events.ended_arm_gates.push(gate); | |
| 8047 | - } | |
| 8048 | - Ok(()) | |
| 8049 | - } | |
| 8050 | - | |
| 8051 | - /// Take every response gate that this event owns. | |
| 8052 | - /// | |
| 8053 | - /// The normal path takes gates moved out by `end_event`. Active frames | |
| 8054 | - /// cover failures that cannot run JavaScript again, such as a timeout or | |
| 8055 | - /// an isolate termination. | |
| 8056 | - fn take_arm_gates(&self) -> Vec<ArmGateRx> { | |
| 8057 | - let mut events = self.events.lock().unwrap(); | |
| 8058 | - if events.arm_gates_sealed { | |
| 8059 | - return Vec::new(); | |
| 8060 | - } | |
| 8061 | - events.arm_gates_sealed = true; | |
| 8062 | - let mut gates = std::mem::take(&mut events.ended_arm_gates); | |
| 8063 | - for frame in &mut events.frames { | |
| 8064 | - gates.append(&mut frame.arm_gates); | |
| 8065 | - } | |
| 8066 | - gates | |
| 8067 | - } | |
| 8068 | - | |
| 8069 | - fn depth(&self) -> usize { | |
| 8070 | - self.events.lock().unwrap().frames.len() | |
| 8071 | - } | |
| 8072 | - | |
| 8073 | - /// Close every isolate-polled socket this request opened. | |
| 8074 | - /// | |
| 8075 | - /// Draining makes the operation idempotent. The drive loop calls it when | |
| 8076 | - /// the request retires, and `drop` covers every earlier failure path. | |
| 8077 | - fn close_sockets(&self) { | |
| 8078 | - let opened = self.sockets.lock().unwrap().drain(..).collect(); | |
| 8079 | - ws_close_request_sockets(opened); | |
| 8080 | - } | |
| 8081 | - | |
| 8082 | - #[doc(hidden)] | |
| 8083 | - pub fn own_body_stream(&self, stream_id: u64) { | |
| 8084 | - let mut owned = self.body_streams.lock().unwrap(); | |
| 8085 | - if owned.insert(stream_id) && !claim_http_stream(stream_id) { | |
| 8086 | - owned.remove(&stream_id); | |
| 8087 | - } | |
| 8088 | - } | |
| 8089 | - | |
| 8090 | - fn transfer_body_stream(&self, stream_id: u64) -> Option<RequestBodyGuard> { | |
| 8091 | - if self.body_streams.lock().unwrap().remove(&stream_id) { | |
| 8092 | - // Move the existing registry claim into the guard. There is no | |
| 8093 | - // unowned interval in which the age sweep can delete the source. | |
| 8094 | - Some(RequestBodyGuard::transferred(stream_id)) | |
| 8095 | - } else { | |
| 8096 | - None | |
| 8097 | - } | |
| 8098 | - } | |
| 8099 | - | |
| 8100 | - /// Replace one request-owned source with the two sources created by a | |
| 8101 | - /// native tee. Response streams are not request-owned, so they keep the | |
| 8102 | - /// registry's ordinary unowned lifecycle. | |
| 8103 | - fn replace_body_stream(&self, stream_id: u64, branches: (u64, u64)) { | |
| 8104 | - let mut owned = self.body_streams.lock().unwrap(); | |
| 8105 | - if !owned.remove(&stream_id) { | |
| 8106 | - return; | |
| 8107 | - } | |
| 8108 | - for branch in [branches.0, branches.1] { | |
| 8109 | - if claim_http_stream(branch) { | |
| 8110 | - owned.insert(branch); | |
| 8111 | - } | |
| 8112 | - } | |
| 8113 | - } | |
| 8114 | - | |
| 8115 | - #[cfg(celld_internal_tests)] | |
| 8116 | - #[doc(hidden)] | |
| 8117 | - pub fn begin_event_for_test(&self) { | |
| 8118 | - self.begin_event(); | |
| 8119 | - } | |
| 8120 | - | |
| 8121 | - #[cfg(celld_internal_tests)] | |
| 8122 | - #[doc(hidden)] | |
| 8123 | - pub fn end_event_for_test(&self) -> Option<()> { | |
| 8124 | - self.end_event().map(drop) | |
| 8125 | - } | |
| 8126 | - | |
| 8127 | - #[cfg(celld_internal_tests)] | |
| 8128 | - #[doc(hidden)] | |
| 8129 | - pub fn register_arm_gate_for_test( | |
| 8130 | - &self, | |
| 8131 | - gate: tokio::sync::oneshot::Receiver<Result<(), String>>, | |
| 8132 | - ) -> Result<(), tokio::sync::oneshot::Receiver<Result<(), String>>> { | |
| 8133 | - self.register_arm_gate(gate) | |
| 8134 | - } | |
| 8135 | - | |
| 8136 | - #[cfg(celld_internal_tests)] | |
| 8137 | - #[doc(hidden)] | |
| 8138 | - pub fn take_arm_gates_for_test( | |
| 8139 | - &self, | |
| 8140 | - ) -> Vec<tokio::sync::oneshot::Receiver<Result<(), String>>> { | |
| 8141 | - self.take_arm_gates() | |
| 8142 | - } | |
| 8143 | -} | |
| 8144 | - | |
| 8145 | -#[cfg(celld_internal_tests)] | |
| 8146 | -#[doc(hidden)] | |
| 8147 | -#[derive(Default)] | |
| 8148 | -pub struct IoContextRegistryForTest(Arc<ActorRuntimeState>); | |
| 8149 | - | |
| 8150 | -#[cfg(celld_internal_tests)] | |
| 8151 | -impl IoContextRegistryForTest { | |
| 8152 | - #[doc(hidden)] | |
| 8153 | - pub fn track(&self) -> (u64, Arc<IoContext>) { | |
| 8154 | - let context = IoContext::tracked(&self.0); | |
| 8155 | - let id = context | |
| 8156 | - .continuation | |
| 8157 | - .as_ref() | |
| 8158 | - .map(|(id, _)| *id) | |
| 8159 | - .expect("a tracked IoContext has a continuation id"); | |
| 8160 | - (id, context) | |
| 8161 | - } | |
| 8162 | - | |
| 8163 | - #[doc(hidden)] | |
| 8164 | - pub fn resolves_to(&self, id: u64, expected: &Arc<IoContext>) -> bool { | |
| 8165 | - self.0 | |
| 8166 | - .io_context(id) | |
| 8167 | - .is_some_and(|context| Arc::ptr_eq(&context, expected)) | |
| 8168 | - } | |
| 8169 | - | |
| 8170 | - #[doc(hidden)] | |
| 8171 | - pub fn contains(&self, id: u64) -> bool { | |
| 8172 | - self.0.io_contexts.lock().unwrap().contains_key(&id) | |
| 8173 | - } | |
| 8174 | - | |
| 8175 | - #[doc(hidden)] | |
| 8176 | - pub fn is_empty(&self) -> bool { | |
| 8177 | - self.0.io_contexts.lock().unwrap().is_empty() | |
| 8178 | - } | |
| 8179 | -} | |
| 8180 | - | |
| 8181 | -/// A Worker socket lives and dies with its request, exactly as it does on | |
| 8182 | -/// Cloudflare. Closing it here rather than at each of the drive loops' exits | |
| 8183 | -/// is the difference between a rule every exit path has to remember and one | |
| 8184 | -/// it cannot get wrong: a request that times out, that is abandoned as stuck, | |
| 8185 | -/// or whose client disconnects drops its context on a path of its own. | |
| 8186 | -impl Drop for IoContext { | |
| 8187 | - fn drop(&mut self) { | |
| 8188 | - self.close_sockets(); | |
| 8189 | - for stream_id in self.body_streams.get_mut().unwrap().drain() { | |
| 8190 | - release_http_stream(stream_id); | |
| 8191 | - } | |
| 8192 | - if let Some((id, runtime_state)) = &self.continuation { | |
| 8193 | - if let Some(runtime_state) = runtime_state.upgrade() { | |
| 8194 | - runtime_state.io_contexts.lock().unwrap().remove(id); | |
| 8195 | - } | |
| 8196 | - } | |
| 8197 | - } | |
| 8198 | -} | |
| 8199 | - | |
| 8200 | -/// What `OwnedIsolate::into_shared` demands of us: every slot value on a | |
| 8201 | -/// shared isolate is reachable, and droppable, from whichever thread holds | |
| 8202 | -/// the lock. The type system cannot check it at the call site, so it is | |
| 8203 | -/// checked here instead. | |
| 8204 | -const _: fn() = || { | |
| 8205 | - fn assert_send_sync<T: Send + Sync>() {} | |
| 8206 | - assert_send_sync::<HeapLimitState>(); | |
| 8207 | - assert_send_sync::<ActorRuntimeState>(); | |
| 8208 | - assert_send_sync::<ModuleRegistry>(); | |
| 8209 | - assert_send_sync::<LoaderOwner>(); | |
| 8210 | -}; | |
| 8211 | - | |
| 8212 | -/// A request must be able to carry its own context across a suspension. A | |
| 8213 | -/// compile-time check, because losing it would surface as an unrelated | |
| 8214 | -/// `Send` error wherever the request task is spawned. | |
| 8215 | -const _: fn() = || { | |
| 8216 | - fn assert_send_sync<T: Send + Sync>() {} | |
| 8217 | - assert_send_sync::<Arc<IoContext>>(); | |
| 8218 | -}; | |
| 8219 | - | |
| 8220 | -thread_local! { | |
| 8221 | - /// The request whose turn is running on this thread, or none between | |
| 8222 | - /// turns. Never set by JS. | |
| 8223 | - static CURRENT: RefCell<Option<Arc<IoContext>>> = | |
| 8224 | - const { RefCell::new(None) }; | |
| 8225 | -} | |
| 8226 | - | |
| 8227 | -/// Install `context` for the duration of a turn, restoring whatever was | |
| 8228 | -/// current when the guard drops. | |
| 8229 | -/// | |
| 8230 | -/// Restoring rather than clearing is what makes nested host dispatch safe: a | |
| 8231 | -/// service binding runs a second handler inside the first one's turn, and the | |
| 8232 | -/// outer request must still be current when it returns. | |
| 8233 | -pub struct CurrentGuard(Option<Arc<IoContext>>); | |
| 8234 | - | |
| 8235 | -impl CurrentGuard { | |
| 8236 | - pub fn enter(context: Arc<IoContext>) -> Self { | |
| 8237 | - CurrentGuard(CURRENT.with(|current| current.borrow_mut().replace(context))) | |
| 8238 | - } | |
| 8239 | -} | |
| 8240 | - | |
| 8241 | -impl Drop for CurrentGuard { | |
| 8242 | - fn drop(&mut self) { | |
| 8243 | - CURRENT.with(|current| *current.borrow_mut() = self.0.take()); | |
| 8244 | - } | |
| 8245 | -} | |
| 8246 | - | |
| 8247 | -/// The context this turn belongs to. | |
| 8248 | -/// | |
| 8249 | -/// A thread that has not had one installed gets a default: every path that | |
| 8250 | -/// runs JS without an explicit request context — a cell isolate, which the | |
| 8251 | -/// DO contract already serializes, an RPC entry, a DO constructor — keeps | |
| 8252 | -/// exactly the semantics it had when the stack lived in JS, one per isolate. | |
| 8253 | -/// Isolation is a property of *installing* a context, so it arrives with the | |
| 8254 | -/// paths that need it rather than being retrofitted to every caller at once. | |
| 8255 | -fn current_context() -> Arc<IoContext> { | |
| 8256 | - CURRENT.with(|current| { | |
| 8257 | - let mut current = current.borrow_mut(); | |
| 8258 | - current.get_or_insert_with(IoContext::new).clone() | |
| 8259 | - }) | |
| 8260 | -} | |
| 8261 | - | |
| 8262 | -#[cfg(celld_internal_tests)] | |
| 8263 | -fn installed_context() -> Option<Arc<IoContext>> { | |
| 8264 | - CURRENT.with(|current| current.borrow().clone()) | |
| 8265 | -} | |
| 8266 | - | |
| 8267 | -fn op_event_begin( | |
| 8268 | - scope: &mut v8::PinScope, | |
| 8269 | - _args: v8::FunctionCallbackArguments, | |
| 8270 | - _rv: v8::ReturnValue<v8::Value>, | |
| 8271 | -) { | |
| 8272 | - let _ = scope; | |
| 8273 | - current_context().begin_event(); | |
| 8274 | -} | |
| 8275 | - | |
| 8276 | -/// Pop the innermost event and return the aggregate of its `waitUntil` | |
| 8277 | -/// promises, or null when it collected none. The aggregate is built here | |
| 8278 | -/// rather than in JS because the promises live here: the host holds them for | |
| 8279 | -/// the request, and the request is what the frame belongs to. | |
| 8280 | -fn op_event_end<'s>( | |
| 8281 | - scope: &mut v8::PinScope<'s, '_>, | |
| 8282 | - _args: v8::FunctionCallbackArguments, | |
| 8283 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8284 | -) { | |
| 8285 | - let Some(frame) = current_context().end_event() else { | |
| 8286 | - rv.set_null(); | |
| 8287 | - return; | |
| 8288 | - }; | |
| 8289 | - if frame.is_empty() { | |
| 8290 | - rv.set_null(); | |
| 8291 | - return; | |
| 8292 | - } | |
| 8293 | - let promises: Vec<v8::Local<v8::Value>> = frame | |
| 8294 | - .iter() | |
| 8295 | - .map(|promise| v8::Local::new(scope, promise).into()) | |
| 8296 | - .collect(); | |
| 8297 | - let array = v8::Array::new_with_elements(scope, &promises); | |
| 8298 | - match all_settled(scope, array.into()) { | |
| 8299 | - Some(aggregate) => rv.set(aggregate), | |
| 8300 | - None => rv.set_null(), | |
| 8301 | - } | |
| 8302 | -} | |
| 8303 | - | |
| 8304 | -fn op_wait_until<'s>( | |
| 8305 | - scope: &mut v8::PinScope<'s, '_>, | |
| 8306 | - args: v8::FunctionCallbackArguments<'s>, | |
| 8307 | - _rv: v8::ReturnValue<v8::Value>, | |
| 8308 | -) { | |
| 8309 | - let value = args.get(0); | |
| 8310 | - let promise = match value.try_cast::<v8::Promise>() { | |
| 8311 | - Ok(promise) => promise, | |
| 8312 | - Err(_) => match resolved_promise(scope, value) { | |
| 8313 | - Ok(promise) => promise, | |
| 8314 | - Err(_) => return, | |
| 8315 | - }, | |
| 8316 | - }; | |
| 8317 | - current_context().register_wait_until(v8::Global::new(scope, promise)); | |
| 8318 | -} | |
| 8319 | - | |
| 8320 | -/// How many events are open on the current request. The harness uses it for | |
| 8321 | -/// workerd's global-scope error, which fires when `waitUntil` is imported and | |
| 8322 | -/// called with no event in progress. | |
| 8323 | -fn op_event_depth( | |
| 8324 | - scope: &mut v8::PinScope, | |
| 8325 | - _args: v8::FunctionCallbackArguments, | |
| 8326 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8327 | -) { | |
| 8328 | - let depth = current_context().depth(); | |
| 8329 | - rv.set(v8::Integer::new(scope, depth as i32).into()); | |
| 8330 | -} | |
| 8331 | - | |
| 8332 | -/// `Promise.allSettled(values)`, from the context's own realm. | |
| 8333 | -fn all_settled<'s>( | |
| 8334 | - scope: &mut v8::PinScope<'s, '_>, | |
| 8335 | - values: v8::Local<'s, v8::Value>, | |
| 8336 | -) -> Option<v8::Local<'s, v8::Value>> { | |
| 8337 | - let global = scope.get_current_context().global(scope); | |
| 8338 | - let key = v8::String::new(scope, "Promise").unwrap(); | |
| 8339 | - let promise_ctor: v8::Local<v8::Object> = global.get(scope, key.into())?.try_into().ok()?; | |
| 8340 | - let key = v8::String::new(scope, "allSettled").unwrap(); | |
| 8341 | - let all_settled: v8::Local<v8::Function> = | |
| 8342 | - promise_ctor.get(scope, key.into())?.try_into().ok()?; | |
| 8343 | - all_settled.call(scope, promise_ctor.into(), &[values]) | |
| 8344 | -} | |
| 8345 | - | |
| 8346 | -fn op_als_get( | |
| 8347 | - scope: &mut v8::PinScope, | |
| 8348 | - _args: v8::FunctionCallbackArguments, | |
| 8349 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8350 | -) { | |
| 8351 | - rv.set(cped_frame(scope)); | |
| 8352 | -} | |
| 8353 | - | |
| 8354 | -fn op_als_set( | |
| 8355 | - scope: &mut v8::PinScope, | |
| 8356 | - args: v8::FunctionCallbackArguments, | |
| 8357 | - _rv: v8::ReturnValue<v8::Value>, | |
| 8358 | -) { | |
| 8359 | - let trace = cped_trace(scope); | |
| 8360 | - let io_context = cped_io_context(scope); | |
| 8361 | - set_cped(scope, args.get(0), trace, io_context); | |
| 8362 | -} | |
| 8363 | - | |
| 8364 | -// node:util prelude calls these; registration is the sole per-isolate cost. | |
| 8365 | - | |
| 8366 | -/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js. | |
| 8367 | -fn op_util_type_flags( | |
| 8368 | - _scope: &mut v8::PinScope, | |
| 8369 | - args: v8::FunctionCallbackArguments, | |
| 8370 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8371 | -) { | |
| 8372 | - let v = args.get(0); | |
| 8373 | - let checks: [bool; 27] = [ | |
| 8374 | - v.is_external(), | |
| 8375 | - v.is_date(), | |
| 8376 | - v.is_arguments_object(), | |
| 8377 | - v.is_big_int_object(), | |
| 8378 | - v.is_boolean_object(), | |
| 8379 | - v.is_number_object(), | |
| 8380 | - v.is_string_object(), | |
| 8381 | - v.is_symbol_object(), | |
| 8382 | - v.is_native_error(), | |
| 8383 | - v.is_reg_exp(), | |
| 8384 | - v.is_async_function(), | |
| 8385 | - v.is_generator_function(), | |
| 8386 | - v.is_generator_object(), | |
| 8387 | - v.is_promise(), | |
| 8388 | - v.is_map(), | |
| 8389 | - v.is_set(), | |
| 8390 | - v.is_map_iterator(), | |
| 8391 | - v.is_set_iterator(), | |
| 8392 | - v.is_weak_map(), | |
| 8393 | - v.is_weak_set(), | |
| 8394 | - v.is_array_buffer(), | |
| 8395 | - v.is_data_view(), | |
| 8396 | - v.is_shared_array_buffer(), | |
| 8397 | - v.is_proxy(), | |
| 8398 | - v.is_module_namespace_object(), | |
| 8399 | - v.is_typed_array(), | |
| 8400 | - v.is_array_buffer_view(), | |
| 8401 | - ]; | |
| 8402 | - let mut flags: u32 = 0; | |
| 8403 | - for (i, hit) in checks.iter().enumerate() { | |
| 8404 | - if *hit { | |
| 8405 | - flags |= 1 << i; | |
| 8406 | - } | |
| 8407 | - } | |
| 8408 | - rv.set_uint32(flags); | |
| 8409 | -} | |
| 8410 | - | |
| 8411 | -fn op_util_constructor_name( | |
| 8412 | - _scope: &mut v8::PinScope, | |
| 8413 | - args: v8::FunctionCallbackArguments, | |
| 8414 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8415 | -) { | |
| 8416 | - let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else { | |
| 8417 | - return; // undefined | |
| 8418 | - }; | |
| 8419 | - rv.set(obj.get_constructor_name().into()); | |
| 8420 | -} | |
| 8421 | - | |
| 8422 | -/// `[target, handler]` for a proxy, undefined otherwise. | |
| 8423 | -fn op_util_proxy_details( | |
| 8424 | - scope: &mut v8::PinScope, | |
| 8425 | - args: v8::FunctionCallbackArguments, | |
| 8426 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8427 | -) { | |
| 8428 | - let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else { | |
| 8429 | - return; | |
| 8430 | - }; | |
| 8431 | - let target = proxy.get_target(scope); | |
| 8432 | - let handler = proxy.get_handler(scope); | |
| 8433 | - rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into()); | |
| 8434 | -} | |
| 8435 | - | |
| 8436 | -/// `[state]` for a pending promise, `[state, result]` otherwise, | |
| 8437 | -/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected. | |
| 8438 | -fn op_util_promise_details( | |
| 8439 | - scope: &mut v8::PinScope, | |
| 8440 | - args: v8::FunctionCallbackArguments, | |
| 8441 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8442 | -) { | |
| 8443 | - let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else { | |
| 8444 | - return; | |
| 8445 | - }; | |
| 8446 | - let state = match promise.state() { | |
| 8447 | - v8::PromiseState::Pending => 0, | |
| 8448 | - v8::PromiseState::Fulfilled => 1, | |
| 8449 | - v8::PromiseState::Rejected => 2, | |
| 8450 | - }; | |
| 8451 | - let pending = state == 0; | |
| 8452 | - let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into(); | |
| 8453 | - let elements = if pending { | |
| 8454 | - vec![state] | |
| 8455 | - } else { | |
| 8456 | - vec![state, promise.result(scope)] | |
| 8457 | - }; | |
| 8458 | - rv.set(v8::Array::new_with_elements(scope, &elements).into()); | |
| 8459 | -} | |
| 8460 | - | |
| 8461 | -/// `[entries, isKeyValue]` for collections and their iterators (V8's | |
| 8462 | -/// PreviewEntries), undefined when V8 has no preview. | |
| 8463 | -fn op_util_preview_entries( | |
| 8464 | - scope: &mut v8::PinScope, | |
| 8465 | - args: v8::FunctionCallbackArguments, | |
| 8466 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8467 | -) { | |
| 8468 | - let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else { | |
| 8469 | - return; | |
| 8470 | - }; | |
| 8471 | - let (entries, is_key_value) = obj.preview_entries(scope); | |
| 8472 | - let Some(entries) = entries else { return }; | |
| 8473 | - let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into(); | |
| 8474 | - rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into()); | |
| 8475 | -} | |
| 8476 | - | |
| 8477 | -fn op_alarm_set( | |
| 8478 | - scope: &mut v8::PinScope, | |
| 8479 | - args: v8::FunctionCallbackArguments, | |
| 8480 | - _rv: v8::ReturnValue<v8::Value>, | |
| 8481 | -) { | |
| 8482 | - let s = args.get(0).to_rust_string_lossy(scope); | |
| 8483 | - let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64; | |
| 8484 | - match storage::set_alarm(&s, at) { | |
| 8485 | - Err(error) => throw_storage_error(scope, "setAlarm", error), | |
| 8486 | - // Committed immediately: register the wake-entry PUT against the | |
| 8487 | - // current event's output gate. Inside an explicit transaction (`Ok(None)`) | |
| 8488 | - // the gate registers at that transaction's commit instead. | |
| 8489 | - Ok(Some(committed)) if committed >= 0 => { | |
| 8490 | - spawn_arm_gate(&s, committed, current_reaction_io_context(scope)) | |
| 8491 | - } | |
| 8492 | - Ok(_) => {} | |
| 8493 | - } | |
| 8494 | -} | |
| 8495 | -fn op_alarm_get( | |
| 8496 | - scope: &mut v8::PinScope, | |
| 8497 | - args: v8::FunctionCallbackArguments, | |
| 8498 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8499 | -) { | |
| 8500 | - let s = args.get(0).to_rust_string_lossy(scope); | |
| 8501 | - match storage::get_alarm(&s) { | |
| 8502 | - Some(at) => rv.set(v8::Number::new(scope, at as f64).into()), | |
| 8503 | - None => rv.set(v8::null(scope).into()), | |
| 8504 | - } | |
| 8505 | -} | |
| 8506 | -fn op_alarm_delete( | |
| 8507 | - scope: &mut v8::PinScope, | |
| 8508 | - args: v8::FunctionCallbackArguments, | |
| 8509 | - _rv: v8::ReturnValue<v8::Value>, | |
| 8510 | -) { | |
| 8511 | - let s = args.get(0).to_rust_string_lossy(scope); | |
| 8512 | - if let Err(error) = storage::delete_alarm(&s) { | |
| 8513 | - throw_storage_error(scope, "deleteAlarm", error); | |
| 8514 | - } | |
| 8515 | -} | |
| 8516 | - | |
| 8517 | -/// The reserved cron cell's whole schedule decision, in one call so the policy | |
| 8518 | -/// has one home in `celld_logic::cron` rather than a JavaScript copy that can | |
| 8519 | -/// drift from it. | |
| 8520 | -/// | |
| 8521 | -/// `firedMs` is the occurrence being handled, or negative when the cell is | |
| 8522 | -/// only arming. Returns `{ matching, armAt, armIsRetry }`: which expressions | |
| 8523 | -/// the occurrence belongs to, by index into the list passed in, when to arm | |
| 8524 | -/// next — `null` when the schedule is exhausted and the cell should retire — | |
| 8525 | -/// and whether that deadline is the failure backoff rather than the next | |
| 8526 | -/// occurrence. | |
| 8527 | -fn op_cron_plan( | |
| 8528 | - scope: &mut v8::PinScope, | |
| 8529 | - args: v8::FunctionCallbackArguments, | |
| 8530 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8531 | -) { | |
| 8532 | - let Ok(list) = v8::Local::<v8::Array>::try_from(args.get(0)) else { | |
| 8533 | - return; | |
| 8534 | - }; | |
| 8535 | - let mut crons = Vec::with_capacity(list.length() as usize); | |
| 8536 | - // Where each parsed expression sits in the list the caller passed. A | |
| 8537 | - // malformed expression is already refused by `celld deploy`, but the | |
| 8538 | - // control plane checks only the field count, so one can still arrive here. | |
| 8539 | - // Skipping it keeps one bad entry from silencing a script's other crons, | |
| 8540 | - // and this map is what keeps the skip from renumbering them: the caller | |
| 8541 | - // reports `controller.cron` by index, so a shifted index names the wrong | |
| 8542 | - // expression for every entry after the bad one. | |
| 8543 | - let mut positions = Vec::with_capacity(list.length() as usize); | |
| 8544 | - for index in 0..list.length() { | |
| 8545 | - let Some(value) = list.get_index(scope, index) else { | |
| 8546 | - continue; | |
| 8547 | - }; | |
| 8548 | - if let Ok(cron) = celld_logic::cron::parse(&value.to_rust_string_lossy(scope)) { | |
| 8549 | - crons.push(cron); | |
| 8550 | - positions.push(index as usize); | |
| 8551 | - } | |
| 8552 | - } | |
| 8553 | - let fired_ms = args.get(1).number_value(scope).unwrap_or(-1.0) as i64; | |
| 8554 | - let now_ms = args.get(2).number_value(scope).unwrap_or(0.0) as i64; | |
| 8555 | - let retry = args.get(3).number_value(scope).unwrap_or(0.0) as i64; | |
| 8556 | - let failed = args.get(4).boolean_value(scope); | |
| 8557 | - | |
| 8558 | - let matching = if fired_ms >= 0 { | |
| 8559 | - celld_logic::cron::matching(&crons, fired_ms) | |
| 8560 | - } else { | |
| 8561 | - Vec::new() | |
| 8562 | - }; | |
| 8563 | - let next = celld_logic::cron::next_across(&crons, now_ms); | |
| 8564 | - // The retry backoff is `alarm::alarm_retry`'s, not a second schedule: | |
| 8565 | - // a cron that fails behaves like any other failing alarm, except that | |
| 8566 | - // `cron_rearm` never lets the backoff outlast the next occurrence. | |
| 8567 | - let retry_at = failed | |
| 8568 | - .then(|| celld_logic::alarm::alarm_retry(now_ms, retry, retry, true)) | |
| 8569 | - .flatten(); | |
| 8570 | - let arm_at = celld_logic::cron::cron_rearm(next, retry_at); | |
| 8571 | - // Which of the two the deadline belongs to. `cron_rearm` takes the earlier | |
| 8572 | - // and gives a tie to the occurrence, so `armAt` alone cannot say — and the | |
| 8573 | - // caller has to know, because a retry owes the expressions of the | |
| 8574 | - // occurrence that failed, while a deadline that is an occurrence owes the | |
| 8575 | - // expressions that match it. | |
| 8576 | - let arm_is_retry = match (arm_at, next) { | |
| 8577 | - (Some(at), Some(occurrence)) => at < occurrence, | |
| 8578 | - (Some(_), None) => true, | |
| 8579 | - (None, _) => false, | |
| 8580 | - }; | |
| 8581 | - | |
| 8582 | - let indices = v8::Array::new(scope, matching.len() as i32); | |
| 8583 | - for (slot, index) in matching.iter().enumerate() { | |
| 8584 | - let value = v8::Number::new(scope, positions[*index] as f64); | |
| 8585 | - indices.set_index(scope, slot as u32, value.into()); | |
| 8586 | - } | |
| 8587 | - let result = v8::Object::new(scope); | |
| 8588 | - let key = v8::String::new(scope, "matching").unwrap(); | |
| 8589 | - result.set(scope, key.into(), indices.into()); | |
| 8590 | - let key = v8::String::new(scope, "armAt").unwrap(); | |
| 8591 | - let value: v8::Local<v8::Value> = match arm_at { | |
| 8592 | - Some(at) => v8::Number::new(scope, at as f64).into(), | |
| 8593 | - None => v8::null(scope).into(), | |
| 8594 | - }; | |
| 8595 | - result.set(scope, key.into(), value); | |
| 8596 | - let key = v8::String::new(scope, "armIsRetry").unwrap(); | |
| 8597 | - let value = v8::Boolean::new(scope, arm_is_retry); | |
| 8598 | - result.set(scope, key.into(), value.into()); | |
| 8599 | - rv.set(result.into()); | |
| 8600 | -} | |
| 8601 | - | |
| 8602 | -fn op_btoa( | |
| 8603 | - scope: &mut v8::PinScope, | |
| 8604 | - args: v8::FunctionCallbackArguments, | |
| 8605 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8606 | -) { | |
| 8607 | - use base64::Engine; | |
| 8608 | - // The public `btoa()` wrapper always supplies a string. The KV operator | |
| 8609 | - // protocol supplies a typed view directly, which avoids constructing a | |
| 8610 | - // second 25 MiB binary string only to encode it here. | |
| 8611 | - let bytes = view_bytes(args.get(0)).unwrap_or_else(|| { | |
| 8612 | - args.get(0) | |
| 8613 | - .to_rust_string_lossy(scope) | |
| 8614 | - .chars() | |
| 8615 | - .map(|c| c as u8) | |
| 8616 | - .collect() | |
| 8617 | - }); | |
| 8618 | - let s = base64::engine::general_purpose::STANDARD.encode(bytes); | |
| 8619 | - rv.set(v8::String::new(scope, &s).unwrap().into()); | |
| 8620 | -} | |
| 8621 | - | |
| 8622 | -// ---- WHATWG text decoders (encoding_rs) ---- | |
| 8623 | -// | |
| 8624 | -// These ops back every TextDecoder decode. src/js/text_encoding.js | |
| 8625 | -// resolves the label and owns the decoder's lifetime, and encoding_rs | |
| 8626 | -// does the decoding — for utf-8 and utf-16 as much as for every other | |
| 8627 | -// WHATWG label (windows-1252, Big5, GBK/GB18030, ISO-2022-JP, | |
| 8628 | -// x-user-defined, …). Previous utf-8 and utf-16 JS decoders were slower | |
| 8629 | -// than these ops at every measured size. | |
| 8630 | -// Streaming decoders live in a per-isolate table keyed by id; JS frees | |
| 8631 | -// one on the final decode (last=true), on a fatal error (encoding_rs | |
| 8632 | -// poisons an errored decoder), or via FinalizationRegistry when a | |
| 8633 | -// mid-stream decoder is abandoned. Ids are never reused, so a late | |
| 8634 | -// finalizer free of an already-closed id is a no-op. | |
| 8635 | - | |
| 8636 | -/// Live streaming decoders for one isolate, keyed by an id JS holds across | |
| 8637 | -/// awaits. | |
| 8638 | -/// | |
| 8639 | -/// An isolate slot rather than a process-wide `Mutex<HashMap<..>>` like | |
| 8640 | -/// [`zlib_streams`]. The reason that one is process-wide holds here too — a | |
| 8641 | -/// `TextDecoder` in streaming mode outlives the turn that made it, and the | |
| 8642 | -/// next turn can run on a different tokio worker — but it argues against a | |
| 8643 | -/// *thread-local*, not against this. A `TextDecoder` is a JS object, so it | |
| 8644 | -/// never leaves the isolate that made it, and every op that touches its | |
| 8645 | -/// decoder runs under that isolate's `v8::Locker`. The lock the embedder | |
| 8646 | -/// already holds is what makes the access exclusive, which `&mut Isolate` | |
| 8647 | -/// on the slot then proves. A second lock inside it buys nothing. | |
| 8648 | -/// | |
| 8649 | -/// This removes a ceiling rather than a measured regression, and the | |
| 8650 | -/// difference matters. In isolation the pattern does collapse: replayed on | |
| 8651 | -/// its own — remove, decode outside the lock, insert — 256-byte chunks | |
| 8652 | -/// peaked at two threads and then went *backwards*, 8 threads serving | |
| 8653 | -/// 0.46x what 1 thread served against 6.7x for the same decoding with no | |
| 8654 | -/// table. But celld end to end shows no difference between the two, at any | |
| 8655 | -/// concurrency this hardware can drive, because a chunk costs about 42us | |
| 8656 | -/// of stream and turn machinery around a lock held for about 100ns. So the | |
| 8657 | -/// mutex was not what any cell was waiting on. It was a process-wide | |
| 8658 | -/// serialisation point on a path that every stream now takes, and it went | |
| 8659 | -/// because it does not need to exist, not because it was costing anything | |
| 8660 | -/// yet. | |
| 8661 | -/// | |
| 8662 | -/// Dropping the isolate drops the table, so a decoder abandoned by a cell | |
| 8663 | -/// that goes away needs no finalizer to run. | |
| 8664 | -#[derive(Default)] | |
| 8665 | -struct TextDecoders(HashMap<u64, encoding_rs::Decoder>); | |
| 8666 | - | |
| 8667 | -static TEXT_DECODER_NEXT: AtomicU64 = AtomicU64::new(1); | |
| 8668 | - | |
| 8669 | -/// The calling isolate's decoder table, created on first use. | |
| 8670 | -fn text_decoders<'a>(scope: &'a mut v8::PinScope) -> &'a mut HashMap<u64, encoding_rs::Decoder> { | |
| 8671 | - if scope.get_slot::<TextDecoders>().is_none() { | |
| 8672 | - scope.set_slot(TextDecoders::default()); | |
| 8673 | - } | |
| 8674 | - &mut scope.get_slot_mut::<TextDecoders>().expect("just set").0 | |
| 8675 | -} | |
| 8676 | - | |
| 8677 | -/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined | |
| 8678 | -/// for unknown labels and the replacement encoding (RangeError in JS). | |
| 8679 | -fn op_text_decoder_label( | |
| 8680 | - scope: &mut v8::PinScope, | |
| 8681 | - args: v8::FunctionCallbackArguments, | |
| 8682 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8683 | -) { | |
| 8684 | - let label = args.get(0).to_rust_string_lossy(scope); | |
| 8685 | - if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) { | |
| 8686 | - let name = enc.name().to_ascii_lowercase(); | |
| 8687 | - rv.set(v8::String::new(scope, &name).unwrap().into()); | |
| 8688 | - } | |
| 8689 | -} | |
| 8690 | - | |
| 8691 | -/// `$$textDecoderNew(name, ignoreBOM)` -> id. | |
| 8692 | -fn op_text_decoder_new( | |
| 8693 | - scope: &mut v8::PinScope, | |
| 8694 | - args: v8::FunctionCallbackArguments, | |
| 8695 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8696 | -) { | |
| 8697 | - let name = args.get(0).to_rust_string_lossy(scope); | |
| 8698 | - let ignore_bom = args.get(1).boolean_value(scope); | |
| 8699 | - let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label"); | |
| 8700 | - let dec = if ignore_bom { | |
| 8701 | - enc.new_decoder_without_bom_handling() | |
| 8702 | - } else { | |
| 8703 | - enc.new_decoder_with_bom_removal() | |
| 8704 | - }; | |
| 8705 | - let id = TEXT_DECODER_NEXT.fetch_add(1, Ordering::Relaxed); | |
| 8706 | - text_decoders(scope).insert(id, dec); | |
| 8707 | - rv.set(v8::Number::new(scope, id as f64).into()); | |
| 8708 | -} | |
| 8709 | - | |
| 8710 | -/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the | |
| 8711 | -/// decoder when `last` is true or on a fatal malformed sequence | |
| 8712 | -/// (TypeError). | |
| 8713 | -fn op_text_decoder_decode( | |
| 8714 | - scope: &mut v8::PinScope, | |
| 8715 | - args: v8::FunctionCallbackArguments, | |
| 8716 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8717 | -) { | |
| 8718 | - let id = args.get(0).integer_value(scope).unwrap_or(0) as u64; | |
| 8719 | - let bytes = view_bytes(args.get(1)).unwrap_or_default(); | |
| 8720 | - let fatal = args.get(2).boolean_value(scope); | |
| 8721 | - let last = args.get(3).boolean_value(scope); | |
| 8722 | - // Per spec an empty streaming chunk is a no-op, but encoding_rs | |
| 8723 | - // 0.8 flushes a pending multibyte lead when fed an empty non-last | |
| 8724 | - // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead | |
| 8725 | - // of あ). Skip the decoder entirely. | |
| 8726 | - if bytes.is_empty() && !last { | |
| 8727 | - rv.set(v8::String::empty(scope).into()); | |
| 8728 | - return; | |
| 8729 | - } | |
| 8730 | - let mut dec = text_decoders(scope) | |
| 8731 | - .remove(&id) | |
| 8732 | - .expect("JS holds the only live id"); | |
| 8733 | - let Ok(out) = run_decoder(&mut dec, &bytes, fatal, last) else { | |
| 8734 | - throw_invalid_encoded_data(scope); | |
| 8735 | - return; | |
| 8736 | - }; | |
| 8737 | - if !last { | |
| 8738 | - text_decoders(scope).insert(id, dec); | |
| 8739 | - } | |
| 8740 | - rv.set(v8::String::new(scope, &out).unwrap().into()); | |
| 8741 | -} | |
| 8742 | - | |
| 8743 | -/// `$$textDecoderDecodeOnce(name, view, fatal, ignoreBOM)` -> string, for | |
| 8744 | -/// a complete buffer. | |
| 8745 | -/// | |
| 8746 | -/// The whole decode is one call, so the decoder never outlives it and | |
| 8747 | -/// never reaches [`text_decoders`]. That saves an insert and a remove, | |
| 8748 | -/// and it keeps every non-streaming decode on the node off a table that | |
| 8749 | -/// is one mutex for the whole process — which is most decodes, because | |
| 8750 | -/// `request.text()` and `response.text()` are not streams. A stream | |
| 8751 | -/// still takes that lock twice per chunk, which is a cost per chunk | |
| 8752 | -/// rather than per byte, and it has not been measured under load; | |
| 8753 | -/// sharding the table is the answer if it ever shows. | |
| 8754 | -fn op_text_decoder_decode_once( | |
| 8755 | - scope: &mut v8::PinScope, | |
| 8756 | - args: v8::FunctionCallbackArguments, | |
| 8757 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 8758 | -) { | |
| 8759 | - let name = args.get(0).to_rust_string_lossy(scope); | |
| 8760 | - let bytes = view_bytes(args.get(1)).unwrap_or_default(); | |
| 8761 | - let fatal = args.get(2).boolean_value(scope); | |
| 8762 | - let ignore_bom = args.get(3).boolean_value(scope); | |
| 8763 | - let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label"); | |
| 8764 | - let mut dec = if ignore_bom { | |
| 8765 | - enc.new_decoder_without_bom_handling() | |
| 8766 | - } else { | |
| 8767 | - enc.new_decoder_with_bom_removal() | |
| 8768 | - }; | |
| 8769 | - match run_decoder(&mut dec, &bytes, fatal, true) { | |
| 8770 | - Ok(out) => rv.set(v8::String::new(scope, &out).unwrap().into()), | |
| 8771 | - Err(()) => throw_invalid_encoded_data(scope), | |
| 8772 | - } | |
| 8773 | -} | |
| 8774 | - | |
| 8775 | -/// Feeds `bytes` to `dec` and answers the text. `Err` means `fatal` was | |
| 8776 | -/// set and the input was malformed. | |
| 8777 | -fn run_decoder( | |
| 8778 | - dec: &mut encoding_rs::Decoder, | |
| 8779 | - bytes: &[u8], | |
| 8780 | - fatal: bool, | |
| 8781 | - last: bool, | |
| 8782 | -) -> Result<String, ()> { | |
| 8783 | - let mut out = String::new(); | |
| 8784 | - if fatal { | |
| 8785 | - let cap = dec | |
| 8786 | - .max_utf8_buffer_length_without_replacement(bytes.len()) | |
| 8787 | - .unwrap(); | |
| 8788 | - out.reserve(cap); | |
| 8789 | - if !matches!( | |
| 8790 | - dec.decode_to_string_without_replacement(bytes, &mut out, last), | |
| 8791 | - (encoding_rs::DecoderResult::InputEmpty, _), | |
| 8792 | - ) { | |
| 8793 | - return Err(()); | |
| 8794 | - } | |
| 8795 | - } else { | |
| 8796 | - let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap(); | |
| 8797 | - out.reserve(cap); | |
| 8798 | - let _ = dec.decode_to_string(bytes, &mut out, last); | |
| 8799 | - } | |
| 8800 | - Ok(out) | |
| 8801 | -} | |
| 8802 | - | |
| 8803 | -fn throw_invalid_encoded_data(scope: &mut v8::PinScope) { | |
| 8804 | - let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap(); | |
| 8805 | - let exc = v8::Exception::type_error(scope, msg); | |
| 8806 | - scope.throw_exception(exc); | |
| 8807 | -} | |
| 8808 | - | |
| 8809 | -/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder | |
| 8810 | -/// abandoned mid-stream. | |
| 8811 | -fn op_text_decoder_free( | |
| 8812 | - scope: &mut v8::PinScope, | |
| 8813 | - args: v8::FunctionCallbackArguments, | |
| 8814 | - _rv: v8::ReturnValue<v8::Value>, | |
| 8815 | -) { | |
| 8816 | - let id = args.get(0).integer_value(scope).unwrap_or(0) as u64; | |
| 8817 | - text_decoders(scope).remove(&id); | |
| 8818 | -} | |
| 8819 | - | |
| 8820 | -// ---- the JS harness: Web API + the DO object model ---- | |
| 8821 | - | |
| 8822 | -#[doc(hidden)] | |
| 8823 | -pub mod bootstrap; | |
| 8824 | -pub mod modules; | |
| 8825 | -mod v8_strings; | |
| 8826 | -use bootstrap::{ | |
| 8827 | - adopt_cell, begin_event_context, build_env, end_event_context, harness_env, | |
| 8828 | - inject_compatibility_flags, inject_crons, inject_kv_limits, inject_namespace_keys, | |
| 8829 | - inject_queue_config, inject_routing, inject_storage_compatibility, inject_workflows, | |
| 8830 | - install_harness, install_prelude, populate_cf_exports, register_class, register_entrypoints, | |
| 8831 | - validate_workflow_classes, | |
| 8832 | -}; | |
| 8833 | -use modules::{ | |
| 8834 | - compile_module, host_import_module_dynamically, install_lazy_globals, op_builtin_module, | |
| 8835 | - register_loader_modules, register_stubs, register_wasm_modules, resolve_external, | |
| 8836 | - ModuleRegistry, | |
| 8837 | -}; | |
| 8838 | -use v8_strings::key as static_key; | |
| 8839 | -/// Like `make_request`, but marks the request as incoming. Its signal is | |
| 8840 | -/// registered only if the handler actually suspends, preserving the | |
| 8841 | -/// synchronous request path. | |
| 8842 | -fn make_incoming_request<'s>( | |
| 8843 | - tc: &mut v8::PinScope<'s, '_>, | |
| 8844 | - url: &str, | |
| 8845 | - method: &str, | |
| 8846 | - body: RequestBody, | |
| 8847 | - headers: &[(String, String)], | |
| 8848 | -) -> Result<v8::Local<'s, v8::Value>> { | |
| 8849 | - let global = tc.get_current_context().global(tc); | |
| 8850 | - let key = v8::String::new(tc, "__makeIncomingRequest").unwrap(); | |
| 8851 | - let f: v8::Local<v8::Function> = global | |
| 8852 | - .get(tc, key.into()) | |
| 8853 | - .ok_or_else(|| anyhow!("no __makeIncomingRequest"))? | |
| 8854 | - .try_into() | |
| 8855 | - .map_err(|_| anyhow!("not fn"))?; | |
| 8856 | - let url = v8::String::new(tc, url).unwrap(); | |
| 8857 | - let method = v8::String::new(tc, method).unwrap(); | |
| 8858 | - let headers = v8::String::new( | |
| 8859 | - tc, | |
| 8860 | - &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()), | |
| 8861 | - ) | |
| 8862 | - .unwrap(); | |
| 8863 | - // A streamed body passes its id, and the harness builds the body | |
| 8864 | - // stream around that id. A held body passes the bytes. | |
| 8865 | - let stream_id = body.stream_id(); | |
| 8866 | - let (body, stream_id) = match stream_id { | |
| 8867 | - None => ( | |
| 8868 | - bytes_value(tc, body.into_held_bytes().unwrap()), | |
| 8869 | - v8::undefined(tc).into(), | |
| 8870 | - ), | |
| 8871 | - Some(id) => ( | |
| 8872 | - v8::undefined(tc).into(), | |
| 8873 | - v8::Number::new(tc, id as f64).into(), | |
| 8874 | - ), | |
| 8875 | - }; | |
| 8876 | - let recv = v8::undefined(tc).into(); | |
| 8877 | - f.call( | |
| 8878 | - tc, | |
| 8879 | - recv, | |
| 8880 | - &[url.into(), method.into(), body, headers.into(), stream_id], | |
| 8881 | - ) | |
| 8882 | - .ok_or_else(|| anyhow!("__makeIncomingRequest threw")) | |
| 8883 | -} | |
| 8884 | - | |
| 8885 | -fn register_incoming_request( | |
| 8886 | - tc: &mut v8::PinScope, | |
| 8887 | - request_id: RequestId, | |
| 8888 | - request: v8::Local<v8::Value>, | |
| 8889 | -) -> Result<()> { | |
| 8890 | - let global = tc.get_current_context().global(tc); | |
| 8891 | - let key = v8::String::new(tc, "__registerIncomingRequest").unwrap(); | |
| 8892 | - let function: v8::Local<v8::Function> = global | |
| 8893 | - .get(tc, key.into()) | |
| 8894 | - .ok_or_else(|| anyhow!("no __registerIncomingRequest"))? | |
| 8895 | - .try_into() | |
| 8896 | - .map_err(|_| anyhow!("__registerIncomingRequest is not a function"))?; | |
| 8897 | - let id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 8898 | - let recv = v8::undefined(tc).into(); | |
| 8899 | - function | |
| 8900 | - .call(tc, recv, &[id.into(), request]) | |
| 8901 | - .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?; | |
| 8902 | - Ok(()) | |
| 8903 | -} | |
| 8904 | - | |
| 8905 | -fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) { | |
| 8906 | - let global = tc.get_current_context().global(tc); | |
| 8907 | - let key = v8::String::new(tc, "__finishIncomingRequest").unwrap(); | |
| 8908 | - let Some(value) = global.get(tc, key.into()) else { | |
| 8909 | - return; | |
| 8910 | - }; | |
| 8911 | - let Ok(function) = value.try_cast::<v8::Function>() else { | |
| 8912 | - return; | |
| 8913 | - }; | |
| 8914 | - let id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 8915 | - let recv = v8::undefined(tc).into(); | |
| 8916 | - let _ = function.call(tc, recv, &[id.into()]); | |
| 8917 | -} | |
| 8918 | - | |
| 8919 | -fn make_request<'s>( | |
| 8920 | - tc: &mut v8::PinScope<'s, '_>, | |
| 8921 | - url: &str, | |
| 8922 | - method: &str, | |
| 8923 | - body: RequestBody, | |
| 8924 | - headers: &[(String, String)], | |
| 8925 | -) -> Result<v8::Local<'s, v8::Value>> { | |
| 8926 | - let g = tc.get_current_context().global(tc); | |
| 8927 | - let k = v8::String::new(tc, "__makeRequest").unwrap(); | |
| 8928 | - let f: v8::Local<v8::Function> = g.get(tc, k.into()).unwrap().try_into().unwrap(); | |
| 8929 | - let u = v8::String::new(tc, url).unwrap(); | |
| 8930 | - let m = v8::String::new(tc, method).unwrap(); | |
| 8931 | - let bytes = body.into_held_bytes().unwrap_or_default(); | |
| 8932 | - let b = bytes_value(tc, bytes); | |
| 8933 | - let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap(); | |
| 8934 | - let recv = v8::undefined(tc).into(); | |
| 8935 | - f.call(tc, recv, &[u.into(), m.into(), b, h.into()]) | |
| 8936 | - .ok_or_else(|| anyhow!("makeRequest threw")) | |
| 8937 | -} | |
| 8938 | - | |
| 8939 | -fn read_response(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> Result<HttpResponse> { | |
| 8940 | - let ctx = scope.get_current_context(); | |
| 8941 | - let global = ctx.global(scope); | |
| 8942 | - let key = v8::String::new(scope, "__readResponse").unwrap(); | |
| 8943 | - let f: v8::Local<v8::Function> = global | |
| 8944 | - .get(scope, key.into()) | |
| 8945 | - .ok_or_else(|| anyhow!("no __readResponse"))? | |
| 8946 | - .try_into() | |
| 8947 | - .map_err(|_| anyhow!("not fn"))?; | |
| 8948 | - let recv = v8::undefined(scope).into(); | |
| 8949 | - let out = f | |
| 8950 | - .call(scope, recv, &[ret]) | |
| 8951 | - .ok_or_else(|| anyhow!("readResponse threw"))?; | |
| 8952 | - // The harness response reader is synchronous. Keeping this assertion at | |
| 8953 | - // the native boundary prevents a future harness change from quietly | |
| 8954 | - // reintroducing a nested async runtime while an isolate is entered. | |
| 8955 | - if out.is_promise() { | |
| 8956 | - return Err(anyhow!("__readResponse returned a promise")); | |
| 8957 | - } | |
| 8958 | - let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?; | |
| 8959 | - let ek = v8::String::new(scope, "error").unwrap(); | |
| 8960 | - if let Some(error) = out.get(scope, ek.into()).filter(|value| value.is_string()) { | |
| 8961 | - return Err(anyhow!(error.to_rust_string_lossy(scope))); | |
| 8962 | - } | |
| 8963 | - let sk = v8::String::new(scope, "status").unwrap(); | |
| 8964 | - let bk = v8::String::new(scope, "bodyBytes").unwrap(); | |
| 8965 | - let tk = v8::String::new(scope, "bodyStreamId").unwrap(); | |
| 8966 | - let hk = v8::String::new(scope, "headersJson").unwrap(); | |
| 8967 | - let wk = v8::String::new(scope, "wsTargetJson").unwrap(); | |
| 8968 | - let worker_wk = v8::String::new(scope, "workerSocketId").unwrap(); | |
| 8969 | - let status = out | |
| 8970 | - .get(scope, sk.into()) | |
| 8971 | - .and_then(|v| v.uint32_value(scope)) | |
| 8972 | - .unwrap_or(200) as u16; | |
| 8973 | - // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON | |
| 8974 | - // number array (which was ~4x the bytes to serialize + parse per response). | |
| 8975 | - let body = out | |
| 8976 | - .get(scope, bk.into()) | |
| 8977 | - .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok()) | |
| 8978 | - .map(|view| { | |
| 8979 | - let mut buf = vec![0u8; view.byte_length()]; | |
| 8980 | - view.copy_contents(&mut buf); | |
| 8981 | - buf | |
| 8982 | - }) | |
| 8983 | - .unwrap_or_default(); | |
| 8984 | - let stream_id = out | |
| 8985 | - .get(scope, tk.into()) | |
| 8986 | - .and_then(|value| value.integer_value(scope)) | |
| 8987 | - .unwrap_or(0) | |
| 8988 | - .max(0) as u64; | |
| 8989 | - let stream = if stream_id == 0 { | |
| 8990 | - None | |
| 8991 | - } else { | |
| 8992 | - http_streams() | |
| 8993 | - .lock() | |
| 8994 | - .unwrap() | |
| 8995 | - .remove(&stream_id) | |
| 8996 | - .and_then(|stream| stream.source) | |
| 8997 | - .map(http_chunk_stream) | |
| 8998 | - }; | |
| 8999 | - if stream_id != 0 && stream.is_none() { | |
| 9000 | - return Err(anyhow!( | |
| 9001 | - "response stream {stream_id} is no longer available" | |
| 9002 | - )); | |
| 9003 | - } | |
| 9004 | - let headers = out | |
| 9005 | - .get(scope, hk.into()) | |
| 9006 | - .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok()) | |
| 9007 | - .unwrap_or_default(); | |
| 9008 | - let ws_json = out | |
| 9009 | - .get(scope, wk.into()) | |
| 9010 | - .map(|v| v.to_rust_string_lossy(scope)) | |
| 9011 | - .unwrap_or_else(|| "null".into()); | |
| 9012 | - let ws = serde_json::from_str(&ws_json).ok(); | |
| 9013 | - let worker_id = out | |
| 9014 | - .get(scope, worker_wk.into()) | |
| 9015 | - .and_then(|value| value.integer_value(scope)) | |
| 9016 | - .unwrap_or(0) | |
| 9017 | - .max(0) as u64; | |
| 9018 | - let worker_ws = if worker_id == 0 { | |
| 9019 | - None | |
| 9020 | - } else { | |
| 9021 | - Some( | |
| 9022 | - websocket::transfer_worker_websocket_handoff(worker_id) | |
| 9023 | - .ok_or_else(|| anyhow!("Worker WebSocket {worker_id} has no frame handoff"))?, | |
| 9024 | - ) | |
| 9025 | - }; | |
| 9026 | - if status == 101 { | |
| 9027 | - tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response"); | |
| 9028 | - } | |
| 9029 | - let websocket = match (ws, worker_ws) { | |
| 9030 | - (Some(target), None) => Some(HttpResponseWebSocket::Cell(target)), | |
| 9031 | - (None, Some(worker)) => Some(HttpResponseWebSocket::Worker(worker)), | |
| 9032 | - (None, None) => None, | |
| 9033 | - (Some(_), Some(_)) => return Err(anyhow!("Worker response has two WebSocket targets")), | |
| 9034 | - }; | |
| 9035 | - Ok(HttpResponse { | |
| 9036 | - status, | |
| 9037 | - body, | |
| 9038 | - stream, | |
| 9039 | - headers, | |
| 9040 | - websocket, | |
| 9041 | - write_position: None, | |
| 24 | +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; | |
| 25 | +use std::sync::{Arc, Mutex, OnceLock, Weak}; | |
| 26 | +use std::time::{Duration, Instant}; | |
| 27 | +use v8::{ValueDeserializerHelper, ValueSerializerHelper}; | |
| 28 | + | |
| 29 | +pub(crate) mod input_gate_lifecycle; | |
| 30 | +use input_gate_lifecycle::{CrossEntryGateClaim, CrossEntryGateClaims}; | |
| 31 | + | |
| 32 | +#[cfg(all(test, celld_internal_tests))] | |
| 33 | +pub(crate) fn fail_post_checkpoint_facet_flush_for_test() { | |
| 34 | + asyncrt::services() | |
| 35 | + .wake_entry() | |
| 36 | + .fail_post_checkpoint_facet_flush | |
| 37 | + .store(true, Ordering::Release); | |
| 38 | +} | |
| 39 | + | |
| 40 | +#[cfg(all(test, celld_internal_tests))] | |
| 41 | +pub(crate) fn fail_next_embedded_delete_for_test() { | |
| 42 | + asyncrt::services() | |
| 43 | + .wake_entry() | |
| 44 | + .fail_next_embedded_delete | |
| 45 | + .store(true, Ordering::Release); | |
| 46 | +} | |
| 47 | + | |
| 48 | +#[cfg(all(test, celld_internal_tests))] | |
| 49 | +pub(crate) fn take_embedded_delete_fault_for_test() -> bool { | |
| 50 | + asyncrt::services() | |
| 51 | + .wake_entry() | |
| 52 | + .fail_next_embedded_delete | |
| 53 | + .swap(false, Ordering::AcqRel) | |
| 54 | +} | |
| 55 | + | |
| 56 | +/// Bare Node builtin specifiers that the bundler leaves for the runtime. | |
| 57 | +/// Root entries also match subpaths in esbuild and in module resolution. | |
| 58 | +pub(crate) const BARE_NODE_BUILTINS: &[&str] = &[ | |
| 59 | + "assert", | |
| 60 | + "async_hooks", | |
| 61 | + "buffer", | |
| 62 | + "child_process", | |
| 63 | + "cluster", | |
| 64 | + "constants", | |
| 65 | + "crypto", | |
| 66 | + "dgram", | |
| 67 | + "diagnostics_channel", | |
| 68 | + "dns", | |
| 69 | + "events", | |
| 70 | + "fs", | |
| 71 | + "fs/promises", | |
| 72 | + "http", | |
| 73 | + "http2", | |
| 74 | + "https", | |
| 75 | + "inspector", | |
| 76 | + "module", | |
| 77 | + "net", | |
| 78 | + "os", | |
| 79 | + "path", | |
| 80 | + "perf_hooks", | |
| 81 | + "process", | |
| 82 | + "punycode", | |
| 83 | + "querystring", | |
| 84 | + "readline", | |
| 85 | + "sqlite", | |
| 86 | + "stream", | |
| 87 | + "string_decoder", | |
| 88 | + "timers", | |
| 89 | + "tls", | |
| 90 | + "tty", | |
| 91 | + "url", | |
| 92 | + "util", | |
| 93 | + "util/types", | |
| 94 | + "v8", | |
| 95 | + "vm", | |
| 96 | + "worker_threads", | |
| 97 | + "zlib", | |
| 98 | +]; | |
| 99 | + | |
| 100 | +/// The pending exception text from a TryCatch scope (a macro so it needs no | |
| 101 | +/// bound on the crate-private scope traits). | |
| 102 | +macro_rules! exc { | |
| 103 | + ($tc:expr) => { | |
| 104 | + $tc.exception() | |
| 105 | + .map(|e| e.to_rust_string_lossy(&*$tc)) | |
| 106 | + .unwrap_or_else(|| "<none>".into()) | |
| 107 | + }; | |
| 108 | +} | |
| 109 | + | |
| 110 | +/// A cross-node dispatch: the isolate hit `env.NS.get(id)` for a cell this node | |
| 111 | +/// does not own. The op hands this to the tokio runtime, which resolves the | |
| 112 | +/// owner and HTTP-proxies the fetch, replying on `reply` (an async oneshot the | |
| 113 | +/// async-op future awaits — the JS thread is never blocked). | |
| 114 | +pub struct DoCallReq { | |
| 115 | + pub request_id: Option<RequestId>, | |
| 116 | + pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, | |
| 117 | + /// An explicit JavaScript AbortSignal must reach the target handler, even | |
| 118 | + /// when it fires before cold routing completes. Transport cancellation has | |
| 119 | + /// no handler contract and can stop the cold route immediately. | |
| 120 | + pub deliver_abort_to_handler: bool, | |
| 121 | + pub scope: String, | |
| 122 | + pub name: Option<String>, | |
| 123 | + pub url: String, | |
| 124 | + pub method: String, | |
| 125 | + pub body: RequestBody, | |
| 126 | + /// Owns a streamed body while the call waits for routing or admission. | |
| 127 | + pub body_guard: RequestBodyGuard, | |
| 128 | + pub headers: Vec<(String, String)>, | |
| 129 | + pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 130 | + /// Where this call sits in its caller's order for this cell. | |
| 131 | + pub order: Option<CallOrder>, | |
| 132 | + /// The dispatching handler's trace context, read from CPED at the | |
| 133 | + /// call site, so the cell's span joins the caller's trace. | |
| 134 | + pub parent: Option<crate::telemetry::TraceContext>, | |
| 135 | +} | |
| 136 | +static DO_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<DoCallReq>> = OnceLock::new(); | |
| 137 | + | |
| 138 | +/// Delivery order, per caller and per cell. | |
| 139 | +/// | |
| 140 | +/// Two calls a script makes back-to-back on one Durable Object stub reach | |
| 141 | +/// the cell in that order. Workerd guarantees it — one pipe per stub — and | |
| 142 | +/// celld did too, while a cell's events came off one channel. Nothing | |
| 143 | +/// between the call and the cell keeps it now: the caller's two ops race to | |
| 144 | +/// the proxy channel, the proxy polls them in a `FuturesUnordered`, and two | |
| 145 | +/// drives race for the isolate. So the order is taken where it is still | |
| 146 | +/// true, synchronously in `op_do_call_impl`, and carried to the one place | |
| 147 | +/// that decides when an event is delivered. | |
| 148 | +/// | |
| 149 | +/// It is a chain, not a counter: each call leaves behind the receiver its | |
| 150 | +/// successor waits on, and takes its predecessor's. | |
| 151 | +/// | |
| 152 | +/// **The chain lives on the caller.** It was a process-wide map keyed by | |
| 153 | +/// `(context, cell)`, which made every Durable Object call in the node take | |
| 154 | +/// one global lock to record something only its own caller could ever read. | |
| 155 | +/// A shared mutex on a per-request path is a scalability cliff that a small | |
| 156 | +/// machine cannot show you, and the state was never shared to begin with. | |
| 157 | +/// | |
| 158 | +/// **Local delivery only.** A call routed to another node crosses HTTP, | |
| 159 | +/// where this order has nowhere to ride, so it is dropped there. Workerd | |
| 160 | +/// has the same seam in a different place, and a cell that moves mid-flight | |
| 161 | +/// reorders under both. | |
| 162 | +pub struct CallOrder { | |
| 163 | + /// The call before this one, or `None` if this is the first. | |
| 164 | + ahead: Option<tokio::sync::oneshot::Receiver<Place>>, | |
| 165 | + /// What the call behind this one waits on. | |
| 166 | + release: Option<tokio::sync::oneshot::Sender<Place>>, | |
| 167 | + /// The caller that owns the chain, and this call's place in it. | |
| 168 | + caller: Arc<IoContext>, | |
| 169 | + cell: String, | |
| 170 | + seq: u64, | |
| 171 | + delivered: bool, | |
| 172 | +} | |
| 173 | + | |
| 174 | +/// What a call hands to the one behind it. | |
| 175 | +/// | |
| 176 | +/// `None` once this call has been delivered: the queue has moved on. `Some` | |
| 177 | +/// when it died on the way to a cell and never took its turn, and then it | |
| 178 | +/// is this call's own unfinished place — so the call behind waits for what | |
| 179 | +/// this one was waiting for instead of jumping the queue. | |
| 180 | +/// | |
| 181 | +/// Without the handoff a failed call releases its successor immediately, | |
| 182 | +/// and a third call can be delivered ahead of a first that is still in | |
| 183 | +/// flight. Rare, since it needs a call to fail between two that do not, and | |
| 184 | +/// silent, since every call involved still gets an answer. | |
| 185 | +#[doc(hidden)] | |
| 186 | +pub struct Place(Option<Box<tokio::sync::oneshot::Receiver<Place>>>); | |
| 187 | + | |
| 188 | +impl CallOrder { | |
| 189 | + /// Wait for every call before this one to be delivered. | |
| 190 | + /// | |
| 191 | + /// A loop rather than one await because a call that died hands back | |
| 192 | + /// what *it* was waiting for. `Err` is the chain ahead going away | |
| 193 | + /// entirely, which is nothing left to wait for. | |
| 194 | + pub async fn wait(&mut self) { | |
| 195 | + let mut ahead = self.ahead.take(); | |
| 196 | + while let Some(place) = ahead { | |
| 197 | + ahead = match place.await { | |
| 198 | + Ok(Place(forward)) => forward.map(|boxed| *boxed), | |
| 199 | + Err(_) => None, | |
| 200 | + }; | |
| 201 | + } | |
| 202 | + } | |
| 203 | + | |
| 204 | + /// This call has been delivered; the one behind it may go. | |
| 205 | + pub fn delivered(&mut self) { | |
| 206 | + self.delivered = true; | |
| 207 | + } | |
| 208 | +} | |
| 209 | + | |
| 210 | +impl Drop for CallOrder { | |
| 211 | + fn drop(&mut self) { | |
| 212 | + // Nothing followed this call, so the chain is empty and its tail is | |
| 213 | + // only a leak. A caller's chains outlive its calls otherwise, and a | |
| 214 | + // cell isolate's default caller outlives everything. | |
| 215 | + let mut chains = self.caller.call_chains.lock().unwrap(); | |
| 216 | + if chains | |
| 217 | + .tails | |
| 218 | + .get(&self.cell) | |
| 219 | + .is_some_and(|(seq, _)| *seq == self.seq) | |
| 220 | + { | |
| 221 | + chains.tails.remove(&self.cell); | |
| 222 | + } | |
| 223 | + drop(chains); | |
| 224 | + if let Some(release) = self.release.take() { | |
| 225 | + let forward = (!self.delivered).then(|| self.ahead.take()).flatten(); | |
| 226 | + let _ = release.send(Place(forward.map(Box::new))); | |
| 227 | + } | |
| 228 | + } | |
| 229 | +} | |
| 230 | + | |
| 231 | +/// One caller's chains, one per cell it has called. | |
| 232 | +#[derive(Default)] | |
| 233 | +#[doc(hidden)] | |
| 234 | +pub struct CallChains { | |
| 235 | + next_seq: u64, | |
| 236 | + pub tails: HashMap<String, (u64, tokio::sync::oneshot::Receiver<Place>)>, | |
| 237 | +} | |
| 238 | + | |
| 239 | +/// Take this call's place in its caller's chain for `cell`. Synchronous, so | |
| 240 | +/// the places are taken in the order the script made the calls. | |
| 241 | +#[doc(hidden)] | |
| 242 | +pub fn enter_call_order(caller: Arc<IoContext>, cell: &str) -> CallOrder { | |
| 243 | + let (release, next) = tokio::sync::oneshot::channel(); | |
| 244 | + let (seq, ahead) = { | |
| 245 | + let mut chains = caller.call_chains.lock().unwrap(); | |
| 246 | + chains.next_seq += 1; | |
| 247 | + let seq = chains.next_seq; | |
| 248 | + let ahead = chains | |
| 249 | + .tails | |
| 250 | + .insert(cell.to_string(), (seq, next)) | |
| 251 | + .map(|(_, ahead)| ahead); | |
| 252 | + (seq, ahead) | |
| 253 | + }; | |
| 254 | + CallOrder { | |
| 255 | + ahead, | |
| 256 | + release: Some(release), | |
| 257 | + caller, | |
| 258 | + cell: cell.to_string(), | |
| 259 | + seq, | |
| 260 | + delivered: false, | |
| 261 | + } | |
| 262 | +} | |
| 263 | + | |
| 264 | +/// A ticket asking the actor whether an outbound effect may leave the process. | |
| 265 | +/// | |
| 266 | +/// Every in-handler channel takes one: `fetch`, a service binding, a call to | |
| 267 | +/// another cell, and a frame on a socket the isolate opened. `position` is | |
| 268 | +/// present when the running event wrote through it, absent when the event only | |
| 269 | +/// read and the effect must trail whatever the cell already has outstanding. | |
| 270 | +pub struct GateReq { | |
| 271 | + pub scope: String, | |
| 272 | + /// The route the held effect would leave by, the position it must see | |
| 273 | + /// proven, and the epoch that position was sampled at. The sample happens | |
| 274 | + /// in the handler's turn, before `dispatch_gate` acquires the request that | |
| 275 | + /// pins the cell; a reset in between discards the sampled write and the | |
| 276 | + /// request would activate the next epoch, so the core refuses a ticket | |
| 277 | + /// whose epoch is not the resident one. The core stores the route and | |
| 278 | + /// hands it back, so the shell can route the release to the adapter | |
| 279 | + /// holding the effect. | |
| 280 | + pub ticket: crate::actor::GateTicket, | |
| 281 | + pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>, | |
| 282 | +} | |
| 283 | +static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new(); | |
| 284 | +pub fn set_gate_tx(tx: tokio::sync::mpsc::UnboundedSender<GateReq>) { | |
| 285 | + let _ = GATE_TX.set(tx); | |
| 286 | +} | |
| 287 | + | |
| 288 | +/// A service-binding call: `env.NAME.fetch()`. Unlike a Durable Object call | |
| 289 | +/// there is no identity to resolve — any isolate running `script` will do — so | |
| 290 | +/// the runtime hands this straight to that script's stateless isolate pool. | |
| 291 | +pub struct SvcCallReq { | |
| 292 | + /// Fires when the caller's request signal aborts, so the router stops | |
| 293 | + /// waiting on the target instead of leaving the call outstanding. | |
| 294 | + pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, | |
| 295 | + /// The application generation of the calling isolate. The target is | |
| 296 | + /// resolved in that generation's service graph, so a caller built for | |
| 297 | + /// one deployment never reaches a target from another. | |
| 298 | + pub generation: crate::generation::GenerationId, | |
| 299 | + pub script: String, | |
| 300 | + pub url: String, | |
| 301 | + pub method: String, | |
| 302 | + pub body: RequestBody, | |
| 303 | + /// Owns a streamed body until the target installs its request context. | |
| 304 | + pub body_guard: RequestBodyGuard, | |
| 305 | + pub headers: Vec<(String, String)>, | |
| 306 | + pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 307 | +} | |
| 308 | +static SVC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcCallReq>> = OnceLock::new(); | |
| 309 | + | |
| 310 | +/// A Worker assets-binding call. The script name selects the immutable asset | |
| 311 | +/// index loaded for that Worker; unlike ingress this never falls back into the | |
| 312 | +/// Worker and therefore cannot recurse. | |
| 313 | +pub struct AssetCallReq { | |
| 314 | + /// The calling isolate's application generation; see `SvcCallReq`. | |
| 315 | + pub generation: crate::generation::GenerationId, | |
| 316 | + pub script: String, | |
| 317 | + pub url: String, | |
| 318 | + pub method: String, | |
| 319 | + pub headers: Vec<(String, String)>, | |
| 320 | + pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 321 | +} | |
| 322 | +static ASSET_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<AssetCallReq>> = OnceLock::new(); | |
| 323 | + | |
| 324 | +/// An RPC call on a named `WorkerEntrypoint` of another script. Arguments and | |
| 325 | +/// the result cross as V8 structured-clone bytes. | |
| 326 | +pub struct SvcRpcReq { | |
| 327 | + /// The calling isolate's application generation; see `SvcCallReq`. | |
| 328 | + pub generation: crate::generation::GenerationId, | |
| 329 | + pub script: String, | |
| 330 | + pub entrypoint: String, | |
| 331 | + pub method: String, | |
| 332 | + pub args: Vec<u8>, | |
| 333 | + pub reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>, | |
| 334 | +} | |
| 335 | +static SVC_RPC_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcRpcReq>> = OnceLock::new(); | |
| 336 | + | |
| 337 | +/// The persisted identity a consumer settlement must match for one message. | |
| 338 | +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] | |
| 339 | +pub struct QueueLeaseRef { | |
| 340 | + pub message_id: String, | |
| 341 | + pub seq: i64, | |
| 342 | + pub generation: u64, | |
| 343 | +} | |
| 344 | + | |
| 345 | +/// A durable broker batch released through its output gate. | |
| 346 | +pub struct QueueDispatchReq { | |
| 347 | + pub scope: String, | |
| 348 | + /// The dispatching queue cell's application generation; see | |
| 349 | + /// `SvcCallReq`. | |
| 350 | + pub generation: crate::generation::GenerationId, | |
| 351 | + pub script: String, | |
| 352 | + pub lease_id: String, | |
| 353 | + pub leases: Vec<QueueLeaseRef>, | |
| 354 | + pub batch: QueueBatch, | |
| 355 | +} | |
| 356 | +static QUEUE_DISPATCH_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<QueueDispatchReq>> = | |
| 357 | + OnceLock::new(); | |
| 358 | +/// The fleet bucket used by KV values that are too large for a namespace cell. | |
| 359 | +/// | |
| 360 | +/// The landed R2 binding established the safe pattern: a cloneable bucket | |
| 361 | +/// handle can live beside the asynchronous ops, so independent requests do not | |
| 362 | +/// queue behind one task that awaits every object-store operation in order. | |
| 363 | +static KV_BLOB_STORE: OnceLock<crate::bucket::Bucket> = OnceLock::new(); | |
| 364 | + | |
| 365 | +pub fn set_kv_blob_store(store: crate::bucket::Bucket) { | |
| 366 | + let _ = KV_BLOB_STORE.set(store); | |
| 367 | +} | |
| 368 | + | |
| 369 | +fn kv_blob_store() -> std::result::Result<&'static crate::bucket::Bucket, String> { | |
| 370 | + KV_BLOB_STORE | |
| 371 | + .get() | |
| 372 | + .ok_or_else(|| "KV large values need a fleet bucket".to_string()) | |
| 373 | +} | |
| 374 | + | |
| 375 | +pub fn set_svc_rpc_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcRpcReq>) { | |
| 376 | + let _ = SVC_RPC_TX.set(tx); | |
| 377 | +} | |
| 378 | +pub fn set_svc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcCallReq>) { | |
| 379 | + let _ = SVC_CALL_TX.set(tx); | |
| 380 | +} | |
| 381 | +pub fn set_queue_dispatch_tx(tx: tokio::sync::mpsc::UnboundedSender<QueueDispatchReq>) { | |
| 382 | + let _ = QUEUE_DISPATCH_TX.set(tx); | |
| 383 | +} | |
| 384 | +pub fn set_asset_call_tx(tx: tokio::sync::mpsc::UnboundedSender<AssetCallReq>) { | |
| 385 | + let _ = ASSET_CALL_TX.set(tx); | |
| 386 | +} | |
| 387 | +pub fn set_do_call_tx(tx: tokio::sync::mpsc::UnboundedSender<DoCallReq>) { | |
| 388 | + let _ = DO_CALL_TX.set(tx); | |
| 389 | +} | |
| 390 | + | |
| 391 | +/// Hand a Durable Object call to the dispatcher. Public HTTP ingress uses the | |
| 392 | +/// same queue a Worker's `env.NAME.get(id).fetch()` does, so both resolve | |
| 393 | +/// ownership, forward, and redispatch by one policy rather than two. | |
| 394 | +#[must_use] | |
| 395 | +pub fn submit_do_call(call: DoCallReq) -> bool { | |
| 396 | + DO_CALL_TX.get().is_some_and(|tx| tx.send(call).is_ok()) | |
| 397 | +} | |
| 398 | + | |
| 399 | +/// The arm-time wake-entry gate, output-gate style (matching Durable | |
| 400 | +/// Objects): `setAlarm()` resolves optimistically on the committed local | |
| 401 | +/// write — it never yields the cell's event scheduling to remote I/O — and | |
| 402 | +/// the cell's response edge is withheld until every wake-entry PUT that this | |
| 403 | +/// event registered before its response boundary has landed. Invariant: an | |
| 404 | +/// arm the caller has OBSERVED acknowledged (received the response) is | |
| 405 | +/// covered by a durable entry. | |
| 406 | +pub struct ArmGate { | |
| 407 | + pub bucket: crate::bucket::Bucket, | |
| 408 | + pub flusher: Arc<crate::wake::WakeFlusher>, | |
| 409 | +} | |
| 410 | + | |
| 411 | +type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>; | |
| 412 | + | |
| 413 | +#[derive(Default)] | |
| 414 | +pub(crate) struct WakeEntryService { | |
| 415 | + gate: OnceLock<ArmGate>, | |
| 416 | + #[cfg(celld_internal_tests)] | |
| 417 | + test_pending: Mutex<HashMap<String, Vec<ArmGateRx>>>, | |
| 418 | + #[cfg(celld_internal_tests)] | |
| 419 | + scripted: Mutex<std::collections::VecDeque<ArmGateRx>>, | |
| 420 | + #[cfg(celld_internal_tests)] | |
| 421 | + scripted_by_cell: Mutex<HashMap<String, std::collections::VecDeque<ArmGateRx>>>, | |
| 422 | + #[cfg(celld_internal_tests)] | |
| 423 | + drop_next_gated_reply_task: AtomicBool, | |
| 424 | + #[cfg(all(test, celld_internal_tests))] | |
| 425 | + fail_post_checkpoint_facet_flush: AtomicBool, | |
| 426 | + #[cfg(all(test, celld_internal_tests))] | |
| 427 | + fail_next_embedded_delete: AtomicBool, | |
| 428 | +} | |
| 429 | + | |
| 430 | +pub use r2_ops::set_r2_store; | |
| 431 | + | |
| 432 | +pub fn set_arm_gate(gate: ArmGate) { | |
| 433 | + let _ = asyncrt::services().wake_entry().gate.set(gate); | |
| 434 | +} | |
| 435 | + | |
| 436 | +/// Whether this node still holds a wake entry for `cell`. | |
| 437 | +pub fn wake_entry_tracked(cell: &str) -> bool { | |
| 438 | + asyncrt::services() | |
| 439 | + .wake_entry() | |
| 440 | + .gate | |
| 441 | + .get() | |
| 442 | + .is_some_and(|gate| gate.flusher.tracks(cell)) | |
| 443 | +} | |
| 444 | + | |
| 445 | +/// Drop this node's belief about `cell`'s wake entry — the cell fenced or | |
| 446 | +/// resolved to a remote owner, so the entry is no longer ours to manage. | |
| 447 | +/// A node that loses a cell must also forget its wake entry. | |
| 448 | +pub fn forget_wake_entry(cell: &str) { | |
| 449 | + let services = asyncrt::services(); | |
| 450 | + if let Some(gate) = services.wake_entry().gate.get() { | |
| 451 | + gate.flusher.forget(cell); | |
| 452 | + } | |
| 453 | +} | |
| 454 | + | |
| 455 | +/// Adopt the wake entry a restored alarm implies, so consuming that alarm | |
| 456 | +/// deletes it rather than orphaning it. | |
| 457 | +pub fn adopt_wake_entry(cell: &str, at_ms: i64) { | |
| 458 | + let services = asyncrt::services(); | |
| 459 | + if let Some(gate) = services.wake_entry().gate.get() { | |
| 460 | + gate.flusher.adopt(cell, at_ms); | |
| 461 | + } | |
| 462 | +} | |
| 463 | + | |
| 464 | +/// Bring the bucket's wake entry for `cell` into line with its alarm. | |
| 465 | +/// | |
| 466 | +/// Arming writes an entry; something has to take it away again once the alarm | |
| 467 | +/// has been consumed, or the entry outlives its alarm and every later due scan | |
| 468 | +/// finds it and wakes a cell with nothing to do. `consume_durable` gates that | |
| 469 | +/// final delete on the consuming commit being replicated -- removing the hint | |
| 470 | +/// while the commit that consumed the alarm is still only local would lose | |
| 471 | +/// both the alarm and the record that could have revived it. | |
| 472 | +pub async fn reconcile_wake_entry(cell: &str, next_alarm_ms: i64, consume_durable: bool) { | |
| 473 | + let services = asyncrt::services(); | |
| 474 | + let Some(gate) = services.wake_entry().gate.get() else { | |
| 475 | + return; | |
| 476 | + }; | |
| 477 | + gate.flusher | |
| 478 | + .reconcile(&gate.bucket, cell, next_alarm_ms, consume_durable) | |
| 479 | + .await; | |
| 480 | +} | |
| 481 | + | |
| 482 | +/// A committed alarm tightened the durable wake bound: launch the entry PUT | |
| 483 | +/// and register it against the current event's output gate. No-op when the | |
| 484 | +/// bound already covers it or no gate is configured. | |
| 485 | +fn spawn_arm_gate(cell: &str, at_ms: i64, context: Option<Arc<IoContext>>) { | |
| 486 | + if let Some(rx) = launch_arm_gate(cell, at_ms) { | |
| 487 | + register_arm_gate_with_current_event(rx, context); | |
| 488 | + } | |
| 489 | +} | |
| 490 | + | |
| 491 | +/// Launch the durable PUT and return the response edge that observes it. | |
| 492 | +/// Registration is separate because production binds the receiver to a V8 | |
| 493 | +/// event, while the private S1 driver binds it to its simulated request. | |
| 494 | +fn launch_arm_gate(cell: &str, at_ms: i64) -> Option<ArmGateRx> { | |
| 495 | + let services = asyncrt::services(); | |
| 496 | + #[cfg(celld_internal_tests)] | |
| 497 | + if let Some(rx) = services | |
| 498 | + .wake_entry() | |
| 499 | + .scripted_by_cell | |
| 500 | + .lock() | |
| 501 | + .unwrap() | |
| 502 | + .get_mut(cell) | |
| 503 | + .and_then(std::collections::VecDeque::pop_front) | |
| 504 | + { | |
| 505 | + return Some(rx); | |
| 506 | + } | |
| 507 | + #[cfg(celld_internal_tests)] | |
| 508 | + if let Some(rx) = services.wake_entry().scripted.lock().unwrap().pop_front() { | |
| 509 | + return Some(rx); | |
| 510 | + } | |
| 511 | + let gate = services.wake_entry().gate.get()?; | |
| 512 | + let Some(celld_logic::wake::Op::Put { key, due_ms }) = gate.flusher.arm_op(cell, at_ms) else { | |
| 513 | + return None; | |
| 514 | + }; | |
| 515 | + let cell_ = cell.to_string(); | |
| 516 | + let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 517 | + asyncrt::spawn(async move { | |
| 518 | + let gate = services.wake_entry().gate.get().unwrap(); | |
| 519 | + // A delete of this exact key may already be on the wire — the tracked | |
| 520 | + // entry's consume-delete, or the move-delete of a key this arm is | |
| 521 | + // about to re-PUT. Either way the PUT must land after that delete, | |
| 522 | + // not race it (S3 orders concurrent same-key writes arbitrarily). | |
| 523 | + // Deletes of the cell's OTHER keys cannot touch this PUT, and waiting | |
| 524 | + // on them would hold the response behind unrelated store latency. | |
| 525 | + gate.flusher.await_key_deletable(&cell_, &key).await; | |
| 526 | + let body = format!("{{\"cell\":{cell_:?},\"due_ms\":{due_ms}}}"); | |
| 527 | + let result = gate | |
| 528 | + .bucket | |
| 529 | + .put(&key, body.into_bytes()) | |
| 530 | + .await | |
| 531 | + .map(|_| gate.flusher.confirm_arm(&cell_, due_ms, key)) | |
| 532 | + .map_err(|e| format!("setAlarm wake entry: {e}")); | |
| 533 | + let _ = tx.send(result); | |
| 534 | + }) | |
| 535 | + .detach(); | |
| 536 | + Some(rx) | |
| 537 | +} | |
| 538 | + | |
| 539 | +fn register_arm_gate_with_current_event(gate: ArmGateRx, context: Option<Arc<IoContext>>) { | |
| 540 | + let Some(context) = context else { | |
| 541 | + drop(gate); | |
| 542 | + return; | |
| 543 | + }; | |
| 544 | + if let Err(gate) = context.register_arm_gate(gate) { | |
| 545 | + // The response boundary sealed this context. The PUT itself | |
| 546 | + // continues, but its receiver cannot migrate into a later event's | |
| 547 | + // reply batch. | |
| 548 | + drop(gate); | |
| 549 | + } | |
| 550 | +} | |
| 551 | + | |
| 552 | +#[cfg(celld_internal_tests)] | |
| 553 | +fn register_test_pending_arm_gate(cell: &str, gate: ArmGateRx) { | |
| 554 | + let services = asyncrt::services(); | |
| 555 | + let mut pending = services.wake_entry().test_pending.lock().unwrap(); | |
| 556 | + let gates = pending.entry(cell.to_string()).or_default(); | |
| 557 | + gates.retain_mut(|gate| { | |
| 558 | + matches!( | |
| 559 | + gate.try_recv(), | |
| 560 | + Err(tokio::sync::oneshot::error::TryRecvError::Empty) | |
| 561 | + ) | |
| 562 | + }); | |
| 563 | + gates.push(gate); | |
| 564 | +} | |
| 565 | + | |
| 566 | +#[cfg(celld_internal_tests)] | |
| 567 | +pub(crate) fn spawn_arm_gate_for_test(cell: &str, at_ms: i64) { | |
| 568 | + let Some(gate) = launch_arm_gate(cell, at_ms) else { | |
| 569 | + return; | |
| 570 | + }; | |
| 571 | + match installed_context() { | |
| 572 | + Some(context) => register_arm_gate_with_current_event(gate, Some(context)), | |
| 573 | + None => register_test_pending_arm_gate(cell, gate), | |
| 574 | + } | |
| 575 | +} | |
| 576 | + | |
| 577 | +#[cfg(celld_internal_tests)] | |
| 578 | +#[doc(hidden)] | |
| 579 | +pub fn pause_next_arm_gate_for_test() -> tokio::sync::oneshot::Sender<Result<(), String>> { | |
| 580 | + let (resume, paused) = tokio::sync::oneshot::channel(); | |
| 581 | + asyncrt::services() | |
| 582 | + .wake_entry() | |
| 583 | + .scripted | |
| 584 | + .lock() | |
| 585 | + .unwrap() | |
| 586 | + .push_back(paused); | |
| 587 | + resume | |
| 588 | +} | |
| 589 | + | |
| 590 | +#[cfg(celld_internal_tests)] | |
| 591 | +#[doc(hidden)] | |
| 592 | +pub fn pause_next_arm_gate_for_cell_for_test( | |
| 593 | + cell: &str, | |
| 594 | +) -> tokio::sync::oneshot::Sender<Result<(), String>> { | |
| 595 | + let (resume, paused) = tokio::sync::oneshot::channel(); | |
| 596 | + asyncrt::services() | |
| 597 | + .wake_entry() | |
| 598 | + .scripted_by_cell | |
| 599 | + .lock() | |
| 600 | + .unwrap() | |
| 601 | + .entry(cell.to_string()) | |
| 602 | + .or_default() | |
| 603 | + .push_back(paused); | |
| 604 | + resume | |
| 605 | +} | |
| 606 | + | |
| 607 | +#[cfg(celld_internal_tests)] | |
| 608 | +#[doc(hidden)] | |
| 609 | +pub fn next_arm_gate_is_paused_for_test() -> bool { | |
| 610 | + !asyncrt::services() | |
| 611 | + .wake_entry() | |
| 612 | + .scripted | |
| 613 | + .lock() | |
| 614 | + .unwrap() | |
| 615 | + .is_empty() | |
| 616 | +} | |
| 617 | + | |
| 618 | +#[cfg(celld_internal_tests)] | |
| 619 | +#[doc(hidden)] | |
| 620 | +pub fn next_arm_gate_for_cell_is_paused_for_test(cell: &str) -> bool { | |
| 621 | + asyncrt::services() | |
| 622 | + .wake_entry() | |
| 623 | + .scripted_by_cell | |
| 624 | + .lock() | |
| 625 | + .unwrap() | |
| 626 | + .get(cell) | |
| 627 | + .is_some_and(|gates| !gates.is_empty()) | |
| 628 | +} | |
| 629 | + | |
| 630 | +/// Drain the compatibility wake-entry PUT gates for a simulated S1 cell. | |
| 631 | +#[cfg(celld_internal_tests)] | |
| 632 | +#[doc(hidden)] | |
| 633 | +pub async fn drain_arm_gates(cell: &str) -> Result<(), String> { | |
| 634 | + let services = asyncrt::services(); | |
| 635 | + let gates = services | |
| 636 | + .wake_entry() | |
| 637 | + .test_pending | |
| 638 | + .lock() | |
| 639 | + .unwrap() | |
| 640 | + .remove(cell); | |
| 641 | + let Some(gates) = gates else { | |
| 642 | + return Ok(()); | |
| 643 | + }; | |
| 644 | + await_arm_gates(gates).await | |
| 645 | +} | |
| 646 | + | |
| 647 | +pub type RequestId = u128; | |
| 648 | + | |
| 649 | +#[derive(Clone, Copy)] | |
| 650 | +pub struct FetchRequest<'a> { | |
| 651 | + pub url: &'a str, | |
| 652 | + pub method: &'a str, | |
| 653 | + pub body: &'a [u8], | |
| 654 | + pub headers: &'a [(String, String)], | |
| 655 | + pub request_id: Option<RequestId>, | |
| 656 | +} | |
| 657 | + | |
| 658 | +/// Allocate an id for an ingress or service-binding request so it can be | |
| 659 | +/// aborted mid-flight. | |
| 660 | +pub fn next_request_id() -> RequestId { | |
| 661 | + next_do_request_id() | |
| 662 | +} | |
| 663 | + | |
| 664 | +static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1); | |
| 665 | +static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new(); | |
| 666 | +static DO_CALL_CANCELS: OnceLock< | |
| 667 | + std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>>, | |
| 668 | +> = OnceLock::new(); | |
| 669 | +fn do_call_cancels( | |
| 670 | +) -> &'static std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>> { | |
| 671 | + DO_CALL_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 672 | +} | |
| 673 | + | |
| 674 | +#[doc(hidden)] | |
| 675 | +pub fn next_do_request_id() -> RequestId { | |
| 676 | + let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| { | |
| 677 | + let mut bytes = [0; 8]; | |
| 678 | + getrandom::fill(&mut bytes).expect("OS random source unavailable"); | |
| 679 | + u64::from_ne_bytes(bytes) | |
| 680 | + }); | |
| 681 | + let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed); | |
| 682 | + (u128::from(prefix) << 64) | u128::from(sequence) | |
| 683 | +} | |
| 684 | + | |
| 685 | +pub fn request_id_string(request_id: RequestId) -> String { | |
| 686 | + format!("{request_id:032x}") | |
| 687 | +} | |
| 688 | + | |
| 689 | +pub fn parse_request_id(value: &str) -> Option<RequestId> { | |
| 690 | + u128::from_str_radix(value, 16).ok() | |
| 691 | +} | |
| 692 | + | |
| 693 | +/// Publish `request_id` on a pending call's promise as the token the JS | |
| 694 | +/// harness hands back to `__do_call_cancel`. | |
| 695 | +/// | |
| 696 | +/// The only writer of `__celldCancelId`, and the counterpart of | |
| 697 | +/// [`parse_request_id`]. Each cancellable op used to spell the property name | |
| 698 | +/// and the encoding out for itself, and `op_svc_call_impl` wrote decimal while | |
| 699 | +/// `op_do_call_cancel` reads hexadecimal. Every decimal digit is also a | |
| 700 | +/// hexadecimal digit, so the parse succeeded on a different number, the | |
| 701 | +/// registry lookup missed, and the cancel was dropped with no error — a | |
| 702 | +/// service-binding abort rejected the caller and left the target running. One | |
| 703 | +/// writer paired with one parser removes the chance to disagree. | |
| 704 | +fn attach_cancel_id( | |
| 705 | + scope: &mut v8::PinScope, | |
| 706 | + promise: v8::Local<v8::Value>, | |
| 707 | + request_id: RequestId, | |
| 708 | +) { | |
| 709 | + let Some(object) = promise.to_object(scope) else { | |
| 710 | + return; | |
| 711 | + }; | |
| 712 | + let key = v8::String::new(scope, "__celldCancelId").unwrap(); | |
| 713 | + let value = v8::String::new(scope, &request_id_string(request_id)).unwrap(); | |
| 714 | + object.set(scope, key.into(), value.into()); | |
| 715 | +} | |
| 716 | + | |
| 717 | +struct DoCallCancelGuard(Option<RequestId>); | |
| 718 | + | |
| 719 | +impl DoCallCancelGuard { | |
| 720 | + fn new(request: RequestId) -> Self { | |
| 721 | + Self(Some(request)) | |
| 722 | + } | |
| 723 | + | |
| 724 | + fn disarm(&mut self) { | |
| 725 | + if let Some(request) = self.0.take() { | |
| 726 | + do_call_cancels().lock().unwrap().remove(&request); | |
| 727 | + } | |
| 728 | + } | |
| 729 | +} | |
| 730 | + | |
| 731 | +impl Drop for DoCallCancelGuard { | |
| 732 | + fn drop(&mut self) { | |
| 733 | + let Some(request) = self.0.take() else { | |
| 734 | + return; | |
| 735 | + }; | |
| 736 | + if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request) { | |
| 737 | + let _ = cancel.send(()); | |
| 738 | + } | |
| 739 | + } | |
| 740 | +} | |
| 741 | + | |
| 742 | +/// An RPC payload crossing the host boundary. JS stubs marshal by V8 | |
| 743 | +/// structured clone (`V8`), and legacy callers use the JSON envelope (`Json`). | |
| 744 | +/// `__dispatchRpc` answers in the flavor it was asked in. | |
| 745 | +pub enum RpcData { | |
| 746 | + Json(String), | |
| 747 | + V8(bytes::Bytes), | |
| 748 | +} | |
| 749 | + | |
| 750 | +/// A native Durable Object RPC call (`stub.someMethod(...args)`). | |
| 751 | +/// Routing/activation is identical to fetch calls. | |
| 752 | +pub struct RpcCallReq { | |
| 753 | + pub scope: String, | |
| 754 | + pub name: Option<String>, | |
| 755 | + pub method: String, | |
| 756 | + pub args: RpcData, | |
| 757 | + pub reply: tokio::sync::oneshot::Sender<Result<RpcData>>, | |
| 758 | +} | |
| 759 | +static RPC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<RpcCallReq>> = OnceLock::new(); | |
| 760 | +pub fn set_rpc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<RpcCallReq>) { | |
| 761 | + let _ = RPC_CALL_TX.set(tx); | |
| 762 | +} | |
| 763 | + | |
| 764 | +pub struct OutboundWsReq { | |
| 765 | + pub scope: String, | |
| 766 | + pub id: u64, | |
| 767 | + pub url: String, | |
| 768 | + pub protocols: Vec<String>, | |
| 769 | + /// Present for an isolate-polled (Worker) socket. Created and registered | |
| 770 | + /// on the JS thread before the request is sent, so `__ws_next` can never | |
| 771 | + /// run ahead of its own queue. | |
| 772 | + pub pull: Option<WsPullSender>, | |
| 773 | + /// Extra request headers, for the `fetch()` upgrade form. | |
| 774 | + pub headers: Vec<(String, String)>, | |
| 775 | + /// A `fetch()` upgrade wants the whole handshake outcome, including the | |
| 776 | + /// ordinary response a server that declines to upgrade sent instead. | |
| 777 | + pub want_response: bool, | |
| 778 | + /// A socket already upgraded in this process, which this request joins | |
| 779 | + /// instead of dialing `url`. It is the cell end of a Durable Object | |
| 780 | + /// subrequest whose caller kept the client end, so there is no handshake | |
| 781 | + /// to run and no connection to open: the host only has to carry frames | |
| 782 | + /// between two isolates. | |
| 783 | + pub target: Option<WsTarget>, | |
| 784 | + pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>, | |
| 785 | +} | |
| 786 | + | |
| 787 | +/// The ordinary HTTP response a server sent instead of upgrading. `fetch()` | |
| 788 | +/// returns it verbatim rather than turning it into a connection error. | |
| 789 | +pub struct DeclinedUpgrade { | |
| 790 | + pub status: u16, | |
| 791 | + pub headers: Vec<(String, String)>, | |
| 792 | + pub body: Vec<u8>, | |
| 793 | +} | |
| 794 | + | |
| 795 | +/// What an outbound handshake produced. | |
| 796 | +pub struct OutboundWsOpen { | |
| 797 | + pub protocol: Option<String>, | |
| 798 | + pub declined: Option<DeclinedUpgrade>, | |
| 799 | +} | |
| 800 | +static OUTBOUND_WS_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> = | |
| 801 | + OnceLock::new(); | |
| 802 | +pub fn set_outbound_ws_tx(tx: tokio::sync::mpsc::UnboundedSender<OutboundWsReq>) { | |
| 803 | + let _ = OUTBOUND_WS_TX.set(tx); | |
| 804 | +} | |
| 805 | + | |
| 806 | +#[cfg(celld_internal_tests)] | |
| 807 | +/// An outbound connector scoped to the current internal-test JS thread. | |
| 808 | +/// | |
| 809 | +/// The production connector is process-wide. Installing a test sender there | |
| 810 | +/// captures requests from unrelated suites, and those suites have no receiver | |
| 811 | +/// that can answer them. The thread-local sender follows the current-thread V8 | |
| 812 | +/// harnesses, while this handle owns its receiver and removes the sender when | |
| 813 | +/// the case ends. | |
| 814 | +#[doc(hidden)] | |
| 815 | +pub struct TestOutboundWsConnector { | |
| 816 | + requests: tokio::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<OutboundWsReq>>, | |
| 817 | + /// A scoped connector must drop on the thread where it installed its sender. | |
| 818 | + _not_send: std::marker::PhantomData<std::rc::Rc<()>>, | |
| 819 | +} | |
| 820 | + | |
| 821 | +#[cfg(celld_internal_tests)] | |
| 822 | +impl TestOutboundWsConnector { | |
| 823 | + #[doc(hidden)] | |
| 824 | + pub fn requests( | |
| 825 | + &self, | |
| 826 | + ) -> &tokio::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<OutboundWsReq>> { | |
| 827 | + &self.requests | |
| 828 | + } | |
| 829 | +} | |
| 830 | + | |
| 831 | +#[cfg(celld_internal_tests)] | |
| 832 | +thread_local! { | |
| 833 | + static TEST_OUTBOUND_WS_TX: RefCell<Option<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>>> = | |
| 834 | + const { RefCell::new(None) }; | |
| 835 | +} | |
| 836 | + | |
| 837 | +#[cfg(celld_internal_tests)] | |
| 838 | +impl Drop for TestOutboundWsConnector { | |
| 839 | + fn drop(&mut self) { | |
| 840 | + TEST_OUTBOUND_WS_TX.with(|slot| { | |
| 841 | + assert!( | |
| 842 | + slot.borrow_mut().take().is_some(), | |
| 843 | + "test outbound WebSocket connector was not installed", | |
| 844 | + ); | |
| 845 | + }); | |
| 846 | + } | |
| 847 | +} | |
| 848 | + | |
| 849 | +#[cfg(celld_internal_tests)] | |
| 850 | +/// Install the internal-test connector for the current JS thread. | |
| 851 | +#[doc(hidden)] | |
| 852 | +pub fn install_outbound_ws_connector_for_test() -> TestOutboundWsConnector { | |
| 853 | + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); | |
| 854 | + TEST_OUTBOUND_WS_TX.with(|slot| { | |
| 855 | + let mut slot = slot.borrow_mut(); | |
| 856 | + assert!( | |
| 857 | + slot.is_none(), | |
| 858 | + "test outbound WebSocket connector is already installed" | |
| 859 | + ); | |
| 860 | + *slot = Some(tx); | |
| 861 | + }); | |
| 862 | + TestOutboundWsConnector { | |
| 863 | + requests: tokio::sync::Mutex::new(rx), | |
| 864 | + _not_send: std::marker::PhantomData, | |
| 865 | + } | |
| 866 | +} | |
| 867 | + | |
| 868 | +/// Select the scoped internal-test connector before the production connector. | |
| 869 | +fn outbound_ws_tx() -> Option<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> { | |
| 870 | + #[cfg(celld_internal_tests)] | |
| 871 | + if let Some(tx) = TEST_OUTBOUND_WS_TX.with(|slot| slot.borrow().clone()) { | |
| 872 | + return Some(tx); | |
| 873 | + } | |
| 874 | + OUTBOUND_WS_TX.get().cloned() | |
| 875 | +} | |
| 876 | + | |
| 877 | +static NEXT_TIMER_ID: AtomicU64 = AtomicU64::new(1); | |
| 878 | +static TIMER_CANCELS: OnceLock<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>> = | |
| 879 | + OnceLock::new(); | |
| 880 | +fn timer_cancels() -> &'static std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>> { | |
| 881 | + TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 882 | +} | |
| 883 | +// Keep IDs process-global. A counter in each Domain could reuse an ID from a | |
| 884 | +// closed Domain, so a stale caller could read an unrelated new stream. | |
| 885 | +static NEXT_HTTP_STREAM_ID: AtomicU64 = AtomicU64::new(1); | |
| 886 | +/// What `__http_stream_read` resolves with at end of stream. | |
| 887 | +/// | |
| 888 | +/// The reader identifies the end by type, not by value. A chunk always | |
| 889 | +/// resolves as a `Uint8Array`, therefore body bytes can never look like | |
| 890 | +/// this marker. The value stays distinctive, so a reader that does compare | |
| 891 | +/// the value cannot match a plausible body. | |
| 892 | +const HTTP_STREAM_DONE: &str = "__celld_http_stream_end__"; | |
| 893 | +const HTTP_STREAM_IDLE_TIMEOUT_MS: u64 = 60_000; | |
| 894 | +const HTTP_STREAM_REGISTRATION_CLOSED: &str = "the HTTP stream service is closed"; | |
| 895 | +const HTTP_TEE_BRANCH_CAPACITY: usize = 16; | |
| 896 | +const RESPONSE_STREAM_CONSUMER_CANCELED: &str = "response stream consumer canceled"; | |
| 897 | +const RESPONSE_STREAM_CLOSE_IN_PROGRESS: &str = "response stream close is already in progress"; | |
| 898 | +enum HttpStreamSource { | |
| 899 | + Response(reqwest::Response), | |
| 900 | + Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>), | |
| 901 | + Stream(HttpChunkStream), | |
| 902 | +} | |
| 903 | + | |
| 904 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 905 | +#[repr(u8)] | |
| 906 | +enum HttpStreamTerminationReason { | |
| 907 | + Live = 0, | |
| 908 | + Finished = 1, | |
| 909 | + Cancelled = 2, | |
| 910 | + Expired = 3, | |
| 911 | +} | |
| 912 | + | |
| 913 | +impl HttpStreamTerminationReason { | |
| 914 | + fn from_u8(value: u8) -> Self { | |
| 915 | + match value { | |
| 916 | + 0 => Self::Live, | |
| 917 | + 1 => Self::Finished, | |
| 918 | + 2 => Self::Cancelled, | |
| 919 | + 3 => Self::Expired, | |
| 920 | + _ => unreachable!("invalid HTTP stream termination reason {value}"), | |
| 921 | + } | |
| 922 | + } | |
| 923 | +} | |
| 924 | + | |
| 925 | +struct HttpStreamTermination { | |
| 926 | + reason: AtomicU8, | |
| 927 | + waiter: futures_util::task::AtomicWaker, | |
| 928 | +} | |
| 929 | + | |
| 930 | +impl HttpStreamTermination { | |
| 931 | + fn new() -> Self { | |
| 932 | + Self { | |
| 933 | + reason: AtomicU8::new(HttpStreamTerminationReason::Live as u8), | |
| 934 | + waiter: futures_util::task::AtomicWaker::new(), | |
| 935 | + } | |
| 936 | + } | |
| 937 | + | |
| 938 | + fn reason(&self) -> HttpStreamTerminationReason { | |
| 939 | + HttpStreamTerminationReason::from_u8(self.reason.load(Ordering::Acquire)) | |
| 940 | + } | |
| 941 | + | |
| 942 | + /// Commit the reason while the registry lock still linearizes removal. | |
| 943 | + /// Waking is a separate operation because a waker can run arbitrary code. | |
| 944 | + fn commit(&self, reason: HttpStreamTerminationReason) { | |
| 945 | + let _ = self.reason.compare_exchange( | |
| 946 | + HttpStreamTerminationReason::Live as u8, | |
| 947 | + reason as u8, | |
| 948 | + Ordering::AcqRel, | |
| 949 | + Ordering::Acquire, | |
| 950 | + ); | |
| 951 | + } | |
| 952 | + | |
| 953 | + fn poll_reason( | |
| 954 | + &self, | |
| 955 | + context: &mut std::task::Context<'_>, | |
| 956 | + ) -> std::task::Poll<HttpStreamTerminationReason> { | |
| 957 | + let reason = self.reason(); | |
| 958 | + if reason != HttpStreamTerminationReason::Live { | |
| 959 | + return std::task::Poll::Ready(reason); | |
| 960 | + } | |
| 961 | + self.waiter.register(context.waker()); | |
| 962 | + let reason = self.reason(); | |
| 963 | + if reason == HttpStreamTerminationReason::Live { | |
| 964 | + std::task::Poll::Pending | |
| 965 | + } else { | |
| 966 | + std::task::Poll::Ready(reason) | |
| 967 | + } | |
| 968 | + } | |
| 969 | + | |
| 970 | + fn take_waiter(&self) -> Option<std::task::Waker> { | |
| 971 | + self.waiter.take() | |
| 972 | + } | |
| 973 | +} | |
| 974 | + | |
| 975 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 976 | +enum HttpSourceLeaseMode { | |
| 977 | + Pull, | |
| 978 | + Transfer, | |
| 979 | +} | |
| 980 | + | |
| 981 | +enum HttpStreamSourceSlot { | |
| 982 | + Available(HttpStreamSource), | |
| 983 | + Leased { | |
| 984 | + token: u64, | |
| 985 | + mode: HttpSourceLeaseMode, | |
| 986 | + }, | |
| 987 | +} | |
| 988 | + | |
| 989 | +struct HttpStreamEntry { | |
| 990 | + generation: u64, | |
| 991 | + deadline_ms: u64, | |
| 992 | + source: HttpStreamSourceSlot, | |
| 993 | + termination: Arc<HttpStreamTermination>, | |
| 994 | + /// Request contexts that can still read this source. A dispatch guard can | |
| 995 | + /// reclaim the entry only while this is zero. | |
| 996 | + owners: usize, | |
| 997 | + active_writes: usize, | |
| 998 | + active_closes: usize, | |
| 999 | + closing: bool, | |
| 1000 | +} | |
| 1001 | + | |
| 1002 | +struct ResponseStreamWriter { | |
| 1003 | + writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 1004 | + finished: tokio::sync::watch::Sender<bool>, | |
| 1005 | +} | |
| 1006 | + | |
| 1007 | +impl HttpStreamEntry { | |
| 1008 | + fn new(generation: u64, deadline_ms: u64, source: HttpStreamSource) -> Self { | |
| 1009 | + Self { | |
| 1010 | + generation, | |
| 1011 | + deadline_ms, | |
| 1012 | + source: HttpStreamSourceSlot::Available(source), | |
| 1013 | + termination: Arc::new(HttpStreamTermination::new()), | |
| 1014 | + owners: 0, | |
| 1015 | + active_writes: 0, | |
| 1016 | + active_closes: 0, | |
| 1017 | + closing: false, | |
| 1018 | + } | |
| 1019 | + } | |
| 1020 | + | |
| 1021 | + fn is_expiry_eligible(&self) -> bool { | |
| 1022 | + matches!(self.source, HttpStreamSourceSlot::Available(_)) | |
| 1023 | + && self.owners == 0 | |
| 1024 | + && self.active_writes == 0 | |
| 1025 | + && self.active_closes == 0 | |
| 1026 | + } | |
| 1027 | + | |
| 1028 | + fn is_due(&self, now_ms: u64) -> bool { | |
| 1029 | + self.is_expiry_eligible() && now_ms >= self.deadline_ms | |
| 1030 | + } | |
| 1031 | +} | |
| 1032 | + | |
| 1033 | +impl ResponseStreamWriter { | |
| 1034 | + fn new( | |
| 1035 | + writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 1036 | + finished: tokio::sync::watch::Sender<bool>, | |
| 1037 | + ) -> Self { | |
| 1038 | + Self { writer, finished } | |
| 1039 | + } | |
| 1040 | +} | |
| 1041 | + | |
| 1042 | +type ResponseStreamCloseWatch = ( | |
| 1043 | + tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 1044 | + tokio::sync::watch::Receiver<bool>, | |
| 1045 | +); | |
| 1046 | + | |
| 1047 | +struct HttpStreamState { | |
| 1048 | + closed: bool, | |
| 1049 | + next_generation: u64, | |
| 1050 | + next_token: u64, | |
| 1051 | + sweeper_running: bool, | |
| 1052 | + sources: HashMap<u64, HttpStreamEntry>, | |
| 1053 | + response_writers: HashMap<u64, ResponseStreamWriter>, | |
| 1054 | + #[cfg(all(test, celld_internal_tests))] | |
| 1055 | + sweeper_starts: u64, | |
| 1056 | + #[cfg(all(test, celld_internal_tests))] | |
| 1057 | + sweeper_active: usize, | |
| 1058 | + #[cfg(all(test, celld_internal_tests))] | |
| 1059 | + sweeper_exit_gate: Option<Arc<HttpSweeperExitGate>>, | |
| 1060 | + #[cfg(all(test, celld_internal_tests))] | |
| 1061 | + pull_completion_gate: Option<HttpPullCompletionGate>, | |
| 1062 | +} | |
| 1063 | + | |
| 1064 | +pub(crate) struct HttpStreamService { | |
| 1065 | + state: std::sync::Mutex<HttpStreamState>, | |
| 1066 | + sweeper_notify: Arc<tokio::sync::Notify>, | |
| 1067 | + owner: OnceLock<asyncrt::DomainToken>, | |
| 1068 | + #[cfg(all(test, celld_internal_tests))] | |
| 1069 | + registration_clock_reads: AtomicU64, | |
| 1070 | +} | |
| 1071 | + | |
| 1072 | +#[cfg(all(test, celld_internal_tests))] | |
| 1073 | +struct HttpPullCompletionGate { | |
| 1074 | + stream_id: u64, | |
| 1075 | + reached: std::sync::mpsc::SyncSender<()>, | |
| 1076 | + release: std::sync::mpsc::Receiver<()>, | |
| 1077 | +} | |
| 1078 | + | |
| 1079 | +#[cfg(all(test, celld_internal_tests))] | |
| 1080 | +impl HttpPullCompletionGate { | |
| 1081 | + fn pause(self) { | |
| 1082 | + if self.reached.send(()).is_ok() { | |
| 1083 | + let _ = self.release.recv(); | |
| 1084 | + } | |
| 1085 | + } | |
| 1086 | +} | |
| 1087 | + | |
| 1088 | +#[cfg(all(test, celld_internal_tests))] | |
| 1089 | +struct HttpSweeperExitGate { | |
| 1090 | + reached: AtomicBool, | |
| 1091 | + released: AtomicBool, | |
| 1092 | + waiter: futures_util::task::AtomicWaker, | |
| 1093 | +} | |
| 1094 | + | |
| 1095 | +#[cfg(all(test, celld_internal_tests))] | |
| 1096 | +impl HttpSweeperExitGate { | |
| 1097 | + fn new() -> Self { | |
| 1098 | + Self { | |
| 1099 | + reached: AtomicBool::new(false), | |
| 1100 | + released: AtomicBool::new(false), | |
| 1101 | + waiter: futures_util::task::AtomicWaker::new(), | |
| 1102 | + } | |
| 1103 | + } | |
| 1104 | + | |
| 1105 | + async fn wait(self: Arc<Self>) { | |
| 1106 | + self.reached.store(true, Ordering::Release); | |
| 1107 | + futures_util::future::poll_fn(|context| { | |
| 1108 | + if self.released.load(Ordering::Acquire) { | |
| 1109 | + return std::task::Poll::Ready(()); | |
| 1110 | + } | |
| 1111 | + self.waiter.register(context.waker()); | |
| 1112 | + if self.released.load(Ordering::Acquire) { | |
| 1113 | + std::task::Poll::Ready(()) | |
| 1114 | + } else { | |
| 1115 | + std::task::Poll::Pending | |
| 1116 | + } | |
| 1117 | + }) | |
| 1118 | + .await; | |
| 1119 | + } | |
| 1120 | + | |
| 1121 | + fn release(&self) { | |
| 1122 | + self.released.store(true, Ordering::Release); | |
| 1123 | + self.waiter.wake(); | |
| 1124 | + } | |
| 1125 | +} | |
| 1126 | + | |
| 1127 | +#[cfg(all(test, celld_internal_tests))] | |
| 1128 | +struct HttpSweeperRunGuard { | |
| 1129 | + service: Weak<HttpStreamService>, | |
| 1130 | +} | |
| 1131 | + | |
| 1132 | +struct HttpSweeperOwnerGuard { | |
| 1133 | + service: Weak<HttpStreamService>, | |
| 1134 | + armed: bool, | |
| 1135 | +} | |
| 1136 | + | |
| 1137 | +impl HttpSweeperOwnerGuard { | |
| 1138 | + fn disarm(&mut self) { | |
| 1139 | + self.armed = false; | |
| 1140 | + } | |
| 1141 | +} | |
| 1142 | + | |
| 1143 | +impl Drop for HttpSweeperOwnerGuard { | |
| 1144 | + fn drop(&mut self) { | |
| 1145 | + if self.armed { | |
| 1146 | + if let Some(service) = self.service.upgrade() { | |
| 1147 | + service.owner_lost(); | |
| 1148 | + } | |
| 1149 | + } | |
| 1150 | + } | |
| 1151 | +} | |
| 1152 | + | |
| 1153 | +#[cfg(all(test, celld_internal_tests))] | |
| 1154 | +impl Drop for HttpSweeperRunGuard { | |
| 1155 | + fn drop(&mut self) { | |
| 1156 | + if let Some(service) = self.service.upgrade() { | |
| 1157 | + let mut state = service.state.lock().unwrap(); | |
| 1158 | + state.sweeper_active = state.sweeper_active.saturating_sub(1); | |
| 1159 | + } | |
| 1160 | + } | |
| 1161 | +} | |
| 1162 | + | |
| 1163 | +#[derive(Default)] | |
| 1164 | +struct HttpStreamDrain { | |
| 1165 | + sources: Vec<(u64, HttpStreamEntry)>, | |
| 1166 | + detached_sources: Vec<(u64, HttpStreamSource)>, | |
| 1167 | + response_writers: Vec<(u64, ResponseStreamWriter)>, | |
| 1168 | +} | |
| 1169 | + | |
| 1170 | +impl HttpStreamDrain { | |
| 1171 | + fn dispose(mut self, propagate_panic: bool) { | |
| 1172 | + // A source destructor can panic. HashMap drain order can change across | |
| 1173 | + // processes, so ID order makes wakes and the retained panic replayable. | |
| 1174 | + self.sources.sort_unstable_by_key(|(id, _)| *id); | |
| 1175 | + self.detached_sources.sort_unstable_by_key(|(id, _)| *id); | |
| 1176 | + self.response_writers.sort_unstable_by_key(|(id, _)| *id); | |
| 1177 | + let mut first_panic = None; | |
| 1178 | + for (_, source) in self.sources { | |
| 1179 | + if let Some(waiter) = source.termination.take_waiter() { | |
| 1180 | + let wake = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | |
| 1181 | + waiter.wake_by_ref(); | |
| 1182 | + })); | |
| 1183 | + if wake.is_err() { | |
| 1184 | + // A waker destructor can also panic. Preserve the wake | |
| 1185 | + // failure and leak this exceptional handle so cleanup can | |
| 1186 | + // continue without a double panic. | |
| 1187 | + std::mem::forget(waiter); | |
| 1188 | + } else { | |
| 1189 | + let drop_waiter = | |
| 1190 | + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(waiter))); | |
| 1191 | + retain_first_http_cleanup_panic(&mut first_panic, drop_waiter); | |
| 1192 | + } | |
| 1193 | + retain_first_http_cleanup_panic(&mut first_panic, wake); | |
| 1194 | + } | |
| 1195 | + let disposal = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(source))); | |
| 1196 | + retain_first_http_cleanup_panic(&mut first_panic, disposal); | |
| 1197 | + } | |
| 1198 | + for (_, source) in self.detached_sources { | |
| 1199 | + let disposal = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(source))); | |
| 1200 | + retain_first_http_cleanup_panic(&mut first_panic, disposal); | |
| 1201 | + } | |
| 1202 | + for (_, writer) in self.response_writers { | |
| 1203 | + let disposal = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(writer))); | |
| 1204 | + retain_first_http_cleanup_panic(&mut first_panic, disposal); | |
| 1205 | + } | |
| 1206 | + if let Some(payload) = first_panic { | |
| 1207 | + if propagate_panic { | |
| 1208 | + std::panic::resume_unwind(payload); | |
| 1209 | + } | |
| 1210 | + std::mem::forget(payload); | |
| 1211 | + } | |
| 1212 | + } | |
| 1213 | + | |
| 1214 | + fn dispose_propagating(self) { | |
| 1215 | + self.dispose(true); | |
| 1216 | + } | |
| 1217 | + | |
| 1218 | + fn dispose_suppressing(self) { | |
| 1219 | + self.dispose(false); | |
| 1220 | + } | |
| 1221 | +} | |
| 1222 | + | |
| 1223 | +fn retain_first_http_cleanup_panic( | |
| 1224 | + first: &mut Option<Box<dyn std::any::Any + Send>>, | |
| 1225 | + result: std::thread::Result<()>, | |
| 1226 | +) { | |
| 1227 | + if let Err(payload) = result { | |
| 1228 | + if first.is_none() { | |
| 1229 | + *first = Some(payload); | |
| 1230 | + } else { | |
| 1231 | + // The payload is opaque, and its destructor can panic while the | |
| 1232 | + // first cleanup failure is already retained. | |
| 1233 | + std::mem::forget(payload); | |
| 1234 | + } | |
| 1235 | + } | |
| 1236 | +} | |
| 1237 | + | |
| 1238 | +fn dispose_http_waiter_suppressing(waiter: Option<std::task::Waker>) { | |
| 1239 | + if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(waiter))) { | |
| 1240 | + std::mem::forget(payload); | |
| 1241 | + } | |
| 1242 | +} | |
| 1243 | + | |
| 1244 | +fn run_http_cleanup_from_drop(cleanup: impl FnOnce()) { | |
| 1245 | + let already_panicking = std::thread::panicking(); | |
| 1246 | + if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(cleanup)) { | |
| 1247 | + if already_panicking { | |
| 1248 | + // A cleanup panic cannot replace the panic that already owns this | |
| 1249 | + // unwind. The opaque payload is leaked because its destructor can | |
| 1250 | + // also panic. | |
| 1251 | + std::mem::forget(payload); | |
| 1252 | + } else { | |
| 1253 | + std::panic::resume_unwind(payload); | |
| 1254 | + } | |
| 1255 | + } | |
| 1256 | +} | |
| 1257 | + | |
| 1258 | +fn dispose_http_completion(waiter: Option<std::task::Waker>, drain: HttpStreamDrain) { | |
| 1259 | + let already_panicking = std::thread::panicking(); | |
| 1260 | + let mut first_panic = None; | |
| 1261 | + retain_first_http_cleanup_panic( | |
| 1262 | + &mut first_panic, | |
| 1263 | + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(waiter))), | |
| 1264 | + ); | |
| 1265 | + retain_first_http_cleanup_panic( | |
| 1266 | + &mut first_panic, | |
| 1267 | + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drain.dispose_propagating())), | |
| 1268 | + ); | |
| 1269 | + if let Some(payload) = first_panic { | |
| 1270 | + if already_panicking { | |
| 1271 | + std::mem::forget(payload); | |
| 1272 | + } else { | |
| 1273 | + std::panic::resume_unwind(payload); | |
| 1274 | + } | |
| 1275 | + } | |
| 1276 | +} | |
| 1277 | + | |
| 1278 | +impl Default for HttpStreamState { | |
| 1279 | + fn default() -> Self { | |
| 1280 | + Self { | |
| 1281 | + closed: false, | |
| 1282 | + next_generation: 1, | |
| 1283 | + next_token: 1, | |
| 1284 | + sweeper_running: false, | |
| 1285 | + sources: HashMap::new(), | |
| 1286 | + response_writers: HashMap::new(), | |
| 1287 | + #[cfg(all(test, celld_internal_tests))] | |
| 1288 | + sweeper_starts: 0, | |
| 1289 | + #[cfg(all(test, celld_internal_tests))] | |
| 1290 | + sweeper_active: 0, | |
| 1291 | + #[cfg(all(test, celld_internal_tests))] | |
| 1292 | + sweeper_exit_gate: None, | |
| 1293 | + #[cfg(all(test, celld_internal_tests))] | |
| 1294 | + pull_completion_gate: None, | |
| 1295 | + } | |
| 1296 | + } | |
| 1297 | +} | |
| 1298 | + | |
| 1299 | +impl Default for HttpStreamService { | |
| 1300 | + fn default() -> Self { | |
| 1301 | + Self { | |
| 1302 | + state: std::sync::Mutex::new(HttpStreamState::default()), | |
| 1303 | + sweeper_notify: Arc::new(tokio::sync::Notify::new()), | |
| 1304 | + owner: OnceLock::new(), | |
| 1305 | + #[cfg(all(test, celld_internal_tests))] | |
| 1306 | + registration_clock_reads: AtomicU64::new(0), | |
| 1307 | + } | |
| 1308 | + } | |
| 1309 | +} | |
| 1310 | + | |
| 1311 | +enum HttpSweepWait { | |
| 1312 | + Deadline(u64), | |
| 1313 | + Notification, | |
| 1314 | + Exit, | |
| 1315 | +} | |
| 1316 | + | |
| 1317 | +impl HttpStreamService { | |
| 1318 | + pub(crate) fn bind_domain(&self, owner: asyncrt::DomainToken) { | |
| 1319 | + if let Err(candidate) = self.owner.set(owner) { | |
| 1320 | + assert!( | |
| 1321 | + self.owner | |
| 1322 | + .get() | |
| 1323 | + .is_some_and(|current| current.same_owner(&candidate)), | |
| 1324 | + "one HTTP stream service was bound to two execution Domains" | |
| 1325 | + ); | |
| 1326 | + } | |
| 1327 | + } | |
| 1328 | + | |
| 1329 | + fn next_sequence(sequence: &mut u64) -> u64 { | |
| 1330 | + let value = *sequence; | |
| 1331 | + *sequence = sequence.wrapping_add(1).max(1); | |
| 1332 | + value | |
| 1333 | + } | |
| 1334 | + | |
| 1335 | + fn expired_error(stream_id: u64) -> String { | |
| 1336 | + format!( | |
| 1337 | + "HTTP stream {stream_id} expired after {} seconds of inactivity", | |
| 1338 | + HTTP_STREAM_IDLE_TIMEOUT_MS / 1_000 | |
| 1339 | + ) | |
| 1340 | + } | |
| 1341 | + | |
| 1342 | + fn unknown_error(stream_id: u64) -> String { | |
| 1343 | + format!("HTTP stream {stream_id} expired or is not registered") | |
| 1344 | + } | |
| 1345 | + | |
| 1346 | + fn termination_result( | |
| 1347 | + stream_id: u64, | |
| 1348 | + reason: HttpStreamTerminationReason, | |
| 1349 | + ) -> Result<Option<Vec<u8>>, String> { | |
| 1350 | + match reason { | |
| 1351 | + HttpStreamTerminationReason::Finished | HttpStreamTerminationReason::Cancelled => { | |
| 1352 | + Ok(None) | |
| 1353 | + } | |
| 1354 | + HttpStreamTerminationReason::Expired => Err(Self::expired_error(stream_id)), | |
| 1355 | + HttpStreamTerminationReason::Live => Err(Self::unknown_error(stream_id)), | |
| 1356 | + } | |
| 1357 | + } | |
| 1358 | + | |
| 1359 | + fn remove_locked( | |
| 1360 | + state: &mut HttpStreamState, | |
| 1361 | + stream_id: u64, | |
| 1362 | + reason: HttpStreamTerminationReason, | |
| 1363 | + drain: &mut HttpStreamDrain, | |
| 1364 | + ) -> bool { | |
| 1365 | + let Some(source) = state.sources.remove(&stream_id) else { | |
| 1366 | + return false; | |
| 1367 | + }; | |
| 1368 | + source.termination.commit(reason); | |
| 1369 | + if let Some(writer) = state.response_writers.remove(&stream_id) { | |
| 1370 | + drain.response_writers.push((stream_id, writer)); | |
| 1371 | + } | |
| 1372 | + drain.sources.push((stream_id, source)); | |
| 1373 | + true | |
| 1374 | + } | |
| 1375 | + | |
| 1376 | + fn close_locked(state: &mut HttpStreamState, drain: &mut HttpStreamDrain) { | |
| 1377 | + state.closed = true; | |
| 1378 | + state.sweeper_running = false; | |
| 1379 | + let mut ids = state.sources.keys().copied().collect::<Vec<_>>(); | |
| 1380 | + ids.sort_unstable(); | |
| 1381 | + for id in ids { | |
| 1382 | + Self::remove_locked(state, id, HttpStreamTerminationReason::Cancelled, drain); | |
| 1383 | + } | |
| 1384 | + debug_assert!(state.response_writers.is_empty()); | |
| 1385 | + } | |
| 1386 | + | |
| 1387 | + fn registration_clock( | |
| 1388 | + &self, | |
| 1389 | + state: &mut HttpStreamState, | |
| 1390 | + drain: &mut HttpStreamDrain, | |
| 1391 | + ) -> Option<(asyncrt::DomainToken, u64)> { | |
| 1392 | + #[cfg(all(test, celld_internal_tests))] | |
| 1393 | + self.registration_clock_reads.fetch_add(1, Ordering::SeqCst); | |
| 1394 | + let owner = self.owner.get()?.clone(); | |
| 1395 | + match owner.mono_ms() { | |
| 1396 | + Ok(now_ms) => Some((owner, now_ms)), | |
| 1397 | + Err(_) => { | |
| 1398 | + Self::close_locked(state, drain); | |
| 1399 | + None | |
| 1400 | + } | |
| 1401 | + } | |
| 1402 | + } | |
| 1403 | + | |
| 1404 | + fn spawn_sweeper(self: &Arc<Self>, owner: &asyncrt::DomainToken) -> bool { | |
| 1405 | + let service = Arc::downgrade(self); | |
| 1406 | + #[cfg(all(test, celld_internal_tests))] | |
| 1407 | + let run_guard = { | |
| 1408 | + let mut state = self.state.lock().unwrap(); | |
| 1409 | + state.sweeper_starts = state.sweeper_starts.saturating_add(1); | |
| 1410 | + state.sweeper_active = state.sweeper_active.saturating_add(1); | |
| 1411 | + HttpSweeperRunGuard { | |
| 1412 | + service: service.clone(), | |
| 1413 | + } | |
| 1414 | + }; | |
| 1415 | + let owner_guard = HttpSweeperOwnerGuard { | |
| 1416 | + service: service.clone(), | |
| 1417 | + armed: true, | |
| 1418 | + }; | |
| 1419 | + let notify = self.sweeper_notify.clone(); | |
| 1420 | + let sweeper_owner = owner.clone(); | |
| 1421 | + owner | |
| 1422 | + .spawn_detached("http-stream-idle-sweeper", async move { | |
| 1423 | + #[cfg(all(test, celld_internal_tests))] | |
| 1424 | + let _run_guard = run_guard; | |
| 1425 | + let mut owner_guard = owner_guard; | |
| 1426 | + http_stream_sweeper(service, notify, sweeper_owner, &mut owner_guard).await; | |
| 1427 | + }) | |
| 1428 | + .is_ok() | |
| 1429 | + } | |
| 1430 | + | |
| 1431 | + fn owner_lost(self: &Arc<Self>) { | |
| 1432 | + let drain = { | |
| 1433 | + let mut state = self.state.lock().unwrap(); | |
| 1434 | + let mut drain = HttpStreamDrain::default(); | |
| 1435 | + // Simulation quarantine closes registration before it drops tasks. | |
| 1436 | + // Its explicit HTTP phase must remain the only place that drains | |
| 1437 | + // sources, so task and timer destructors always run first. | |
| 1438 | + if !state.closed { | |
| 1439 | + Self::close_locked(&mut state, &mut drain); | |
| 1440 | + } | |
| 1441 | + drain | |
| 1442 | + }; | |
| 1443 | + self.sweeper_notify.notify_one(); | |
| 1444 | + drain.dispose_suppressing(); | |
| 1445 | + } | |
| 1446 | + | |
| 1447 | + #[must_use = "a rejected HTTP stream must not publish an ID"] | |
| 1448 | + fn register_source(self: &Arc<Self>, source: HttpStreamSource) -> Option<u64> { | |
| 1449 | + let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 1450 | + self.register(stream_id, source, None).then_some(stream_id) | |
| 1451 | + } | |
| 1452 | + | |
| 1453 | + #[must_use = "a rejected response stream must not publish an ID"] | |
| 1454 | + fn register_response_pair( | |
| 1455 | + self: &Arc<Self>, | |
| 1456 | + receiver: tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>, | |
| 1457 | + writer: ResponseStreamWriter, | |
| 1458 | + ) -> Option<u64> { | |
| 1459 | + let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 1460 | + self.register( | |
| 1461 | + stream_id, | |
| 1462 | + HttpStreamSource::Receiver(receiver), | |
| 1463 | + Some(writer), | |
| 1464 | + ) | |
| 1465 | + .then_some(stream_id) | |
| 1466 | + } | |
| 1467 | + | |
| 1468 | + fn register( | |
| 1469 | + self: &Arc<Self>, | |
| 1470 | + stream_id: u64, | |
| 1471 | + source: HttpStreamSource, | |
| 1472 | + writer: Option<ResponseStreamWriter>, | |
| 1473 | + ) -> bool { | |
| 1474 | + let mut candidate_source = Some(source); | |
| 1475 | + let mut candidate_writer = writer; | |
| 1476 | + let mut drain = HttpStreamDrain::default(); | |
| 1477 | + let mut owner = None; | |
| 1478 | + let mut start_sweeper = false; | |
| 1479 | + let accepted = { | |
| 1480 | + let mut state = self.state.lock().unwrap(); | |
| 1481 | + if state.closed { | |
| 1482 | + false | |
| 1483 | + } else if let Some((bound_owner, now_ms)) = | |
| 1484 | + self.registration_clock(&mut state, &mut drain) | |
| 1485 | + { | |
| 1486 | + Self::remove_locked( | |
| 1487 | + &mut state, | |
| 1488 | + stream_id, | |
| 1489 | + HttpStreamTerminationReason::Cancelled, | |
| 1490 | + &mut drain, | |
| 1491 | + ); | |
| 1492 | + let generation = Self::next_sequence(&mut state.next_generation); | |
| 1493 | + let deadline_ms = now_ms.saturating_add(HTTP_STREAM_IDLE_TIMEOUT_MS); | |
| 1494 | + state.sources.insert( | |
| 1495 | + stream_id, | |
| 1496 | + HttpStreamEntry::new(generation, deadline_ms, candidate_source.take().unwrap()), | |
| 1497 | + ); | |
| 1498 | + if let Some(writer) = candidate_writer.take() { | |
| 1499 | + state.response_writers.insert(stream_id, writer); | |
| 1500 | + } | |
| 1501 | + if !state.sweeper_running { | |
| 1502 | + state.sweeper_running = true; | |
| 1503 | + start_sweeper = true; | |
| 1504 | + } | |
| 1505 | + owner = Some(bound_owner); | |
| 1506 | + true | |
| 1507 | + } else { | |
| 1508 | + false | |
| 1509 | + } | |
| 1510 | + }; | |
| 1511 | + | |
| 1512 | + if !accepted { | |
| 1513 | + if let Some(source) = candidate_source.take() { | |
| 1514 | + let rejected = HttpStreamEntry::new(0, 0, source); | |
| 1515 | + rejected | |
| 1516 | + .termination | |
| 1517 | + .commit(HttpStreamTerminationReason::Cancelled); | |
| 1518 | + drain.sources.push((stream_id, rejected)); | |
| 1519 | + } | |
| 1520 | + if let Some(writer) = candidate_writer.take() { | |
| 1521 | + drain.response_writers.push((stream_id, writer)); | |
| 1522 | + } | |
| 1523 | + } else if start_sweeper { | |
| 1524 | + if !self.spawn_sweeper(owner.as_ref().unwrap()) { | |
| 1525 | + self.owner_lost(); | |
| 1526 | + drain.dispose_suppressing(); | |
| 1527 | + return false; | |
| 1528 | + } | |
| 1529 | + } else { | |
| 1530 | + self.sweeper_notify.notify_one(); | |
| 1531 | + } | |
| 1532 | + drain.dispose_propagating(); | |
| 1533 | + accepted | |
| 1534 | + } | |
| 1535 | + | |
| 1536 | + fn claim(self: &Arc<Self>, stream_id: u64) -> Option<HttpStreamClaim> { | |
| 1537 | + let mut drain = HttpStreamDrain::default(); | |
| 1538 | + let mut generation = None; | |
| 1539 | + { | |
| 1540 | + let mut state = self.state.lock().unwrap(); | |
| 1541 | + if !state.closed { | |
| 1542 | + let now_ms = self | |
| 1543 | + .registration_clock(&mut state, &mut drain) | |
| 1544 | + .map(|(_, now_ms)| now_ms); | |
| 1545 | + if let Some(now_ms) = now_ms { | |
| 1546 | + if state | |
| 1547 | + .sources | |
| 1548 | + .get(&stream_id) | |
| 1549 | + .is_some_and(|entry| entry.is_due(now_ms)) | |
| 1550 | + { | |
| 1551 | + Self::remove_locked( | |
| 1552 | + &mut state, | |
| 1553 | + stream_id, | |
| 1554 | + HttpStreamTerminationReason::Expired, | |
| 1555 | + &mut drain, | |
| 1556 | + ); | |
| 1557 | + } else if let Some(stream) = state.sources.get_mut(&stream_id) { | |
| 1558 | + stream.owners = stream.owners.saturating_add(1); | |
| 1559 | + generation = Some(stream.generation); | |
| 1560 | + } | |
| 1561 | + } | |
| 1562 | + } | |
| 1563 | + } | |
| 1564 | + if !drain.sources.is_empty() || !drain.response_writers.is_empty() { | |
| 1565 | + self.sweeper_notify.notify_one(); | |
| 1566 | + } | |
| 1567 | + drain.dispose_propagating(); | |
| 1568 | + generation.map(|generation| HttpStreamClaim { | |
| 1569 | + service: self.clone(), | |
| 1570 | + stream_id, | |
| 1571 | + generation, | |
| 1572 | + armed: true, | |
| 1573 | + }) | |
| 1574 | + } | |
| 1575 | + | |
| 1576 | + fn release_claim(&self, stream_id: u64, generation: u64) { | |
| 1577 | + let mut drain = HttpStreamDrain::default(); | |
| 1578 | + let mut notify = false; | |
| 1579 | + { | |
| 1580 | + let mut state = self.state.lock().unwrap(); | |
| 1581 | + let mut remove = false; | |
| 1582 | + if let Some(stream) = state | |
| 1583 | + .sources | |
| 1584 | + .get_mut(&stream_id) | |
| 1585 | + .filter(|stream| stream.generation == generation) | |
| 1586 | + { | |
| 1587 | + stream.owners = stream.owners.saturating_sub(1); | |
| 1588 | + // Checkout consumes one claim before the asynchronous pull | |
| 1589 | + // completes. Keep every leased source registered so the pull | |
| 1590 | + // can publish its result. An abandoned lease removes itself, | |
| 1591 | + // and an available source with no owners can be reclaimed now. | |
| 1592 | + remove = stream.owners == 0 | |
| 1593 | + && matches!(stream.source, HttpStreamSourceSlot::Available(_)); | |
| 1594 | + notify = true; | |
| 1595 | + } | |
| 1596 | + if remove { | |
| 1597 | + Self::remove_locked( | |
| 1598 | + &mut state, | |
| 1599 | + stream_id, | |
| 1600 | + HttpStreamTerminationReason::Cancelled, | |
| 1601 | + &mut drain, | |
| 1602 | + ); | |
| 1603 | + } | |
| 1604 | + } | |
| 1605 | + if notify { | |
| 1606 | + self.sweeper_notify.notify_one(); | |
| 1607 | + } | |
| 1608 | + drain.dispose_propagating(); | |
| 1609 | + } | |
| 1610 | + | |
| 1611 | + fn checkout_source( | |
| 1612 | + self: &Arc<Self>, | |
| 1613 | + stream_id: u64, | |
| 1614 | + ) -> Result<(HttpSourceLease, HttpStreamSource), String> { | |
| 1615 | + self.checkout(stream_id, HttpSourceLeaseMode::Pull, None) | |
| 1616 | + } | |
| 1617 | + | |
| 1618 | + fn checkout_transfer( | |
| 1619 | + self: &Arc<Self>, | |
| 1620 | + stream_id: u64, | |
| 1621 | + claim_generation: Option<u64>, | |
| 1622 | + ) -> Result<HttpTransferredStream, String> { | |
| 1623 | + let (lease, source) = | |
| 1624 | + self.checkout(stream_id, HttpSourceLeaseMode::Transfer, claim_generation)?; | |
| 1625 | + Ok(HttpTransferredStream { | |
| 1626 | + inner: http_chunk_stream(source), | |
| 1627 | + lease: HttpTransferLease::new(lease), | |
| 1628 | + finished: false, | |
| 1629 | + }) | |
| 1630 | + } | |
| 1631 | + | |
| 1632 | + fn checkout( | |
| 1633 | + self: &Arc<Self>, | |
| 1634 | + stream_id: u64, | |
| 1635 | + mode: HttpSourceLeaseMode, | |
| 1636 | + claim_generation: Option<u64>, | |
| 1637 | + ) -> Result<(HttpSourceLease, HttpStreamSource), String> { | |
| 1638 | + let mut drain = HttpStreamDrain::default(); | |
| 1639 | + let mut checkout = None; | |
| 1640 | + let mut error = None; | |
| 1641 | + { | |
| 1642 | + let mut state = self.state.lock().unwrap(); | |
| 1643 | + if state.closed { | |
| 1644 | + error = Some(Self::unknown_error(stream_id)); | |
| 1645 | + } else { | |
| 1646 | + let now_ms = self | |
| 1647 | + .registration_clock(&mut state, &mut drain) | |
| 1648 | + .map(|(_, now_ms)| now_ms); | |
| 1649 | + if let Some(now_ms) = now_ms { | |
| 1650 | + if state | |
| 1651 | + .sources | |
| 1652 | + .get(&stream_id) | |
| 1653 | + .is_some_and(|entry| entry.is_due(now_ms)) | |
| 1654 | + { | |
| 1655 | + Self::remove_locked( | |
| 1656 | + &mut state, | |
| 1657 | + stream_id, | |
| 1658 | + HttpStreamTerminationReason::Expired, | |
| 1659 | + &mut drain, | |
| 1660 | + ); | |
| 1661 | + error = Some(Self::expired_error(stream_id)); | |
| 1662 | + } else if !state.sources.contains_key(&stream_id) { | |
| 1663 | + error = Some(Self::unknown_error(stream_id)); | |
| 1664 | + } else { | |
| 1665 | + let token = Self::next_sequence(&mut state.next_token); | |
| 1666 | + let entry = state.sources.get_mut(&stream_id).unwrap(); | |
| 1667 | + if claim_generation.is_some_and(|generation| { | |
| 1668 | + generation != entry.generation || entry.owners == 0 | |
| 1669 | + }) { | |
| 1670 | + error = Some(Self::unknown_error(stream_id)); | |
| 1671 | + } else { | |
| 1672 | + let leased = HttpStreamSourceSlot::Leased { token, mode }; | |
| 1673 | + match std::mem::replace(&mut entry.source, leased) { | |
| 1674 | + HttpStreamSourceSlot::Available(source) => { | |
| 1675 | + if claim_generation.is_some() { | |
| 1676 | + entry.owners = entry.owners.saturating_sub(1); | |
| 1677 | + } | |
| 1678 | + checkout = Some(( | |
| 1679 | + entry.generation, | |
| 1680 | + token, | |
| 1681 | + entry.termination.clone(), | |
| 1682 | + source, | |
| 1683 | + )); | |
| 1684 | + } | |
| 1685 | + occupied @ HttpStreamSourceSlot::Leased { .. } => { | |
| 1686 | + entry.source = occupied; | |
| 1687 | + error = Some(format!( | |
| 1688 | + "HTTP stream {stream_id} source is checked out" | |
| 1689 | + )); | |
| 1690 | + } | |
| 1691 | + } | |
| 1692 | + } | |
| 1693 | + } | |
| 1694 | + } else { | |
| 1695 | + error = Some(Self::unknown_error(stream_id)); | |
| 1696 | + } | |
| 1697 | + } | |
| 1698 | + } | |
| 1699 | + self.sweeper_notify.notify_one(); | |
| 1700 | + drain.dispose_propagating(); | |
| 1701 | + if let Some((generation, token, termination, source)) = checkout { | |
| 1702 | + Ok(( | |
| 1703 | + HttpSourceLease { | |
| 1704 | + service: self.clone(), | |
| 1705 | + stream_id, | |
| 1706 | + generation, | |
| 1707 | + token, | |
| 1708 | + mode, | |
| 1709 | + termination, | |
| 1710 | + settled: false, | |
| 1711 | + }, | |
| 1712 | + source, | |
| 1713 | + )) | |
| 1714 | + } else { | |
| 1715 | + Err(error.unwrap_or_else(|| Self::unknown_error(stream_id))) | |
| 1716 | + } | |
| 1717 | + } | |
| 1718 | + | |
| 1719 | + fn complete_pull( | |
| 1720 | + &self, | |
| 1721 | + lease: &HttpSourceLease, | |
| 1722 | + source: HttpStreamSource, | |
| 1723 | + result: Result<Option<Vec<u8>>, String>, | |
| 1724 | + ) -> Result<Option<Vec<u8>>, String> { | |
| 1725 | + let mut source = Some(source); | |
| 1726 | + let mut drain = HttpStreamDrain::default(); | |
| 1727 | + #[cfg(all(test, celld_internal_tests))] | |
| 1728 | + let mut completion_gate = None; | |
| 1729 | + let (answer, waiter) = { | |
| 1730 | + let mut state = self.state.lock().unwrap(); | |
| 1731 | + let reason = lease.termination.reason(); | |
| 1732 | + let matches = state.sources.get(&lease.stream_id).is_some_and(|entry| { | |
| 1733 | + entry.generation == lease.generation | |
| 1734 | + && matches!( | |
| 1735 | + entry.source, | |
| 1736 | + HttpStreamSourceSlot::Leased { | |
| 1737 | + token, | |
| 1738 | + mode: HttpSourceLeaseMode::Pull, | |
| 1739 | + } if token == lease.token | |
| 1740 | + ) | |
| 1741 | + }); | |
| 1742 | + let answer = if reason != HttpStreamTerminationReason::Live || !matches { | |
| 1743 | + Self::termination_result(lease.stream_id, reason) | |
| 1744 | + } else { | |
| 1745 | + match result { | |
| 1746 | + Ok(Some(bytes)) => { | |
| 1747 | + let now_ms = self.owner.get().and_then(|owner| owner.mono_ms().ok()); | |
| 1748 | + if let Some(now_ms) = now_ms { | |
| 1749 | + let entry = state.sources.get_mut(&lease.stream_id).unwrap(); | |
| 1750 | + entry.source = HttpStreamSourceSlot::Available(source.take().unwrap()); | |
| 1751 | + entry.deadline_ms = now_ms.saturating_add(HTTP_STREAM_IDLE_TIMEOUT_MS); | |
| 1752 | + Ok(Some(bytes)) | |
| 1753 | + } else { | |
| 1754 | + Self::close_locked(&mut state, &mut drain); | |
| 1755 | + Ok(None) | |
| 1756 | + } | |
| 1757 | + } | |
| 1758 | + Ok(None) => { | |
| 1759 | + Self::remove_locked( | |
| 1760 | + &mut state, | |
| 1761 | + lease.stream_id, | |
| 1762 | + HttpStreamTerminationReason::Finished, | |
| 1763 | + &mut drain, | |
| 1764 | + ); | |
| 1765 | + Ok(None) | |
| 1766 | + } | |
| 1767 | + Err(error) => { | |
| 1768 | + Self::remove_locked( | |
| 1769 | + &mut state, | |
| 1770 | + lease.stream_id, | |
| 1771 | + HttpStreamTerminationReason::Finished, | |
| 1772 | + &mut drain, | |
| 1773 | + ); | |
| 1774 | + Err(error) | |
| 1775 | + } | |
| 1776 | + } | |
| 1777 | + }; | |
| 1778 | + // Restoring the source lets a successor lease register a waiter | |
| 1779 | + // as soon as this lock opens. Take only this lease's waiter while | |
| 1780 | + // the registry still prevents that successor checkout. | |
| 1781 | + let waiter = lease.termination.take_waiter(); | |
| 1782 | + #[cfg(all(test, celld_internal_tests))] | |
| 1783 | + if state | |
| 1784 | + .pull_completion_gate | |
| 1785 | + .as_ref() | |
| 1786 | + .is_some_and(|candidate| candidate.stream_id == lease.stream_id) | |
| 1787 | + { | |
| 1788 | + completion_gate = state.pull_completion_gate.take(); | |
| 1789 | + } | |
| 1790 | + (answer, waiter) | |
| 1791 | + }; | |
| 1792 | + #[cfg(all(test, celld_internal_tests))] | |
| 1793 | + if let Some(gate) = completion_gate { | |
| 1794 | + gate.pause(); | |
| 1795 | + } | |
| 1796 | + if let Some(source) = source { | |
| 1797 | + drain.detached_sources.push((lease.stream_id, source)); | |
| 1798 | + } | |
| 1799 | + self.sweeper_notify.notify_one(); | |
| 1800 | + // The waiter must be disposed before an arbitrary source destructor. | |
| 1801 | + // Both can panic, so catch both cleanups and retain only the first. | |
| 1802 | + dispose_http_completion(waiter, drain); | |
| 1803 | + answer | |
| 1804 | + } | |
| 1805 | + | |
| 1806 | + fn transferred_activity( | |
| 1807 | + &self, | |
| 1808 | + stream_id: u64, | |
| 1809 | + generation: u64, | |
| 1810 | + token: u64, | |
| 1811 | + termination: &HttpStreamTermination, | |
| 1812 | + ) -> Result<(), HttpStreamTerminationReason> { | |
| 1813 | + let mut state = self.state.lock().unwrap(); | |
| 1814 | + let reason = termination.reason(); | |
| 1815 | + if reason != HttpStreamTerminationReason::Live { | |
| 1816 | + return Err(reason); | |
| 1817 | + } | |
| 1818 | + let Some(entry) = state.sources.get_mut(&stream_id).filter(|entry| { | |
| 1819 | + entry.generation == generation | |
| 1820 | + && matches!( | |
| 1821 | + entry.source, | |
| 1822 | + HttpStreamSourceSlot::Leased { | |
| 1823 | + token: current, | |
| 1824 | + mode: HttpSourceLeaseMode::Transfer, | |
| 1825 | + } if current == token | |
| 1826 | + ) | |
| 1827 | + }) else { | |
| 1828 | + return Err(termination.reason()); | |
| 1829 | + }; | |
| 1830 | + let Some(now_ms) = self.owner.get().and_then(|owner| owner.mono_ms().ok()) else { | |
| 1831 | + return Err(HttpStreamTerminationReason::Cancelled); | |
| 1832 | + }; | |
| 1833 | + entry.deadline_ms = now_ms.saturating_add(HTTP_STREAM_IDLE_TIMEOUT_MS); | |
| 1834 | + Ok(()) | |
| 1835 | + } | |
| 1836 | + | |
| 1837 | + fn finish_lease( | |
| 1838 | + &self, | |
| 1839 | + stream_id: u64, | |
| 1840 | + generation: u64, | |
| 1841 | + token: u64, | |
| 1842 | + mode: HttpSourceLeaseMode, | |
| 1843 | + termination: &HttpStreamTermination, | |
| 1844 | + requested_reason: HttpStreamTerminationReason, | |
| 1845 | + ) -> HttpStreamTerminationReason { | |
| 1846 | + let mut drain = HttpStreamDrain::default(); | |
| 1847 | + let winning_reason = { | |
| 1848 | + let mut state = self.state.lock().unwrap(); | |
| 1849 | + let matches = state.sources.get(&stream_id).is_some_and(|entry| { | |
| 1850 | + entry.generation == generation | |
| 1851 | + && matches!( | |
| 1852 | + entry.source, | |
| 1853 | + HttpStreamSourceSlot::Leased { | |
| 1854 | + token: current, | |
| 1855 | + mode: current_mode, | |
| 1856 | + } if current == token && current_mode == mode | |
| 1857 | + ) | |
| 1858 | + }); | |
| 1859 | + if matches { | |
| 1860 | + let committed_reason = termination.reason(); | |
| 1861 | + let removal_reason = if committed_reason == HttpStreamTerminationReason::Live { | |
| 1862 | + requested_reason | |
| 1863 | + } else { | |
| 1864 | + committed_reason | |
| 1865 | + }; | |
| 1866 | + Self::remove_locked(&mut state, stream_id, removal_reason, &mut drain); | |
| 1867 | + } | |
| 1868 | + let reason = termination.reason(); | |
| 1869 | + if reason == HttpStreamTerminationReason::Live { | |
| 1870 | + HttpStreamTerminationReason::Cancelled | |
| 1871 | + } else { | |
| 1872 | + reason | |
| 1873 | + } | |
| 1874 | + }; | |
| 1875 | + self.sweeper_notify.notify_one(); | |
| 1876 | + drain.dispose_suppressing(); | |
| 1877 | + winning_reason | |
| 1878 | + } | |
| 1879 | + | |
| 1880 | + fn cancel_lease(&self, lease: &HttpSourceLease) { | |
| 1881 | + self.finish_lease( | |
| 1882 | + lease.stream_id, | |
| 1883 | + lease.generation, | |
| 1884 | + lease.token, | |
| 1885 | + lease.mode, | |
| 1886 | + &lease.termination, | |
| 1887 | + HttpStreamTerminationReason::Cancelled, | |
| 1888 | + ); | |
| 1889 | + } | |
| 1890 | + | |
| 1891 | + fn cancel_source(&self, stream_id: u64) { | |
| 1892 | + let mut drain = HttpStreamDrain::default(); | |
| 1893 | + { | |
| 1894 | + let mut state = self.state.lock().unwrap(); | |
| 1895 | + Self::remove_locked( | |
| 1896 | + &mut state, | |
| 1897 | + stream_id, | |
| 1898 | + HttpStreamTerminationReason::Cancelled, | |
| 1899 | + &mut drain, | |
| 1900 | + ); | |
| 1901 | + } | |
| 1902 | + self.sweeper_notify.notify_one(); | |
| 1903 | + drain.dispose_propagating(); | |
| 1904 | + } | |
| 1905 | + | |
| 1906 | + fn begin_activity( | |
| 1907 | + self: &Arc<Self>, | |
| 1908 | + stream_id: u64, | |
| 1909 | + kind: HttpStreamActivityKind, | |
| 1910 | + ) -> Result<HttpStreamActivity, HttpStreamActivityError> { | |
| 1911 | + let mut drain = HttpStreamDrain::default(); | |
| 1912 | + let mut acquired = None; | |
| 1913 | + let mut error = None; | |
| 1914 | + { | |
| 1915 | + let mut state = self.state.lock().unwrap(); | |
| 1916 | + if state.closed { | |
| 1917 | + error = Some(HttpStreamActivityError::Closed); | |
| 1918 | + } else { | |
| 1919 | + let now_ms = self | |
| 1920 | + .registration_clock(&mut state, &mut drain) | |
| 1921 | + .map(|(_, now_ms)| now_ms); | |
| 1922 | + if let Some(now_ms) = now_ms { | |
| 1923 | + if state | |
| 1924 | + .sources | |
| 1925 | + .get(&stream_id) | |
| 1926 | + .is_some_and(|entry| entry.is_due(now_ms)) | |
| 1927 | + { | |
| 1928 | + Self::remove_locked( | |
| 1929 | + &mut state, | |
| 1930 | + stream_id, | |
| 1931 | + HttpStreamTerminationReason::Expired, | |
| 1932 | + &mut drain, | |
| 1933 | + ); | |
| 1934 | + error = Some(HttpStreamActivityError::Gone); | |
| 1935 | + } else { | |
| 1936 | + let endpoints = state | |
| 1937 | + .response_writers | |
| 1938 | + .get(&stream_id) | |
| 1939 | + .map(|writer| (writer.writer.clone(), writer.finished.clone())); | |
| 1940 | + if let (Some(entry), Some((writer, finished))) = | |
| 1941 | + (state.sources.get_mut(&stream_id), endpoints) | |
| 1942 | + { | |
| 1943 | + if entry.closing { | |
| 1944 | + error = Some(HttpStreamActivityError::Closing); | |
| 1945 | + } else { | |
| 1946 | + match kind { | |
| 1947 | + HttpStreamActivityKind::Write => { | |
| 1948 | + entry.active_writes = entry.active_writes.saturating_add(1) | |
| 1949 | + } | |
| 1950 | + HttpStreamActivityKind::Close => { | |
| 1951 | + entry.active_closes = entry.active_closes.saturating_add(1); | |
| 1952 | + entry.closing = true; | |
| 1953 | + } | |
| 1954 | + } | |
| 1955 | + acquired = Some((writer, finished, entry.generation)); | |
| 1956 | + } | |
| 1957 | + } | |
| 1958 | + } | |
| 1959 | + } else if state.closed { | |
| 1960 | + error = Some(HttpStreamActivityError::Closed); | |
| 1961 | + } | |
| 1962 | + } | |
| 1963 | + } | |
| 1964 | + self.sweeper_notify.notify_one(); | |
| 1965 | + drain.dispose_propagating(); | |
| 1966 | + let Some((writer, finished, generation)) = acquired else { | |
| 1967 | + return Err(error.unwrap_or(HttpStreamActivityError::Gone)); | |
| 1968 | + }; | |
| 1969 | + Ok(HttpStreamActivity { | |
| 1970 | + writer, | |
| 1971 | + finished, | |
| 1972 | + lease: HttpStreamActivityLease { | |
| 1973 | + service: self.clone(), | |
| 1974 | + stream_id, | |
| 1975 | + generation, | |
| 1976 | + kind, | |
| 1977 | + active: true, | |
| 1978 | + }, | |
| 1979 | + }) | |
| 1980 | + } | |
| 1981 | + | |
| 1982 | + fn finish_activity( | |
| 1983 | + &self, | |
| 1984 | + stream_id: u64, | |
| 1985 | + generation: u64, | |
| 1986 | + kind: HttpStreamActivityKind, | |
| 1987 | + remove_writer: bool, | |
| 1988 | + ) { | |
| 1989 | + let mut removed_writer = None; | |
| 1990 | + { | |
| 1991 | + let mut state = self.state.lock().unwrap(); | |
| 1992 | + let now_ms = self.owner.get().and_then(|owner| owner.mono_ms().ok()); | |
| 1993 | + if let Some(entry) = state | |
| 1994 | + .sources | |
| 1995 | + .get_mut(&stream_id) | |
| 1996 | + .filter(|entry| entry.generation == generation) | |
| 1997 | + { | |
| 1998 | + match kind { | |
| 1999 | + HttpStreamActivityKind::Write => { | |
| 2000 | + entry.active_writes = entry.active_writes.saturating_sub(1) | |
| 2001 | + } | |
| 2002 | + HttpStreamActivityKind::Close => { | |
| 2003 | + entry.active_closes = entry.active_closes.saturating_sub(1); | |
| 2004 | + entry.closing = false; | |
| 2005 | + } | |
| 2006 | + } | |
| 2007 | + if let Some(now_ms) = now_ms { | |
| 2008 | + entry.deadline_ms = now_ms.saturating_add(HTTP_STREAM_IDLE_TIMEOUT_MS); | |
| 2009 | + } | |
| 2010 | + if remove_writer { | |
| 2011 | + removed_writer = state.response_writers.remove(&stream_id); | |
| 2012 | + } | |
| 2013 | + } | |
| 2014 | + } | |
| 2015 | + self.sweeper_notify.notify_one(); | |
| 2016 | + drop(removed_writer); | |
| 2017 | + } | |
| 2018 | + | |
| 2019 | + fn abandon_activity(&self, stream_id: u64, generation: u64, kind: HttpStreamActivityKind) { | |
| 2020 | + { | |
| 2021 | + let mut state = self.state.lock().unwrap(); | |
| 2022 | + if let Some(entry) = state | |
| 2023 | + .sources | |
| 2024 | + .get_mut(&stream_id) | |
| 2025 | + .filter(|entry| entry.generation == generation) | |
| 2026 | + { | |
| 2027 | + match kind { | |
| 2028 | + HttpStreamActivityKind::Write => { | |
| 2029 | + entry.active_writes = entry.active_writes.saturating_sub(1) | |
| 2030 | + } | |
| 2031 | + HttpStreamActivityKind::Close => { | |
| 2032 | + entry.active_closes = entry.active_closes.saturating_sub(1); | |
| 2033 | + entry.closing = false; | |
| 2034 | + } | |
| 2035 | + } | |
| 2036 | + } | |
| 2037 | + } | |
| 2038 | + // Drop does not read the clock or manufacture activity. It only makes | |
| 2039 | + // the previous successful-activity deadline eligible again. | |
| 2040 | + self.sweeper_notify.notify_one(); | |
| 2041 | + } | |
| 2042 | + | |
| 2043 | + fn cancel_activity_pair(&self, stream_id: u64, generation: u64, kind: HttpStreamActivityKind) { | |
| 2044 | + let mut drain = HttpStreamDrain::default(); | |
| 2045 | + { | |
| 2046 | + let mut state = self.state.lock().unwrap(); | |
| 2047 | + let matches = state | |
| 2048 | + .sources | |
| 2049 | + .get(&stream_id) | |
| 2050 | + .is_some_and(|entry| entry.generation == generation); | |
| 2051 | + if matches { | |
| 2052 | + if let Some(entry) = state.sources.get_mut(&stream_id) { | |
| 2053 | + match kind { | |
| 2054 | + HttpStreamActivityKind::Write => { | |
| 2055 | + entry.active_writes = entry.active_writes.saturating_sub(1) | |
| 2056 | + } | |
| 2057 | + HttpStreamActivityKind::Close => { | |
| 2058 | + entry.active_closes = entry.active_closes.saturating_sub(1) | |
| 2059 | + } | |
| 2060 | + } | |
| 2061 | + } | |
| 2062 | + Self::remove_locked( | |
| 2063 | + &mut state, | |
| 2064 | + stream_id, | |
| 2065 | + HttpStreamTerminationReason::Cancelled, | |
| 2066 | + &mut drain, | |
| 2067 | + ); | |
| 2068 | + } | |
| 2069 | + } | |
| 2070 | + self.sweeper_notify.notify_one(); | |
| 2071 | + drain.dispose_propagating(); | |
| 2072 | + } | |
| 2073 | + | |
| 2074 | + fn writer_close_watch(&self, stream_id: u64) -> Option<ResponseStreamCloseWatch> { | |
| 2075 | + let state = self.state.lock().unwrap(); | |
| 2076 | + if state.closed { | |
| 2077 | + return None; | |
| 2078 | + } | |
| 2079 | + state | |
| 2080 | + .response_writers | |
| 2081 | + .get(&stream_id) | |
| 2082 | + .map(|stream| (stream.writer.clone(), stream.finished.subscribe())) | |
| 2083 | + } | |
| 2084 | + | |
| 2085 | + fn sweep_step(&self, owner: &asyncrt::DomainToken) -> (HttpSweepWait, HttpStreamDrain) { | |
| 2086 | + let mut drain = HttpStreamDrain::default(); | |
| 2087 | + let wait = { | |
| 2088 | + let mut state = self.state.lock().unwrap(); | |
| 2089 | + if state.closed { | |
| 2090 | + state.sweeper_running = false; | |
| 2091 | + HttpSweepWait::Exit | |
| 2092 | + } else if let Ok(now_ms) = owner.mono_ms() { | |
| 2093 | + let mut due = state | |
| 2094 | + .sources | |
| 2095 | + .iter() | |
| 2096 | + .filter_map(|(id, entry)| entry.is_due(now_ms).then_some(*id)) | |
| 2097 | + .collect::<Vec<_>>(); | |
| 2098 | + due.sort_unstable(); | |
| 2099 | + for id in due { | |
| 2100 | + Self::remove_locked( | |
| 2101 | + &mut state, | |
| 2102 | + id, | |
| 2103 | + HttpStreamTerminationReason::Expired, | |
| 2104 | + &mut drain, | |
| 2105 | + ); | |
| 2106 | + } | |
| 2107 | + if state.sources.is_empty() { | |
| 2108 | + state.sweeper_running = false; | |
| 2109 | + HttpSweepWait::Exit | |
| 2110 | + } else if let Some(deadline_ms) = state | |
| 2111 | + .sources | |
| 2112 | + .values() | |
| 2113 | + .filter(|entry| entry.is_expiry_eligible()) | |
| 2114 | + .map(|entry| entry.deadline_ms) | |
| 2115 | + .min() | |
| 2116 | + { | |
| 2117 | + HttpSweepWait::Deadline(deadline_ms) | |
| 2118 | + } else { | |
| 2119 | + HttpSweepWait::Notification | |
| 2120 | + } | |
| 2121 | + } else { | |
| 2122 | + Self::close_locked(&mut state, &mut drain); | |
| 2123 | + HttpSweepWait::Exit | |
| 2124 | + } | |
| 2125 | + }; | |
| 2126 | + (wait, drain) | |
| 2127 | + } | |
| 2128 | + | |
| 2129 | + #[cfg(all(test, celld_internal_tests))] | |
| 2130 | + fn source_exists_for_test(&self, stream_id: u64) -> bool { | |
| 2131 | + self.state.lock().unwrap().sources.contains_key(&stream_id) | |
| 2132 | + } | |
| 2133 | + | |
| 2134 | + #[cfg(all(test, celld_internal_tests))] | |
| 2135 | + fn writer_exists_for_test(&self, stream_id: u64) -> bool { | |
| 2136 | + self.state | |
| 2137 | + .lock() | |
| 2138 | + .unwrap() | |
| 2139 | + .response_writers | |
| 2140 | + .contains_key(&stream_id) | |
| 2141 | + } | |
| 2142 | + | |
| 2143 | + #[cfg(all(test, celld_internal_tests))] | |
| 2144 | + fn termination_for_test(&self, stream_id: u64) -> Option<Arc<HttpStreamTermination>> { | |
| 2145 | + self.state | |
| 2146 | + .lock() | |
| 2147 | + .unwrap() | |
| 2148 | + .sources | |
| 2149 | + .get(&stream_id) | |
| 2150 | + .map(|entry| entry.termination.clone()) | |
| 2151 | + } | |
| 2152 | + | |
| 2153 | + #[cfg(all(test, celld_internal_tests))] | |
| 2154 | + fn lock_is_available_for_test(&self) -> bool { | |
| 2155 | + self.state.try_lock().is_ok() | |
| 2156 | + } | |
| 2157 | + | |
| 2158 | + #[cfg(all(test, celld_internal_tests))] | |
| 2159 | + fn arm_sweeper_exit_for_test(&self) -> Arc<HttpSweeperExitGate> { | |
| 2160 | + let gate = Arc::new(HttpSweeperExitGate::new()); | |
| 2161 | + let mut state = self.state.lock().unwrap(); | |
| 2162 | + assert!(state.sweeper_exit_gate.replace(gate.clone()).is_none()); | |
| 2163 | + gate | |
| 2164 | + } | |
| 2165 | + | |
| 2166 | + #[cfg(all(test, celld_internal_tests))] | |
| 2167 | + fn take_sweeper_exit_gate_for_test(&self) -> Option<Arc<HttpSweeperExitGate>> { | |
| 2168 | + self.state.lock().unwrap().sweeper_exit_gate.take() | |
| 2169 | + } | |
| 2170 | + | |
| 2171 | + #[cfg(all(test, celld_internal_tests))] | |
| 2172 | + fn sweeper_state_for_test(&self) -> (u64, usize, bool) { | |
| 2173 | + let state = self.state.lock().unwrap(); | |
| 2174 | + ( | |
| 2175 | + state.sweeper_starts, | |
| 2176 | + state.sweeper_active, | |
| 2177 | + state.sweeper_running, | |
| 2178 | + ) | |
| 2179 | + } | |
| 2180 | + | |
| 2181 | + #[cfg(all(test, celld_internal_tests))] | |
| 2182 | + fn registration_clock_reads_for_test(&self) -> u64 { | |
| 2183 | + self.registration_clock_reads.load(Ordering::SeqCst) | |
| 2184 | + } | |
| 2185 | + | |
| 2186 | + #[cfg(all(test, celld_internal_tests))] | |
| 2187 | + fn arm_pull_completion_after_unlock_for_test( | |
| 2188 | + &self, | |
| 2189 | + stream_id: u64, | |
| 2190 | + ) -> ( | |
| 2191 | + std::sync::mpsc::Receiver<()>, | |
| 2192 | + std::sync::mpsc::SyncSender<()>, | |
| 2193 | + ) { | |
| 2194 | + let (reached_sender, reached_receiver) = std::sync::mpsc::sync_channel(1); | |
| 2195 | + let (release_sender, release_receiver) = std::sync::mpsc::sync_channel(1); | |
| 2196 | + let gate = HttpPullCompletionGate { | |
| 2197 | + stream_id, | |
| 2198 | + reached: reached_sender, | |
| 2199 | + release: release_receiver, | |
| 2200 | + }; | |
| 2201 | + assert!(self | |
| 2202 | + .state | |
| 2203 | + .lock() | |
| 2204 | + .unwrap() | |
| 2205 | + .pull_completion_gate | |
| 2206 | + .replace(gate) | |
| 2207 | + .is_none()); | |
| 2208 | + (reached_receiver, release_sender) | |
| 2209 | + } | |
| 2210 | + | |
| 2211 | + #[cfg(all(test, celld_internal_tests))] | |
| 2212 | + fn closing_for_test(&self, stream_id: u64) -> bool { | |
| 2213 | + self.state | |
| 2214 | + .lock() | |
| 2215 | + .unwrap() | |
| 2216 | + .sources | |
| 2217 | + .get(&stream_id) | |
| 2218 | + .is_some_and(|entry| entry.closing) | |
| 2219 | + } | |
| 2220 | + | |
| 2221 | + #[cfg(all(test, celld_internal_tests))] | |
| 2222 | + pub(crate) fn quarantine(&self) { | |
| 2223 | + self.state.lock().unwrap().closed = true; | |
| 2224 | + self.sweeper_notify.notify_one(); | |
| 2225 | + } | |
| 2226 | + | |
| 2227 | + #[cfg(all(test, celld_internal_tests))] | |
| 2228 | + pub(crate) fn close(&self) { | |
| 2229 | + let drain = { | |
| 2230 | + let mut state = self.state.lock().unwrap(); | |
| 2231 | + let mut drain = HttpStreamDrain::default(); | |
| 2232 | + Self::close_locked(&mut state, &mut drain); | |
| 2233 | + drain | |
| 2234 | + }; | |
| 2235 | + self.sweeper_notify.notify_one(); | |
| 2236 | + drain.dispose_propagating(); | |
| 2237 | + } | |
| 2238 | +} | |
| 2239 | + | |
| 2240 | +impl Drop for HttpStreamService { | |
| 2241 | + fn drop(&mut self) { | |
| 2242 | + // The final runtime anchor can disappear before an explicit Domain | |
| 2243 | + // close. Exclusive access still makes a poisoned registry safe to | |
| 2244 | + // drain, so commit every termination before arbitrary cleanup runs. | |
| 2245 | + let state = match self.state.get_mut() { | |
| 2246 | + Ok(state) => state, | |
| 2247 | + Err(poisoned) => poisoned.into_inner(), | |
| 2248 | + }; | |
| 2249 | + let mut drain = HttpStreamDrain::default(); | |
| 2250 | + Self::close_locked(state, &mut drain); | |
| 2251 | + drain.dispose_suppressing(); | |
| 2252 | + } | |
| 2253 | +} | |
| 2254 | + | |
| 2255 | +async fn http_stream_sweeper( | |
| 2256 | + service: Weak<HttpStreamService>, | |
| 2257 | + notify: Arc<tokio::sync::Notify>, | |
| 2258 | + owner: asyncrt::DomainToken, | |
| 2259 | + owner_guard: &mut HttpSweeperOwnerGuard, | |
| 2260 | +) { | |
| 2261 | + loop { | |
| 2262 | + // Create the notification future before the registry snapshot. A | |
| 2263 | + // registration between the snapshot and the await leaves a permit, so | |
| 2264 | + // the sole sweeper cannot sleep through an earlier deadline. | |
| 2265 | + let notified = notify.notified(); | |
| 2266 | + let Some(service) = service.upgrade() else { | |
| 2267 | + return; | |
| 2268 | + }; | |
| 2269 | + let (wait, drain) = service.sweep_step(&owner); | |
| 2270 | + #[cfg(all(test, celld_internal_tests))] | |
| 2271 | + let exit_gate = matches!(wait, HttpSweepWait::Exit) | |
| 2272 | + .then(|| service.take_sweeper_exit_gate_for_test()) | |
| 2273 | + .flatten(); | |
| 2274 | + drop(service); | |
| 2275 | + // An abandoned source can own a panicking destructor. The leak | |
| 2276 | + // backstop must still service later entries after that failure. | |
| 2277 | + drain.dispose_suppressing(); | |
| 2278 | + match wait { | |
| 2279 | + HttpSweepWait::Exit => { | |
| 2280 | + #[cfg(all(test, celld_internal_tests))] | |
| 2281 | + if let Some(gate) = exit_gate { | |
| 2282 | + gate.wait().await; | |
| 2283 | + } | |
| 2284 | + owner_guard.disarm(); | |
| 2285 | + return; | |
| 2286 | + } | |
| 2287 | + HttpSweepWait::Notification => notified.await, | |
| 2288 | + HttpSweepWait::Deadline(deadline_ms) => { | |
| 2289 | + let Ok(sleep) = owner.sleep_until(deadline_ms) else { | |
| 2290 | + return; | |
| 2291 | + }; | |
| 2292 | + crate::asyncrt::select_biased! { | |
| 2293 | + "a registry notification wins a deadline tie so the next sweep uses the refreshed deadline"; | |
| 2294 | + _ = notified => {} | |
| 2295 | + _ = sleep => {} | |
| 2296 | + } | |
| 2297 | + } | |
| 2298 | + } | |
| 2299 | + } | |
| 2300 | +} | |
| 2301 | + | |
| 2302 | +#[derive(Clone, Copy)] | |
| 2303 | +enum HttpStreamActivityKind { | |
| 2304 | + Write, | |
| 2305 | + Close, | |
| 2306 | +} | |
| 2307 | + | |
| 2308 | +#[derive(Clone, Copy)] | |
| 2309 | +enum HttpStreamActivityError { | |
| 2310 | + Closed, | |
| 2311 | + Gone, | |
| 2312 | + Closing, | |
| 2313 | +} | |
| 2314 | + | |
| 2315 | +impl HttpStreamActivityError { | |
| 2316 | + fn write_message(self) -> &'static str { | |
| 2317 | + match self { | |
| 2318 | + Self::Closed => HTTP_STREAM_REGISTRATION_CLOSED, | |
| 2319 | + Self::Gone | Self::Closing => RESPONSE_STREAM_CONSUMER_CANCELED, | |
| 2320 | + } | |
| 2321 | + } | |
| 2322 | +} | |
| 2323 | + | |
| 2324 | +struct HttpStreamActivityLease { | |
| 2325 | + service: Arc<HttpStreamService>, | |
| 2326 | + stream_id: u64, | |
| 2327 | + generation: u64, | |
| 2328 | + kind: HttpStreamActivityKind, | |
| 2329 | + active: bool, | |
| 2330 | +} | |
| 2331 | + | |
| 2332 | +struct HttpStreamActivity { | |
| 2333 | + writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 2334 | + finished: tokio::sync::watch::Sender<bool>, | |
| 2335 | + lease: HttpStreamActivityLease, | |
| 2336 | +} | |
| 2337 | + | |
| 2338 | +impl HttpStreamActivityLease { | |
| 2339 | + fn succeed(mut self, remove_writer: bool) { | |
| 2340 | + self.active = false; | |
| 2341 | + self.service | |
| 2342 | + .finish_activity(self.stream_id, self.generation, self.kind, remove_writer); | |
| 2343 | + } | |
| 2344 | + | |
| 2345 | + fn cancel_pair(mut self) { | |
| 2346 | + self.active = false; | |
| 2347 | + self.service | |
| 2348 | + .cancel_activity_pair(self.stream_id, self.generation, self.kind); | |
| 2349 | + } | |
| 2350 | +} | |
| 2351 | + | |
| 2352 | +impl Drop for HttpStreamActivityLease { | |
| 2353 | + fn drop(&mut self) { | |
| 2354 | + if self.active { | |
| 2355 | + self.service | |
| 2356 | + .abandon_activity(self.stream_id, self.generation, self.kind); | |
| 2357 | + } | |
| 2358 | + } | |
| 2359 | +} | |
| 2360 | + | |
| 2361 | +struct HttpSourceLease { | |
| 2362 | + service: Arc<HttpStreamService>, | |
| 2363 | + stream_id: u64, | |
| 2364 | + generation: u64, | |
| 2365 | + token: u64, | |
| 2366 | + mode: HttpSourceLeaseMode, | |
| 2367 | + termination: Arc<HttpStreamTermination>, | |
| 2368 | + settled: bool, | |
| 2369 | +} | |
| 2370 | + | |
| 2371 | +struct HttpPull { | |
| 2372 | + // Struct fields drop in declaration order. Registry removal therefore | |
| 2373 | + // commits before an arbitrary checked-out source destructor can re-enter | |
| 2374 | + // the service or panic when a pending read future is abandoned. | |
| 2375 | + lease: HttpSourceLease, | |
| 2376 | + source: HttpStreamSource, | |
| 2377 | +} | |
| 2378 | + | |
| 2379 | +impl Drop for HttpSourceLease { | |
| 2380 | + fn drop(&mut self) { | |
| 2381 | + // A settled path already took its waiter while it still owned the | |
| 2382 | + // registry slot. Taking again here could clear a successor's waiter. | |
| 2383 | + if self.settled { | |
| 2384 | + return; | |
| 2385 | + } | |
| 2386 | + let waiter = self.termination.take_waiter(); | |
| 2387 | + self.service.cancel_lease(self); | |
| 2388 | + dispose_http_waiter_suppressing(waiter); | |
| 2389 | + } | |
| 2390 | +} | |
| 2391 | + | |
| 2392 | +struct HttpTransferLease { | |
| 2393 | + inner: Option<HttpSourceLease>, | |
| 2394 | +} | |
| 2395 | + | |
| 2396 | +impl HttpTransferLease { | |
| 2397 | + fn new(lease: HttpSourceLease) -> Self { | |
| 2398 | + debug_assert_eq!(lease.mode, HttpSourceLeaseMode::Transfer); | |
| 2399 | + Self { inner: Some(lease) } | |
| 2400 | + } | |
| 2401 | + | |
| 2402 | + fn termination(&self) -> &HttpStreamTermination { | |
| 2403 | + &self.inner.as_ref().unwrap().termination | |
| 2404 | + } | |
| 2405 | + | |
| 2406 | + fn stream_id(&self) -> u64 { | |
| 2407 | + self.inner.as_ref().unwrap().stream_id | |
| 2408 | + } | |
| 2409 | + | |
| 2410 | + fn successful_activity(&self) -> Result<(), HttpStreamTerminationReason> { | |
| 2411 | + let lease = self.inner.as_ref().unwrap(); | |
| 2412 | + let result = lease.service.transferred_activity( | |
| 2413 | + lease.stream_id, | |
| 2414 | + lease.generation, | |
| 2415 | + lease.token, | |
| 2416 | + &lease.termination, | |
| 2417 | + ); | |
| 2418 | + dispose_http_waiter_suppressing(lease.termination.take_waiter()); | |
| 2419 | + result | |
| 2420 | + } | |
| 2421 | + | |
| 2422 | + fn finish( | |
| 2423 | + &mut self, | |
| 2424 | + requested_reason: HttpStreamTerminationReason, | |
| 2425 | + ) -> HttpStreamTerminationReason { | |
| 2426 | + let mut lease = self.inner.take().unwrap(); | |
| 2427 | + lease.settled = true; | |
| 2428 | + let waiter = lease.termination.take_waiter(); | |
| 2429 | + let winning_reason = lease.service.finish_lease( | |
| 2430 | + lease.stream_id, | |
| 2431 | + lease.generation, | |
| 2432 | + lease.token, | |
| 2433 | + lease.mode, | |
| 2434 | + &lease.termination, | |
| 2435 | + requested_reason, | |
| 2436 | + ); | |
| 2437 | + dispose_http_waiter_suppressing(waiter); | |
| 2438 | + winning_reason | |
| 2439 | + } | |
| 2440 | +} | |
| 2441 | + | |
| 2442 | +struct HttpTransferredStream { | |
| 2443 | + // The lease drops first, so registry cancellation commits before an | |
| 2444 | + // arbitrary source destructor can re-enter the service or panic. | |
| 2445 | + lease: HttpTransferLease, | |
| 2446 | + inner: HttpChunkStream, | |
| 2447 | + finished: bool, | |
| 2448 | +} | |
| 2449 | + | |
| 2450 | +enum HttpTransferredEvent { | |
| 2451 | + Chunk(Vec<u8>), | |
| 2452 | + Error(String), | |
| 2453 | + End, | |
| 2454 | + Terminated(HttpStreamTerminationReason), | |
| 2455 | +} | |
| 2456 | + | |
| 2457 | +fn transferred_termination_poll( | |
| 2458 | + stream_id: u64, | |
| 2459 | + reason: HttpStreamTerminationReason, | |
| 2460 | +) -> std::task::Poll<Option<Result<Vec<u8>, String>>> { | |
| 2461 | + match HttpStreamService::termination_result(stream_id, reason) { | |
| 2462 | + Ok(None) => std::task::Poll::Ready(None), | |
| 2463 | + Ok(Some(bytes)) => std::task::Poll::Ready(Some(Ok(bytes))), | |
| 2464 | + Err(error) => std::task::Poll::Ready(Some(Err(error))), | |
| 2465 | + } | |
| 2466 | +} | |
| 2467 | + | |
| 2468 | +impl HttpTransferredStream { | |
| 2469 | + fn termination_handle(&self) -> Arc<HttpStreamTermination> { | |
| 2470 | + self.lease.inner.as_ref().unwrap().termination.clone() | |
| 2471 | + } | |
| 2472 | + | |
| 2473 | + /// Poll the transferred source without committing a natural terminal | |
| 2474 | + /// event. A direct consumer commits immediately in `poll_next`. The tee | |
| 2475 | + /// pump keeps the lease live until it publishes an error to each live | |
| 2476 | + /// branch, so cancellation can interrupt a backpressured terminal send. | |
| 2477 | + fn poll_event( | |
| 2478 | + &mut self, | |
| 2479 | + context: &mut std::task::Context<'_>, | |
| 2480 | + ) -> std::task::Poll<HttpTransferredEvent> { | |
| 2481 | + debug_assert!(!self.finished); | |
| 2482 | + if let std::task::Poll::Ready(reason) = self.lease.termination().poll_reason(context) { | |
| 2483 | + return std::task::Poll::Ready(HttpTransferredEvent::Terminated(reason)); | |
| 2484 | + } | |
| 2485 | + match self.inner.as_mut().poll_next(context) { | |
| 2486 | + std::task::Poll::Ready(Some(Ok(bytes))) => match self.lease.successful_activity() { | |
| 2487 | + Ok(()) => std::task::Poll::Ready(HttpTransferredEvent::Chunk(bytes)), | |
| 2488 | + Err(reason) => std::task::Poll::Ready(HttpTransferredEvent::Terminated(reason)), | |
| 2489 | + }, | |
| 2490 | + std::task::Poll::Ready(Some(Err(error))) => { | |
| 2491 | + std::task::Poll::Ready(HttpTransferredEvent::Error(error)) | |
| 2492 | + } | |
| 2493 | + std::task::Poll::Ready(None) => std::task::Poll::Ready(HttpTransferredEvent::End), | |
| 2494 | + std::task::Poll::Pending => match self.lease.termination().poll_reason(context) { | |
| 2495 | + std::task::Poll::Ready(reason) => { | |
| 2496 | + std::task::Poll::Ready(HttpTransferredEvent::Terminated(reason)) | |
| 2497 | + } | |
| 2498 | + std::task::Poll::Pending => std::task::Poll::Pending, | |
| 2499 | + }, | |
| 2500 | + } | |
| 2501 | + } | |
| 2502 | + | |
| 2503 | + fn finish( | |
| 2504 | + &mut self, | |
| 2505 | + requested_reason: HttpStreamTerminationReason, | |
| 2506 | + ) -> HttpStreamTerminationReason { | |
| 2507 | + let winning_reason = self.lease.finish(requested_reason); | |
| 2508 | + self.finished = true; | |
| 2509 | + winning_reason | |
| 2510 | + } | |
| 2511 | + | |
| 2512 | + fn finish_poll( | |
| 2513 | + &mut self, | |
| 2514 | + requested_reason: HttpStreamTerminationReason, | |
| 2515 | + ) -> std::task::Poll<Option<Result<Vec<u8>, String>>> { | |
| 2516 | + let stream_id = self.lease.stream_id(); | |
| 2517 | + let winning_reason = self.finish(requested_reason); | |
| 2518 | + transferred_termination_poll(stream_id, winning_reason) | |
| 2519 | + } | |
| 2520 | +} | |
| 2521 | + | |
| 2522 | +impl futures_util::Stream for HttpTransferredStream { | |
| 2523 | + type Item = Result<Vec<u8>, String>; | |
| 2524 | + | |
| 2525 | + fn poll_next( | |
| 2526 | + mut self: Pin<&mut Self>, | |
| 2527 | + context: &mut std::task::Context<'_>, | |
| 2528 | + ) -> std::task::Poll<Option<Self::Item>> { | |
| 2529 | + if self.finished { | |
| 2530 | + return std::task::Poll::Ready(None); | |
| 2531 | + } | |
| 2532 | + let this = self.as_mut().get_mut(); | |
| 2533 | + match this.poll_event(context) { | |
| 2534 | + std::task::Poll::Ready(HttpTransferredEvent::Chunk(bytes)) => { | |
| 2535 | + std::task::Poll::Ready(Some(Ok(bytes))) | |
| 2536 | + } | |
| 2537 | + std::task::Poll::Ready(HttpTransferredEvent::Error(error)) => { | |
| 2538 | + let stream_id = this.lease.stream_id(); | |
| 2539 | + let winning_reason = this.finish(HttpStreamTerminationReason::Finished); | |
| 2540 | + if winning_reason == HttpStreamTerminationReason::Finished { | |
| 2541 | + std::task::Poll::Ready(Some(Err(error))) | |
| 2542 | + } else { | |
| 2543 | + transferred_termination_poll(stream_id, winning_reason) | |
| 2544 | + } | |
| 2545 | + } | |
| 2546 | + std::task::Poll::Ready(HttpTransferredEvent::End) => { | |
| 2547 | + this.finish_poll(HttpStreamTerminationReason::Finished) | |
| 2548 | + } | |
| 2549 | + std::task::Poll::Ready(HttpTransferredEvent::Terminated(reason)) => { | |
| 2550 | + this.finish_poll(reason) | |
| 2551 | + } | |
| 2552 | + std::task::Poll::Pending => std::task::Poll::Pending, | |
| 2553 | + } | |
| 2554 | + } | |
| 2555 | +} | |
| 2556 | + | |
| 2557 | +struct HttpStreamClaim { | |
| 2558 | + service: Arc<HttpStreamService>, | |
| 2559 | + stream_id: u64, | |
| 2560 | + generation: u64, | |
| 2561 | + armed: bool, | |
| 2562 | +} | |
| 2563 | + | |
| 2564 | +impl HttpStreamClaim { | |
| 2565 | + fn take_source(mut self) -> Result<HttpChunkStream, String> { | |
| 2566 | + let source = self | |
| 2567 | + .service | |
| 2568 | + .checkout_transfer(self.stream_id, Some(self.generation)); | |
| 2569 | + if source.is_ok() { | |
| 2570 | + self.armed = false; | |
| 2571 | + } | |
| 2572 | + source.map(|source| Box::pin(source) as HttpChunkStream) | |
| 2573 | + } | |
| 2574 | +} | |
| 2575 | + | |
| 2576 | +impl Drop for HttpStreamClaim { | |
| 2577 | + fn drop(&mut self) { | |
| 2578 | + if self.armed { | |
| 2579 | + self.armed = false; | |
| 2580 | + let service = self.service.clone(); | |
| 2581 | + let stream_id = self.stream_id; | |
| 2582 | + let generation = self.generation; | |
| 2583 | + run_http_cleanup_from_drop(move || { | |
| 2584 | + service.release_claim(stream_id, generation); | |
| 2585 | + }); | |
| 2586 | + } | |
| 2587 | + } | |
| 2588 | +} | |
| 2589 | + | |
| 2590 | +fn http_stream_service() -> Arc<HttpStreamService> { | |
| 2591 | + asyncrt::runtime_services().http_streams() | |
| 2592 | +} | |
| 2593 | + | |
| 2594 | +fn register_http_stream(source: HttpStreamSource) -> Option<u64> { | |
| 2595 | + http_stream_service().register_source(source) | |
| 2596 | +} | |
| 2597 | + | |
| 2598 | +fn claim_http_stream(stream_id: u64) -> Option<HttpStreamClaim> { | |
| 2599 | + http_stream_service().claim(stream_id) | |
| 2600 | +} | |
| 2601 | + | |
| 2602 | +pub type HttpChunkStream = | |
| 2603 | + Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>; | |
| 2604 | + | |
| 2605 | +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] | |
| 2606 | +pub struct WsTarget { | |
| 2607 | + pub id: u64, | |
| 2608 | + pub scope: String, | |
| 2609 | + /// A parked tunneled 101 on the calling node (`peer_tunnel::splice`). | |
| 2610 | + /// The id is meaningful only in the process that parked it, but it must | |
| 2611 | + /// survive the isolate round trip, so it serializes. | |
| 2612 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 2613 | + pub tunnel: Option<u64>, | |
| 2614 | +} | |
| 2615 | + | |
| 2616 | +/// Encode a host response for the JS side. A text body crosses as a | |
| 2617 | +/// JS string (cheap, lossless), binary as a byte array, and a streaming body | |
| 2618 | +/// by id — serializing a Vec<u8> as a JSON number array is the dominant cost | |
| 2619 | +/// for real DO responses. `ws_target` is carried by the paths that can answer | |
| 2620 | +/// with a WebSocket upgrade: a Durable Object call and a service-binding call. | |
| 2621 | +fn encode_http_response( | |
| 2622 | + mut response: HttpResponse, | |
| 2623 | + ws_target: bool, | |
| 2624 | + stream_service: &Arc<HttpStreamService>, | |
| 2625 | +) -> Result<String, String> { | |
| 2626 | + let mut obj = serde_json::json!({ | |
| 2627 | + "status": response.status, | |
| 2628 | + "headers": response.headers, | |
| 2629 | + }); | |
| 2630 | + if ws_target { | |
| 2631 | + let target = match response.websocket.as_ref() { | |
| 2632 | + Some(HttpResponseWebSocket::Cell(target)) => Some(target), | |
| 2633 | + _ => None, | |
| 2634 | + }; | |
| 2635 | + obj["wsTarget"] = serde_json::json!(target); | |
| 2636 | + } | |
| 2637 | + if let Some(stream) = response.stream.take() { | |
| 2638 | + let Some(stream_id) = stream_service.register_source(HttpStreamSource::Stream(stream)) | |
| 2639 | + else { | |
| 2640 | + return Err(HTTP_STREAM_REGISTRATION_CLOSED.into()); | |
| 2641 | + }; | |
| 2642 | + obj["streamId"] = serde_json::json!(stream_id); | |
| 2643 | + } else { | |
| 2644 | + match std::str::from_utf8(&response.body) { | |
| 2645 | + Ok(text) => obj["body"] = serde_json::Value::String(text.into()), | |
| 2646 | + Err(_) => obj["bodyBytes"] = serde_json::json!(response.body), | |
| 2647 | + } | |
| 2648 | + } | |
| 2649 | + Ok(obj.to_string()) | |
| 2650 | +} | |
| 2651 | + | |
| 2652 | +pub enum HttpResponseWebSocket { | |
| 2653 | + Cell(WsTarget), | |
| 2654 | + Worker(websocket::WorkerWebSocket), | |
| 2655 | +} | |
| 2656 | + | |
| 2657 | +pub struct HttpResponse { | |
| 2658 | + pub status: u16, | |
| 2659 | + pub body: Vec<u8>, | |
| 2660 | + /// A response body forwarded without materializing it in memory. | |
| 2661 | + pub stream: Option<HttpChunkStream>, | |
| 2662 | + pub headers: Vec<(String, String)>, | |
| 2663 | + /// The one WebSocket target that owns this response, if it is an upgrade. | |
| 2664 | + pub websocket: Option<HttpResponseWebSocket>, | |
| 2665 | + /// The cell's committed-write position after the handler ran, for a local | |
| 2666 | + /// Durable Object request. The shell gates the response on durability when | |
| 2667 | + /// this advanced past the cell's last seen position. `None` for responses | |
| 2668 | + /// with no cell storage (Worker, asset, or proxied remote). | |
| 2669 | + pub write_position: Option<u64>, | |
| 2670 | + /// The position the answer observed above the cell's published baseline | |
| 2671 | + /// when the handler did not write, so the shell can hold a read-only | |
| 2672 | + /// response behind the proof of another handler's commit. `None` when the | |
| 2673 | + /// cell holds no handler write, or the response has no cell storage. | |
| 2674 | + pub observed_position: Option<u64>, | |
| 2675 | +} | |
| 2676 | + | |
| 2677 | +/// The encoding that the queue producer selected for one message body. | |
| 2678 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 2679 | +pub enum QueueContentType { | |
| 2680 | + Text, | |
| 2681 | + Bytes, | |
| 2682 | + Json, | |
| 2683 | + V8, | |
| 2684 | +} | |
| 2685 | + | |
| 2686 | +impl QueueContentType { | |
| 2687 | + fn as_str(self) -> &'static str { | |
| 2688 | + match self { | |
| 2689 | + Self::Text => "text", | |
| 2690 | + Self::Bytes => "bytes", | |
| 2691 | + Self::Json => "json", | |
| 2692 | + Self::V8 => "v8", | |
| 2693 | + } | |
| 2694 | + } | |
| 2695 | +} | |
| 2696 | + | |
| 2697 | +/// One message handed from a queue cell to a consumer isolate. | |
| 2698 | +pub struct QueueMessage { | |
| 2699 | + pub id: String, | |
| 2700 | + pub timestamp_ms: i64, | |
| 2701 | + pub body: Vec<u8>, | |
| 2702 | + pub content_type: QueueContentType, | |
| 2703 | + pub attempts: u16, | |
| 2704 | +} | |
| 2705 | + | |
| 2706 | +/// The queue state observed when a cell leases a batch. | |
| 2707 | +pub struct QueueMetrics { | |
| 2708 | + pub backlog_count: f64, | |
| 2709 | + pub backlog_bytes: f64, | |
| 2710 | + pub oldest_message_timestamp_ms: Option<i64>, | |
| 2711 | +} | |
| 2712 | + | |
| 2713 | +/// One leased batch handed to the stateless isolate pool. | |
| 2714 | +pub struct QueueBatch { | |
| 2715 | + pub queue: String, | |
| 2716 | + pub messages: Vec<QueueMessage>, | |
| 2717 | + pub metrics: QueueMetrics, | |
| 2718 | +} | |
| 2719 | + | |
| 2720 | +/// The batch-wide retry decision made by a queue handler. | |
| 2721 | +#[derive(Debug, Eq, PartialEq)] | |
| 2722 | +pub struct QueueRetryBatch { | |
| 2723 | + pub retry: bool, | |
| 2724 | + pub delay_seconds: Option<i32>, | |
| 2725 | +} | |
| 2726 | + | |
| 2727 | +/// An explicit retry decision made for one message. | |
| 2728 | +#[derive(Debug, Eq, PartialEq)] | |
| 2729 | +pub struct QueueRetryMessage { | |
| 2730 | + pub msg_id: String, | |
| 2731 | + pub delay_seconds: Option<i32>, | |
| 2732 | +} | |
| 2733 | + | |
| 2734 | +/// How the queue handler itself completed. Infrastructure failures still use | |
| 2735 | +/// the outer `Result`, so a handler exception can preserve earlier acks. | |
| 2736 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 2737 | +pub enum QueueOutcome { | |
| 2738 | + Ok, | |
| 2739 | + Exception, | |
| 2740 | +} | |
| 2741 | + | |
| 2742 | +/// The handler outcome and the settlement instructions it made before return. | |
| 2743 | +#[derive(Debug, Eq, PartialEq)] | |
| 2744 | +pub struct QueueDispatchResult { | |
| 2745 | + pub outcome: QueueOutcome, | |
| 2746 | + pub error: Option<String>, | |
| 2747 | + pub ack_all: bool, | |
| 2748 | + pub retry_batch: QueueRetryBatch, | |
| 2749 | + pub explicit_acks: Vec<String>, | |
| 2750 | + pub retry_messages: Vec<QueueRetryMessage>, | |
| 2751 | +} | |
| 2752 | + | |
| 2753 | +/// Which alarm a dispatch runs, and who owns its bookkeeping. | |
| 2754 | +pub enum AlarmDispatch { | |
| 2755 | + /// Claim whatever is due now, and record the outcome. | |
| 2756 | + Due, | |
| 2757 | + #[cfg(celld_internal_tests)] | |
| 2758 | + Armed, | |
| 2759 | + #[cfg(celld_internal_tests)] | |
| 2760 | + Claimed(i64), | |
| 2761 | +} | |
| 2762 | + | |
| 2763 | +/// One event a cell receives. | |
| 2764 | +/// | |
| 2765 | +/// Every variant is something the outside world did to the cell, and each | |
| 2766 | +/// becomes an `InFlight` entry driven by its own tokio task. Lifecycle — | |
| 2767 | +/// taking a cell in, giving it back, cancelling a request — is not here: it | |
| 2768 | +/// is a direct call on the isolate, because it is not an event and has no | |
| 2769 | +/// handler to run. | |
| 2770 | +pub enum CellJob { | |
| 2771 | + Fetch { | |
| 2772 | + request_id: Option<RequestId>, | |
| 2773 | + scope: String, | |
| 2774 | + name: Option<String>, | |
| 2775 | + url: String, | |
| 2776 | + method: String, | |
| 2777 | + body: RequestBody, | |
| 2778 | + headers: Vec<(String, String)>, | |
| 2779 | + reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 2780 | + /// Where this call sits in its caller's order for this cell, if it | |
| 2781 | + /// came from a script rather than from a peer or the ingress. | |
| 2782 | + order: Option<CallOrder>, | |
| 2783 | + }, | |
| 2784 | + Rpc { | |
| 2785 | + request_id: Option<RequestId>, | |
| 2786 | + scope: String, | |
| 2787 | + name: Option<String>, | |
| 2788 | + method: String, | |
| 2789 | + args: RpcData, | |
| 2790 | + reply: tokio::sync::oneshot::Sender<Result<RpcOutcome>>, | |
| 2791 | + }, | |
| 2792 | + WsOpen { | |
| 2793 | + scope: String, | |
| 2794 | + ws_id: u64, | |
| 2795 | + protocol: String, | |
| 2796 | + reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>, | |
| 2797 | + }, | |
| 2798 | + WsMessage { | |
| 2799 | + scope: String, | |
| 2800 | + ws_id: u64, | |
| 2801 | + data: WsIn, | |
| 2802 | + reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>, | |
| 2803 | + }, | |
| 2804 | + WsClosed { | |
| 2805 | + scope: String, | |
| 2806 | + ws_id: u64, | |
| 2807 | + code: u16, | |
| 2808 | + reason: String, | |
| 2809 | + was_clean: bool, | |
| 2810 | + reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>, | |
| 2811 | + }, | |
| 2812 | + Alarm { | |
| 2813 | + /// The shell task identity used to interrupt a firing during drain. | |
| 2814 | + request_id: Option<RequestId>, | |
| 2815 | + scope: String, | |
| 2816 | + scheduled_ms: i64, | |
| 2817 | + /// Which alarm to run, and who owns the bookkeeping. | |
| 2818 | + claim: AlarmDispatch, | |
| 2819 | + /// Replies with (next alarm, the handler's write delta). The delta is | |
| 2820 | + /// sampled inside the turn — cell storage must never be reached from | |
| 2821 | + /// the shell — and the shell uses it to prove the consuming commit | |
| 2822 | + /// durable before the core settles. Every answer shape samples it the | |
| 2823 | + /// same way now, in `InFlight::answer_settled`. | |
| 2824 | + reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 2825 | + }, | |
| 2826 | + #[cfg(celld_internal_tests)] | |
| 2827 | + SyncErrorForTest { | |
| 2828 | + scope: String, | |
| 2829 | + gate: ArmGateRx, | |
| 2830 | + socket_id: Option<u64>, | |
| 2831 | + terminate: bool, | |
| 2832 | + reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>, | |
| 2833 | + }, | |
| 2834 | +} | |
| 2835 | + | |
| 2836 | +/// A cell event that the runtime refuses before application code starts. | |
| 2837 | +/// | |
| 2838 | +/// The type survives the Rust RPC path. Its display text also survives the V8 | |
| 2839 | +/// promise boundary, so the public ingress can restore the HTTP overload | |
| 2840 | +/// contract after a Worker forwards the refusal. | |
| 2841 | +#[doc(hidden)] | |
| 2842 | +#[derive(Debug)] | |
| 2843 | +pub struct CellOverloaded; | |
| 2844 | + | |
| 2845 | +/// The V8 promise boundary preserves only an error string. Keep the public | |
| 2846 | +/// overload phrase so a Worker can classify a caught Queue producer refusal. | |
| 2847 | +/// Also include an opaque marker so unrelated application text cannot restore | |
| 2848 | +/// an HTTP overload response, and keep the producer and ingress checks on one | |
| 2849 | +/// value. | |
| 2850 | +#[doc(hidden)] | |
| 2851 | +pub const CELL_OVERLOAD_ERROR_MARKER: &str = | |
| 2852 | + "celld-internal-cell-overload-7ec38c64-12d7-4ddc-9e77-b63f9dc14130"; | |
| 2853 | + | |
| 2854 | +impl std::fmt::Display for CellOverloaded { | |
| 2855 | + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 2856 | + write!( | |
| 2857 | + formatter, | |
| 2858 | + "cell overload: admission refused ({CELL_OVERLOAD_ERROR_MARKER})" | |
| 2859 | + ) | |
| 2860 | + } | |
| 2861 | +} | |
| 2862 | + | |
| 2863 | +impl std::error::Error for CellOverloaded {} | |
| 2864 | + | |
| 2865 | +impl CellJob { | |
| 2866 | + /// The cell this event addresses, which is also the realm it runs in. | |
| 2867 | + pub fn scope(&self) -> &str { | |
| 2868 | + match self { | |
| 2869 | + CellJob::Fetch { scope, .. } | |
| 2870 | + | CellJob::Rpc { scope, .. } | |
| 2871 | + | CellJob::WsOpen { scope, .. } | |
| 2872 | + | CellJob::WsMessage { scope, .. } | |
| 2873 | + | CellJob::WsClosed { scope, .. } | |
| 2874 | + | CellJob::Alarm { scope, .. } => scope, | |
| 2875 | + #[cfg(celld_internal_tests)] | |
| 2876 | + CellJob::SyncErrorForTest { scope, .. } => scope, | |
| 2877 | + } | |
| 2878 | + } | |
| 2879 | + | |
| 2880 | + /// The client request that can cancel this event, when it is a fetch. | |
| 2881 | + pub(crate) fn request_id(&self) -> Option<RequestId> { | |
| 2882 | + match self { | |
| 2883 | + CellJob::Fetch { request_id, .. } => *request_id, | |
| 2884 | + _ => None, | |
| 2885 | + } | |
| 2886 | + } | |
| 2887 | + | |
| 2888 | + /// Queue sends use native RPC, so the method is the narrow seam where the | |
| 2889 | + /// owner can bound producer events without limiting an ordinary Durable | |
| 2890 | + /// Object RPC or a Queue alarm and settlement. | |
| 2891 | + pub(crate) fn is_queue_producer(&self) -> bool { | |
| 2892 | + matches!(self, CellJob::Rpc { scope, method, .. } | |
| 2893 | + if scope.split_once(':').is_some_and(|(class, _)| | |
| 2894 | + class == crate::deploy::QUEUE_CLASS) && method == "__queueSend") | |
| 2895 | + } | |
| 2896 | + | |
| 2897 | + /// This event's place in its caller's order, taken out so the drive can | |
| 2898 | + /// wait on it and then release the call behind it. | |
| 2899 | + pub fn take_order(&mut self) -> Option<CallOrder> { | |
| 2900 | + match self { | |
| 2901 | + CellJob::Fetch { order, .. } => order.take(), | |
| 2902 | + _ => None, | |
| 2903 | + } | |
| 2904 | + } | |
| 2905 | + | |
| 2906 | + /// Fail this event without running it. | |
| 2907 | + pub fn fail(self, error: anyhow::Error) { | |
| 2908 | + match self { | |
| 2909 | + CellJob::Fetch { reply, .. } => drop(reply.send(Err(error))), | |
| 2910 | + CellJob::Rpc { reply, .. } => drop(reply.send(Err(error))), | |
| 2911 | + CellJob::WsOpen { reply, .. } => drop(reply.send(Err(error))), | |
| 2912 | + CellJob::WsMessage { reply, .. } => drop(reply.send(Err(error))), | |
| 2913 | + CellJob::WsClosed { reply, .. } => drop(reply.send(Err(error))), | |
| 2914 | + CellJob::Alarm { reply, .. } => drop(reply.send(Err(error))), | |
| 2915 | + #[cfg(celld_internal_tests)] | |
| 2916 | + CellJob::SyncErrorForTest { reply, .. } => drop(reply.send(Err(error))), | |
| 2917 | + } | |
| 2918 | + } | |
| 2919 | +} | |
| 2920 | + | |
| 2921 | +thread_local! { | |
| 2922 | + // One outbound HTTP client per JS thread — building it per fetch rebuilds | |
| 2923 | + // the TLS stack every call (async-op-hazards.md). | |
| 2924 | + static HTTP: reqwest::Client = reqwest::Client::new(); | |
| 2925 | + static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder() | |
| 2926 | + .redirect(reqwest::redirect::Policy::none()).build().unwrap(); | |
| 2927 | + // A separate policy stops an `error` request before reqwest can replay it | |
| 2928 | + // at the destination. Inspecting the final response would be too late: | |
| 2929 | + // the method, body, and credentials could already have left the process. | |
| 2930 | + static HTTP_ERROR: reqwest::Client = reqwest::Client::builder() | |
| 2931 | + .redirect(reqwest::redirect::Policy::custom(|attempt| { | |
| 2932 | + attempt.error("fetch redirect mode is error") | |
| 2933 | + })).build().unwrap(); | |
| 2934 | + static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new()); | |
| 2935 | +} | |
| 2936 | + | |
| 2937 | +#[doc(hidden)] | |
| 2938 | +pub mod websocket; | |
| 2939 | +pub(crate) use websocket::WebSocketService; | |
| 2940 | +pub use websocket::*; | |
| 2941 | +use websocket::{ws_capture_begin, ws_capture_take, ws_close_request_sockets}; | |
| 2942 | + | |
| 2943 | +/// What an outbound effect must trail before it leaves the process. | |
| 2944 | +/// | |
| 2945 | +/// The three cases are named rather than nested inside one another because | |
| 2946 | +/// two of them once shared a representation, and that is what issue #144 was: | |
| 2947 | +/// a reader that starts after another request committed samples the new | |
| 2948 | +/// position as its own baseline and advances nothing, so a two-state gate read | |
| 2949 | +/// it as code that owns no cell at all and let its side effect out ungated. | |
| 2950 | +/// A variant per case makes the distinction one the compiler keeps. | |
| 2951 | +enum EgressGate { | |
| 2952 | + /// No cell event is running. Stateless Worker code owns no cell state, so | |
| 2953 | + /// its egress reveals nothing that can still be lost and leaves directly. | |
| 2954 | + NoCell, | |
| 2955 | + /// This event wrote through the position. The effect waits for that | |
| 2956 | + /// write. The last field is the activation epoch the position belongs to. | |
| 2957 | + Wrote(String, celld_logic::Channel, u64, Option<u64>), | |
| 2958 | + /// A read-only output. It reveals whatever the cell holds, so it carries | |
| 2959 | + /// the position it observed above the cell's published baseline, for the | |
| 2960 | + /// core to hold it behind the proof of a commit whose handler has not | |
| 2961 | + /// taken a ticket yet, and it trails the newest write barrier still open | |
| 2962 | + /// on the cell otherwise. Only the core knows which writes are | |
| 2963 | + /// outstanding, so this asks rather than guesses. The last field is the | |
| 2964 | + /// activation epoch the sample was taken at. | |
| 2965 | + ReadOnly(String, celld_logic::Channel, Option<u64>, Option<u64>), | |
| 2966 | + /// A facet's write did not reach the root database. No proof of that cell | |
| 2967 | + /// can cover it, so the effect fails closed instead of leaving with a | |
| 2968 | + /// write nothing can restore. The field is the storage failure. | |
| 2969 | + Unpersisted(String), | |
| 2970 | +} | |
| 2971 | + | |
| 2972 | +impl EgressGate { | |
| 2973 | + /// Whether the effect must consult the gate before it leaves. True for a | |
| 2974 | + /// read as well as a write: a read whose cell has no barrier is released | |
| 2975 | + /// at once, but only the core can say so. | |
| 2976 | + fn is_gated(&self) -> bool { | |
| 2977 | + !matches!(self, EgressGate::NoCell) | |
| 2978 | + } | |
| 2979 | + | |
| 2980 | + /// The cell whose event raised the effect. The host derives this from the | |
| 2981 | + /// active event, so JavaScript cannot claim another cell's authority. | |
| 2982 | + fn cell_scope(&self) -> Option<&str> { | |
| 2983 | + match self { | |
| 2984 | + EgressGate::NoCell | EgressGate::Unpersisted(_) => None, | |
| 2985 | + EgressGate::Wrote(cell, ..) | EgressGate::ReadOnly(cell, ..) => Some(cell), | |
| 2986 | + } | |
| 2987 | + } | |
| 2988 | +} | |
| 2989 | + | |
| 2990 | +/// The cell event the executing JavaScript belongs to. | |
| 2991 | +/// | |
| 2992 | +/// The continuation's own context first, from CPED: V8 runs a promise | |
| 2993 | +/// reaction of cell A inside another event's microtask checkpoint, and the | |
| 2994 | +/// thread-local turn owner then names that other event. An effect raised by | |
| 2995 | +/// A's reaction would otherwise be gated against the wrong cell's position, or | |
| 2996 | +/// refused as belonging to the wrong cell. The turn owner remains the answer | |
| 2997 | +/// for a context that installs no continuation token. | |
| 2998 | +fn event_context(scope: &mut v8::PinScope) -> Arc<IoContext> { | |
| 2999 | + current_reaction_io_context(scope).unwrap_or_else(current_context) | |
| 3000 | +} | |
| 3001 | + | |
| 3002 | +/// What one cell event's outbound effects gate against. | |
| 3003 | +#[derive(Clone)] | |
| 3004 | +struct EgressFrame { | |
| 3005 | + /// The scope whose connection records this event's writes: the cell for an | |
| 3006 | + /// ordinary event, and the facet for an event of an embedded facet. | |
| 3007 | + storage: String, | |
| 3008 | + /// The committed-write position of `storage` when the event started. | |
| 3009 | + before: u64, | |
| 3010 | + /// The root cell's gate, when `storage` names an embedded facet. Kept | |
| 3011 | + /// beside the scope it stores under, so an effect cannot take one without | |
| 3012 | + /// the other and charge a facet's egress to the facet. | |
| 3013 | + root: Option<storage::RootGate>, | |
| 3014 | +} | |
| 3015 | + | |
| 3016 | +/// The frame of the running event, if a cell event is running at all. | |
| 3017 | +fn current_cell_event(context: &IoContext) -> Option<EgressFrame> { | |
| 3018 | + context.egress.lock().unwrap().last().cloned() | |
| 3019 | +} | |
| 3020 | + | |
| 3021 | +/// Sample what the running handler's outbound effects must trail. Answers for | |
| 3022 | +/// every active cell event, including a read whose core lookup can settle | |
| 3023 | +/// immediately. Every sample here happens in the calling turn; the ticket | |
| 3024 | +/// carries them to the host loop, which must not reach cell storage itself. | |
| 3025 | +fn egress_gate_request(context: &IoContext, channel: celld_logic::Channel) -> EgressGate { | |
| 3026 | + let Some(frame) = current_cell_event(context) else { | |
| 3027 | + return EgressGate::NoCell; | |
| 3028 | + }; | |
| 3029 | + let (cell, before) = (frame.storage, frame.before); | |
| 3030 | + let sample = storage::write_position(&cell); | |
| 3031 | + if let Some(root) = frame.root { | |
| 3032 | + return facet_egress_gate(&cell, sample, before, root, channel); | |
| 3033 | + } | |
| 3034 | + let epoch = storage::activation_epoch(&cell); | |
| 3035 | + match sample.filter(|position| *position > before) { | |
| 3036 | + Some(position) => EgressGate::Wrote(cell, channel, position, epoch), | |
| 3037 | + // A read-only output in a process that configured no output gate has | |
| 3038 | + // nothing to trail. Such a process cannot acknowledge a write either | |
| 3039 | + // -- `await_egress_gate` fails a write closed for want of the same | |
| 3040 | + // channel -- so no committed-but-unproven write exists for a read to | |
| 3041 | + // reveal. Answer as | |
| 3042 | + // if no cell event were running, which keeps the effect on the direct, | |
| 3043 | + // synchronous path it has always taken; a WebSocket frame in | |
| 3044 | + // particular must not join a deferred queue whose flush needs a gate | |
| 3045 | + // to release it. A write still takes a ticket and still fails closed. | |
| 3046 | + None if GATE_TX.get().is_none() => EgressGate::NoCell, | |
| 3047 | + None => { | |
| 3048 | + let observed = storage::observed_position(&cell, sample); | |
| 3049 | + EgressGate::ReadOnly(cell, channel, observed, epoch) | |
| 3050 | + } | |
| 3051 | + } | |
| 3052 | +} | |
| 3053 | + | |
| 3054 | +/// Sample an effect raised by an event of an embedded facet. | |
| 3055 | +/// | |
| 3056 | +/// A facet is not a cell. Its storage is a private image inside the root | |
| 3057 | +/// cell's database, and no Worker exports its class under the id `facet_scope` | |
| 3058 | +/// builds, so a ticket in the facet's name activates a cell that cannot start. | |
| 3059 | +/// The effect reveals the root cell's state, so it names the root cell, and | |
| 3060 | +/// the positions come from `RootGate` because this isolate holds no connection | |
| 3061 | +/// to the root database. | |
| 3062 | +fn facet_egress_gate( | |
| 3063 | + facet: &str, | |
| 3064 | + sample: Option<u64>, | |
| 3065 | + before: u64, | |
| 3066 | + root: storage::RootGate, | |
| 3067 | + channel: celld_logic::Channel, | |
| 3068 | +) -> EgressGate { | |
| 3069 | + if sample.is_some_and(|position| position > before) { | |
| 3070 | + // The write is in the facet's private image and reaches the root | |
| 3071 | + // database at turn end, after this effect leaves. Copy it now, so the | |
| 3072 | + // proof this ticket waits for is a proof of a database that contains | |
| 3073 | + // it. This is the same copy `finish_turn` makes, for the same reason: | |
| 3074 | + // an external effect must not overtake the image that produced it. | |
| 3075 | + storage::flush_embedded(facet); | |
| 3076 | + // A copy that failed leaves the write in an image the root database | |
| 3077 | + // does not hold, so no proof of that cell covers it. The reply of this | |
| 3078 | + // event fails on the same poison; the effect must fail with it rather | |
| 3079 | + // than leave on a proof that proves the wrong thing. | |
| 3080 | + if let Some(error) = storage::sql_critical_error(facet) { | |
| 3081 | + return EgressGate::Unpersisted(error); | |
| 3082 | + } | |
| 3083 | + return EgressGate::Wrote(root.cell, channel, root.position, Some(root.epoch)); | |
| 3084 | + } | |
| 3085 | + // A read-only effect of a facet reveals what the facet read, which the | |
| 3086 | + // root cell committed at or below the sample the parent took for this | |
| 3087 | + // call. It therefore waits exactly as the root cell's own reader waits. | |
| 3088 | + if GATE_TX.get().is_none() { | |
| 3089 | + return EgressGate::NoCell; | |
| 3090 | + } | |
| 3091 | + EgressGate::ReadOnly(root.cell, channel, root.observed, Some(root.epoch)) | |
| 3092 | +} | |
| 3093 | + | |
| 3094 | +/// Why the output gate did not release a ticket. | |
| 3095 | +enum GateRefusal { | |
| 3096 | + /// The process installed no gate channel. A write must still fail closed | |
| 3097 | + /// here: an acknowledgement nobody can prove is the loss this gate exists | |
| 3098 | + /// to prevent. | |
| 3099 | + NoChannel, | |
| 3100 | + /// The core answered, and the answer is that the write is not durable. | |
| 3101 | + Unproven(celld_logic::RequestError), | |
| 3102 | + /// The shell dropped the ticket before the core answered. | |
| 3103 | + Dropped, | |
| 3104 | + /// A facet's write never reached a database a proof can cover. | |
| 3105 | + Unpersisted(String), | |
| 3106 | +} | |
| 3107 | + | |
| 3108 | +impl std::fmt::Display for GateRefusal { | |
| 3109 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 3110 | + match self { | |
| 3111 | + GateRefusal::NoChannel => f.write_str("no output-gate channel"), | |
| 3112 | + GateRefusal::Unproven(error @ celld_logic::RequestError::DurabilityUnproven) => { | |
| 3113 | + write!( | |
| 3114 | + f, | |
| 3115 | + "the write this request follows is not durable ({error:?})" | |
| 3116 | + ) | |
| 3117 | + } | |
| 3118 | + GateRefusal::Unproven(error) => { | |
| 3119 | + write!(f, "the output gate refused the ticket ({error:?})") | |
| 3120 | + } | |
| 3121 | + GateRefusal::Dropped => f.write_str("output gate dropped"), | |
| 3122 | + GateRefusal::Unpersisted(error) => { | |
| 3123 | + write!(f, "the facet's write did not reach its database ({error})") | |
| 3124 | + } | |
| 3125 | + } | |
| 3126 | + } | |
| 3127 | +} | |
| 3128 | + | |
| 3129 | +/// Take one ticket on the output gate and wait for the core's verdict. | |
| 3130 | +/// | |
| 3131 | +/// This is the output gate applied to an in-handler effect rather than to the | |
| 3132 | +/// response. It cannot deadlock the handler that is awaiting it: the ticket is | |
| 3133 | +/// served by `dispatch_gate` on the host's own loop and resolved by the | |
| 3134 | +/// replicator's independent task, neither of which needs the isolate's event | |
| 3135 | +/// loop to run. A read-only ticket carries `None` and the core releases it at | |
| 3136 | +/// once when the cell has no barrier open, so an ordinary read pays one actor | |
| 3137 | +/// hop and no replica write. | |
| 3138 | +async fn egress_gate_verdict(gate: EgressGate) -> std::result::Result<(), GateRefusal> { | |
| 3139 | + let (cell, channel, position, observed, epoch) = match gate { | |
| 3140 | + EgressGate::NoCell => return Ok(()), | |
| 3141 | + EgressGate::Unpersisted(error) => return Err(GateRefusal::Unpersisted(error)), | |
| 3142 | + EgressGate::Wrote(cell, channel, position, epoch) => { | |
| 3143 | + (cell, channel, Some(position), None, epoch) | |
| 3144 | + } | |
| 3145 | + EgressGate::ReadOnly(cell, channel, observed, epoch) => { | |
| 3146 | + (cell, channel, None, observed, epoch) | |
| 3147 | + } | |
| 3148 | + }; | |
| 3149 | + let (tx, receive) = tokio::sync::oneshot::channel(); | |
| 3150 | + let sent = GATE_TX | |
| 3151 | + .get() | |
| 3152 | + .map(|gate| { | |
| 3153 | + gate.send(GateReq { | |
| 3154 | + scope: cell, | |
| 3155 | + ticket: crate::actor::GateTicket { | |
| 3156 | + channel, | |
| 3157 | + position, | |
| 3158 | + observed, | |
| 3159 | + epoch, | |
| 3160 | + }, | |
| 3161 | + reply: tx, | |
| 3162 | + }) | |
| 3163 | + .is_ok() | |
| 3164 | + }) | |
| 3165 | + .unwrap_or(false); | |
| 3166 | + if !sent { | |
| 3167 | + return Err(GateRefusal::NoChannel); | |
| 3168 | + } | |
| 3169 | + match receive.await { | |
| 3170 | + Ok(Ok(())) => Ok(()), | |
| 3171 | + Ok(Err(error)) => Err(GateRefusal::Unproven(error)), | |
| 3172 | + Err(_) => Err(GateRefusal::Dropped), | |
| 3173 | + } | |
| 3174 | +} | |
| 3175 | + | |
| 3176 | +/// Wait for the writes an outbound effect can reveal to be proven durable | |
| 3177 | +/// before it leaves the process. See `egress_gate_verdict`. | |
| 3178 | +async fn await_egress_gate(gate: EgressGate) -> std::result::Result<(), String> { | |
| 3179 | + egress_gate_verdict(gate) | |
| 3180 | + .await | |
| 3181 | + .map_err(|refusal| match refusal { | |
| 3182 | + GateRefusal::Unproven(_) | GateRefusal::Unpersisted(_) => { | |
| 3183 | + format!("refusing to send: {refusal}") | |
| 3184 | + } | |
| 3185 | + GateRefusal::NoChannel | GateRefusal::Dropped => refusal.to_string(), | |
| 3186 | + }) | |
| 3187 | +} | |
| 3188 | + | |
| 3189 | +/// Hold an outbound request until the write it follows is durable, then hand | |
| 3190 | +/// it to the host. | |
| 3191 | +/// | |
| 3192 | +/// The send moves inside the future deliberately. These channels dispatch as | |
| 3193 | +/// soon as `send` is called, so gating anywhere after it would let the effect | |
| 3194 | +/// leave first -- the request would already be on its way while the caller | |
| 3195 | +/// waited for a durability answer that no longer decides anything. | |
| 3196 | +async fn gated_channel_send<T>( | |
| 3197 | + gate: EgressGate, | |
| 3198 | + channel: &'static OnceLock<tokio::sync::mpsc::UnboundedSender<T>>, | |
| 3199 | + request: T, | |
| 3200 | + missing: &'static str, | |
| 3201 | +) -> std::result::Result<(), String> { | |
| 3202 | + await_egress_gate(gate).await?; | |
| 3203 | + match channel.get() { | |
| 3204 | + Some(tx) if tx.send(request).is_ok() => Ok(()), | |
| 3205 | + _ => Err(missing.to_string()), | |
| 3206 | + } | |
| 3207 | +} | |
| 3208 | + | |
| 3209 | +/// One `celld_logic::gate::InputGate` per cell. | |
| 3210 | +/// | |
| 3211 | +/// The logic decides; this is only the map and the ids. It replaces the | |
| 3212 | +/// promise chain that used to live in `harness.js`, which serialised blocks | |
| 3213 | +/// against each other but did nothing about *delivery* — so a second event | |
| 3214 | +/// could arrive mid-block, and under real concurrency that wedged the cell. | |
| 3215 | +/// | |
| 3216 | +/// Keyed by cell scope rather than held on the isolate, because a gate | |
| 3217 | +/// belongs to a cell and cells share isolates. | |
| 3218 | +static CELL_GATES: OnceLock<Mutex<HashMap<String, CellGate>>> = OnceLock::new(); | |
| 3219 | +static NEXT_GATE_EVENT: AtomicU64 = AtomicU64::new(1); | |
| 3220 | +// Cell gates are process-wide, so their owner ids must not repeat in another | |
| 3221 | +// isolate. A per-isolate sequence can make one event appear to own another | |
| 3222 | +// isolate's gate and keep the wrong event alive. | |
| 3223 | +static NEXT_IO_CONTEXT_ID: AtomicU64 = AtomicU64::new(0); | |
| 3224 | + | |
| 3225 | +fn allocate_io_context_id() -> u64 { | |
| 3226 | + NEXT_IO_CONTEXT_ID | |
| 3227 | + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| { | |
| 3228 | + current.checked_add(1) | |
| 3229 | + }) | |
| 3230 | + .unwrap_or_else(|_| panic!("the process exhausted its IoContext ids")) | |
| 3231 | + + 1 | |
| 3232 | +} | |
| 3233 | + | |
| 3234 | +/// One cell's input gate, with the event that holds it and the events queued | |
| 3235 | +/// to take it, named by the continuation id of their `IoContext`. | |
| 3236 | +/// | |
| 3237 | +/// They live beside the gate so that the lock that covers the take covers | |
| 3238 | +/// the record, and a reader sees the two agree. The event named is the turn | |
| 3239 | +/// owner at the take, not the continuation that asked: ops are adopted by | |
| 3240 | +/// the entry whose turn spawned them, so a reaction of one event that runs | |
| 3241 | +/// inside another event's checkpoint spawns the block's ops into that other | |
| 3242 | +/// entry, and it is that entry whose ops must keep running for the block to | |
| 3243 | +/// end. `cancel` reads it for that: the request it ends keeps its ops while | |
| 3244 | +/// it holds or waits for the gate, or the block's `finally` never releases | |
| 3245 | +/// (#733). A continuation resumed later in yet another entry's checkpoint | |
| 3246 | +/// spawns into that entry instead, which this record cannot follow. | |
| 3247 | +#[derive(Default)] | |
| 3248 | +struct CellGate { | |
| 3249 | + gate: celld_logic::gate::InputGate, | |
| 3250 | + holder: Option<u64>, | |
| 3251 | + /// A reaction can belong to an event other than the turn owner. The claim | |
| 3252 | + /// keeps that originating event and its resources active until the block | |
| 3253 | + /// ends. A same-event block needs no claim because its `InFlight` owns the | |
| 3254 | + /// gate itself. | |
| 3255 | + origin: Option<CrossEntryGateClaim>, | |
| 3256 | + /// Counted, because one event can start several blocks at once. | |
| 3257 | + queued: HashMap<u64, u32>, | |
| 3258 | +} | |
| 3259 | + | |
| 3260 | +/// How many holds and queued takes exist across every gate, so the checks | |
| 3261 | +/// every turn makes can skip the map while no event blocks at all, which is | |
| 3262 | +/// nearly always. | |
| 3263 | +static GATE_ENGAGEMENTS: AtomicUsize = AtomicUsize::new(0); | |
| 3264 | + | |
| 3265 | +fn cell_gates() -> &'static Mutex<HashMap<String, CellGate>> { | |
| 3266 | + CELL_GATES.get_or_init(|| Mutex::new(HashMap::new())) | |
| 3267 | +} | |
| 3268 | + | |
| 3269 | +impl CellGate { | |
| 3270 | + fn take( | |
| 3271 | + &mut self, | |
| 3272 | + event: celld_logic::gate::EventId, | |
| 3273 | + owner: Option<u64>, | |
| 3274 | + origin: &mut Option<CrossEntryGateClaim>, | |
| 3275 | + ) -> bool { | |
| 3276 | + let was_open = self.gate.is_open(); | |
| 3277 | + let taken = self.gate.acquire(event); | |
| 3278 | + if taken && was_open { | |
| 3279 | + self.set_holder(owner, origin.take()); | |
| 3280 | + } | |
| 3281 | + taken | |
| 3282 | + } | |
| 3283 | + | |
| 3284 | + fn set_holder(&mut self, owner: Option<u64>, origin: Option<CrossEntryGateClaim>) { | |
| 3285 | + if self.holder.is_none() && owner.is_some() { | |
| 3286 | + GATE_ENGAGEMENTS.fetch_add(1, Ordering::Relaxed); | |
| 3287 | + } | |
| 3288 | + self.holder = owner; | |
| 3289 | + self.origin = origin; | |
| 3290 | + } | |
| 3291 | + | |
| 3292 | + fn clear_holder(&mut self) -> Option<CrossEntryGateClaim> { | |
| 3293 | + if self.holder.take().is_some() { | |
| 3294 | + GATE_ENGAGEMENTS.fetch_sub(1, Ordering::Relaxed); | |
| 3295 | + } | |
| 3296 | + self.origin.take() | |
| 3297 | + } | |
| 3298 | + | |
| 3299 | + fn release( | |
| 3300 | + &mut self, | |
| 3301 | + event: celld_logic::gate::EventId, | |
| 3302 | + ) -> (bool, Option<CrossEntryGateClaim>) { | |
| 3303 | + if !self.gate.release(event) { | |
| 3304 | + return (false, None); | |
| 3305 | + } | |
| 3306 | + (true, self.clear_holder()) | |
| 3307 | + } | |
| 3308 | + | |
| 3309 | + fn abandon( | |
| 3310 | + &mut self, | |
| 3311 | + event: celld_logic::gate::EventId, | |
| 3312 | + ) -> (bool, Option<CrossEntryGateClaim>) { | |
| 3313 | + if !self.gate.abandon(event) { | |
| 3314 | + return (false, None); | |
| 3315 | + } | |
| 3316 | + (true, self.clear_holder()) | |
| 3317 | + } | |
| 3318 | + | |
| 3319 | + fn is_unused(&self) -> bool { | |
| 3320 | + self.gate.is_open() && self.queued.is_empty() | |
| 3321 | + } | |
| 3322 | +} | |
| 3323 | + | |
| 3324 | +/// How the event running under `context` is engaged with the cells' gates: | |
| 3325 | +/// it holds one, it is queued to take one, or neither. | |
| 3326 | +/// | |
| 3327 | +/// Every gate is searched, not only the gate of the event's own cell: a | |
| 3328 | +/// reaction of cell A's event can run inside cell B's checkpoint, and the | |
| 3329 | +/// block it starts then belongs to A's gate while its ops belong to B's | |
| 3330 | +/// entry. B's entry is the one that must keep them, and it finds itself | |
| 3331 | +/// through its own id whichever gate names it. | |
| 3332 | +#[derive(Clone, Copy, PartialEq, Eq)] | |
| 3333 | +enum GateEngagement { | |
| 3334 | + Holds, | |
| 3335 | + Queued, | |
| 3336 | + None, | |
| 3337 | +} | |
| 3338 | + | |
| 3339 | +fn gate_engagement(cell: Option<&str>, context: &Arc<IoContext>) -> GateEngagement { | |
| 3340 | + if GATE_ENGAGEMENTS.load(Ordering::Relaxed) == 0 { | |
| 3341 | + return GateEngagement::None; | |
| 3342 | + } | |
| 3343 | + let Some(id) = context.continuation_id() else { | |
| 3344 | + return GateEngagement::None; | |
| 3345 | + }; | |
| 3346 | + fn of(gate: &CellGate, id: u64) -> GateEngagement { | |
| 3347 | + if !gate.gate.is_open() && gate.holder == Some(id) { | |
| 3348 | + GateEngagement::Holds | |
| 3349 | + } else if gate.queued.contains_key(&id) { | |
| 3350 | + GateEngagement::Queued | |
| 3351 | + } else { | |
| 3352 | + GateEngagement::None | |
| 3353 | + } | |
| 3354 | + } | |
| 3355 | + let gates = cell_gates().lock().unwrap(); | |
| 3356 | + // The event's own cell first: nearly every block is on it, and the walk | |
| 3357 | + // below is the price of the cross-cell case alone. | |
| 3358 | + if let Some(gate) = cell.and_then(|cell| gates.get(cell)) { | |
| 3359 | + let engagement = of(gate, id); | |
| 3360 | + if engagement != GateEngagement::None { | |
| 3361 | + return engagement; | |
| 3362 | + } | |
| 3363 | + } | |
| 3364 | + let mut engagement = GateEngagement::None; | |
| 3365 | + for gate in gates.values() { | |
| 3366 | + match of(gate, id) { | |
| 3367 | + GateEngagement::Holds => return GateEngagement::Holds, | |
| 3368 | + GateEngagement::Queued => engagement = GateEngagement::Queued, | |
| 3369 | + GateEngagement::None => {} | |
| 3370 | + } | |
| 3371 | + } | |
| 3372 | + engagement | |
| 3373 | +} | |
| 3374 | + | |
| 3375 | +/// What a waiting event is told when the gate finally opens: nothing, or | |
| 3376 | +/// the reason the holder failed. | |
| 3377 | +type GateWake = tokio::sync::oneshot::Sender<Result<(), String>>; | |
| 3378 | + | |
| 3379 | +static GATE_WAITERS: OnceLock<Mutex<HashMap<String, Vec<GateWake>>>> = OnceLock::new(); | |
| 3380 | + | |
| 3381 | +/// Events waiting for a cell's input gate to open, in arrival order. | |
| 3382 | +/// | |
| 3383 | +/// An earlier implementation deleted this queue because an event the gate | |
| 3384 | +/// refused stayed on the cell's job channel until a later delivery point | |
| 3385 | +/// took it, so the channel *was* the queue and a second one could disagree | |
| 3386 | +/// with it. Drives have no channel, so a refused event needs somewhere to | |
| 3387 | +/// wait, and workerd keeps the same structure for the same reason | |
| 3388 | +/// (`io-gate.h`, `kj::List<Waiter, &Waiter::link> waiters`). | |
| 3389 | +/// | |
| 3390 | +/// In the shell rather than in `celld_logic::gate`, because what waits is a | |
| 3391 | +/// tokio task and the core is sans-IO. The core still owns the decision — | |
| 3392 | +/// `is_open` — and this owns only the waking. | |
| 3393 | +fn gate_waiters() -> &'static Mutex<HashMap<String, Vec<GateWake>>> { | |
| 3394 | + GATE_WAITERS.get_or_init(|| Mutex::new(HashMap::new())) | |
| 3395 | +} | |
| 3396 | + | |
| 3397 | +/// Take a ticket to be woken when `cell`'s gate opens, or `None` if it is | |
| 3398 | +/// open now. | |
| 3399 | +/// | |
| 3400 | +/// The gate's lock is held across the check and the enqueue, so a release | |
| 3401 | +/// that lands between the two cannot leave an event waiting on a gate that | |
| 3402 | +/// is already open. | |
| 3403 | +pub fn cell_gate_wait(cell: &str) -> Option<tokio::sync::oneshot::Receiver<Result<(), String>>> { | |
| 3404 | + let gates = cell_gates().lock().unwrap(); | |
| 3405 | + if gates.get(cell).is_none_or(|gate| gate.gate.is_open()) { | |
| 3406 | + return None; | |
| 3407 | + } | |
| 3408 | + let (wake, waiter) = tokio::sync::oneshot::channel(); | |
| 3409 | + gate_waiters() | |
| 3410 | + .lock() | |
| 3411 | + .unwrap() | |
| 3412 | + .entry(cell.to_string()) | |
| 3413 | + .or_default() | |
| 3414 | + .push(wake); | |
| 3415 | + drop(gates); | |
| 3416 | + Some(waiter) | |
| 3417 | +} | |
| 3418 | + | |
| 3419 | +enum CellGateAcquisition { | |
| 3420 | + Acquired, | |
| 3421 | + Waiting { | |
| 3422 | + gate: tokio::sync::oneshot::Receiver<Result<(), String>>, | |
| 3423 | + retirement: tokio::sync::watch::Receiver<bool>, | |
| 3424 | + }, | |
| 3425 | + Retired, | |
| 3426 | +} | |
| 3427 | + | |
| 3428 | +/// Acquire `cell` for `event`, or enqueue its next attempt before the gate can | |
| 3429 | +/// change state. | |
| 3430 | +/// | |
| 3431 | +/// A failed holder wakes its existing waiters with an error. Separating the | |
| 3432 | +/// failed acquisition from waiter registration lets that failure land between | |
| 3433 | +/// the two, so the event can miss the error and run against the reset actor. | |
| 3434 | +/// The context lock also covers the successful host claim, so event retirement | |
| 3435 | +/// cannot land between acquiring the process gate and recording its owner. | |
| 3436 | +fn acquire_cell_gate( | |
| 3437 | + context: &IoContext, | |
| 3438 | + cell: &str, | |
| 3439 | + event: celld_logic::gate::EventId, | |
| 3440 | + owner: Option<u64>, | |
| 3441 | + origin: &mut Option<CrossEntryGateClaim>, | |
| 3442 | +) -> CellGateAcquisition { | |
| 3443 | + let mut claims = context.input_gates.lock().unwrap(); | |
| 3444 | + if claims.retired { | |
| 3445 | + return CellGateAcquisition::Retired; | |
| 3446 | + } | |
| 3447 | + let mut gates = cell_gates().lock().unwrap(); | |
| 3448 | + if gates | |
| 3449 | + .entry(cell.to_string()) | |
| 3450 | + .or_default() | |
| 3451 | + .take(event, owner, origin) | |
| 3452 | + { | |
| 3453 | + let previous = claims.held.insert(event, cell.to_string()); | |
| 3454 | + assert!(previous.is_none(), "an input-gate event id was reused"); | |
| 3455 | + return CellGateAcquisition::Acquired; | |
| 3456 | + } | |
| 3457 | + let (wake, waiter) = tokio::sync::oneshot::channel(); | |
| 3458 | + gate_waiters() | |
| 3459 | + .lock() | |
| 3460 | + .unwrap() | |
| 3461 | + .entry(cell.to_string()) | |
| 3462 | + .or_default() | |
| 3463 | + .push(wake); | |
| 3464 | + let retirement = claims.retirement.subscribe(); | |
| 3465 | + drop(gates); | |
| 3466 | + CellGateAcquisition::Waiting { | |
| 3467 | + gate: waiter, | |
| 3468 | + retirement, | |
| 3469 | + } | |
| 3470 | +} | |
| 3471 | + | |
| 3472 | +/// Wake everything waiting on `cell`'s gate. Each re-checks and re-queues if | |
| 3473 | +/// another block took the gate first, so waking all of them is correct and | |
| 3474 | +/// the order they resume in is theirs to lose, not this function's to keep. | |
| 3475 | +fn wake_gate_waiters(cell: &str, outcome: Result<(), String>) { | |
| 3476 | + let waiters = gate_waiters().lock().unwrap().remove(cell); | |
| 3477 | + for wake in waiters.into_iter().flatten() { | |
| 3478 | + let _ = wake.send(outcome.clone()); | |
| 3479 | + } | |
| 3480 | +} | |
| 3481 | + | |
| 3482 | +const ABANDONED_INPUT_GATE: &str = "the cell's critical section ended without releasing"; | |
| 3483 | +const RETIRED_INPUT_GATE: &str = "the cell event ended before it could acquire an input gate"; | |
| 3484 | + | |
| 3485 | +/// Release one completed block and remove the open gate from the process map. | |
| 3486 | +fn release_cell_gate(cell: &str, event: celld_logic::gate::EventId, outcome: Result<(), String>) { | |
| 3487 | + let origin = { | |
| 3488 | + let mut gates = cell_gates().lock().unwrap(); | |
| 3489 | + let Some(gate) = gates.get_mut(cell) else { | |
| 3490 | + return; | |
| 3491 | + }; | |
| 3492 | + let (opened, origin) = gate.release(event); | |
| 3493 | + // A stale release or a remaining nested hold cannot wake the waiters. | |
| 3494 | + // In particular, a stale error must not fail a replacement holder's | |
| 3495 | + // queued events. | |
| 3496 | + if !opened { | |
| 3497 | + return; | |
| 3498 | + } | |
| 3499 | + if gate.is_unused() { | |
| 3500 | + gates.remove(cell); | |
| 3501 | + } | |
| 3502 | + origin | |
| 3503 | + }; | |
| 3504 | + // Releasing the origin claim can wake its drive and eventually run | |
| 3505 | + // `IoContext::drop`, which also locks the gate map. Keep that work outside | |
| 3506 | + // the map's lock. | |
| 3507 | + drop(origin); | |
| 3508 | + wake_gate_waiters(cell, outcome); | |
| 3509 | +} | |
| 3510 | + | |
| 3511 | +/// Retire `context`'s waiters and abandon every input gate that it still owns. | |
| 3512 | +/// | |
| 3513 | +/// The event id is part of each claim. A concurrent event can already be | |
| 3514 | +/// running when this one dies, so a cell name alone cannot safely decide | |
| 3515 | +/// which holder to release. Removing the open map entry also prevents an old | |
| 3516 | +/// cell incarnation from leaving process-wide state for a later one. | |
| 3517 | +fn abandon_context_input_gates(context: &IoContext) -> Vec<(String, celld_logic::gate::EventId)> { | |
| 3518 | + let claims = context.retire_input_gates(); | |
| 3519 | + for (cell, event) in &claims { | |
| 3520 | + let (abandoned, origin) = { | |
| 3521 | + let mut gates = cell_gates().lock().unwrap(); | |
| 3522 | + let (abandoned, origin) = gates | |
| 3523 | + .get_mut(cell) | |
| 3524 | + .map_or((false, None), |gate| gate.abandon(*event)); | |
| 3525 | + if abandoned { | |
| 3526 | + gates.remove(cell); | |
| 3527 | + } | |
| 3528 | + (abandoned, origin) | |
| 3529 | + }; | |
| 3530 | + // See `release_cell_gate`: releasing an origin can re-enter this map | |
| 3531 | + // from its eventual context destructor. | |
| 3532 | + drop(origin); | |
| 3533 | + if abandoned { | |
| 3534 | + wake_gate_waiters(cell, Err(ABANDONED_INPUT_GATE.to_string())); | |
| 3535 | + } | |
| 3536 | + } | |
| 3537 | + claims | |
| 3538 | +} | |
| 3539 | + | |
| 3540 | +/// JS promise resolvers awaiting an async op, keyed by the op's id. | |
| 3541 | +/// | |
| 3542 | +/// **Per isolate, and shared across threads.** Under D1 a request's turns run | |
| 3543 | +/// on whichever tokio worker picks them up, so a resolver registered on one | |
| 3544 | +/// thread is resolved from another; a thread-local map loses it, and | |
| 3545 | +/// `resolve_res` fails to find the resolver and returns silently, leaving the | |
| 3546 | +/// handler awaiting a promise nothing will ever settle. The `Mutex` is what | |
| 3547 | +/// makes that safe, not the map's location. | |
| 3548 | +/// | |
| 3549 | +/// It lives on `ActorRuntimeState` — one per isolate, reached from a scope — | |
| 3550 | +/// so a resolver is only ever looked up in the heap that owns it. One map for | |
| 3551 | +/// the whole process would also work, because op ids come from a single | |
| 3552 | +/// counter (`asyncrt::NEXT_ID`) and an id names exactly one resolver. But that | |
| 3553 | +/// makes an id-allocation bug into cross-isolate handle confusion, where this | |
| 3554 | +/// makes it a miss. | |
| 3555 | +type PromiseMap = HashMap<u64, v8::Global<v8::PromiseResolver>>; | |
| 3556 | + | |
| 3557 | +/// Requests cancelled by a reentrant `AbortFetch`. Global for the same reason | |
| 3558 | +/// as [`promises`]: the turn that observes a cancellation need not be on the | |
| 3559 | +/// thread that recorded it. | |
| 3560 | +static CANCELLED_REQUESTS: OnceLock<Mutex<HashSet<RequestId>>> = OnceLock::new(); | |
| 3561 | + | |
| 3562 | +fn cancelled_requests() -> &'static Mutex<HashSet<RequestId>> { | |
| 3563 | + CANCELLED_REQUESTS.get_or_init(|| Mutex::new(HashSet::new())) | |
| 3564 | +} | |
| 3565 | + | |
| 3566 | +fn promise_store(scope: &mut v8::PinScope, id: u64, r: v8::Global<v8::PromiseResolver>) { | |
| 3567 | + actor_runtime_state(scope) | |
| 3568 | + .promises | |
| 3569 | + .lock() | |
| 3570 | + .unwrap() | |
| 3571 | + .insert(id, r); | |
| 3572 | +} | |
| 3573 | + | |
| 3574 | +/// Resolve or reject op `id`'s promise with its outcome. | |
| 3575 | +fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) { | |
| 3576 | + let g = match actor_runtime_state(tc).promises.lock().unwrap().remove(&id) { | |
| 3577 | + Some(g) => g, | |
| 3578 | + None => return, | |
| 3579 | + }; | |
| 3580 | + let r = v8::Local::new(tc, g); | |
| 3581 | + match res { | |
| 3582 | + Ok(asyncrt::OpOut::Str(v)) => { | |
| 3583 | + let s = v8::String::new(tc, &v).unwrap(); | |
| 3584 | + r.resolve(tc, s.into()); | |
| 3585 | + } | |
| 3586 | + Ok(asyncrt::OpOut::Bytes(b)) => { | |
| 3587 | + let v = bytes_value(tc, b); | |
| 3588 | + r.resolve(tc, v); | |
| 3589 | + } | |
| 3590 | + Err(e) => { | |
| 3591 | + let s = v8::String::new(tc, &e).unwrap(); | |
| 3592 | + let ex = v8::Exception::error(tc, s); | |
| 3593 | + r.reject(tc, ex); | |
| 3594 | + } | |
| 3595 | + } | |
| 3596 | +} | |
| 3597 | + | |
| 3598 | +/// Move `bytes` into a `Uint8Array` without copying. | |
| 3599 | +fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> { | |
| 3600 | + #[cfg(celld_internal_tests)] | |
| 3601 | + let input = bytes.as_ptr() as usize; | |
| 3602 | + let len = bytes.len(); | |
| 3603 | + let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared(); | |
| 3604 | + let buffer = v8::ArrayBuffer::with_backing_store(scope, &store); | |
| 3605 | + #[cfg(celld_internal_tests)] | |
| 3606 | + record_bytes_value_allocation_for_test( | |
| 3607 | + input, | |
| 3608 | + buffer | |
| 3609 | + .get_backing_store() | |
| 3610 | + .data() | |
| 3611 | + .map(|data| data.as_ptr() as usize), | |
| 3612 | + ); | |
| 3613 | + v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into() | |
| 3614 | +} | |
| 3615 | + | |
| 3616 | +#[cfg(celld_internal_tests)] | |
| 3617 | +static BYTES_VALUE_ALLOCATION_PROBE: Mutex<Option<(usize, Option<usize>)>> = Mutex::new(None); | |
| 3618 | + | |
| 3619 | +#[cfg(celld_internal_tests)] | |
| 3620 | +#[doc(hidden)] | |
| 3621 | +pub fn capture_bytes_value_allocation_for_test(expected: *const u8) { | |
| 3622 | + *BYTES_VALUE_ALLOCATION_PROBE.lock().unwrap() = Some((expected as usize, None)); | |
| 3623 | +} | |
| 3624 | + | |
| 3625 | +#[cfg(celld_internal_tests)] | |
| 3626 | +fn record_bytes_value_allocation_for_test(input: usize, output: Option<usize>) { | |
| 3627 | + let mut probe = BYTES_VALUE_ALLOCATION_PROBE.lock().unwrap(); | |
| 3628 | + if probe | |
| 3629 | + .as_ref() | |
| 3630 | + .is_some_and(|(expected, _)| *expected == input) | |
| 3631 | + { | |
| 3632 | + *probe = Some((input, output)); | |
| 3633 | + } | |
| 3634 | +} | |
| 3635 | + | |
| 3636 | +#[cfg(celld_internal_tests)] | |
| 3637 | +#[doc(hidden)] | |
| 3638 | +pub fn take_bytes_value_allocation_for_test() -> Option<usize> { | |
| 3639 | + BYTES_VALUE_ALLOCATION_PROBE | |
| 3640 | + .lock() | |
| 3641 | + .unwrap() | |
| 3642 | + .take() | |
| 3643 | + .and_then(|(_, output)| output) | |
| 3644 | +} | |
| 3645 | + | |
| 3646 | +pub fn handler_budget() -> Duration { | |
| 3647 | + static BUDGET: OnceLock<Duration> = OnceLock::new(); | |
| 3648 | + *BUDGET.get_or_init(|| { | |
| 3649 | + Duration::from_secs( | |
| 3650 | + crate::env_vars::positive_or("CELLD_HANDLER_BUDGET_S", 300) | |
| 3651 | + .expect("validated CELLD_HANDLER_BUDGET_S"), | |
| 3652 | + ) | |
| 3653 | + }) | |
| 3654 | +} | |
| 3655 | + | |
| 3656 | +/// Aborts raised by an HTTP or service-binding caller disconnecting while the | |
| 3657 | +/// target runs in the stateless isolate pool. Durable Object aborts can also | |
| 3658 | +/// arrive as a reentrant `CellJob::AbortFetch`, so the abort has to be visible | |
| 3659 | +/// from whichever turn observes it. | |
| 3660 | +/// | |
| 3661 | +/// The counter keeps the common path to one relaxed atomic load per loop turn: | |
| 3662 | +/// with nothing pending, the mutex is never taken. | |
| 3663 | +static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> = | |
| 3664 | + OnceLock::new(); | |
| 3665 | +static SHUTDOWN_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> = | |
| 3666 | + OnceLock::new(); | |
| 3667 | +static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | |
| 3668 | + | |
| 3669 | +fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> { | |
| 3670 | + PENDING_ABORTS.get_or_init(Default::default) | |
| 3671 | +} | |
| 3672 | + | |
| 3673 | +fn shutdown_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> { | |
| 3674 | + SHUTDOWN_ABORTS.get_or_init(Default::default) | |
| 3675 | +} | |
| 3676 | + | |
| 3677 | +#[cfg(all(test, celld_internal_tests))] | |
| 3678 | +type AbortRequestPauseForTest = ( | |
| 3679 | + RequestId, | |
| 3680 | + std::sync::mpsc::Sender<()>, | |
| 3681 | + std::sync::mpsc::Receiver<()>, | |
| 3682 | +); | |
| 3683 | + | |
| 3684 | +#[cfg(all(test, celld_internal_tests))] | |
| 3685 | +static ABORT_REQUEST_PAUSE_FOR_TEST: Mutex<Option<AbortRequestPauseForTest>> = Mutex::new(None); | |
| 3686 | + | |
| 3687 | +#[cfg(all(test, celld_internal_tests))] | |
| 3688 | +pub(crate) struct AbortRequestPauseHandleForTest { | |
| 3689 | + entered: std::sync::mpsc::Receiver<()>, | |
| 3690 | + release: Option<std::sync::mpsc::Sender<()>>, | |
| 3691 | +} | |
| 3692 | + | |
| 3693 | +#[cfg(all(test, celld_internal_tests))] | |
| 3694 | +impl AbortRequestPauseHandleForTest { | |
| 3695 | + pub(crate) fn wait_until_entered(&self) { | |
| 3696 | + self.entered | |
| 3697 | + .recv() | |
| 3698 | + .expect("the abort publisher dropped before its publication seam"); | |
| 3699 | + } | |
| 3700 | + | |
| 3701 | + pub(crate) fn release(mut self) { | |
| 3702 | + self.release | |
| 3703 | + .take() | |
| 3704 | + .expect("the abort publication pause was released twice") | |
| 3705 | + .send(()) | |
| 3706 | + .expect("the abort publisher dropped while paused"); | |
| 3707 | + } | |
| 3708 | +} | |
| 3709 | + | |
| 3710 | +#[cfg(all(test, celld_internal_tests))] | |
| 3711 | +pub(crate) fn pause_abort_request_for_test( | |
| 3712 | + request_id: RequestId, | |
| 3713 | +) -> AbortRequestPauseHandleForTest { | |
| 3714 | + let (entered_tx, entered) = std::sync::mpsc::channel(); | |
| 3715 | + let (release, release_rx) = std::sync::mpsc::channel(); | |
| 3716 | + let previous = ABORT_REQUEST_PAUSE_FOR_TEST | |
| 3717 | + .lock() | |
| 3718 | + .unwrap() | |
| 3719 | + .replace((request_id, entered_tx, release_rx)); | |
| 3720 | + assert!( | |
| 3721 | + previous.is_none(), | |
| 3722 | + "an abort publication pause is already armed" | |
| 3723 | + ); | |
| 3724 | + AbortRequestPauseHandleForTest { | |
| 3725 | + entered, | |
| 3726 | + release: Some(release), | |
| 3727 | + } | |
| 3728 | +} | |
| 3729 | + | |
| 3730 | +#[cfg(all(test, celld_internal_tests))] | |
| 3731 | +pub(crate) fn pause_abort_request_if_armed_for_test(request_id: RequestId) { | |
| 3732 | + let pause = { | |
| 3733 | + let mut pause = ABORT_REQUEST_PAUSE_FOR_TEST.lock().unwrap(); | |
| 3734 | + if pause | |
| 3735 | + .as_ref() | |
| 3736 | + .is_some_and(|(expected, _, _)| *expected == request_id) | |
| 3737 | + { | |
| 3738 | + pause.take() | |
| 3739 | + } else { | |
| 3740 | + None | |
| 3741 | + } | |
| 3742 | + }; | |
| 3743 | + if let Some((_, entered, release)) = pause { | |
| 3744 | + entered | |
| 3745 | + .send(()) | |
| 3746 | + .expect("the abort publication test dropped its observer"); | |
| 3747 | + release | |
| 3748 | + .recv() | |
| 3749 | + .expect("the abort publication test dropped its release"); | |
| 3750 | + } | |
| 3751 | +} | |
| 3752 | + | |
| 3753 | +#[cfg(all(test, celld_internal_tests))] | |
| 3754 | +pub(crate) fn request_cancellation_state_for_test(request_id: RequestId) -> (bool, bool) { | |
| 3755 | + ( | |
| 3756 | + pending_aborts().lock().unwrap().contains(&request_id), | |
| 3757 | + cancelled_requests().lock().unwrap().contains(&request_id), | |
| 3758 | + ) | |
| 3759 | +} | |
| 3760 | + | |
| 3761 | +/// Mark an in-flight request cancelled from any thread. | |
| 3762 | +pub fn abort_request(request_id: RequestId) { | |
| 3763 | + #[cfg(all(test, celld_internal_tests))] | |
| 3764 | + pause_abort_request_if_armed_for_test(request_id); | |
| 3765 | + if pending_aborts().lock().unwrap().insert(request_id) { | |
| 3766 | + PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed); | |
| 3767 | + } | |
| 3768 | +} | |
| 3769 | + | |
| 3770 | +/// Force a cell event to retire for a lifecycle transition. Unlike a client | |
| 3771 | +/// disconnect, shutdown cannot preserve `waitUntil` work because the runtime | |
| 3772 | +/// and its ownership are about to leave this process. | |
| 3773 | +pub fn abort_request_for_shutdown(request_id: RequestId) { | |
| 3774 | + shutdown_aborts().lock().unwrap().insert(request_id); | |
| 3775 | + abort_request(request_id); | |
| 3776 | +} | |
| 3777 | + | |
| 3778 | +pub(crate) fn clear_request_cancellation(request_id: RequestId) { | |
| 3779 | + let _ = take_pending_abort(request_id); | |
| 3780 | + cancelled_requests().lock().unwrap().remove(&request_id); | |
| 3781 | + shutdown_aborts().lock().unwrap().remove(&request_id); | |
| 3782 | +} | |
| 3783 | + | |
| 3784 | +pub fn take_shutdown_cancellation(request_id: Option<RequestId>) -> bool { | |
| 3785 | + request_id.is_some_and(|request_id| shutdown_aborts().lock().unwrap().remove(&request_id)) | |
| 3786 | +} | |
| 3787 | + | |
| 3788 | +#[cfg(celld_internal_tests)] | |
| 3789 | +#[doc(hidden)] | |
| 3790 | +pub fn clear_request_cancellation_for_test(request_id: RequestId) { | |
| 3791 | + clear_request_cancellation(request_id); | |
| 3792 | +} | |
| 3793 | + | |
| 3794 | +fn take_pending_abort(request_id: RequestId) -> bool { | |
| 3795 | + if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 { | |
| 3796 | + return false; | |
| 3797 | + } | |
| 3798 | + if pending_aborts().lock().unwrap().remove(&request_id) { | |
| 3799 | + PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed); | |
| 3800 | + return true; | |
| 3801 | + } | |
| 3802 | + false | |
| 3803 | +} | |
| 3804 | + | |
| 3805 | +pub fn take_request_cancellation(request_id: Option<RequestId>) -> bool { | |
| 3806 | + request_id.is_some_and(|request_id| { | |
| 3807 | + cancelled_requests().lock().unwrap().remove(&request_id) || take_pending_abort(request_id) | |
| 3808 | + }) | |
| 3809 | +} | |
| 3810 | + | |
| 3811 | +fn resolved_promise<'s>( | |
| 3812 | + tc: &mut v8::PinScope<'s, '_>, | |
| 3813 | + value: v8::Local<'s, v8::Value>, | |
| 3814 | +) -> Result<v8::Local<'s, v8::Promise>> { | |
| 3815 | + let resolver = | |
| 3816 | + v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?; | |
| 3817 | + resolver.resolve(tc, value); | |
| 3818 | + Ok(resolver.get_promise(tc)) | |
| 3819 | +} | |
| 3820 | + | |
| 3821 | +fn abort_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) -> Result<bool> { | |
| 3822 | + let function = event_hook(tc, |hooks| &hooks.abort_incoming_request)?; | |
| 3823 | + let request_id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 3824 | + let recv = v8::undefined(tc).into(); | |
| 3825 | + let result = function | |
| 3826 | + .call(tc, recv, &[request_id.into()]) | |
| 3827 | + .ok_or_else(|| anyhow!("__abortIncomingRequest threw"))?; | |
| 3828 | + Ok(result.boolean_value(tc)) | |
| 3829 | +} | |
| 3830 | + | |
| 3831 | +/// The rejection reason of a settled-rejected promise, with a little stack. | |
| 3832 | +fn reject_reason(tc: &mut v8::PinScope, p: v8::Local<v8::Promise>) -> String { | |
| 3833 | + let r = p.result(tc); | |
| 3834 | + let msg = r.to_rust_string_lossy(tc); | |
| 3835 | + let stk = r | |
| 3836 | + .to_object(tc) | |
| 3837 | + .and_then(|o| { | |
| 3838 | + let k = v8::String::new(tc, "stack")?; | |
| 3839 | + o.get(tc, k.into()) | |
| 3840 | + }) | |
| 3841 | + .map(|s| s.to_rust_string_lossy(tc)) | |
| 3842 | + .unwrap_or_default(); | |
| 3843 | + let tail = stk | |
| 3844 | + .lines() | |
| 3845 | + .skip(1) | |
| 3846 | + .take(3) | |
| 3847 | + .map(|l| l.trim()) | |
| 3848 | + .collect::<Vec<_>>() | |
| 3849 | + .join(" <- "); | |
| 3850 | + if tail.is_empty() { | |
| 3851 | + msg | |
| 3852 | + } else { | |
| 3853 | + format!("{msg} [{tail}]") | |
| 3854 | + } | |
| 3855 | +} | |
| 3856 | + | |
| 3857 | +pub struct Engine; | |
| 3858 | +impl Engine { | |
| 3859 | + pub fn init() { | |
| 3860 | + // V8 is process-global, so the guard belongs to the initializer. A | |
| 3861 | + // guard at each caller allowed two callers to each initialize V8 once, | |
| 3862 | + // which poisoned the global state when both ran. | |
| 3863 | + static INIT: std::sync::Once = std::sync::Once::new(); | |
| 3864 | + INIT.call_once(|| { | |
| 3865 | + #[cfg(celld_internal_tests)] | |
| 3866 | + v8::V8::set_flags_from_string("--expose-gc"); | |
| 3867 | + // No `v8::icu::set_common_data_78` call: the rusty_v8 152 prebuilt | |
| 3868 | + // statically links the complete ICU data (full locale tables and | |
| 3869 | + // regex property-of-strings, e.g. /\p{RGI_Emoji}/v — verified | |
| 3870 | + // empirically), so overriding it with an embedded icudtl.dat only | |
| 3871 | + // duplicated 10.8 MB in the binary. The required coverage is | |
| 3872 | + // explicit, so a future v8 bump that reduces the builtin data | |
| 3873 | + // fails rather than silently narrowing it; the fix would be to | |
| 3874 | + // re-embed rusty_v8's `third_party/icu/common/icudtl.dat`, | |
| 3875 | + // 16-byte-aligned. | |
| 3876 | + let platform = v8::new_default_platform(0, false).make_shared(); | |
| 3877 | + v8::V8::initialize_platform(platform); | |
| 3878 | + v8::V8::initialize(); | |
| 3879 | + }); | |
| 3880 | + } | |
| 3881 | +} | |
| 3882 | + | |
| 3883 | +/// Per-worker compatibility switches, derived from the manifest's | |
| 3884 | +/// compatibility date and flags (Workerd compatibility-date.capnp). `Default` | |
| 3885 | +/// is every switch off; production derives real values in `main`. | |
| 3886 | +#[derive(Clone, Copy, Default)] | |
| 3887 | +pub struct Compat { | |
| 3888 | + pub delete_all_deletes_alarm: bool, | |
| 3889 | + /// `js_rpc`: RPC on a Durable Object class that does not extend | |
| 3890 | + /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()). | |
| 3891 | + pub js_rpc: bool, | |
| 3892 | + /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`, | |
| 3893 | + /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/ | |
| 3894 | + /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher). | |
| 3895 | + pub fetcher_get_put_delete: bool, | |
| 3896 | + /// `sqlite_vec`: expose the pre-v1 sqlite-vec extension to SQLite-backed | |
| 3897 | + /// Durable Objects. This switch is explicit and has no date default. | |
| 3898 | + pub sqlite_vec: bool, | |
| 3899 | + /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and | |
| 3900 | + /// a binary message arrives as a `Blob`, per the WHATWG default. Without | |
| 3901 | + /// it celld keeps the historical `"arraybuffer"`. | |
| 3902 | + pub websocket_standard_binary_type: bool, | |
| 3903 | + /// Queue bodies default to JSON on compatibility dates after 2024-03-18; | |
| 3904 | + /// older deployments retain the V8 structured-clone default. | |
| 3905 | + pub queue_json_messages: bool, | |
| 3906 | +} | |
| 3907 | + | |
| 3908 | +/// The resource name the entry module compiles under. It is also the name the | |
| 3909 | +/// entry module is projected under in `/bundle`, so a stack frame and a bundle | |
| 3910 | +/// path name the same file. | |
| 3911 | +const ENTRY_MODULE_NAME: &str = "worker.js"; | |
| 3912 | + | |
| 3913 | +/// A non-main module the worker's main module may import, tagged by how the | |
| 3914 | +/// runtime materializes it. | |
| 3915 | +#[derive(Clone)] | |
| 3916 | +pub enum ModuleSource { | |
| 3917 | + /// UTF-8 content served as `export default "<content>"` (wrangler's Text | |
| 3918 | + /// rule), registered under the given specifier verbatim. | |
| 3919 | + Text(String), | |
| 3920 | + /// JS source compiled as a sibling ES module (Worker Loader multi-module | |
| 3921 | + /// bundles), registered under both `name` and `./name`. | |
| 3922 | + EsModule(String), | |
| 3923 | + /// Wasm bytes served as a module whose default export is the compiled | |
| 3924 | + /// `WebAssembly.Module` (Wrangler's `CompiledWasm` rule), registered | |
| 3925 | + /// under both `name` and `./name`. | |
| 3926 | + Wasm(bytes::Bytes), | |
| 3927 | +} | |
| 3928 | + | |
| 3929 | +/// A Workflow binding keeps the three names distinct across deployment | |
| 3930 | +/// loading, environment construction, and runtime class injection. | |
| 3931 | +pub struct WorkflowBinding { | |
| 3932 | + pub environment: String, | |
| 3933 | + pub workflow: String, | |
| 3934 | + pub class: String, | |
| 3935 | +} | |
| 3936 | + | |
| 3937 | +/// One Queue producer binding in a Worker environment. | |
| 3938 | +#[derive(Clone)] | |
| 3939 | +pub struct QueueBinding { | |
| 3940 | + pub environment: String, | |
| 3941 | + pub queue: String, | |
| 3942 | + pub delivery_delay: u32, | |
| 3943 | +} | |
| 3944 | + | |
| 3945 | +/// One queue's push consumer after the owning script has been resolved. | |
| 3946 | +#[derive(Clone)] | |
| 3947 | +pub struct QueueConsumerRegistration { | |
| 3948 | + pub script: String, | |
| 3949 | + pub config: crate::protocol::QueueConsumerConfig, | |
| 3950 | +} | |
| 3951 | + | |
| 3952 | +pub struct WorkerConfig { | |
| 3953 | + src: String, | |
| 3954 | + pub script_name: String, | |
| 3955 | + do_classes: Vec<String>, | |
| 3956 | + bindings: Vec<(String, String)>, | |
| 3957 | + /// `r2_buckets`: (environment name, bucket name). The bucket name is | |
| 3958 | + /// the key space the binding owns inside the fleet bucket; see [[r2]]. | |
| 3959 | + r2_bindings: Vec<(String, String)>, | |
| 3960 | + /// `d1_databases`: (environment name, stable database identity). The | |
| 3961 | + /// identity addresses the cell that holds the database; see [[d1]]. | |
| 3962 | + d1_bindings: Vec<(String, String)>, | |
| 3963 | + /// `kv_namespaces`: (environment name, namespace identity). The identity is | |
| 3964 | + /// the config's `id` verbatim, and it addresses the namespace's cells; see | |
| 3965 | + /// [[kv]]. | |
| 3966 | + kv_bindings: Vec<(String, String)>, | |
| 3967 | + queue_bindings: Vec<QueueBinding>, | |
| 3968 | + queue_consumers: Vec<QueueConsumerRegistration>, | |
| 3969 | + /// This script declared a consumer in its own manifest. The deployment- | |
| 3970 | + /// wide catalog later replaces `queue_consumers` in every isolate, so the | |
| 3971 | + /// catalog cannot answer whether this particular default export can omit | |
| 3972 | + /// `fetch` and provide only `queue`. | |
| 3973 | + declares_queue_consumer: bool, | |
| 3974 | + workflow_bindings: Vec<WorkflowBinding>, | |
| 3975 | + ai_binding: Option<String>, | |
| 3976 | + vars: Vec<(String, String)>, | |
| 3977 | + node: String, | |
| 3978 | + /// The worker's non-main modules, so the main module can import siblings. | |
| 3979 | + modules: Vec<(String, ModuleSource)>, | |
| 3980 | + compat: Compat, | |
| 3981 | + /// `[[services]]`: (binding name, target script, optional entrypoint). | |
| 3982 | + /// The target runs in this process; see [[service-bindings]]. | |
| 3983 | + services: Vec<(String, String, Option<String>)>, | |
| 3984 | + asset_binding: Option<String>, | |
| 3985 | + /// `env` name of the Worker Loader binding, if this Worker may spawn | |
| 3986 | + /// dynamic isolates. | |
| 3987 | + loader_binding: Option<String>, | |
| 3988 | + /// Ambient outbound authority. Loaded workers may be denied. | |
| 3989 | + egress: EgressPolicy, | |
| 3990 | + /// Extra `env` values a loaded worker was handed, as a JSON object string | |
| 3991 | + /// merged onto its `env`. Loader-only; empty for normal workers. | |
| 3992 | + loader_env: Option<String>, | |
| 3993 | + /// `triggers.crons` from the deployment. Empty for a loaded worker and for | |
| 3994 | + /// any script without cron triggers. | |
| 3995 | + pub crons: Vec<String>, | |
| 3996 | + /// The application generation this configuration belongs to. Every | |
| 3997 | + /// isolate built from it carries the value as a slot, so its host calls | |
| 3998 | + /// resolve against the deployment graph it was built with. | |
| 3999 | + pub generation: crate::generation::GenerationId, | |
| 4000 | + /// The external (`node:*`/`cloudflare:*`) imports of `src`. | |
| 4001 | + /// | |
| 4002 | + /// The scan walks the whole bundle, which an esbuild artifact makes | |
| 4003 | + /// megabytes, and its answer depends only on `src` — a field nothing | |
| 4004 | + /// mutates after construction. It used to run inside `load_config`, | |
| 4005 | + /// so a deployment paid it again on every cell wake and on every | |
| 4006 | + /// stateless pool thread. One `Arc<WorkerConfig>` backs all of those | |
| 4007 | + /// isolates, so scanning here pays it once instead. | |
| 4008 | + main_imports: modules::ExternalImports, | |
| 4009 | + /// The same scan for each `ModuleSource::EsModule` sibling, in the order | |
| 4010 | + /// `es_module_sources` yields them. Read through | |
| 4011 | + /// [`WorkerConfig::es_modules`], which hands a module and its scan out | |
| 4012 | + /// together so no caller can pair a module with another module's scan. | |
| 4013 | + module_imports: Vec<modules::ExternalImports>, | |
| 4014 | +} | |
| 4015 | + | |
| 4016 | +/// The `ModuleSource::EsModule` siblings of a worker, as (name, source). | |
| 4017 | +/// | |
| 4018 | +/// The single definition of that order: `WorkerConfig::new` scans in it and | |
| 4019 | +/// `WorkerConfig::es_modules` zips against it, so the two cannot disagree. | |
| 4020 | +fn es_module_sources(modules: &[(String, ModuleSource)]) -> impl Iterator<Item = (&str, &str)> { | |
| 4021 | + modules.iter().filter_map(|(name, source)| match source { | |
| 4022 | + ModuleSource::EsModule(source) => Some((name.as_str(), source.as_str())), | |
| 4023 | + _ => None, | |
| 4024 | + }) | |
| 4025 | +} | |
| 4026 | + | |
| 4027 | +pub struct WorkerConfigOptions { | |
| 4028 | + pub src: String, | |
| 4029 | + pub script_name: String, | |
| 4030 | + pub do_classes: Vec<String>, | |
| 4031 | + pub bindings: Vec<(String, String)>, | |
| 4032 | + pub r2_bindings: Vec<(String, String)>, | |
| 4033 | + pub d1_bindings: Vec<(String, String)>, | |
| 4034 | + pub kv_bindings: Vec<(String, String)>, | |
| 4035 | + pub queue_bindings: Vec<QueueBinding>, | |
| 4036 | + pub queue_consumers: Vec<crate::protocol::QueueConsumerConfig>, | |
| 4037 | + pub workflow_bindings: Vec<WorkflowBinding>, | |
| 4038 | + pub ai_binding: Option<String>, | |
| 4039 | + pub vars: Vec<(String, String)>, | |
| 4040 | + pub node: String, | |
| 4041 | + pub modules: Vec<(String, ModuleSource)>, | |
| 4042 | + pub compat: Compat, | |
| 4043 | +} | |
| 4044 | + | |
| 4045 | +impl WorkerConfig { | |
| 4046 | + pub fn new(options: WorkerConfigOptions) -> Self { | |
| 4047 | + let WorkerConfigOptions { | |
| 4048 | + src, | |
| 4049 | + script_name, | |
| 4050 | + do_classes, | |
| 4051 | + bindings, | |
| 4052 | + r2_bindings, | |
| 4053 | + d1_bindings, | |
| 4054 | + kv_bindings, | |
| 4055 | + queue_bindings, | |
| 4056 | + queue_consumers, | |
| 4057 | + workflow_bindings, | |
| 4058 | + ai_binding, | |
| 4059 | + vars, | |
| 4060 | + node, | |
| 4061 | + modules, | |
| 4062 | + compat, | |
| 4063 | + } = options; | |
| 4064 | + let main_imports = modules::scan_external_imports(&src); | |
| 4065 | + let module_imports = es_module_sources(&modules) | |
| 4066 | + .map(|(_name, source)| modules::scan_external_imports(source)) | |
| 4067 | + .collect(); | |
| 4068 | + let declares_queue_consumer = !queue_consumers.is_empty(); | |
| 4069 | + let queue_consumers = queue_consumers | |
| 4070 | + .into_iter() | |
| 4071 | + .map(|config| QueueConsumerRegistration { | |
| 4072 | + script: script_name.clone(), | |
| 4073 | + config, | |
| 4074 | + }) | |
| 4075 | + .collect(); | |
| 4076 | + Self { | |
| 4077 | + src, | |
| 4078 | + script_name, | |
| 4079 | + do_classes, | |
| 4080 | + bindings, | |
| 4081 | + r2_bindings, | |
| 4082 | + d1_bindings, | |
| 4083 | + kv_bindings, | |
| 4084 | + queue_bindings, | |
| 4085 | + queue_consumers, | |
| 4086 | + declares_queue_consumer, | |
| 4087 | + workflow_bindings, | |
| 4088 | + ai_binding, | |
| 4089 | + vars, | |
| 4090 | + node, | |
| 4091 | + modules, | |
| 4092 | + compat, | |
| 4093 | + services: Vec::new(), | |
| 4094 | + asset_binding: None, | |
| 4095 | + loader_binding: None, | |
| 4096 | + egress: EgressPolicy::Allow, | |
| 4097 | + loader_env: None, | |
| 4098 | + crons: Vec::new(), | |
| 4099 | + generation: 0, | |
| 4100 | + main_imports, | |
| 4101 | + module_imports, | |
| 4102 | + } | |
| 4103 | + } | |
| 4104 | + | |
| 4105 | + /// Stamp this Worker with the application generation it serves. | |
| 4106 | + pub fn with_generation(mut self, generation: crate::generation::GenerationId) -> Self { | |
| 4107 | + self.generation = generation; | |
| 4108 | + self | |
| 4109 | + } | |
| 4110 | + | |
| 4111 | + pub fn with_queue_consumers(mut self, consumers: Vec<QueueConsumerRegistration>) -> Self { | |
| 4112 | + self.queue_consumers = consumers; | |
| 4113 | + self | |
| 4114 | + } | |
| 4115 | + | |
| 4116 | + /// Every `ModuleSource::EsModule` sibling with its name, its source and | |
| 4117 | + /// its scanned external imports. | |
| 4118 | + fn es_modules(&self) -> impl Iterator<Item = (&str, &str, &modules::ExternalImports)> { | |
| 4119 | + // `zip` would truncate silently if the two ever disagreed, and a | |
| 4120 | + // truncated scan means a sibling links against a stub missing its | |
| 4121 | + // names. Both are filled from `es_module_sources` in `new`, so a | |
| 4122 | + // disagreement is a bug in a future mutator, not a reachable state. | |
| 4123 | + debug_assert_eq!( | |
| 4124 | + es_module_sources(&self.modules).count(), | |
| 4125 | + self.module_imports.len(), | |
| 4126 | + "an ES sibling lost its scanned imports", | |
| 4127 | + ); | |
| 4128 | + es_module_sources(&self.modules) | |
| 4129 | + .zip(&self.module_imports) | |
| 4130 | + .map(|((name, source), imports)| (name, source, imports)) | |
| 4131 | + } | |
| 4132 | + | |
| 4133 | + /// Give this Worker the deployment's cron trigger expressions. | |
| 4134 | + pub fn with_crons(mut self, crons: Vec<String>) -> Self { | |
| 4135 | + self.crons = crons; | |
| 4136 | + self | |
| 4137 | + } | |
| 4138 | + | |
| 4139 | + /// Grant this Worker a Worker Loader binding at `env` name `binding`. | |
| 4140 | + pub fn with_loader(mut self, binding: Option<String>) -> Self { | |
| 4141 | + self.loader_binding = binding; | |
| 4142 | + self | |
| 4143 | + } | |
| 4144 | + | |
| 4145 | + /// Set this Worker's ambient outbound authority (loaded workers only). | |
| 4146 | + fn with_egress(mut self, egress: EgressPolicy) -> Self { | |
| 4147 | + self.egress = egress; | |
| 4148 | + self | |
| 4149 | + } | |
| 4150 | + | |
| 4151 | + /// Merge `env` (a JSON object string) onto a loaded worker's `env`. | |
| 4152 | + fn with_loader_env(mut self, env: Option<String>) -> Self { | |
| 4153 | + self.loader_env = env; | |
| 4154 | + self | |
| 4155 | + } | |
| 4156 | + | |
| 4157 | + /// Declare the service bindings this Worker may call. | |
| 4158 | + pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self { | |
| 4159 | + self.services = services; | |
| 4160 | + self | |
| 4161 | + } | |
| 4162 | + | |
| 4163 | + pub fn with_asset_binding(mut self, binding: Option<String>) -> Self { | |
| 4164 | + self.asset_binding = binding; | |
| 4165 | + self | |
| 4166 | + } | |
| 4167 | +} | |
| 4168 | + | |
| 4169 | +/// The storage authority installed when a cell enters an isolate. | |
| 4170 | +/// | |
| 4171 | +/// The path and epoch form one value because opening either one without the | |
| 4172 | +/// other would let later asynchronous work use the wrong ownership epoch. | |
| 4173 | +#[doc(hidden)] | |
| 4174 | +pub struct CellStorage<'a> { | |
| 4175 | + pub path: &'a str, | |
| 4176 | + pub epoch: u64, | |
| 4177 | + /// The activation's paged VFS, when its restore paged. The file at `path` | |
| 4178 | + /// is then sparse; opening it without this VFS reads holes as data. | |
| 4179 | + pub vfs: Option<&'a str>, | |
| 4180 | +} | |
| 4181 | + | |
| 4182 | +pub struct Worker { | |
| 4183 | + inner: Option<WorkerIsolate>, | |
| 4184 | +} | |
| 4185 | + | |
| 4186 | +pub struct WorkerIsolate { | |
| 4187 | + /// Shared rather than owned: under D1 an isolate belongs to no thread, | |
| 4188 | + /// and a worker enters it by taking its `v8::Locker`. | |
| 4189 | + /// | |
| 4190 | + /// Every `lock()` below blocks until the current holder releases. That is | |
| 4191 | + /// only safe because the pool takes an async permit for this isolate | |
| 4192 | + /// first, so the lock is uncontended by construction; a `lock()` reached | |
| 4193 | + /// without that permit would be a blocking call on a tokio worker. | |
| 4194 | + isolate: v8::SharedIsolate, | |
| 4195 | + /// The one realm this isolate has: its context, and the entry `fetch` | |
| 4196 | + /// that lives in it. | |
| 4197 | + /// | |
| 4198 | + /// It was a `HashMap` keyed by cell, on the premise that a cell needs a | |
| 4199 | + /// realm of its own. It does not, and nothing ever put a second one in. | |
| 4200 | + /// The harness already keys instances by scope (`__cell.instances`), and | |
| 4201 | + /// Durable Objects **share** a context per script rather than getting one | |
| 4202 | + /// each — a context per cell would also duplicate the compiled module per | |
| 4203 | + /// cell, which is most of what sharing an isolate saves. | |
| 4204 | + realm: Realm, | |
| 4205 | + original_heap_limit: usize, | |
| 4206 | + compat: Compat, | |
| 4207 | + /// Identity used to reclaim every dynamic Worker this isolate created. | |
| 4208 | + /// Named Worker Loader identity lives in this isolate's JavaScript heap, | |
| 4209 | + /// so no child can remain charged to the registry after its owner is gone. | |
| 4210 | + loader_owner: LoaderOwner, | |
| 4211 | + /// The storage of the cells this isolate hosts. | |
| 4212 | + /// | |
| 4213 | + /// It lives here, and not in a thread-local, because a driven cell's | |
| 4214 | + /// turns run on whatever tokio worker holds the isolate. See | |
| 4215 | + /// `storage::Cells`. | |
| 4216 | + cells: storage::Cells, | |
| 4217 | +} | |
| 4218 | + | |
| 4219 | +/// An isolate's context and the entry `fetch` that lives in it. | |
| 4220 | +/// | |
| 4221 | +/// `fetch` is here rather than beside the isolate because a function is a | |
| 4222 | +/// value in the realm that created it. | |
| 4223 | +struct Realm { | |
| 4224 | + context: v8::Global<v8::Context>, | |
| 4225 | + fetch: v8::Global<v8::Function>, | |
| 4226 | +} | |
| 4227 | + | |
| 4228 | +impl WorkerIsolate { | |
| 4229 | + /// Take the isolate for one turn, and make the cells it hosts reachable | |
| 4230 | + /// while it is held. | |
| 4231 | + /// | |
| 4232 | + /// The two belong together. The lock is what makes this thread the only | |
| 4233 | + /// one that can touch the isolate, and a cell's SQLite handles are part | |
| 4234 | + /// of what it may touch — so a locker taken without installing them | |
| 4235 | + /// would let a turn reach no storage at all, or another isolate's. | |
| 4236 | + /// Pairing them here is why no call site has to remember. | |
| 4237 | + fn lock(&self) -> (v8::Locker<'_>, storage::Installed) { | |
| 4238 | + (self.isolate.lock(), self.cells.install()) | |
| 4239 | + } | |
| 4240 | + | |
| 4241 | + /// Lift condemnation from an isolate whose heap has drained. | |
| 4242 | + /// | |
| 4243 | + /// `near_heap_limit` latches a flag that nothing used to clear, so a cell | |
| 4244 | + /// that reached its limit once stayed condemned until the process | |
| 4245 | + /// restarted. The flag is re-read here, between turns rather than inside | |
| 4246 | + /// one, because a handler must not see the isolate recover halfway | |
| 4247 | + /// through. | |
| 4248 | + /// | |
| 4249 | + /// A heap still over the line buys one `low_memory_notification` and a | |
| 4250 | + /// second reading. V8 stops collecting once it is past the limit, so a | |
| 4251 | + /// drained isolate holds the dead heap until something allocates again — | |
| 4252 | + /// without the forced collection the reading that decides recovery is a | |
| 4253 | + /// reading of garbage. `HEAP_GC_NUDGE_INTERVAL` bounds the cost. | |
| 4254 | + /// | |
| 4255 | + /// Removing the callback with the original limit puts back the limit | |
| 4256 | + /// `near_heap_limit` raised; re-adding it re-arms the guard. | |
| 4257 | + fn recover_heap(&self, locker: &mut v8::Locker<'_>) { | |
| 4258 | + let Some(state) = locker.get_slot::<Arc<HeapLimitState>>().cloned() else { | |
| 4259 | + return; | |
| 4260 | + }; | |
| 4261 | + if !state.excessively_exceeded.load(Ordering::Relaxed) { | |
| 4262 | + return; | |
| 4263 | + } | |
| 4264 | + if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE { | |
| 4265 | + if !state.due_for_gc_nudge() { | |
| 4266 | + return; | |
| 4267 | + } | |
| 4268 | + locker.low_memory_notification(); | |
| 4269 | + if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE { | |
| 4270 | + return; | |
| 4271 | + } | |
| 4272 | + } | |
| 4273 | + state.excessively_exceeded.store(false, Ordering::Relaxed); | |
| 4274 | + let data = Arc::as_ptr(&state) as *mut HeapLimitState as *mut std::ffi::c_void; | |
| 4275 | + locker.remove_near_heap_limit_callback(near_heap_limit, state.limit); | |
| 4276 | + locker.add_near_heap_limit_callback(near_heap_limit, data); | |
| 4277 | + tracing::info!( | |
| 4278 | + event = "isolate_heap_recovered", | |
| 4279 | + limit_bytes = state.limit, | |
| 4280 | + "isolate heap fell back under its limit, so it serves again" | |
| 4281 | + ); | |
| 4282 | + } | |
| 4283 | + | |
| 4284 | + /// Localise the realm for one turn. | |
| 4285 | + /// | |
| 4286 | + /// **Taking the scope is the point.** Reaching a realm means touching | |
| 4287 | + /// `Global` handles, which on a shared isolate is only legal while its | |
| 4288 | + /// `Locker` is held — and there is no scope to pass until the isolate is | |
| 4289 | + /// locked. So the requirement is structural rather than a comment asking | |
| 4290 | + /// callers to remember it. It was a comment, and the one call site that | |
| 4291 | + /// forgot cloned two `Global`s a line too early; the panic happened | |
| 4292 | + /// inside a spawned request task, where tokio swallowed it and it | |
| 4293 | + /// surfaced only as a poisoned mutex on every later request. | |
| 4294 | + fn realm<'s>(&self, hs: &mut v8::PinScope<'s, '_, ()>) -> Entered<'s> { | |
| 4295 | + Entered { | |
| 4296 | + context: v8::Local::new(hs, &self.realm.context), | |
| 4297 | + fetch: v8::Local::new(hs, &self.realm.fetch), | |
| 4298 | + } | |
| 4299 | + } | |
| 4300 | +} | |
| 4301 | + | |
| 4302 | +/// One realm, entered. Valid only for the scope that produced it, which is | |
| 4303 | +/// what ties it to the isolate being locked. | |
| 4304 | +struct Entered<'s> { | |
| 4305 | + context: v8::Local<'s, v8::Context>, | |
| 4306 | + fetch: v8::Local<'s, v8::Function>, | |
| 4307 | +} | |
| 4308 | + | |
| 4309 | +impl std::ops::Deref for Worker { | |
| 4310 | + type Target = WorkerIsolate; | |
| 4311 | + | |
| 4312 | + fn deref(&self) -> &Self::Target { | |
| 4313 | + self.inner.as_ref().expect("Worker isolate unavailable") | |
| 4314 | + } | |
| 4315 | +} | |
| 4316 | + | |
| 4317 | +impl std::ops::DerefMut for Worker { | |
| 4318 | + fn deref_mut(&mut self) -> &mut Self::Target { | |
| 4319 | + self.inner.as_mut().expect("Worker isolate unavailable") | |
| 4320 | + } | |
| 4321 | +} | |
| 4322 | + | |
| 4323 | +const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024; | |
| 4324 | +const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024; | |
| 4325 | + | |
| 4326 | +/// Share of the heap limit past which an isolate takes on no more retained | |
| 4327 | +/// state. It sits below the near-limit callback on purpose: this refuses one | |
| 4328 | +/// hibernatable socket while the isolate still works, where the callback | |
| 4329 | +/// fires once it no longer does. | |
| 4330 | +const HEAP_ADMISSION_SHARE: f64 = 0.9; | |
| 4331 | + | |
| 4332 | +/// Share of the heap limit under which a condemned isolate is condemned no | |
| 4333 | +/// more. Under `HEAP_ADMISSION_SHARE` by enough that recovery does not | |
| 4334 | +/// immediately re-admit into a heap that is about to fail again. | |
| 4335 | +const HEAP_RECOVERY_SHARE: f64 = 0.75; | |
| 4336 | + | |
| 4337 | +/// The shortest gap between two collections forced by `recover_heap`. A full | |
| 4338 | +/// collection of a 128 MB heap costs tens of milliseconds and a loaded cell | |
| 4339 | +/// begins many turns each second, so an unbounded nudge would spend more of a | |
| 4340 | +/// condemned isolate on collecting than on serving. | |
| 4341 | +const HEAP_GC_NUDGE_INTERVAL: Duration = Duration::from_secs(1); | |
| 4342 | + | |
| 4343 | +struct HeapLimitState { | |
| 4344 | + excessively_exceeded: AtomicBool, | |
| 4345 | + /// The limit V8 gave this isolate, before any emergency extension. | |
| 4346 | + /// Recovery measures against this one because `near_heap_limit` raises | |
| 4347 | + /// the current one. | |
| 4348 | + limit: usize, | |
| 4349 | + last_gc_nudge: Mutex<Option<Instant>>, | |
| 4350 | + /// An explicit admission refusal cannot use the condemnation flag because | |
| 4351 | + /// recovery clears that flag at the next turn. | |
| 4352 | + #[cfg(celld_internal_tests)] | |
| 4353 | + forced_admission_refusal: AtomicBool, | |
| 4354 | +} | |
| 4355 | + | |
| 4356 | +impl HeapLimitState { | |
| 4357 | + /// Whether a condemned isolate can pay for another forced collection. | |
| 4358 | + /// | |
| 4359 | + /// Rate-limited rather than once for each condemnation: the load can | |
| 4360 | + /// still be live at the first reading and gone by the second, so a | |
| 4361 | + /// one-shot nudge would leave the cell condemned exactly as before. | |
| 4362 | + fn due_for_gc_nudge(&self) -> bool { | |
| 4363 | + let Ok(mut last) = self.last_gc_nudge.lock() else { | |
| 4364 | + return false; | |
| 4365 | + }; | |
| 4366 | + let now = Instant::now(); | |
| 4367 | + if last.is_some_and(|at| now.duration_since(at) < HEAP_GC_NUDGE_INTERVAL) { | |
| 4368 | + return false; | |
| 4369 | + } | |
| 4370 | + *last = Some(now); | |
| 4371 | + true | |
| 4372 | + } | |
| 4373 | +} | |
| 4374 | + | |
| 4375 | +#[cfg(celld_internal_tests)] | |
| 4376 | +fn admission_refusal_forced(state: &HeapLimitState) -> bool { | |
| 4377 | + state.forced_admission_refusal.load(Ordering::Relaxed) | |
| 4378 | +} | |
| 4379 | + | |
| 4380 | +#[cfg(not(celld_internal_tests))] | |
| 4381 | +fn admission_refusal_forced(_state: &HeapLimitState) -> bool { | |
| 4382 | + false | |
| 4383 | +} | |
| 4384 | + | |
| 4385 | +type SerializedPut = (String, Vec<u8>); | |
| 4386 | +type PendingPuts = HashMap<String, Vec<SerializedPut>>; | |
| 4387 | + | |
| 4388 | +/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a | |
| 4389 | +/// Worker Loader can hand a loaded worker `Deny` (globalOutbound: null) so its | |
| 4390 | +/// global `fetch()` throws and it must reach the world through `env` | |
| 4391 | +/// capabilities. | |
| 4392 | +#[derive(Clone, Copy, Default, PartialEq)] | |
| 4393 | +enum EgressPolicy { | |
| 4394 | + #[default] | |
| 4395 | + Allow, | |
| 4396 | + Deny, | |
| 4397 | +} | |
| 4398 | + | |
| 4399 | +#[derive(Default)] | |
| 4400 | +struct ActorRuntimeState { | |
| 4401 | + promises: std::sync::Mutex<PromiseMap>, | |
| 4402 | + termination: std::sync::Mutex<Option<ExecutionTermination>>, | |
| 4403 | + pending_puts: std::sync::Mutex<PendingPuts>, | |
| 4404 | + io_contexts: std::sync::Mutex<HashMap<u64, Weak<IoContext>>>, | |
| 4405 | + egress: EgressPolicy, | |
| 4406 | + event_hooks: OnceLock<EventHooks>, | |
| 4407 | +} | |
| 4408 | + | |
| 4409 | +/// The harness functions the host calls on the boundary of every cell event. | |
| 4410 | +/// | |
| 4411 | +/// `harness.js` installs `__beginEvent`, `__endEvent`, `__advanceIoTime`, and | |
| 4412 | +/// `__abortIncomingRequest` on the global once per isolate and never replaces | |
| 4413 | +/// them. Reading each one back by name per event costs a fresh `v8::String` | |
| 4414 | +/// plus a lookup on the global object for a result that cannot change; | |
| 4415 | +/// holding the functions removes the string and the lookup together. | |
| 4416 | +/// | |
| 4417 | +/// The four are resolved together on purpose. A partial resolution would | |
| 4418 | +/// leave one hook still reached by name, so `install_harness` builds all four | |
| 4419 | +/// or the isolate fails to load, and no caller has to remember which of them | |
| 4420 | +/// is cached. | |
| 4421 | +/// | |
| 4422 | +/// A `v8::Global` is only valid in the isolate that created it, which is why | |
| 4423 | +/// this hangs off `ActorRuntimeState` — an isolate slot — and not off a | |
| 4424 | +/// process-wide `static`. `ModuleRegistry` documents the same constraint. | |
| 4425 | +struct EventHooks { | |
| 4426 | + begin_event: v8::Global<v8::Function>, | |
| 4427 | + end_event: v8::Global<v8::Function>, | |
| 4428 | + advance_io_time: v8::Global<v8::Function>, | |
| 4429 | + abort_incoming_request: v8::Global<v8::Function>, | |
| 4430 | +} | |
| 4431 | + | |
| 4432 | +/// One cached hook, opened into `scope`. | |
| 4433 | +/// | |
| 4434 | +/// `pick` names the hook rather than a getter per hook, so the four call | |
| 4435 | +/// sites stay one line each. | |
| 4436 | +fn event_hook<'s>( | |
| 4437 | + scope: &mut v8::PinScope<'s, '_>, | |
| 4438 | + pick: fn(&EventHooks) -> &v8::Global<v8::Function>, | |
| 4439 | +) -> Result<v8::Local<'s, v8::Function>> { | |
| 4440 | + let state = actor_runtime_state(scope); | |
| 4441 | + let hooks = state | |
| 4442 | + .event_hooks | |
| 4443 | + .get() | |
| 4444 | + .ok_or_else(|| anyhow!("event hooks are not installed"))?; | |
| 4445 | + Ok(v8::Local::new(scope, pick(hooks))) | |
| 4446 | +} | |
| 4447 | + | |
| 4448 | +/// Advance the isolate clock at an I/O boundary before JavaScript resumes. | |
| 4449 | +/// | |
| 4450 | +/// The cached hook is installed before user code loads, so a script cannot | |
| 4451 | +/// replace the function that owns this invariant. Each caller is a complete | |
| 4452 | +/// JavaScript turn caused by external input or by a completed native op. | |
| 4453 | +fn advance_io_time(scope: &mut v8::PinScope) { | |
| 4454 | + let hook = event_hook(scope, |hooks| &hooks.advance_io_time) | |
| 4455 | + .expect("the isolate clock hook is installed"); | |
| 4456 | + let timestamp = v8::Number::new(scope, unix_now_ms() as f64); | |
| 4457 | + let recv = v8::undefined(scope).into(); | |
| 4458 | + hook.call(scope, recv, &[timestamp.into()]) | |
| 4459 | + .expect("the isolate clock hook cannot throw"); | |
| 4460 | +} | |
| 4461 | + | |
| 4462 | +impl ActorRuntimeState { | |
| 4463 | + fn io_context(&self, id: u64) -> Option<Arc<IoContext>> { | |
| 4464 | + let mut contexts = self.io_contexts.lock().unwrap(); | |
| 4465 | + let context = contexts.get(&id)?.upgrade(); | |
| 4466 | + if context.is_none() { | |
| 4467 | + contexts.remove(&id); | |
| 4468 | + } | |
| 4469 | + context | |
| 4470 | + } | |
| 4471 | +} | |
| 4472 | + | |
| 4473 | +struct ExecutionTermination { | |
| 4474 | + error: String, | |
| 4475 | + actor_scope: Option<String>, | |
| 4476 | + context_id: Option<u64>, | |
| 4477 | +} | |
| 4478 | + | |
| 4479 | +fn finish_terminated_actor_event(scope: &mut v8::PinScope, context: &IoContext) { | |
| 4480 | + finish_retired_input_gate_context(scope, context); | |
| 4481 | +} | |
| 4482 | + | |
| 4483 | +fn finish_retired_input_gate_context(scope: &mut v8::PinScope, context: &IoContext) { | |
| 4484 | + context.force_retire_cross_entry_gates(); | |
| 4485 | + let _ = abandon_context_input_gates(context); | |
| 4486 | + let context_id = context.continuation_id().unwrap_or_default(); | |
| 4487 | + retire_input_gate_js_context(scope, context_id); | |
| 4488 | +} | |
| 4489 | + | |
| 4490 | +fn retire_input_gate_js_context(scope: &mut v8::PinScope, context_id: u64) { | |
| 4491 | + let global = scope.get_current_context().global(scope); | |
| 4492 | + let key = v8::String::new(scope, "__retireInputGateContext").unwrap(); | |
| 4493 | + let Some(value) = global.get(scope, key.into()) else { | |
| 4494 | + return; | |
| 4495 | + }; | |
| 4496 | + let Ok(function) = v8::Local::<v8::Function>::try_from(value) else { | |
| 4497 | + return; | |
| 4498 | + }; | |
| 4499 | + let context_id = v8::String::new(scope, &context_id.to_string()).unwrap(); | |
| 4500 | + let recv = v8::undefined(scope).into(); | |
| 4501 | + let _ = function.call(scope, recv, &[context_id.into()]); | |
| 4502 | +} | |
| 4503 | + | |
| 4504 | +/// Compile and run a JS expression that evaluates to a function. | |
| 4505 | +fn compile_fn<'s>( | |
| 4506 | + scope: &mut v8::PinScope<'s, '_>, | |
| 4507 | + src: &str, | |
| 4508 | +) -> Result<v8::Local<'s, v8::Function>> { | |
| 4509 | + let code = v8::String::new(scope, src).unwrap(); | |
| 4510 | + let script = | |
| 4511 | + v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compile shim: {src}"))?; | |
| 4512 | + let value = script | |
| 4513 | + .run(scope) | |
| 4514 | + .ok_or_else(|| anyhow!("run shim: {src}"))?; | |
| 4515 | + value | |
| 4516 | + .try_into() | |
| 4517 | + .map_err(|_| anyhow!("shim is not a function: {src}")) | |
| 4518 | +} | |
| 4519 | + | |
| 4520 | +/// Whether `register_entrypoints` put `name` in the `__cell.<registry>` | |
| 4521 | +/// object (e.g. `entrypoints`, `doExports`). | |
| 4522 | +fn cell_registry_has(scope: &mut v8::PinScope, registry: &str, name: &str) -> Result<bool> { | |
| 4523 | + let context = scope.get_current_context(); | |
| 4524 | + let global = context.global(scope); | |
| 4525 | + let cell_key = static_key(scope, &v8_strings::CELL); | |
| 4526 | + let registry_key = v8::String::new(scope, registry).unwrap(); | |
| 4527 | + let registry_obj = global | |
| 4528 | + .get(scope, cell_key.into()) | |
| 4529 | + .and_then(|value| value.to_object(scope)) | |
| 4530 | + .and_then(|cell| cell.get(scope, registry_key.into())) | |
| 4531 | + .and_then(|value| value.to_object(scope)) | |
| 4532 | + .ok_or_else(|| anyhow!("missing __cell.{registry} registry"))?; | |
| 4533 | + let name_key = v8::String::new(scope, name).unwrap(); | |
| 4534 | + Ok(registry_obj | |
| 4535 | + .has_own_property(scope, name_key.into()) | |
| 4536 | + .unwrap_or(false)) | |
| 4537 | +} | |
| 4538 | + | |
| 4539 | +fn take_execution_termination_in_context( | |
| 4540 | + scope: &mut v8::PinScope, | |
| 4541 | + context: Option<&IoContext>, | |
| 4542 | +) -> Option<anyhow::Error> { | |
| 4543 | + let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned(); | |
| 4544 | + let termination = state | |
| 4545 | + .as_ref() | |
| 4546 | + .and_then(|state| state.termination.lock().ok()?.take()); | |
| 4547 | + let is_terminating = scope.is_execution_terminating(); | |
| 4548 | + if termination.is_some() || is_terminating { | |
| 4549 | + scope.cancel_terminate_execution(); | |
| 4550 | + } | |
| 4551 | + if let Some(termination) = termination { | |
| 4552 | + if termination.actor_scope.is_some() { | |
| 4553 | + if let Some(context_id) = termination.context_id { | |
| 4554 | + if let Some(context) = state | |
| 4555 | + .as_ref() | |
| 4556 | + .and_then(|state| state.io_context(context_id)) | |
| 4557 | + { | |
| 4558 | + finish_terminated_actor_event(scope, &context); | |
| 4559 | + } | |
| 4560 | + } else if let Some(context) = context { | |
| 4561 | + finish_terminated_actor_event(scope, context); | |
| 4562 | + } else { | |
| 4563 | + finish_terminated_actor_event(scope, ¤t_context()); | |
| 4564 | + } | |
| 4565 | + } | |
| 4566 | + return Some(anyhow!(termination.error)); | |
| 4567 | + } | |
| 4568 | + is_terminating.then(|| anyhow!("JavaScript execution was terminated")) | |
| 4569 | +} | |
| 4570 | + | |
| 4571 | +fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> { | |
| 4572 | + take_execution_termination_in_context(scope, None) | |
| 4573 | +} | |
| 4574 | + | |
| 4575 | +extern "C" fn near_heap_limit( | |
| 4576 | + data: *mut std::ffi::c_void, | |
| 4577 | + current_heap_limit: usize, | |
| 4578 | + _initial_heap_limit: usize, | |
| 4579 | +) -> usize { | |
| 4580 | + // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop | |
| 4581 | + // removes this callback before the isolate (and its slots) are destroyed. | |
| 4582 | + let state = unsafe { &*(data as *const HeapLimitState) }; | |
| 4583 | + state.excessively_exceeded.store(true, Ordering::Relaxed); | |
| 4584 | + // V8 fatally aborts the process if a near-limit callback does not extend | |
| 4585 | + // the limit. This reserve lets JS observe condemnation and unwind. | |
| 4586 | + // | |
| 4587 | + // The extension must also cover one allocation as large as the limit | |
| 4588 | + // itself: flattening a 128 MiB cons string asks V8 for a single 128 MiB | |
| 4589 | + // block, and V8 re-invokes this callback across last-resort GC rounds | |
| 4590 | + // only unreliably (under parallel load it often stops after one round | |
| 4591 | + // and aborts the process). Doubling the original limit makes the first | |
| 4592 | + // invocation sufficient on its own; `recover_heap` and `Drop` still | |
| 4593 | + // restore the original limit, so nothing else changes. | |
| 4594 | + current_heap_limit | |
| 4595 | + .saturating_add(V8_HEAP_EMERGENCY_BYTES) | |
| 4596 | + .max(state.limit.saturating_mul(2)) | |
| 4597 | +} | |
| 4598 | + | |
| 4599 | +/// Live heap use, as a share of `limit`. | |
| 4600 | +fn heap_share(isolate: &mut v8::Isolate, limit: usize) -> f64 { | |
| 4601 | + if limit == 0 { | |
| 4602 | + return 0.0; | |
| 4603 | + } | |
| 4604 | + isolate.get_heap_statistics().used_heap_size() as f64 / limit as f64 | |
| 4605 | +} | |
| 4606 | + | |
| 4607 | +fn v8_heap_limit_bytes() -> usize { | |
| 4608 | + crate::env_vars::positive::<usize>("CELLD_V8_HEAP_LIMIT_MB") | |
| 4609 | + .expect("validated CELLD_V8_HEAP_LIMIT_MB") | |
| 4610 | + .map(|megabytes| { | |
| 4611 | + megabytes | |
| 4612 | + .checked_mul(1024 * 1024) | |
| 4613 | + .expect("validated CELLD_V8_HEAP_LIMIT_MB range") | |
| 4614 | + }) | |
| 4615 | + .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES) | |
| 4616 | +} | |
| 4617 | + | |
| 4618 | +impl Drop for WorkerIsolate { | |
| 4619 | + fn drop(&mut self) { | |
| 4620 | + // Detach children while their IDs are still attributable to this | |
| 4621 | + // parent, but do not drop their V8 isolates while this one is entered. | |
| 4622 | + // In-flight child calls hold their own receiver clones and finish | |
| 4623 | + // normally; this removes only the registry's ownership reference. | |
| 4624 | + let loaded_children = take_loader_owner(self.loader_owner); | |
| 4625 | + let limit = self.original_heap_limit; | |
| 4626 | + { | |
| 4627 | + let (mut locker, _cells) = self.lock(); | |
| 4628 | + locker.remove_near_heap_limit_callback(near_heap_limit, limit); | |
| 4629 | + } | |
| 4630 | + drop(loaded_children); | |
| 4631 | + } | |
| 4632 | +} | |
| 4633 | + | |
| 4634 | +/// One in-flight request inside a shared isolate. | |
| 4635 | +/// | |
| 4636 | +/// Owned by the request's own tokio task, which is why every field is | |
| 4637 | +/// `Send`: the task suspends between turns and can resume on any worker, | |
| 4638 | +/// then re-enters the isolate it is affiliated with. | |
| 4639 | +/// Where a finished handler's result goes, and in what shape. | |
| 4640 | +/// | |
| 4641 | +/// A fetch answers an `HttpResponse` and an entrypoint RPC answers bytes. | |
| 4642 | +/// Everything between — the turn loop, the op region, cancellation, the | |
| 4643 | +/// budget — is identical, so the difference lives here rather than in two | |
| 4644 | +/// copies of `drive`. | |
| 4645 | +pub enum Answer { | |
| 4646 | + Fetch(tokio::sync::oneshot::Sender<Result<HttpResponse>>), | |
| 4647 | + Rpc(tokio::sync::oneshot::Sender<Result<Vec<u8>>>), | |
| 4648 | + Queue(tokio::sync::oneshot::Sender<Result<QueueDispatchResult>>), | |
| 4649 | + /// A DO method call, which answers a value rather than a response. | |
| 4650 | + CellRpc(tokio::sync::oneshot::Sender<Result<RpcOutcome>>), | |
| 4651 | + /// A `webSocketMessage`, which answers the frames the output gate held | |
| 4652 | + /// and the write they are gated on. | |
| 4653 | + WsMessage(tokio::sync::oneshot::Sender<Result<WsDispatch>>), | |
| 4654 | + /// An event whose result is that it finished: `webSocketOpen`, | |
| 4655 | + /// `webSocketClose`. It answers the position its writes reached, so the | |
| 4656 | + /// shell can open the barrier they need. | |
| 4657 | + Ack(tokio::sync::oneshot::Sender<Result<Option<u64>>>), | |
| 4658 | + /// An alarm, which answers whatever alarm the handler left armed. | |
| 4659 | + Alarm(tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>), | |
| 4660 | +} | |
| 4661 | + | |
| 4662 | +impl Answer { | |
| 4663 | + /// Send an error, whichever shape the caller is waiting for. | |
| 4664 | + fn fail(self, error: anyhow::Error) { | |
| 4665 | + let _ = self.fail_with_arm_gates(error, Vec::new()); | |
| 4666 | + } | |
| 4667 | + | |
| 4668 | + fn fail_with_arm_gates( | |
| 4669 | + self, | |
| 4670 | + error: anyhow::Error, | |
| 4671 | + gates: Vec<ArmGateRx>, | |
| 4672 | + ) -> Option<GatedReplyRx> { | |
| 4673 | + match self { | |
| 4674 | + Answer::Fetch(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 4675 | + Answer::Rpc(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 4676 | + Answer::Queue(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 4677 | + Answer::CellRpc(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 4678 | + Answer::WsMessage(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 4679 | + Answer::Ack(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 4680 | + Answer::Alarm(reply) => send_answer_after_arm_gates(reply, Err(error), gates), | |
| 4681 | + } | |
| 4682 | + } | |
| 4683 | +} | |
| 4684 | + | |
| 4685 | +async fn await_arm_gates(gates: Vec<ArmGateRx>) -> Result<(), String> { | |
| 4686 | + let mut first_failure = None; | |
| 4687 | + for gate in gates { | |
| 4688 | + let failure = match gate.await { | |
| 4689 | + Ok(Ok(())) => None, | |
| 4690 | + Ok(Err(error)) => Some(error), | |
| 4691 | + Err(_) => Some("wake-entry gate task dropped".into()), | |
| 4692 | + }; | |
| 4693 | + if first_failure.is_none() { | |
| 4694 | + first_failure = failure; | |
| 4695 | + } | |
| 4696 | + } | |
| 4697 | + match first_failure { | |
| 4698 | + Some(failure) => Err(failure), | |
| 4699 | + None => Ok(()), | |
| 4700 | + } | |
| 4701 | +} | |
| 4702 | + | |
| 4703 | +fn send_answer_after_arm_gates<T: Send + 'static>( | |
| 4704 | + mut reply: tokio::sync::oneshot::Sender<Result<T>>, | |
| 4705 | + value: Result<T>, | |
| 4706 | + gates: Vec<ArmGateRx>, | |
| 4707 | +) -> Option<GatedReplyRx> { | |
| 4708 | + if gates.is_empty() { | |
| 4709 | + drop(reply.send(value)); | |
| 4710 | + return None; | |
| 4711 | + } | |
| 4712 | + let (completed, completion) = tokio::sync::oneshot::channel(); | |
| 4713 | + let (cancel, mut cancelled) = tokio::sync::oneshot::channel(); | |
| 4714 | + #[cfg(celld_internal_tests)] | |
| 4715 | + let drop_task = asyncrt::services() | |
| 4716 | + .wake_entry() | |
| 4717 | + .drop_next_gated_reply_task | |
| 4718 | + .swap(false, Ordering::AcqRel); | |
| 4719 | + asyncrt::spawn(async move { | |
| 4720 | + #[cfg(celld_internal_tests)] | |
| 4721 | + if drop_task { | |
| 4722 | + return; | |
| 4723 | + } | |
| 4724 | + enum GateWait { | |
| 4725 | + Completed(Result<(), String>), | |
| 4726 | + CallerClosed, | |
| 4727 | + Cancelled, | |
| 4728 | + DriverDropped, | |
| 4729 | + } | |
| 4730 | + let gate_wait = { | |
| 4731 | + let mut waiting = Box::pin(await_arm_gates(gates)); | |
| 4732 | + let result = asyncrt::select_biased! { | |
| 4733 | + "a completed gate aggregate wins a tie with caller cancellation"; | |
| 4734 | + result = &mut waiting => GateWait::Completed(result), | |
| 4735 | + cancellation = async { | |
| 4736 | + asyncrt::select_biased! { | |
| 4737 | + "a closed caller wins a tie with an explicit cancellation signal"; | |
| 4738 | + _ = reply.closed() => GateWait::CallerClosed, | |
| 4739 | + cancelled = &mut cancelled => match cancelled { | |
| 4740 | + Ok(()) => GateWait::Cancelled, | |
| 4741 | + Err(_) => GateWait::DriverDropped, | |
| 4742 | + }, | |
| 4743 | + } | |
| 4744 | + } => cancellation, | |
| 4745 | + }; | |
| 4746 | + // On either cancellation path this drops every unobserved gate | |
| 4747 | + // receiver before the completion becomes visible to the driver. | |
| 4748 | + drop(waiting); | |
| 4749 | + result | |
| 4750 | + }; | |
| 4751 | + let value = match gate_wait { | |
| 4752 | + GateWait::Completed(gate_result) => match (value, gate_result) { | |
| 4753 | + (value, Ok(())) => value, | |
| 4754 | + (Ok(_), Err(error)) => Err(anyhow!("wake-entry gate: {error}")), | |
| 4755 | + (Err(primary), Err(error)) => { | |
| 4756 | + tracing::error!( | |
| 4757 | + event = "wake_entry_gate_failed_after_handler_error", | |
| 4758 | + handler_error = %primary, | |
| 4759 | + gate_error = %error, | |
| 4760 | + ); | |
| 4761 | + Err(primary.context(format!("wake-entry gate also failed: {error}"))) | |
| 4762 | + } | |
| 4763 | + }, | |
| 4764 | + GateWait::CallerClosed => { | |
| 4765 | + let failure = value | |
| 4766 | + .as_ref() | |
| 4767 | + .err() | |
| 4768 | + .map(|error| crate::telemetry::cap_error(format!("{error:#}"))); | |
| 4769 | + drop(value); | |
| 4770 | + let _ = completed.send(GatedReplyCompletion::CallerClosed { failure }); | |
| 4771 | + return; | |
| 4772 | + } | |
| 4773 | + // The driver observed a request cancellation after the handler | |
| 4774 | + // fixed its reply. Do not enter JavaScript again: the handler is | |
| 4775 | + // already over. A successful answer becomes a disconnect error, | |
| 4776 | + // while an existing handler error remains the primary failure. | |
| 4777 | + GateWait::Cancelled => match value { | |
| 4778 | + Ok(_) => Err(anyhow!("The client has disconnected")), | |
| 4779 | + Err(primary) => Err(primary), | |
| 4780 | + }, | |
| 4781 | + // Dropping the driver drops both halves of its completion handle. | |
| 4782 | + // Release every detached resource, but do not let an abandoned | |
| 4783 | + // driver manufacture a reply that nothing owns any longer. | |
| 4784 | + GateWait::DriverDropped => { | |
| 4785 | + drop(value); | |
| 4786 | + return; | |
| 4787 | + } | |
| 4788 | + }; | |
| 4789 | + let failure = value | |
| 4790 | + .as_ref() | |
| 4791 | + .err() | |
| 4792 | + .map(|error| crate::telemetry::cap_error(format!("{error:#}"))); | |
| 4793 | + let completion = match reply.send(value) { | |
| 4794 | + Ok(()) => GatedReplyCompletion::Sent { failure }, | |
| 4795 | + Err(value) => { | |
| 4796 | + drop(value); | |
| 4797 | + GatedReplyCompletion::CallerClosed { failure } | |
| 4798 | + } | |
| 4799 | + }; | |
| 4800 | + let _ = completed.send(completion); | |
| 4801 | + }) | |
| 4802 | + .detach(); | |
| 4803 | + Some(GatedReplyRx { | |
| 4804 | + completion, | |
| 4805 | + cancel: Some(cancel), | |
| 4806 | + }) | |
| 4807 | +} | |
| 4808 | + | |
| 4809 | +pub(crate) enum GatedReplyCompletion { | |
| 4810 | + /// The final reply value is now visible to the receiver. | |
| 4811 | + Sent { failure: Option<String> }, | |
| 4812 | + /// The receiver disappeared, so no reply remains to deliver. | |
| 4813 | + CallerClosed { failure: Option<String> }, | |
| 4814 | +} | |
| 4815 | + | |
| 4816 | +pub(crate) struct GatedReplyRx { | |
| 4817 | + completion: tokio::sync::oneshot::Receiver<GatedReplyCompletion>, | |
| 4818 | + cancel: Option<tokio::sync::oneshot::Sender<()>>, | |
| 4819 | +} | |
| 4820 | + | |
| 4821 | +impl GatedReplyRx { | |
| 4822 | + /// Stop waiting on event gates after a request cancellation. The detached | |
| 4823 | + /// task owns the reply value and gate receivers, so it performs their | |
| 4824 | + /// ordered cleanup and reports completion back to the driver. | |
| 4825 | + pub(crate) fn cancel(&mut self) { | |
| 4826 | + if let Some(cancel) = self.cancel.take() { | |
| 4827 | + let _ = cancel.send(()); | |
| 4828 | + } | |
| 4829 | + } | |
| 4830 | +} | |
| 4831 | + | |
| 4832 | +impl std::future::Future for GatedReplyRx { | |
| 4833 | + type Output = Result<GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>; | |
| 4834 | + | |
| 4835 | + fn poll( | |
| 4836 | + self: Pin<&mut Self>, | |
| 4837 | + context: &mut std::task::Context<'_>, | |
| 4838 | + ) -> std::task::Poll<Self::Output> { | |
| 4839 | + Pin::new(&mut self.get_mut().completion).poll(context) | |
| 4840 | + } | |
| 4841 | +} | |
| 4842 | + | |
| 4843 | +#[cfg(celld_internal_tests)] | |
| 4844 | +#[doc(hidden)] | |
| 4845 | +pub async fn await_arm_gates_for_test( | |
| 4846 | + gates: Vec<tokio::sync::oneshot::Receiver<Result<(), String>>>, | |
| 4847 | +) -> Result<(), String> { | |
| 4848 | + await_arm_gates(gates).await | |
| 4849 | +} | |
| 4850 | + | |
| 4851 | +#[cfg(celld_internal_tests)] | |
| 4852 | +#[doc(hidden)] | |
| 4853 | +pub enum GatedReplyCompletionForTest { | |
| 4854 | + Sent { failure: Option<String> }, | |
| 4855 | + CallerClosed { failure: Option<String> }, | |
| 4856 | +} | |
| 4857 | + | |
| 4858 | +#[cfg(celld_internal_tests)] | |
| 4859 | +#[doc(hidden)] | |
| 4860 | +pub struct GatedReplyForTest(GatedReplyRx); | |
| 4861 | + | |
| 4862 | +#[cfg(celld_internal_tests)] | |
| 4863 | +impl std::future::Future for GatedReplyForTest { | |
| 4864 | + type Output = Result<GatedReplyCompletionForTest, tokio::sync::oneshot::error::RecvError>; | |
| 4865 | + | |
| 4866 | + fn poll( | |
| 4867 | + self: Pin<&mut Self>, | |
| 4868 | + context: &mut std::task::Context<'_>, | |
| 4869 | + ) -> std::task::Poll<Self::Output> { | |
| 4870 | + Pin::new(&mut self.get_mut().0).poll(context).map(|result| { | |
| 4871 | + result.map(|completion| match completion { | |
| 4872 | + GatedReplyCompletion::Sent { failure } => { | |
| 4873 | + GatedReplyCompletionForTest::Sent { failure } | |
| 4874 | + } | |
| 4875 | + GatedReplyCompletion::CallerClosed { failure } => { | |
| 4876 | + GatedReplyCompletionForTest::CallerClosed { failure } | |
| 4877 | + } | |
| 4878 | + }) | |
| 4879 | + }) | |
| 4880 | + } | |
| 4881 | +} | |
| 4882 | + | |
| 4883 | +#[cfg(celld_internal_tests)] | |
| 4884 | +#[doc(hidden)] | |
| 4885 | +pub fn send_answer_after_arm_gates_for_test<T: Send + 'static>( | |
| 4886 | + reply: tokio::sync::oneshot::Sender<Result<T>>, | |
| 4887 | + value: Result<T>, | |
| 4888 | + gates: Vec<tokio::sync::oneshot::Receiver<Result<(), String>>>, | |
| 4889 | +) -> Option<GatedReplyForTest> { | |
| 4890 | + send_answer_after_arm_gates(reply, value, gates).map(GatedReplyForTest) | |
| 4891 | +} | |
| 4892 | + | |
| 4893 | +#[cfg(celld_internal_tests)] | |
| 4894 | +#[doc(hidden)] | |
| 4895 | +pub fn drop_next_gated_reply_task_for_test() { | |
| 4896 | + asyncrt::services() | |
| 4897 | + .wake_entry() | |
| 4898 | + .drop_next_gated_reply_task | |
| 4899 | + .store(true, Ordering::Release); | |
| 4900 | +} | |
| 4901 | + | |
| 4902 | +pub struct InFlight { | |
| 4903 | + /// The handler's promise. A `Global` because it outlives the turn that | |
| 4904 | + /// created it: Locals never cross a turn, exactly as workerd's | |
| 4905 | + /// `Worker::Lock` never does. | |
| 4906 | + promise: v8::Global<v8::Promise>, | |
| 4907 | + context: Arc<IoContext>, | |
| 4908 | + /// The cell this event belongs to, and `None` for stateless work. | |
| 4909 | + /// | |
| 4910 | + /// It is what the storage-shaped parts of settling — the durability | |
| 4911 | + /// position, a fatal SQL error — are read against. | |
| 4912 | + scope: Option<String>, | |
| 4913 | + /// The cell's committed-write position before the handler ran. | |
| 4914 | + /// | |
| 4915 | + /// The answer carries a write position only if the handler advanced it, | |
| 4916 | + /// so the output gate sees a write this event made and ignores celld's | |
| 4917 | + /// own activation writes (the actor name, alarm bookkeeping). | |
| 4918 | + writes_before: Option<u64>, | |
| 4919 | + request_id: Option<RequestId>, | |
| 4920 | + active_request_id: Option<RequestId>, | |
| 4921 | + reply: Option<Answer>, | |
| 4922 | + gated_reply: Option<GatedReplyRx>, | |
| 4923 | + /// `waitUntil` work still running after the response was sent. The | |
| 4924 | + /// request stays in flight until it settles, as the single-request loop | |
| 4925 | + /// keeps driving it. | |
| 4926 | + background: Option<v8::Global<v8::Promise>>, | |
| 4927 | + /// Ops this request is waiting on, so a completion can be attributed to | |
| 4928 | + /// the request whose context must be current while its continuation runs. | |
| 4929 | + ops: std::collections::HashSet<u64>, | |
| 4930 | + /// The subset of `ops` whose resource owns this event's `IoContext`. | |
| 4931 | + /// These operations continue after the handler and `waitUntil` settle. | |
| 4932 | + io_context_ops: std::collections::HashSet<u64>, | |
| 4933 | + /// The alarm bookkeeping this entry still owes, if it is one. | |
| 4934 | + alarm: Option<AlarmClaim>, | |
| 4935 | + started: Instant, | |
| 4936 | + /// The propagation context for this entry. A rejected foreign context | |
| 4937 | + /// stays here with `sampled` clear, so continuations can forward it | |
| 4938 | + /// without treating it as permission to record spans or logs. | |
| 4939 | + trace: Option<crate::telemetry::TraceContext>, | |
| 4940 | + /// Why the event failed, captured for the span's `error` so a query sees | |
| 4941 | + /// the reason, not only that it failed. This also records an output-gate | |
| 4942 | + /// failure after a successful handler. | |
| 4943 | + failure: Option<String>, | |
| 4944 | + /// The isolate this entry's ops belong to, so `abandon` can drop their | |
| 4945 | + /// resolvers without a scope to reach the isolate through. | |
| 4946 | + runtime_state: Arc<ActorRuntimeState>, | |
| 4947 | +} | |
| 4948 | + | |
| 4949 | +impl InFlight { | |
| 4950 | + /// Read the handler's settled value in the shape this entry answers, end | |
| 4951 | + /// the event, and reply. | |
| 4952 | + /// | |
| 4953 | + /// Every shape ends the event exactly once, whether it produced a value | |
| 4954 | + /// or an error — ending it is what yields the `waitUntil` work the entry | |
| 4955 | + /// keeps driving afterwards, and a shape that skipped it on the error | |
| 4956 | + /// path would leave the context open. | |
| 4957 | + fn answer_settled<'s>( | |
| 4958 | + &mut self, | |
| 4959 | + tc: &mut v8::PinScope<'s, '_>, | |
| 4960 | + value: v8::Local<'s, v8::Value>, | |
| 4961 | + ) { | |
| 4962 | + let Some(reply) = self.reply.take() else { | |
| 4963 | + return; | |
| 4964 | + }; | |
| 4965 | + // A cell whose SQL failed fatally cannot answer whatever the handler | |
| 4966 | + // returned: the storage the handler read may not be what the cell | |
| 4967 | + // has. | |
| 4968 | + if let Some(error) = self.scope.as_deref().and_then(storage::sql_critical_error) { | |
| 4969 | + let _ = end_event_context(tc); | |
| 4970 | + if self.trace.is_some_and(|trace| trace.sampled) { | |
| 4971 | + self.failure = Some(crate::telemetry::cap_error(error.to_string())); | |
| 4972 | + } | |
| 4973 | + self.gated_reply = | |
| 4974 | + reply.fail_with_arm_gates(anyhow!(error), self.context.take_arm_gates()); | |
| 4975 | + return; | |
| 4976 | + } | |
| 4977 | + let (background, gated_reply) = match reply { | |
| 4978 | + Answer::Fetch(reply) => { | |
| 4979 | + // A value the decoder refuses is a failure in the turn like a | |
| 4980 | + // throw is, so it carries the same positions. | |
| 4981 | + let positions = self.gate_positions(); | |
| 4982 | + let (write_position, observed_position) = positions; | |
| 4983 | + let read = read_response(tc, value) | |
| 4984 | + .map(|mut response| { | |
| 4985 | + response.write_position = write_position; | |
| 4986 | + response.observed_position = observed_position; | |
| 4987 | + response | |
| 4988 | + }) | |
| 4989 | + .map_err(|error| fail_in_turn_error(error, positions)); | |
| 4990 | + send_and_end(tc, &self.context, reply, read) | |
| 4991 | + } | |
| 4992 | + Answer::Rpc(reply) => { | |
| 4993 | + let read = | |
| 4994 | + view_bytes(value).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes")); | |
| 4995 | + send_and_end(tc, &self.context, reply, read) | |
| 4996 | + } | |
| 4997 | + Answer::Queue(reply) => { | |
| 4998 | + let read = read_queue_result(tc, value); | |
| 4999 | + if let Ok(result) = &read { | |
| 5000 | + if result.outcome == QueueOutcome::Exception | |
| 5001 | + && self.trace.is_some_and(|trace| trace.sampled) | |
| 5002 | + { | |
| 5003 | + self.failure = Some(crate::telemetry::cap_error( | |
| 5004 | + result | |
| 5005 | + .error | |
| 5006 | + .clone() | |
| 5007 | + .unwrap_or_else(|| "queue handler rejected".to_string()), | |
| 5008 | + )); | |
| 5009 | + } | |
| 5010 | + } | |
| 5011 | + send_and_end(tc, &self.context, reply, read) | |
| 5012 | + } | |
| 5013 | + Answer::CellRpc(reply) => { | |
| 5014 | + let (write_position, observed_position) = self.gate_positions(); | |
| 5015 | + #[cfg(celld_internal_tests)] | |
| 5016 | + if self.scope.as_deref().is_some_and(|scope| { | |
| 5017 | + scope | |
| 5018 | + .split_once(':') | |
| 5019 | + .is_some_and(|(class, _)| class == crate::deploy::QUEUE_CLASS) | |
| 5020 | + }) { | |
| 5021 | + QUEUE_PRODUCER_WRITE_POSITIONS | |
| 5022 | + .with(|positions| positions.borrow_mut().push(write_position)); | |
| 5023 | + } | |
| 5024 | + let outcome = RpcOutcome { | |
| 5025 | + data: rpc_data_ret(tc, value), | |
| 5026 | + write_position, | |
| 5027 | + observed_position, | |
| 5028 | + }; | |
| 5029 | + send_and_end(tc, &self.context, reply, Ok(outcome)) | |
| 5030 | + } | |
| 5031 | + Answer::WsMessage(reply) => { | |
| 5032 | + let (write_position, observed_position) = self.gate_positions(); | |
| 5033 | + let dispatch = WsDispatch { | |
| 5034 | + frames: ws_capture_take(), | |
| 5035 | + write_position, | |
| 5036 | + observed_position, | |
| 5037 | + }; | |
| 5038 | + send_and_end(tc, &self.context, reply, Ok(dispatch)) | |
| 5039 | + } | |
| 5040 | + Answer::Ack(reply) => send_and_end(tc, &self.context, reply, Ok(self.write_delta())), | |
| 5041 | + Answer::Alarm(reply) => { | |
| 5042 | + // The handler ran and returned, so close the claim as a | |
| 5043 | + // success. This is the only path that does: every other | |
| 5044 | + // `settle_alarm` call site records a failure, and without | |
| 5045 | + // this one a *successful* alarm was recorded as one to | |
| 5046 | + // retry — which re-armed it forever, kept the cell busy, | |
| 5047 | + // and meant an eviction waiting for the cell to go quiet | |
| 5048 | + // never got its turn. | |
| 5049 | + self.settle_alarm(true, false); | |
| 5050 | + // Read what stands *after* that cleanup, and take the delta | |
| 5051 | + // last so it covers the cleanup's own commit — which is the | |
| 5052 | + // write the core must prove durable before it settles the | |
| 5053 | + // alarm. | |
| 5054 | + let alarm = self | |
| 5055 | + .scope | |
| 5056 | + .as_deref() | |
| 5057 | + .map(storage::get_alarm) | |
| 5058 | + .unwrap_or(None); | |
| 5059 | + send_and_end(tc, &self.context, reply, Ok((alarm, self.write_delta()))) | |
| 5060 | + } | |
| 5061 | + }; | |
| 5062 | + self.background = background; | |
| 5063 | + self.gated_reply = gated_reply; | |
| 5064 | + } | |
| 5065 | + | |
| 5066 | + /// The write position to gate this answer on: `None` unless the handler | |
| 5067 | + /// advanced the cell's committed writes past where they were. | |
| 5068 | + fn write_delta(&self) -> Option<u64> { | |
| 5069 | + self.gate_positions().0 | |
| 5070 | + } | |
| 5071 | + | |
| 5072 | + /// The positions this answer's ticket carries: the write position when | |
| 5073 | + /// the handler advanced the cell's committed writes past where they were, | |
| 5074 | + /// and the position the answer observed above the cell's published | |
| 5075 | + /// baseline. One sample serves both, so they cannot disagree about what | |
| 5076 | + /// the cell holds. | |
| 5077 | + fn gate_positions(&self) -> (Option<u64>, Option<u64>) { | |
| 5078 | + let Some(scope) = self.scope.as_deref() else { | |
| 5079 | + return (None, None); | |
| 5080 | + }; | |
| 5081 | + gate_positions(scope, self.writes_before) | |
| 5082 | + } | |
| 5083 | + | |
| 5084 | + /// Fail whichever shape is waiting, without knowing which. | |
| 5085 | + /// | |
| 5086 | + /// This must not touch cell storage: a budget overrun and a stuck | |
| 5087 | + /// handler are found on the driving task, between turns, where the | |
| 5088 | + /// storage thread-local is null — settling the alarm claim here | |
| 5089 | + /// panicked the node (denoland/celld#170). The claim stays put, and | |
| 5090 | + /// the drive loop's `owes_alarm` turn records it as not counting | |
| 5091 | + /// against the retry limit, because a failure here is not the | |
| 5092 | + /// handler's. A handler that threw is recorded by `settle`, which | |
| 5093 | + /// knows that it did, before it reaches this. | |
| 5094 | + /// | |
| 5095 | + /// For the same reason the error leaves here without the position the | |
| 5096 | + /// handler's commits reached: `fail_in_turn` is the half that can sample | |
| 5097 | + /// it. A write a handler made before it ran out of budget is therefore | |
| 5098 | + /// still an unproven commit with no barrier of its own. | |
| 5099 | + fn fail(&mut self, error: anyhow::Error) { | |
| 5100 | + if let Some(reply) = self.reply.take() { | |
| 5101 | + if self.trace.is_some_and(|trace| trace.sampled) { | |
| 5102 | + self.failure = Some(crate::telemetry::cap_error(error.to_string())); | |
| 5103 | + } | |
| 5104 | + self.gated_reply = reply.fail_with_arm_gates(error, self.context.take_arm_gates()); | |
| 5105 | + } | |
| 5106 | + } | |
| 5107 | + | |
| 5108 | + /// Fail the event from inside its isolate turn, where the cell's storage | |
| 5109 | + /// is at hand. The error carries the positions the turn sampled, so the | |
| 5110 | + /// shell gates it as it gates a success. A commit a handler made before it | |
| 5111 | + /// threw is as unproven as one it answered with, and without a ticket it | |
| 5112 | + /// opened no barrier, so a read-only request that followed revealed it | |
| 5113 | + /// while a crash could still lose it. A handler that only read carries the | |
| 5114 | + /// observed position for the same reason: the message it throws with can | |
| 5115 | + /// quote what it read, and the error answer reveals that state as a | |
| 5116 | + /// response body does. An alarm that rejected settled its claim before | |
| 5117 | + /// this, so the delta covers its retry record too; one that failed any | |
| 5118 | + /// other way still owes that record, and `turn_finish_alarm` samples again | |
| 5119 | + /// after writing it. | |
| 5120 | + fn fail_in_turn(&mut self, error: anyhow::Error) { | |
| 5121 | + let positions = self.gate_positions(); | |
| 5122 | + self.fail(fail_in_turn_error(error, positions)); | |
| 5123 | + } | |
| 5124 | + | |
| 5125 | + /// Fail the event of a client that has hung up. The write half of | |
| 5126 | + /// `fail_in_turn` applies — a commit the handler made still needs its | |
| 5127 | + /// barrier — but the read-only half does not: there is no client left to | |
| 5128 | + /// tell, so no message carries what the handler read, and a read-only | |
| 5129 | + /// ticket would only hold the request's pin, and a shutdown, for a | |
| 5130 | + /// durability round trip that proves nothing. | |
| 5131 | + fn fail_cancelled(&mut self, error: anyhow::Error) { | |
| 5132 | + let (write_position, _) = self.gate_positions(); | |
| 5133 | + self.fail(fail_in_turn_error(error, (write_position, None))); | |
| 5134 | + } | |
| 5135 | + | |
| 5136 | + /// Record how a claimed alarm ended. Runs once; later calls do nothing. | |
| 5137 | + fn settle_alarm(&mut self, ok: bool, counts_against_limit: bool) { | |
| 5138 | + let (Some(scope), Some(claim)) = (self.scope.as_deref(), self.alarm.take()) else { | |
| 5139 | + return; | |
| 5140 | + }; | |
| 5141 | + if ok { | |
| 5142 | + storage::finish_alarm_handler(scope, true, claim.now_ms); | |
| 5143 | + } else { | |
| 5144 | + storage::finish_alarm_handler_with_retry_policy( | |
| 5145 | + scope, | |
| 5146 | + false, | |
| 5147 | + claim.now_ms, | |
| 5148 | + counts_against_limit, | |
| 5149 | + ); | |
| 5150 | + } | |
| 5151 | + } | |
| 5152 | + | |
| 5153 | + /// Whether a claimed alarm's outcome is still unrecorded. True only | |
| 5154 | + /// where the event ended without ever entering the isolate again. | |
| 5155 | + pub fn owes_alarm(&self) -> bool { | |
| 5156 | + self.alarm.is_some() | |
| 5157 | + } | |
| 5158 | + | |
| 5159 | + /// Done when the response has been sent and nothing is left running. | |
| 5160 | + pub fn finished(&self) -> bool { | |
| 5161 | + self.retired() && self.ops.is_empty() | |
| 5162 | + } | |
| 5163 | + | |
| 5164 | + /// The gate waiter that still owns this event's reply, if any. | |
| 5165 | + pub(crate) fn gated_reply(&mut self) -> Option<&mut GatedReplyRx> { | |
| 5166 | + self.gated_reply.as_mut() | |
| 5167 | + } | |
| 5168 | + | |
| 5169 | + #[cfg(celld_internal_tests)] | |
| 5170 | + #[doc(hidden)] | |
| 5171 | + pub fn has_gated_reply_for_test(&self) -> bool { | |
| 5172 | + self.gated_reply.is_some() | |
| 5173 | + } | |
| 5174 | + | |
| 5175 | + #[cfg(celld_internal_tests)] | |
| 5176 | + #[doc(hidden)] | |
| 5177 | + pub async fn finish_gated_reply_for_test(&mut self) -> bool { | |
| 5178 | + let Some(gated_reply) = self.gated_reply.as_mut() else { | |
| 5179 | + return false; | |
| 5180 | + }; | |
| 5181 | + let completion = gated_reply.await; | |
| 5182 | + self.finish_gated_reply(completion); | |
| 5183 | + true | |
| 5184 | + } | |
| 5185 | + | |
| 5186 | + /// Ask the detached gate owner to release every event gate and finish the | |
| 5187 | + /// reply edge. The driver waits for its completion before it retires the | |
| 5188 | + /// event, so response resources cannot outlive that cleanup. | |
| 5189 | + pub(crate) fn cancel_gated_reply(&mut self) { | |
| 5190 | + if let Some(gated_reply) = &mut self.gated_reply { | |
| 5191 | + gated_reply.cancel(); | |
| 5192 | + } | |
| 5193 | + } | |
| 5194 | + | |
| 5195 | + /// Retire a gate waiter after it sent the reply or observed caller-close. | |
| 5196 | + /// | |
| 5197 | + /// This method also closes request sockets when the completion makes the | |
| 5198 | + /// entry retire. `finish_turn` cannot do that earlier because the reply | |
| 5199 | + /// value can still own response resources while the gate is pending. | |
| 5200 | + pub(crate) fn finish_gated_reply( | |
| 5201 | + &mut self, | |
| 5202 | + completion: Result<GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>, | |
| 5203 | + ) { | |
| 5204 | + self.gated_reply = None; | |
| 5205 | + if self.trace.is_some_and(|trace| trace.sampled) { | |
| 5206 | + match completion { | |
| 5207 | + Ok(GatedReplyCompletion::Sent { | |
| 5208 | + failure: Some(failure), | |
| 5209 | + }) | |
| 5210 | + | Ok(GatedReplyCompletion::CallerClosed { | |
| 5211 | + failure: Some(failure), | |
| 5212 | + }) => self.failure = Some(failure), | |
| 5213 | + Ok(GatedReplyCompletion::Sent { failure: None }) => {} | |
| 5214 | + Ok(GatedReplyCompletion::CallerClosed { failure: None }) => { | |
| 5215 | + if self.failure.is_none() { | |
| 5216 | + self.failure = Some("The client has disconnected".to_string()); | |
| 5217 | + } | |
| 5218 | + } | |
| 5219 | + Err(_) => { | |
| 5220 | + if self.failure.is_none() { | |
| 5221 | + self.failure = Some("wake-entry reply gate task dropped".to_string()); | |
| 5222 | + } | |
| 5223 | + } | |
| 5224 | + } | |
| 5225 | + } | |
| 5226 | + if self.retired() { | |
| 5227 | + self.context.close_sockets(); | |
| 5228 | + } | |
| 5229 | + } | |
| 5230 | + | |
| 5231 | + /// The request has answered and its `waitUntil` work has settled. | |
| 5232 | + /// | |
| 5233 | + /// An isolate-polled WebSocket can still own an op after this point, and | |
| 5234 | + /// that op must not defer retirement. Retiring closes the sockets the | |
| 5235 | + /// request opened, and the pump of an outbound socket ends only with a | |
| 5236 | + /// close, so a retirement that waited for the pump waited for itself and | |
| 5237 | + /// the request never left the drive loop. The op keeps the entry's ops | |
| 5238 | + /// alive instead, through `keeps_native_ops`, which is what a socket the | |
| 5239 | + /// response took over needs: that socket left the request's set at the | |
| 5240 | + /// handoff, so retiring does not close it, and its pump runs until the | |
| 5241 | + /// client closes it. | |
| 5242 | + fn retired(&self) -> bool { | |
| 5243 | + self.reply.is_none() | |
| 5244 | + && self.gated_reply.is_none() | |
| 5245 | + && self.background.is_none() | |
| 5246 | + // A block that holds the gate is still this event's work: | |
| 5247 | + // retiring would close the sockets its callback may still read. | |
| 5248 | + && !self.holds_gate() | |
| 5249 | + // A reaction from this event can run its block during another | |
| 5250 | + // event's turn. Retain this event until that block releases its | |
| 5251 | + // claim, or retirement closes resources the callback still uses. | |
| 5252 | + && self.context.retire_without_cross_entry_gate() | |
| 5253 | + } | |
| 5254 | + | |
| 5255 | + /// Why the event failed, when a sampled trace captured it. | |
| 5256 | + pub fn failure(&self) -> Option<&str> { | |
| 5257 | + self.failure.as_deref() | |
| 5258 | + } | |
| 5259 | + | |
| 5260 | + /// How long this handler may still run, or `None` once it has answered. | |
| 5261 | + /// | |
| 5262 | + /// The budget bounds the *response*, not the request: `waitUntil` work | |
| 5263 | + /// continues after the client has been served and is not charged for the | |
| 5264 | + /// time the handler already spent. | |
| 5265 | + pub fn remaining(&self, budget: Duration) -> Option<Duration> { | |
| 5266 | + self.reply | |
| 5267 | + .is_some() | |
| 5268 | + .then(|| budget.saturating_sub(self.started.elapsed())) | |
| 5269 | + } | |
| 5270 | + | |
| 5271 | + /// Give up on a handler that will not settle. | |
| 5272 | + pub fn time_out(&mut self, budget: Duration) { | |
| 5273 | + self.fail(anyhow!("handler exceeded {}s budget", budget.as_secs())); | |
| 5274 | + } | |
| 5275 | + | |
| 5276 | + /// Nothing this request awaits can move it, so it will never settle on | |
| 5277 | + /// its own. Reachable when a handler awaits a promise only some *other* | |
| 5278 | + /// request could resolve — which the pump concealed, because it settled | |
| 5279 | + /// every entry on every turn whoever the turn belonged to. | |
| 5280 | + pub fn stuck(&mut self) { | |
| 5281 | + self.fail(anyhow!("handler is waiting on nothing")); | |
| 5282 | + self.background = None; | |
| 5283 | + } | |
| 5284 | + | |
| 5285 | + /// Has the client been answered? `waitUntil` work can still be running. | |
| 5286 | + pub fn answered(&self) -> bool { | |
| 5287 | + self.reply.is_none() && self.gated_reply.is_none() | |
| 5288 | + } | |
| 5289 | + | |
| 5290 | + /// Whether a native operation can still resume JavaScript for this event. | |
| 5291 | + /// | |
| 5292 | + /// A detached reply gate is host work. It cannot keep handler operations | |
| 5293 | + /// alive after the handler ends, but explicit `waitUntil` work, an | |
| 5294 | + /// operation that owns the event's `IoContext`, and a block that holds | |
| 5295 | + /// or is queued to take a cell's input gate can. The block belongs to | |
| 5296 | + /// the object, not to the client: it runs to completion as workerd's | |
| 5297 | + /// critical section does, and its `finally` is what opens the gate. | |
| 5298 | + /// Dropping its ops with the reply dropped the timer or subrequest it | |
| 5299 | + /// awaited, and the gate stayed shut for every later event (#733). | |
| 5300 | + pub(crate) fn keeps_native_ops(&self) -> bool { | |
| 5301 | + self.reply.is_some() | |
| 5302 | + || !self.io_context_ops.is_empty() | |
| 5303 | + || self.keeps_native_ops_after_disconnect() | |
| 5304 | + } | |
| 5305 | + | |
| 5306 | + /// Whether work that survives a normal client disconnect still needs | |
| 5307 | + /// this event's native operations. | |
| 5308 | + /// | |
| 5309 | + /// An origin claim covers operations started before a cross-entry block. | |
| 5310 | + /// Its callback can already hold their promises even though another | |
| 5311 | + /// event owns the block's turn and therefore owns the gate engagement. | |
| 5312 | + fn keeps_native_ops_after_disconnect(&self) -> bool { | |
| 5313 | + self.background.is_some() | |
| 5314 | + || self.engages_gate() | |
| 5315 | + || self.context.has_cross_entry_gate_claim() | |
| 5316 | + } | |
| 5317 | + | |
| 5318 | + /// Complete the resource-retirement edge that a claim release woke. | |
| 5319 | + pub(crate) fn finish_cross_entry_gates(&self) { | |
| 5320 | + if self.retired() { | |
| 5321 | + self.context.close_sockets(); | |
| 5322 | + } | |
| 5323 | + } | |
| 5324 | + | |
| 5325 | + /// Whether this event holds a cell's input gate now, or is queued to | |
| 5326 | + /// take one. | |
| 5327 | + fn engages_gate(&self) -> bool { | |
| 5328 | + gate_engagement(self.scope.as_deref(), &self.context) != GateEngagement::None | |
| 5329 | + } | |
| 5330 | + | |
| 5331 | + /// Whether this event holds a cell's input gate now. A queued block has | |
| 5332 | + /// not started, so only a held one keeps the event's sockets: a stale | |
| 5333 | + /// queue count from a future that was never adopted must not keep the | |
| 5334 | + /// event from retiring. | |
| 5335 | + fn holds_gate(&self) -> bool { | |
| 5336 | + gate_engagement(self.scope.as_deref(), &self.context) == GateEngagement::Holds | |
| 5337 | + } | |
| 5338 | + | |
| 5339 | + /// Whether a client can still disconnect from this request. A request | |
| 5340 | + /// with no id is internal and has no client to hang up. | |
| 5341 | + pub fn cancellable(&self) -> bool { | |
| 5342 | + self.reply.is_some() && self.request_id.is_some() | |
| 5343 | + } | |
| 5344 | + | |
| 5345 | + pub fn request_id(&self) -> Option<RequestId> { | |
| 5346 | + self.request_id | |
| 5347 | + } | |
| 5348 | + | |
| 5349 | + /// The request is over and its remaining ops are being dropped. Purge | |
| 5350 | + /// their resolvers. | |
| 5351 | + /// | |
| 5352 | + /// An op that never completes would otherwise leave its | |
| 5353 | + /// `Global<PromiseResolver>` in the isolate's map for as long as the | |
| 5354 | + /// isolate lives. A request that drives itself has to purge them on its | |
| 5355 | + /// own way out. | |
| 5356 | + pub fn abandon(&mut self) { | |
| 5357 | + self.io_context_ops.clear(); | |
| 5358 | + if self.ops.is_empty() { | |
| 5359 | + return; | |
| 5360 | + } | |
| 5361 | + let mut promises = self.runtime_state.promises.lock().unwrap(); | |
| 5362 | + for id in self.ops.drain() { | |
| 5363 | + promises.remove(&id); | |
| 5364 | + } | |
| 5365 | + } | |
| 5366 | + | |
| 5367 | + fn retire_background_for_shutdown(&mut self) { | |
| 5368 | + self.background = None; | |
| 5369 | + self.context.close_sockets(); | |
| 5370 | + } | |
| 5371 | +} | |
| 5372 | + | |
| 5373 | +/// The CPED slot carries three riders in one immutable record: the | |
| 5374 | +/// harness's async-context frame (`__als_get`/`__als_set` — ALS and | |
| 5375 | +/// request-context confinement), telemetry's trace context, and the native | |
| 5376 | +/// `IoContext` token. Each write builds a fresh three-element array preserving | |
| 5377 | +/// the other riders, so V8's per-reaction snapshots restore them atomically. | |
| 5378 | +/// Telemetry once took the whole slot and exposed this collision. | |
| 5379 | +/// | |
| 5380 | +/// When all three riders are absent, the slot stays undefined and V8 can use | |
| 5381 | +/// its empty-state fast path. Stateless code can retain that path. A cell | |
| 5382 | +/// event intentionally installs the native token even when telemetry is off. | |
| 5383 | +fn cped_parts<'s>( | |
| 5384 | + scope: &mut v8::PinScope<'s, '_>, | |
| 5385 | +) -> ( | |
| 5386 | + v8::Local<'s, v8::Value>, | |
| 5387 | + v8::Local<'s, v8::Value>, | |
| 5388 | + v8::Local<'s, v8::Value>, | |
| 5389 | +) { | |
| 5390 | + let data = scope.get_continuation_preserved_embedder_data(); | |
| 5391 | + if let Ok(record) = v8::Local::<v8::Array>::try_from(data) { | |
| 5392 | + if record.length() == 3 { | |
| 5393 | + let undefined = v8::undefined(scope).into(); | |
| 5394 | + return ( | |
| 5395 | + record.get_index(scope, 0).unwrap_or(undefined), | |
| 5396 | + record.get_index(scope, 1).unwrap_or(undefined), | |
| 5397 | + record.get_index(scope, 2).unwrap_or(undefined), | |
| 5398 | + ); | |
| 5399 | + } | |
| 5400 | + // Accept snapshots created by the former two-rider layout. They can | |
| 5401 | + // still be live while an isolate upgrades across this code boundary. | |
| 5402 | + if record.length() == 2 { | |
| 5403 | + let undefined = v8::undefined(scope).into(); | |
| 5404 | + return ( | |
| 5405 | + record.get_index(scope, 0).unwrap_or(undefined), | |
| 5406 | + record.get_index(scope, 1).unwrap_or(undefined), | |
| 5407 | + undefined, | |
| 5408 | + ); | |
| 5409 | + } | |
| 5410 | + } | |
| 5411 | + // Any non-record value is a bare frame from before this scheme, or | |
| 5412 | + // the empty slot. | |
| 5413 | + ( | |
| 5414 | + data, | |
| 5415 | + v8::undefined(scope).into(), | |
| 5416 | + v8::undefined(scope).into(), | |
| 5417 | + ) | |
| 5418 | +} | |
| 5419 | + | |
| 5420 | +fn cped_frame<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { | |
| 5421 | + cped_parts(scope).0 | |
| 5422 | +} | |
| 5423 | + | |
| 5424 | +fn cped_trace<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { | |
| 5425 | + cped_parts(scope).1 | |
| 5426 | +} | |
| 5427 | + | |
| 5428 | +fn cped_io_context<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { | |
| 5429 | + cped_parts(scope).2 | |
| 5430 | +} | |
| 5431 | + | |
| 5432 | +fn set_cped( | |
| 5433 | + scope: &mut v8::PinScope, | |
| 5434 | + frame: v8::Local<v8::Value>, | |
| 5435 | + trace: v8::Local<v8::Value>, | |
| 5436 | + io_context: v8::Local<v8::Value>, | |
| 5437 | +) { | |
| 5438 | + if frame.is_undefined() && trace.is_undefined() && io_context.is_undefined() { | |
| 5439 | + let undefined = v8::undefined(scope).into(); | |
| 5440 | + scope.set_continuation_preserved_embedder_data(undefined); | |
| 5441 | + return; | |
| 5442 | + } | |
| 5443 | + let record = v8::Array::new(scope, 3); | |
| 5444 | + record.set_index(scope, 0, frame); | |
| 5445 | + record.set_index(scope, 1, trace); | |
| 5446 | + record.set_index(scope, 2, io_context); | |
| 5447 | + scope.set_continuation_preserved_embedder_data(record.into()); | |
| 5448 | +} | |
| 5449 | + | |
| 5450 | +/// Install a trace context into the isolate's CPED slot for one turn. | |
| 5451 | +/// | |
| 5452 | +/// V8 snapshots continuation-preserved embedder data when a promise | |
| 5453 | +/// reaction is registered and restores it while the reaction runs. That | |
| 5454 | +/// is the exactness `console.log` correlation needs: a continuation | |
| 5455 | +/// belonging to a *different* entry that runs during this turn's | |
| 5456 | +/// microtask checkpoint carries its own context, not this turn's. The | |
| 5457 | +/// layout is 16 trace-id bytes, 8 span-id bytes, and one sampling byte | |
| 5458 | +/// in one ArrayBuffer. Sampled contexts pay the existing cost, and only a | |
| 5459 | +/// rejected foreign context adds this cost to an unsampled request. | |
| 5460 | +/// | |
| 5461 | +/// Returns the previous slot value *only when a trace was installed*; the | |
| 5462 | +/// caller restores it before releasing the isolate. An untraced turn does not | |
| 5463 | +/// install the trace rider. A cell event separately installs its `IoContext` | |
| 5464 | +/// token, so V8 can attribute a continuation that runs during another event's | |
| 5465 | +/// checkpoint. | |
| 5466 | +fn install_trace<'s>( | |
| 5467 | + scope: &mut v8::PinScope<'s, '_>, | |
| 5468 | + trace: Option<&crate::telemetry::TraceContext>, | |
| 5469 | +) -> Option<v8::Local<'s, v8::Value>> { | |
| 5470 | + let context = trace?; | |
| 5471 | + let previous = scope.get_continuation_preserved_embedder_data(); | |
| 5472 | + let buffer = v8::ArrayBuffer::new(scope, 25); | |
| 5473 | + let data = buffer.get_backing_store().data()?; | |
| 5474 | + let bytes = data.as_ptr() as *mut u8; | |
| 5475 | + // SAFETY: a freshly created 25-byte buffer, written before any JS | |
| 5476 | + // can see it. | |
| 5477 | + unsafe { | |
| 5478 | + std::ptr::copy_nonoverlapping(context.trace_id.as_ptr(), bytes, 16); | |
| 5479 | + std::ptr::copy_nonoverlapping(context.span_id.as_ptr(), bytes.add(16), 8); | |
| 5480 | + bytes.add(24).write(u8::from(context.sampled)); | |
| 5481 | + } | |
| 5482 | + let frame = cped_frame(scope); | |
| 5483 | + let io_context = cped_io_context(scope); | |
| 5484 | + set_cped(scope, frame, buffer.into(), io_context); | |
| 5485 | + Some(previous) | |
| 5486 | +} | |
| 5487 | + | |
| 5488 | +fn restore_trace(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) { | |
| 5489 | + if let Some(previous) = previous { | |
| 5490 | + scope.set_continuation_preserved_embedder_data(previous); | |
| 5491 | + } | |
| 5492 | +} | |
| 5493 | + | |
| 5494 | +/// Install the current cell event's native context in CPED. V8 restores this | |
| 5495 | +/// token for each reaction, including a reaction that runs during another | |
| 5496 | +/// event's microtask checkpoint. | |
| 5497 | +fn install_io_context<'s>( | |
| 5498 | + scope: &mut v8::PinScope<'s, '_>, | |
| 5499 | + context: &IoContext, | |
| 5500 | +) -> Option<v8::Local<'s, v8::Value>> { | |
| 5501 | + let (id, _) = context.continuation.as_ref()?; | |
| 5502 | + let previous = scope.get_continuation_preserved_embedder_data(); | |
| 5503 | + let frame = cped_frame(scope); | |
| 5504 | + let trace = cped_trace(scope); | |
| 5505 | + let token: v8::Local<v8::Value> = v8::BigInt::new_from_u64(scope, *id).into(); | |
| 5506 | + set_cped(scope, frame, trace, token); | |
| 5507 | + Some(previous) | |
| 5508 | +} | |
| 5509 | + | |
| 5510 | +fn restore_io_context(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) { | |
| 5511 | + if let Some(previous) = previous { | |
| 5512 | + scope.set_continuation_preserved_embedder_data(previous); | |
| 5513 | + } | |
| 5514 | +} | |
| 5515 | + | |
| 5516 | +fn current_reaction_io_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> { | |
| 5517 | + let token = v8::Local::<v8::BigInt>::try_from(cped_io_context(scope)).ok()?; | |
| 5518 | + let (id, lossless) = token.u64_value(); | |
| 5519 | + lossless | |
| 5520 | + .then(|| actor_runtime_state(scope).io_context(id)) | |
| 5521 | + .flatten() | |
| 5522 | +} | |
| 5523 | + | |
| 5524 | +/// Resolve the exact tracked reaction, or use the active context when this | |
| 5525 | +/// isolate does not track reactions at all. | |
| 5526 | +/// | |
| 5527 | +/// Cell events always install a token. A token that no longer resolves names | |
| 5528 | +/// a retired event and must not borrow another event's ambient context. | |
| 5529 | +/// Stateless requests install no token, so their current turn remains the | |
| 5530 | +/// only context that can own a synchronous operation such as `process.exit`. | |
| 5531 | +fn current_reaction_or_untracked_io_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> { | |
| 5532 | + if cped_io_context(scope).is_undefined() { | |
| 5533 | + return Some(current_context()); | |
| 5534 | + } | |
| 5535 | + current_reaction_io_context(scope) | |
| 5536 | +} | |
| 5537 | + | |
| 5538 | +/// The trace context current at this exact point of JS execution, read | |
| 5539 | +/// from CPED — the running turn's, or the running continuation's if V8 | |
| 5540 | +/// restored one. `None` when telemetry is off or execution is outside an | |
| 5541 | +/// entry. An unsampled foreign context remains present with its flag clear. | |
| 5542 | +pub(crate) fn current_trace_context( | |
| 5543 | + scope: &mut v8::PinScope, | |
| 5544 | +) -> Option<crate::telemetry::TraceContext> { | |
| 5545 | + if !crate::telemetry::active() { | |
| 5546 | + return None; | |
| 5547 | + } | |
| 5548 | + let data = cped_trace(scope); | |
| 5549 | + let buffer = v8::Local::<v8::ArrayBuffer>::try_from(data).ok()?; | |
| 5550 | + if buffer.byte_length() != 25 { | |
| 5551 | + return None; | |
| 5552 | + } | |
| 5553 | + let data = buffer.get_backing_store().data()?; | |
| 5554 | + let bytes = data.as_ptr() as *const u8; | |
| 5555 | + let mut trace_id = [0u8; 16]; | |
| 5556 | + let mut span_id = [0u8; 8]; | |
| 5557 | + // SAFETY: length checked; the buffer is alive for this scope. | |
| 5558 | + unsafe { | |
| 5559 | + std::ptr::copy_nonoverlapping(bytes, trace_id.as_mut_ptr(), 16); | |
| 5560 | + std::ptr::copy_nonoverlapping(bytes.add(16), span_id.as_mut_ptr(), 8); | |
| 5561 | + } | |
| 5562 | + let sampled = unsafe { bytes.add(24).read() != 0 }; | |
| 5563 | + Some(crate::telemetry::TraceContext { | |
| 5564 | + trace_id, | |
| 5565 | + span_id, | |
| 5566 | + sampled, | |
| 5567 | + }) | |
| 5568 | +} | |
| 5569 | + | |
| 5570 | +/// The isolate, entered for one turn. Everything a request does to a shared | |
| 5571 | +/// isolate goes through one of these, and none of them may be held across an | |
| 5572 | +/// await: the caller takes the pool's async permit first, runs a turn, and | |
| 5573 | +/// leaves. | |
| 5574 | +impl Worker { | |
| 5575 | + /// Run a request's first turn. | |
| 5576 | + /// | |
| 5577 | + /// Returns what is now in flight — `None` when nothing is, the reply | |
| 5578 | + /// already carrying the error — and the ops the handler enqueued, which | |
| 5579 | + /// the caller awaits with no isolate held. | |
| 5580 | + pub fn turn_begin( | |
| 5581 | + &mut self, | |
| 5582 | + job: crate::WorkerJob, | |
| 5583 | + trace: Option<crate::telemetry::TraceContext>, | |
| 5584 | + ) -> (Option<InFlight>, Vec<Op>) { | |
| 5585 | + let Some(inner) = self.inner.as_mut() else { | |
| 5586 | + return (None, Vec::new()); | |
| 5587 | + }; | |
| 5588 | + let (mut locker, _cells) = inner.lock(); | |
| 5589 | + inner.recover_heap(&mut locker); | |
| 5590 | + v8::scope!(let hs, &mut *locker); | |
| 5591 | + let realm = inner.realm(hs); | |
| 5592 | + let context = realm.context; | |
| 5593 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 5594 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 5595 | + let tc = &mut tc.init(); | |
| 5596 | + | |
| 5597 | + advance_io_time(tc); | |
| 5598 | + let previous = install_trace(tc, trace.as_ref()); | |
| 5599 | + let out = match begin(tc, realm.fetch, job) { | |
| 5600 | + Begun::Running(mut entry) => { | |
| 5601 | + entry.trace = trace; | |
| 5602 | + // A handler that returned an already-resolved promise is | |
| 5603 | + // finished before it ever suspends, and must not wait for an | |
| 5604 | + // op it will never start. | |
| 5605 | + let ops = finish_turn(tc, &mut entry); | |
| 5606 | + (Some(*entry), ops) | |
| 5607 | + } | |
| 5608 | + Begun::Threw(answer) => { | |
| 5609 | + answer.fail(anyhow!("fetch threw: {}", exc!(tc))); | |
| 5610 | + (None, Vec::new()) | |
| 5611 | + } | |
| 5612 | + Begun::Nothing => (None, Vec::new()), | |
| 5613 | + }; | |
| 5614 | + restore_trace(tc, previous); | |
| 5615 | + out | |
| 5616 | + } | |
| 5617 | + | |
| 5618 | + /// Enter the isolate solely to end a request whose client has hung up. | |
| 5619 | + /// | |
| 5620 | + /// A suspended request notices the disconnect without any isolate — the | |
| 5621 | + /// flag is host state — so this is reached only when it has actually | |
| 5622 | + /// fired, rather than on a timer as the blocking run loop did. | |
| 5623 | + pub fn turn_cancel(&mut self, entry: &mut InFlight) -> Vec<Op> { | |
| 5624 | + self.cancel_turn(entry, false) | |
| 5625 | + } | |
| 5626 | + | |
| 5627 | + /// The runtime is stopping: end the event as a client hang-up does, but | |
| 5628 | + /// keep nothing running for it, a critical section included. The block | |
| 5629 | + /// would not reach its end before the process exits, so its gate is | |
| 5630 | + /// abandoned and the events queued behind it are refused now rather | |
| 5631 | + /// than left waiting through the shutdown. | |
| 5632 | + pub fn turn_cancel_for_shutdown(&mut self, entry: &mut InFlight) -> Vec<Op> { | |
| 5633 | + self.cancel_turn(entry, true) | |
| 5634 | + } | |
| 5635 | + | |
| 5636 | + fn cancel_turn(&mut self, entry: &mut InFlight, shutdown: bool) -> Vec<Op> { | |
| 5637 | + let Some(inner) = self.inner.as_mut() else { | |
| 5638 | + return Vec::new(); | |
| 5639 | + }; | |
| 5640 | + let (mut locker, _cells) = inner.lock(); | |
| 5641 | + v8::scope!(let hs, &mut *locker); | |
| 5642 | + let realm = inner.realm(hs); | |
| 5643 | + let context = realm.context; | |
| 5644 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 5645 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 5646 | + let tc = &mut tc.init(); | |
| 5647 | + | |
| 5648 | + advance_io_time(tc); | |
| 5649 | + let previous_io_context = install_io_context(tc, &entry.context); | |
| 5650 | + let previous = install_trace(tc, entry.trace.as_ref()); | |
| 5651 | + cancel(tc, entry, shutdown); | |
| 5652 | + let ops = finish_turn(tc, entry); | |
| 5653 | + restore_trace(tc, previous); | |
| 5654 | + restore_io_context(tc, previous_io_context); | |
| 5655 | + ops | |
| 5656 | + } | |
| 5657 | + | |
| 5658 | + /// Retire input-gate work for an event that cannot run JavaScript again. | |
| 5659 | + /// | |
| 5660 | + /// The host claims are taken before the isolate lock because the caller | |
| 5661 | + /// already owns this slot. A newly woken event can queue for the slot, but | |
| 5662 | + /// it cannot enter the isolate until the stale actor state is removed. | |
| 5663 | + pub(crate) fn turn_retire_input_gates(&mut self, entry: &InFlight) { | |
| 5664 | + entry.context.force_retire_cross_entry_gates(); | |
| 5665 | + let _ = abandon_context_input_gates(&entry.context); | |
| 5666 | + self.turn_retire_input_gate_context(entry); | |
| 5667 | + } | |
| 5668 | + | |
| 5669 | + /// Enforce the host-side invariant when an ordinarily completed event | |
| 5670 | + /// drops its final owner. The JavaScript `finally` normally released every | |
| 5671 | + /// gate, so entering the isolate is necessary only when a hold remains. | |
| 5672 | + pub(crate) fn turn_abandon_input_gates(&mut self, entry: &InFlight) { | |
| 5673 | + let abandoned = abandon_context_input_gates(&entry.context); | |
| 5674 | + if abandoned.is_empty() { | |
| 5675 | + return; | |
| 5676 | + } | |
| 5677 | + self.turn_retire_input_gate_context(entry); | |
| 5678 | + } | |
| 5679 | + | |
| 5680 | + fn turn_retire_input_gate_context(&mut self, entry: &InFlight) { | |
| 5681 | + let Some(inner) = self.inner.as_mut() else { | |
| 5682 | + return; | |
| 5683 | + }; | |
| 5684 | + let (mut locker, _cells) = inner.lock(); | |
| 5685 | + v8::scope!(let hs, &mut *locker); | |
| 5686 | + let realm = inner.realm(hs); | |
| 5687 | + let context = realm.context; | |
| 5688 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 5689 | + let context_id = entry.context.continuation_id().unwrap_or_default(); | |
| 5690 | + retire_input_gate_js_context(cs, context_id); | |
| 5691 | + } | |
| 5692 | + | |
| 5693 | + /// Run a later turn: resolve one of this request's ops, drain the | |
| 5694 | + /// microtasks that follow, and answer if the handler settled. | |
| 5695 | + pub fn turn_deliver( | |
| 5696 | + &mut self, | |
| 5697 | + entry: &mut InFlight, | |
| 5698 | + op: u64, | |
| 5699 | + res: Result<asyncrt::OpOut, String>, | |
| 5700 | + ) -> Vec<Op> { | |
| 5701 | + let Some(inner) = self.inner.as_mut() else { | |
| 5702 | + return Vec::new(); | |
| 5703 | + }; | |
| 5704 | + let (mut locker, _cells) = inner.lock(); | |
| 5705 | + v8::scope!(let hs, &mut *locker); | |
| 5706 | + let realm = inner.realm(hs); | |
| 5707 | + let context = realm.context; | |
| 5708 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 5709 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 5710 | + let tc = &mut tc.init(); | |
| 5711 | + | |
| 5712 | + advance_io_time(tc); | |
| 5713 | + let previous_io_context = install_io_context(tc, &entry.context); | |
| 5714 | + let previous = install_trace(tc, entry.trace.as_ref()); | |
| 5715 | + deliver(tc, entry, op, res); | |
| 5716 | + cancelled(tc, entry); | |
| 5717 | + let ops = finish_turn(tc, entry); | |
| 5718 | + restore_trace(tc, previous); | |
| 5719 | + restore_io_context(tc, previous_io_context); | |
| 5720 | + ops | |
| 5721 | + } | |
| 5722 | +} | |
| 5723 | + | |
| 5724 | +/// Close a turn, whatever the turn did. | |
| 5725 | +/// | |
| 5726 | +/// Every step earns its place and the order is the whole point: | |
| 5727 | +/// | |
| 5728 | +/// 1. **settle** — the handler's promise may have resolved, so marshal the | |
| 5729 | +/// response and answer. Marshalling can start a JS-to-host body pump and | |
| 5730 | +/// register it with `waitUntil`. | |
| 5731 | +/// 2. **checkpoint** — that pump's native ops exist only once the microtasks | |
| 5732 | +/// which create them run. | |
| 5733 | +/// 3. **release the facet gate** — the second facet flush can now cover every | |
| 5734 | +/// write exposed by the checkpoint, or reject the held response. | |
| 5735 | +/// 4. **settle again** — the checkpoint may itself have settled the promise, | |
| 5736 | +/// or the `waitUntil` aggregate. | |
| 5737 | +/// 5. **adopt** — only now is the set of ops this request waits on complete. | |
| 5738 | +/// 6. **close** — close the sockets the request opened, once it has retired. | |
| 5739 | +/// A socket the response took over left that set at the handoff. | |
| 5740 | +/// | |
| 5741 | +/// Draining before step 2 is the bug that made a streaming handler answer | |
| 5742 | +/// with nothing outstanding and conclude it was waiting on nothing. | |
| 5743 | +/// The checkpoint before adoption is what makes response-body pumps visible. | |
| 5744 | +/// | |
| 5745 | +/// An accepted Worker socket starts its next `__ws_next` before the fetch | |
| 5746 | +/// response retires. The driver used to drop that receive future with the | |
| 5747 | +/// handler's other ops once the handler answered, so later frames hung. An op | |
| 5748 | +/// that owns the `IoContext` therefore keeps the entry's ops alive after the | |
| 5749 | +/// answer, through `keeps_native_ops`. The lifetime travels in the spawn | |
| 5750 | +/// record rather than in a separate op-id tag: a tag can outlive a failed | |
| 5751 | +/// turn, and the spawn and its classification drain together. Such an op | |
| 5752 | +/// does not defer retirement: see `retired`. | |
| 5753 | +fn finish_turn(tc: &mut v8::PinScope, entry: &mut InFlight) -> Vec<Op> { | |
| 5754 | + // `settle` can consume and send the reply before the checkpoint below | |
| 5755 | + // exposes a final facet write. Hold an embedded facet's reply in the | |
| 5756 | + // event-owned gate set, so a successful response and its image write are | |
| 5757 | + // one result. Checking the poison after sending cannot retract the reply. | |
| 5758 | + let embedded_reply = entry | |
| 5759 | + .scope | |
| 5760 | + .as_deref() | |
| 5761 | + .is_some_and(|scope| entry.reply.is_some() && storage::is_embedded(scope)); | |
| 5762 | + // A pending promise cannot send during the first `settle`; if the | |
| 5763 | + // checkpoint fulfills it, the second flush still runs before the second | |
| 5764 | + // `settle`. Gate only a reply that the first `settle` can consume, so a | |
| 5765 | + // long handler does not accumulate one resolved receiver on every turn. | |
| 5766 | + let needs_facet_flush_gate = embedded_reply && { | |
| 5767 | + let promise = v8::Local::new(tc, &entry.promise); | |
| 5768 | + matches!(promise.state(), v8::PromiseState::Fulfilled) | |
| 5769 | + }; | |
| 5770 | + let facet_flush_gate = if needs_facet_flush_gate { | |
| 5771 | + let (send, receive) = tokio::sync::oneshot::channel(); | |
| 5772 | + match entry.context.register_arm_gate(receive) { | |
| 5773 | + Ok(()) => Some(send), | |
| 5774 | + Err(_) => { | |
| 5775 | + entry.fail(anyhow!( | |
| 5776 | + "the facet persistence gate was sealed before settlement" | |
| 5777 | + )); | |
| 5778 | + None | |
| 5779 | + } | |
| 5780 | + } | |
| 5781 | + } else { | |
| 5782 | + None | |
| 5783 | + }; | |
| 5784 | + if let Some(scope) = entry.scope.as_deref() { | |
| 5785 | + storage::flush_embedded(scope); | |
| 5786 | + } | |
| 5787 | + settle(tc, entry); | |
| 5788 | + tc.perform_microtask_checkpoint(); | |
| 5789 | + if let Some(scope) = entry.scope.as_deref() { | |
| 5790 | + #[cfg(all(test, celld_internal_tests))] | |
| 5791 | + if storage::is_embedded(scope) | |
| 5792 | + && asyncrt::services() | |
| 5793 | + .wake_entry() | |
| 5794 | + .fail_post_checkpoint_facet_flush | |
| 5795 | + .swap(false, Ordering::AcqRel) | |
| 5796 | + { | |
| 5797 | + storage::poison_sql_for_test(scope, "injected facet image write failure"); | |
| 5798 | + } | |
| 5799 | + storage::flush_embedded(scope); | |
| 5800 | + } | |
| 5801 | + if let Some(gate) = facet_flush_gate { | |
| 5802 | + let result = entry | |
| 5803 | + .scope | |
| 5804 | + .as_deref() | |
| 5805 | + .and_then(storage::sql_critical_error) | |
| 5806 | + .map_or(Ok(()), Err); | |
| 5807 | + let _ = gate.send(result); | |
| 5808 | + } | |
| 5809 | + // `abort()` and `process.exit()` terminate execution without settling | |
| 5810 | + // the handler's promise, so an entry that only watched the promise would | |
| 5811 | + // wait on it forever and then report that it was waiting on nothing. | |
| 5812 | + // The blocking loop broke out of its loop here; an entry fails here. | |
| 5813 | + if let Some(error) = take_execution_termination_in_context(tc, Some(&entry.context)) { | |
| 5814 | + entry.fail_in_turn(error); | |
| 5815 | + entry.background = None; | |
| 5816 | + entry.abandon(); | |
| 5817 | + return Vec::new(); | |
| 5818 | + } | |
| 5819 | + settle(tc, entry); | |
| 5820 | + let ops = adopt(entry); | |
| 5821 | + // 6. **close the request's sockets** — see above. | |
| 5822 | + if entry.retired() { | |
| 5823 | + entry.context.close_sockets(); | |
| 5824 | + } | |
| 5825 | + ops | |
| 5826 | +} | |
| 5827 | + | |
| 5828 | +/// An op the JS enqueued, and the id whose promise it resolves. | |
| 5829 | +pub type Op = (u64, asyncrt::OpFuture); | |
| 5830 | + | |
| 5831 | +/// Take the ops this turn enqueued, recording them as the request's own. | |
| 5832 | +/// | |
| 5833 | +/// Drained after `settle`, not before: ending an event runs JS, and anything | |
| 5834 | +/// that starts there belongs to this request too. The pump drained first and | |
| 5835 | +/// so could attribute those to whichever entry it settled next. | |
| 5836 | +fn adopt(entry: &mut InFlight) -> Vec<Op> { | |
| 5837 | + let spawns = asyncrt::drain_spawns(); | |
| 5838 | + let mut ops = Vec::with_capacity(spawns.len()); | |
| 5839 | + for (id, future, keeps_io_context) in spawns { | |
| 5840 | + entry.ops.insert(id); | |
| 5841 | + if keeps_io_context { | |
| 5842 | + entry.io_context_ops.insert(id); | |
| 5843 | + } | |
| 5844 | + ops.push((id, future)); | |
| 5845 | + } | |
| 5846 | + ops | |
| 5847 | +} | |
| 5848 | + | |
| 5849 | +/// What starting a request produced. | |
| 5850 | +enum Begun { | |
| 5851 | + /// In flight. Its ops must be adopted and its promise driven. | |
| 5852 | + Running(Box<InFlight>), | |
| 5853 | + /// The handler threw before it could suspend, so nothing is in flight. | |
| 5854 | + /// The exception belongs to the caller's `TryCatch` — an unnameable type | |
| 5855 | + /// no signature here can take — so the caller reads it and answers. | |
| 5856 | + Threw(Answer), | |
| 5857 | + /// Nothing started: the job was not a fetch, or the reply already | |
| 5858 | + /// carries the error. | |
| 5859 | + Nothing, | |
| 5860 | +} | |
| 5861 | + | |
| 5862 | +/// Start a request: build it, call the Worker's `fetch`, and hand back what | |
| 5863 | +/// is now in flight. | |
| 5864 | +/// | |
| 5865 | +/// The half of a turn that runs *before* anything can suspend. | |
| 5866 | +fn begin<'s>( | |
| 5867 | + tc: &mut v8::PinScope<'s, '_>, | |
| 5868 | + fetch: v8::Local<'s, v8::Function>, | |
| 5869 | + job: crate::WorkerJob, | |
| 5870 | +) -> Begun { | |
| 5871 | + let job = match job { | |
| 5872 | + crate::WorkerJob::Rpc { | |
| 5873 | + entrypoint, | |
| 5874 | + method, | |
| 5875 | + args, | |
| 5876 | + reply, | |
| 5877 | + } => return begin_entrypoint_rpc(tc, &entrypoint, &method, args, reply), | |
| 5878 | + crate::WorkerJob::Queue { batch, reply, .. } => { | |
| 5879 | + return begin_queue(tc, batch, reply); | |
| 5880 | + } | |
| 5881 | + job => job, | |
| 5882 | + }; | |
| 5883 | + let crate::WorkerJob::Fetch { | |
| 5884 | + url, | |
| 5885 | + method, | |
| 5886 | + body, | |
| 5887 | + headers, | |
| 5888 | + request_id, | |
| 5889 | + reply, | |
| 5890 | + .. | |
| 5891 | + } = job | |
| 5892 | + else { | |
| 5893 | + return Begun::Nothing; | |
| 5894 | + }; | |
| 5895 | + let context = IoContext::new(); | |
| 5896 | + if let Some(stream_id) = body.stream_id() { | |
| 5897 | + context.own_body_stream(stream_id); | |
| 5898 | + } | |
| 5899 | + let guard = CurrentGuard::enter(context.clone()); | |
| 5900 | + let started = start_fetch(tc, fetch, &url, &method, body, &headers, request_id); | |
| 5901 | + let promise = match started { | |
| 5902 | + Ok(Started::Running(ret, active)) => match ret.try_cast::<v8::Promise>() { | |
| 5903 | + Ok(promise) => Ok((promise, active)), | |
| 5904 | + Err(_) => resolved_promise(tc, ret).map(|promise| (promise, active)), | |
| 5905 | + }, | |
| 5906 | + Ok(Started::Threw) => { | |
| 5907 | + drop(guard); | |
| 5908 | + return Begun::Threw(Answer::Fetch(reply)); | |
| 5909 | + } | |
| 5910 | + Err(error) => Err(error), | |
| 5911 | + }; | |
| 5912 | + match promise { | |
| 5913 | + Ok((promise, active_request_id)) => { | |
| 5914 | + tc.perform_microtask_checkpoint(); | |
| 5915 | + let entry = InFlight { | |
| 5916 | + runtime_state: actor_runtime_state(tc), | |
| 5917 | + promise: v8::Global::new(tc, promise), | |
| 5918 | + context, | |
| 5919 | + scope: None, | |
| 5920 | + writes_before: None, | |
| 5921 | + request_id, | |
| 5922 | + active_request_id, | |
| 5923 | + reply: Some(Answer::Fetch(reply)), | |
| 5924 | + gated_reply: None, | |
| 5925 | + background: None, | |
| 5926 | + ops: std::collections::HashSet::new(), | |
| 5927 | + io_context_ops: std::collections::HashSet::new(), | |
| 5928 | + alarm: None, | |
| 5929 | + started: Instant::now(), | |
| 5930 | + trace: None, | |
| 5931 | + failure: None, | |
| 5932 | + }; | |
| 5933 | + drop(guard); | |
| 5934 | + Begun::Running(Box::new(entry)) | |
| 5935 | + } | |
| 5936 | + Err(error) => { | |
| 5937 | + drop(guard); | |
| 5938 | + let _ = reply.send(Err(error)); | |
| 5939 | + Begun::Nothing | |
| 5940 | + } | |
| 5941 | + } | |
| 5942 | +} | |
| 5943 | + | |
| 5944 | +/// Start an entrypoint RPC's first turn. | |
| 5945 | +/// | |
| 5946 | +/// The same shape as a fetch and deliberately so: call the handler, keep the | |
| 5947 | +/// promise, and let `drive` pump it with no isolate held across the awaits. | |
| 5948 | +/// The old dispatcher blocked until the promise settled, which is why RPC | |
| 5949 | +/// needed a thread of its own and why `WorkerPool` outlived the fetch path. | |
| 5950 | +fn begin_entrypoint_rpc( | |
| 5951 | + tc: &mut v8::PinScope, | |
| 5952 | + entrypoint: &str, | |
| 5953 | + method: &str, | |
| 5954 | + args: Vec<u8>, | |
| 5955 | + reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>, | |
| 5956 | +) -> Begun { | |
| 5957 | + let context = IoContext::new(); | |
| 5958 | + let guard = CurrentGuard::enter(context.clone()); | |
| 5959 | + let global = tc.get_current_context().global(tc); | |
| 5960 | + let started = (|| { | |
| 5961 | + let key = v8::String::new(tc, "__dispatchEntrypointRpc").unwrap(); | |
| 5962 | + let f: v8::Local<v8::Function> = global | |
| 5963 | + .get(tc, key.into()) | |
| 5964 | + .ok_or_else(|| anyhow!("no __dispatchEntrypointRpc"))? | |
| 5965 | + .try_into() | |
| 5966 | + .map_err(|_| anyhow!("__dispatchEntrypointRpc is not a function"))?; | |
| 5967 | + let entrypoint = v8::String::new(tc, entrypoint).unwrap(); | |
| 5968 | + let method = v8::String::new(tc, method).unwrap(); | |
| 5969 | + let args = bytes_value(tc, args); | |
| 5970 | + let recv = v8::undefined(tc).into(); | |
| 5971 | + begin_event_context(tc)?; | |
| 5972 | + let ret = f | |
| 5973 | + .call(tc, recv, &[entrypoint.into(), method.into(), args]) | |
| 5974 | + .ok_or_else(|| anyhow!("entrypoint RPC threw"))?; | |
| 5975 | + match ret.try_cast::<v8::Promise>() { | |
| 5976 | + Ok(promise) => Ok(promise), | |
| 5977 | + Err(_) => resolved_promise(tc, ret), | |
| 5978 | + } | |
| 5979 | + })(); | |
| 5980 | + let event_started = Instant::now(); | |
| 5981 | + match started { | |
| 5982 | + Ok(promise) => { | |
| 5983 | + tc.perform_microtask_checkpoint(); | |
| 5984 | + let entry = InFlight { | |
| 5985 | + runtime_state: actor_runtime_state(tc), | |
| 5986 | + promise: v8::Global::new(tc, promise), | |
| 5987 | + context, | |
| 5988 | + scope: None, | |
| 5989 | + writes_before: None, | |
| 5990 | + request_id: None, | |
| 5991 | + active_request_id: None, | |
| 5992 | + reply: Some(Answer::Rpc(reply)), | |
| 5993 | + gated_reply: None, | |
| 5994 | + background: None, | |
| 5995 | + ops: std::collections::HashSet::new(), | |
| 5996 | + io_context_ops: std::collections::HashSet::new(), | |
| 5997 | + alarm: None, | |
| 5998 | + started: event_started, | |
| 5999 | + trace: None, | |
| 6000 | + failure: None, | |
| 6001 | + }; | |
| 6002 | + drop(guard); | |
| 6003 | + Begun::Running(Box::new(entry)) | |
| 6004 | + } | |
| 6005 | + Err(error) => { | |
| 6006 | + let _ = end_event_context(tc); | |
| 6007 | + let error = take_execution_termination(tc).unwrap_or(error); | |
| 6008 | + drop(guard); | |
| 6009 | + let _ = reply.send(Err(error)); | |
| 6010 | + Begun::Nothing | |
| 6011 | + } | |
| 6012 | + } | |
| 6013 | +} | |
| 6014 | + | |
| 6015 | +fn queue_property<'s>( | |
| 6016 | + scope: &mut v8::PinScope<'s, '_>, | |
| 6017 | + object: v8::Local<'s, v8::Object>, | |
| 6018 | + name: &str, | |
| 6019 | +) -> Result<v8::Local<'s, v8::Value>> { | |
| 6020 | + let key = v8::String::new(scope, name).unwrap(); | |
| 6021 | + object | |
| 6022 | + .get(scope, key.into()) | |
| 6023 | + .ok_or_else(|| anyhow!("queue result has no {name}")) | |
| 6024 | +} | |
| 6025 | + | |
| 6026 | +fn queue_bool<'s>( | |
| 6027 | + scope: &mut v8::PinScope<'s, '_>, | |
| 6028 | + object: v8::Local<'s, v8::Object>, | |
| 6029 | + name: &str, | |
| 6030 | +) -> Result<bool> { | |
| 6031 | + let value = queue_property(scope, object, name)?; | |
| 6032 | + anyhow::ensure!(value.is_boolean(), "queue result {name} is not a boolean"); | |
| 6033 | + Ok(value.boolean_value(scope)) | |
| 6034 | +} | |
| 6035 | + | |
| 6036 | +fn queue_delay<'s>( | |
| 6037 | + scope: &mut v8::PinScope<'s, '_>, | |
| 6038 | + object: v8::Local<'s, v8::Object>, | |
| 6039 | +) -> Result<Option<i32>> { | |
| 6040 | + let value = queue_property(scope, object, "delaySeconds")?; | |
| 6041 | + if value.is_undefined() { | |
| 6042 | + return Ok(None); | |
| 6043 | + } | |
| 6044 | + value | |
| 6045 | + .int32_value(scope) | |
| 6046 | + .map(Some) | |
| 6047 | + .ok_or_else(|| anyhow!("queue retry delaySeconds is not a 32-bit integer")) | |
| 6048 | +} | |
| 6049 | + | |
| 6050 | +fn queue_string_array<'s>( | |
| 6051 | + scope: &mut v8::PinScope<'s, '_>, | |
| 6052 | + object: v8::Local<'s, v8::Object>, | |
| 6053 | + name: &str, | |
| 6054 | +) -> Result<Vec<String>> { | |
| 6055 | + let value = queue_property(scope, object, name)?; | |
| 6056 | + let array: v8::Local<v8::Array> = value | |
| 6057 | + .try_into() | |
| 6058 | + .map_err(|_| anyhow!("queue result {name} is not an array"))?; | |
| 6059 | + (0..array.length()) | |
| 6060 | + .map(|index| { | |
| 6061 | + let value = array | |
| 6062 | + .get_index(scope, index) | |
| 6063 | + .ok_or_else(|| anyhow!("queue result {name}[{index}] is missing"))?; | |
| 6064 | + anyhow::ensure!( | |
| 6065 | + value.is_string(), | |
| 6066 | + "queue result {name}[{index}] is not a string" | |
| 6067 | + ); | |
| 6068 | + Ok(value.to_rust_string_lossy(scope)) | |
| 6069 | + }) | |
| 6070 | + .collect() | |
| 6071 | +} | |
| 6072 | + | |
| 6073 | +fn read_queue_result<'s>( | |
| 6074 | + scope: &mut v8::PinScope<'s, '_>, | |
| 6075 | + value: v8::Local<'s, v8::Value>, | |
| 6076 | +) -> Result<QueueDispatchResult> { | |
| 6077 | + let object: v8::Local<v8::Object> = value | |
| 6078 | + .try_into() | |
| 6079 | + .map_err(|_| anyhow!("queue handler answered a non-object"))?; | |
| 6080 | + let outcome = queue_property(scope, object, "outcome")?; | |
| 6081 | + anyhow::ensure!(outcome.is_string(), "queue result outcome is not a string"); | |
| 6082 | + let outcome = match outcome.to_rust_string_lossy(scope).as_str() { | |
| 6083 | + "ok" => QueueOutcome::Ok, | |
| 6084 | + "exception" => QueueOutcome::Exception, | |
| 6085 | + outcome => return Err(anyhow!("unknown queue result outcome {outcome}")), | |
| 6086 | + }; | |
| 6087 | + let error = queue_property(scope, object, "error")?; | |
| 6088 | + let error = if error.is_undefined() { | |
| 6089 | + None | |
| 6090 | + } else { | |
| 6091 | + anyhow::ensure!(error.is_string(), "queue result error is not a string"); | |
| 6092 | + Some(error.to_rust_string_lossy(scope)) | |
| 6093 | + }; | |
| 6094 | + let retry_batch: v8::Local<v8::Object> = queue_property(scope, object, "retryBatch")? | |
| 6095 | + .try_into() | |
| 6096 | + .map_err(|_| anyhow!("queue result retryBatch is not an object"))?; | |
| 6097 | + let retries = queue_property(scope, object, "retryMessages")?; | |
| 6098 | + let retries: v8::Local<v8::Array> = retries | |
| 6099 | + .try_into() | |
| 6100 | + .map_err(|_| anyhow!("queue result retryMessages is not an array"))?; | |
| 6101 | + let mut retry_messages = Vec::with_capacity(retries.length() as usize); | |
| 6102 | + for index in 0..retries.length() { | |
| 6103 | + let retry: v8::Local<v8::Object> = retries | |
| 6104 | + .get_index(scope, index) | |
| 6105 | + .ok_or_else(|| anyhow!("queue result retryMessages[{index}] is missing"))? | |
| 6106 | + .try_into() | |
| 6107 | + .map_err(|_| anyhow!("queue result retryMessages[{index}] is not an object"))?; | |
| 6108 | + let msg_id = queue_property(scope, retry, "msgId")?; | |
| 6109 | + anyhow::ensure!( | |
| 6110 | + msg_id.is_string(), | |
| 6111 | + "queue result retryMessages[{index}].msgId is not a string" | |
| 6112 | + ); | |
| 6113 | + retry_messages.push(QueueRetryMessage { | |
| 6114 | + msg_id: msg_id.to_rust_string_lossy(scope), | |
| 6115 | + delay_seconds: queue_delay(scope, retry)?, | |
| 6116 | + }); | |
| 6117 | + } | |
| 6118 | + Ok(QueueDispatchResult { | |
| 6119 | + outcome, | |
| 6120 | + error, | |
| 6121 | + ack_all: queue_bool(scope, object, "ackAll")?, | |
| 6122 | + retry_batch: QueueRetryBatch { | |
| 6123 | + retry: queue_bool(scope, retry_batch, "retry")?, | |
| 6124 | + delay_seconds: queue_delay(scope, retry_batch)?, | |
| 6125 | + }, | |
| 6126 | + explicit_acks: queue_string_array(scope, object, "explicitAcks")?, | |
| 6127 | + retry_messages, | |
| 6128 | + }) | |
| 6129 | +} | |
| 6130 | + | |
| 6131 | +fn set_queue_property<'s>( | |
| 6132 | + scope: &mut v8::PinScope<'s, '_>, | |
| 6133 | + object: v8::Local<'s, v8::Object>, | |
| 6134 | + name: &str, | |
| 6135 | + value: v8::Local<'s, v8::Value>, | |
| 6136 | +) -> Result<()> { | |
| 6137 | + let key = v8::String::new(scope, name).unwrap(); | |
| 6138 | + anyhow::ensure!( | |
| 6139 | + object.create_data_property(scope, key.into(), value) == Some(true), | |
| 6140 | + "could not construct queue batch field {name}" | |
| 6141 | + ); | |
| 6142 | + Ok(()) | |
| 6143 | +} | |
| 6144 | + | |
| 6145 | +fn queue_batch_value<'s>( | |
| 6146 | + scope: &mut v8::PinScope<'s, '_>, | |
| 6147 | + batch: QueueBatch, | |
| 6148 | +) -> Result<v8::Local<'s, v8::Value>> { | |
| 6149 | + let QueueBatch { | |
| 6150 | + queue, | |
| 6151 | + messages, | |
| 6152 | + metrics, | |
| 6153 | + } = batch; | |
| 6154 | + let mut message_values = Vec::with_capacity(messages.len()); | |
| 6155 | + for message in messages { | |
| 6156 | + let object = v8::Object::new(scope); | |
| 6157 | + let id = v8::String::new(scope, &message.id).unwrap(); | |
| 6158 | + set_queue_property(scope, object, "id", id.into())?; | |
| 6159 | + let timestamp = v8::Number::new(scope, message.timestamp_ms as f64); | |
| 6160 | + set_queue_property(scope, object, "timestamp", timestamp.into())?; | |
| 6161 | + let body = bytes_value(scope, message.body); | |
| 6162 | + set_queue_property(scope, object, "body", body)?; | |
| 6163 | + let content_type = v8::String::new(scope, message.content_type.as_str()).unwrap(); | |
| 6164 | + set_queue_property(scope, object, "contentType", content_type.into())?; | |
| 6165 | + let attempts = v8::Integer::new_from_unsigned(scope, u32::from(message.attempts)); | |
| 6166 | + set_queue_property(scope, object, "attempts", attempts.into())?; | |
| 6167 | + message_values.push(object.into()); | |
| 6168 | + } | |
| 6169 | + | |
| 6170 | + let metrics_value = v8::Object::new(scope); | |
| 6171 | + let count = v8::Number::new(scope, metrics.backlog_count); | |
| 6172 | + set_queue_property(scope, metrics_value, "backlogCount", count.into())?; | |
| 6173 | + let bytes = v8::Number::new(scope, metrics.backlog_bytes); | |
| 6174 | + set_queue_property(scope, metrics_value, "backlogBytes", bytes.into())?; | |
| 6175 | + let oldest = match metrics.oldest_message_timestamp_ms { | |
| 6176 | + Some(timestamp) => v8::Number::new(scope, timestamp as f64).into(), | |
| 6177 | + None => v8::undefined(scope).into(), | |
| 6178 | + }; | |
| 6179 | + set_queue_property(scope, metrics_value, "oldestMessageTimestamp", oldest)?; | |
| 6180 | + | |
| 6181 | + let value = v8::Object::new(scope); | |
| 6182 | + let queue = v8::String::new(scope, &queue).unwrap(); | |
| 6183 | + set_queue_property(scope, value, "queue", queue.into())?; | |
| 6184 | + let messages = v8::Array::new_with_elements(scope, &message_values); | |
| 6185 | + set_queue_property(scope, value, "messages", messages.into())?; | |
| 6186 | + set_queue_property(scope, value, "metrics", metrics_value.into())?; | |
| 6187 | + Ok(value.into()) | |
| 6188 | +} | |
| 6189 | + | |
| 6190 | +/// Start a queue consumer's first turn. The batch body bytes move directly | |
| 6191 | +/// into V8, and only the small settlement record crosses back out. | |
| 6192 | +fn begin_queue( | |
| 6193 | + tc: &mut v8::PinScope, | |
| 6194 | + batch: QueueBatch, | |
| 6195 | + reply: tokio::sync::oneshot::Sender<Result<QueueDispatchResult>>, | |
| 6196 | +) -> Begun { | |
| 6197 | + let context = IoContext::new(); | |
| 6198 | + let guard = CurrentGuard::enter(context.clone()); | |
| 6199 | + let started = (|| { | |
| 6200 | + let dispatch = dispatcher(tc, "__dispatchEntrypointQueue")?; | |
| 6201 | + let batch = queue_batch_value(tc, batch)?; | |
| 6202 | + let entrypoint = v8::String::new(tc, "default").unwrap(); | |
| 6203 | + let recv = v8::undefined(tc).into(); | |
| 6204 | + begin_event_context(tc)?; | |
| 6205 | + let ret = dispatch | |
| 6206 | + .call(tc, recv, &[entrypoint.into(), batch]) | |
| 6207 | + .ok_or_else(|| anyhow!("queue dispatch threw"))?; | |
| 6208 | + match ret.try_cast::<v8::Promise>() { | |
| 6209 | + Ok(promise) => Ok(promise), | |
| 6210 | + Err(_) => resolved_promise(tc, ret), | |
| 6211 | + } | |
| 6212 | + })(); | |
| 6213 | + match started { | |
| 6214 | + Ok(promise) => { | |
| 6215 | + tc.perform_microtask_checkpoint(); | |
| 6216 | + let entry = InFlight { | |
| 6217 | + runtime_state: actor_runtime_state(tc), | |
| 6218 | + promise: v8::Global::new(tc, promise), | |
| 6219 | + context, | |
| 6220 | + scope: None, | |
| 6221 | + writes_before: None, | |
| 6222 | + request_id: None, | |
| 6223 | + active_request_id: None, | |
| 6224 | + reply: Some(Answer::Queue(reply)), | |
| 6225 | + gated_reply: None, | |
| 6226 | + background: None, | |
| 6227 | + ops: std::collections::HashSet::new(), | |
| 6228 | + io_context_ops: std::collections::HashSet::new(), | |
| 6229 | + alarm: None, | |
| 6230 | + started: Instant::now(), | |
| 6231 | + trace: None, | |
| 6232 | + failure: None, | |
| 6233 | + }; | |
| 6234 | + drop(guard); | |
| 6235 | + Begun::Running(Box::new(entry)) | |
| 6236 | + } | |
| 6237 | + Err(error) => { | |
| 6238 | + let _ = end_event_context(tc); | |
| 6239 | + let error = take_execution_termination(tc).unwrap_or(error); | |
| 6240 | + drop(guard); | |
| 6241 | + let _ = reply.send(Err(error)); | |
| 6242 | + Begun::Nothing | |
| 6243 | + } | |
| 6244 | + } | |
| 6245 | +} | |
| 6246 | + | |
| 6247 | +/// for the JSON flavor, a `Uint8Array` for structured clone. | |
| 6248 | +fn rpc_data_value<'s>(scope: &mut v8::PinScope<'s, '_>, data: RpcData) -> v8::Local<'s, v8::Value> { | |
| 6249 | + match data { | |
| 6250 | + RpcData::Json(json) => v8::String::new(scope, &json).unwrap().into(), | |
| 6251 | + RpcData::V8(bytes) => bytes_value(scope, bytes.into()), | |
| 6252 | + } | |
| 6253 | +} | |
| 6254 | + | |
| 6255 | +/// The inverse: `__dispatchRpc` answers in the flavor it was asked in. | |
| 6256 | +fn rpc_data_ret(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> RpcData { | |
| 6257 | + match view_bytes(ret) { | |
| 6258 | + Some(bytes) => RpcData::V8(bytes.into()), | |
| 6259 | + None => RpcData::Json(ret.to_rust_string_lossy(scope)), | |
| 6260 | + } | |
| 6261 | +} | |
| 6262 | + | |
| 6263 | +fn unix_now_ms() -> i64 { | |
| 6264 | + std::time::SystemTime::now() | |
| 6265 | + .duration_since(std::time::UNIX_EPOCH) | |
| 6266 | + .unwrap_or_default() | |
| 6267 | + .as_millis() | |
| 6268 | + .min(i64::MAX as u128) as i64 | |
| 6269 | +} | |
| 6270 | + | |
| 6271 | +/// End the event, then answer with what the handler produced. | |
| 6272 | +/// | |
| 6273 | +/// Ending it is what yields the `waitUntil` aggregate the entry keeps | |
| 6274 | +/// driving after the caller has been served, so it happens for every answer | |
| 6275 | +/// shape and on the error path too. | |
| 6276 | +fn send_and_end<T>( | |
| 6277 | + tc: &mut v8::PinScope, | |
| 6278 | + context: &IoContext, | |
| 6279 | + reply: tokio::sync::oneshot::Sender<Result<T>>, | |
| 6280 | + value: Result<T>, | |
| 6281 | +) -> (Option<v8::Global<v8::Promise>>, Option<GatedReplyRx>) | |
| 6282 | +where | |
| 6283 | + T: Send + 'static, | |
| 6284 | +{ | |
| 6285 | + let background = end_event_context(tc).ok().flatten(); | |
| 6286 | + let gated_reply = send_answer_after_arm_gates(reply, value, context.take_arm_gates()); | |
| 6287 | + ( | |
| 6288 | + background.map(|promise| v8::Global::new(tc, promise)), | |
| 6289 | + gated_reply, | |
| 6290 | + ) | |
| 6291 | +} | |
| 6292 | + | |
| 6293 | +/// The positions an answer's ticket carries, sampled from a cell's storage: | |
| 6294 | +/// the write position when the handler advanced the cell's committed writes | |
| 6295 | +/// past `writes_before`, and otherwise the position the answer observed above | |
| 6296 | +/// the cell's published baseline. One sample serves both, so they cannot | |
| 6297 | +/// disagree about what the cell holds, and they are returned together because | |
| 6298 | +/// a site that gates on one alone releases the output the other covers. | |
| 6299 | +fn gate_positions(scope: &str, writes_before: Option<u64>) -> (Option<u64>, Option<u64>) { | |
| 6300 | + let sample = storage::write_position(scope); | |
| 6301 | + let write = write_delta(writes_before, sample); | |
| 6302 | + let observed = if write.is_none() { | |
| 6303 | + storage::observed_position(scope, sample) | |
| 6304 | + } else { | |
| 6305 | + None | |
| 6306 | + }; | |
| 6307 | + (write, observed) | |
| 6308 | +} | |
| 6309 | + | |
| 6310 | +/// A committed-write position only counts when the handler advanced it; celld's | |
| 6311 | +/// own activation writes are already below `before`. | |
| 6312 | +pub(crate) fn write_delta(before: Option<u64>, after: Option<u64>) -> Option<u64> { | |
| 6313 | + match (before, after) { | |
| 6314 | + (Some(before), Some(after)) if after > before => Some(after), | |
| 6315 | + _ => None, | |
| 6316 | + } | |
| 6317 | +} | |
| 6318 | + | |
| 6319 | +/// A handler that failed inside its turn, with the positions that turn | |
| 6320 | +/// sampled from the cell. | |
| 6321 | +/// | |
| 6322 | +/// A commit the handler made before it failed is as real as one a successful | |
| 6323 | +/// handler made: it stays in the local database, unproven, and a read-only | |
| 6324 | +/// output that followed would trail no barrier and reveal it while a crash can | |
| 6325 | +/// still lose it. The error answer therefore takes the same write ticket a | |
| 6326 | +/// success takes. | |
| 6327 | +/// | |
| 6328 | +/// A handler that committed nothing still reveals what it read, because the | |
| 6329 | +/// message it throws with can quote it — "insufficient funds: balance is 90" | |
| 6330 | +/// is an ordinary shape — and that value can be another event's commit that no | |
| 6331 | +/// proof covers yet. An error answer reveals cell state exactly as a 200 does, | |
| 6332 | +/// so a read-only failure carries the observed position and the gate holds it | |
| 6333 | +/// behind the newest barrier, as it holds a read-only success (#765). | |
| 6334 | +/// | |
| 6335 | +/// The failure the handler reported is the source; this wrapper displays its | |
| 6336 | +/// message and continues its chain, so a client and a log see the handler's | |
| 6337 | +/// own words. | |
| 6338 | +#[derive(Debug)] | |
| 6339 | +pub struct FailedInTurn { | |
| 6340 | + write_position: Option<u64>, | |
| 6341 | + observed_position: Option<u64>, | |
| 6342 | + source: anyhow::Error, | |
| 6343 | +} | |
| 6344 | + | |
| 6345 | +impl std::fmt::Display for FailedInTurn { | |
| 6346 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 6347 | + write!(f, "{}", self.source) | |
| 6348 | + } | |
| 6349 | +} | |
| 6350 | + | |
| 6351 | +impl std::error::Error for FailedInTurn { | |
| 6352 | + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | |
| 6353 | + // The wrapped error's own message is this wrapper's display, so the | |
| 6354 | + // chain continues below it rather than repeating it. The wrapped | |
| 6355 | + // error's own type is therefore not in the chain: a `downcast_ref` | |
| 6356 | + // for it, or a `chain()` walk that looks for it, sees this wrapper | |
| 6357 | + // instead. Every error that reaches `fail_in_turn_error` today is a | |
| 6358 | + // plain message, so nothing looks; a typed handler failure would have | |
| 6359 | + // to be matched through `failed_write_position` and its text. | |
| 6360 | + let source: &(dyn std::error::Error + 'static) = self.source.as_ref(); | |
| 6361 | + source.source() | |
| 6362 | + } | |
| 6363 | +} | |
| 6364 | + | |
| 6365 | +/// Attach the positions a failing handler's turn sampled, when it has either. | |
| 6366 | +/// The pair comes from one `gate_positions` call, so an error cannot report a | |
| 6367 | +/// write and an observation that disagree. | |
| 6368 | +fn fail_in_turn_error( | |
| 6369 | + error: anyhow::Error, | |
| 6370 | + positions: (Option<u64>, Option<u64>), | |
| 6371 | +) -> anyhow::Error { | |
| 6372 | + let (write_position, observed_position) = positions; | |
| 6373 | + if write_position.is_none() && observed_position.is_none() { | |
| 6374 | + return error; | |
| 6375 | + } | |
| 6376 | + anyhow::Error::new(FailedInTurn { | |
| 6377 | + write_position, | |
| 6378 | + observed_position, | |
| 6379 | + source: error, | |
| 6380 | + }) | |
| 6381 | +} | |
| 6382 | + | |
| 6383 | +/// The position a failed handler committed before it failed, when it did. | |
| 6384 | +pub fn failed_write_position(error: &anyhow::Error) -> Option<u64> { | |
| 6385 | + error | |
| 6386 | + .downcast_ref::<FailedInTurn>() | |
| 6387 | + .and_then(|failed| failed.write_position) | |
| 6388 | +} | |
| 6389 | + | |
| 6390 | +/// An answer the shell gates: a success reports the position its writes | |
| 6391 | +/// reached, and the position it observed when it wrote nothing, in its own | |
| 6392 | +/// shape. | |
| 6393 | +pub trait GatedAnswer { | |
| 6394 | + fn write_position(&self) -> Option<u64>; | |
| 6395 | + fn observed_position(&self) -> Option<u64>; | |
| 6396 | +} | |
| 6397 | + | |
| 6398 | +impl GatedAnswer for HttpResponse { | |
| 6399 | + fn write_position(&self) -> Option<u64> { | |
| 6400 | + self.write_position | |
| 6401 | + } | |
| 6402 | + | |
| 6403 | + fn observed_position(&self) -> Option<u64> { | |
| 6404 | + self.observed_position | |
| 6405 | + } | |
| 6406 | +} | |
| 6407 | + | |
| 6408 | +impl GatedAnswer for RpcOutcome { | |
| 6409 | + fn write_position(&self) -> Option<u64> { | |
| 6410 | + self.write_position | |
| 6411 | + } | |
| 6412 | + | |
| 6413 | + fn observed_position(&self) -> Option<u64> { | |
| 6414 | + self.observed_position | |
| 6415 | + } | |
| 6416 | +} | |
| 6417 | + | |
| 6418 | +/// The ticket an answer takes through the output gate, or `None` when it | |
| 6419 | +/// takes none. | |
| 6420 | +/// | |
| 6421 | +/// A success always takes one: a write ticket when the handler advanced the | |
| 6422 | +/// position, and otherwise a read-only ticket that carries what the answer | |
| 6423 | +/// observed and trails the newest barrier on the cell. A failure raised inside | |
| 6424 | +/// the handler's turn takes the same two shapes, which [`FailedInTurn`] | |
| 6425 | +/// reports, because an error message can carry the cell's state as a body can. | |
| 6426 | +/// A failure raised outside a turn — a budget overrun, a handler waiting on | |
| 6427 | +/// nothing — took no sample and reports the host's own words, so it reveals | |
| 6428 | +/// nothing and takes no ticket. The shell reads both arms through this one | |
| 6429 | +/// function so that no answer site can gate one and forget the other. | |
| 6430 | +pub fn answer_ticket<T: GatedAnswer>(result: &Result<T>) -> Option<crate::actor::GateTicket> { | |
| 6431 | + match result { | |
| 6432 | + Ok(answer) => Some(crate::actor::GateTicket::response( | |
| 6433 | + answer.write_position(), | |
| 6434 | + answer.observed_position(), | |
| 6435 | + )), | |
| 6436 | + Err(error) => error.downcast_ref::<FailedInTurn>().map(|failed| { | |
| 6437 | + crate::actor::GateTicket::response(failed.write_position, failed.observed_position) | |
| 6438 | + }), | |
| 6439 | + } | |
| 6440 | +} | |
| 6441 | + | |
| 6442 | +/// What a Durable Object RPC method returned, plus the position its writes | |
| 6443 | +/// reached, so the caller can hold the reply behind durability. | |
| 6444 | +pub struct RpcOutcome { | |
| 6445 | + pub data: RpcData, | |
| 6446 | + pub write_position: Option<u64>, | |
| 6447 | + /// As on `HttpResponse`: what a read-only reply observed above the cell's | |
| 6448 | + /// published baseline. | |
| 6449 | + pub observed_position: Option<u64>, | |
| 6450 | +} | |
| 6451 | + | |
| 6452 | +/// What a claimed alarm still owes its bookkeeping. | |
| 6453 | +/// | |
| 6454 | +/// `finish_alarm_handler` must run exactly once however the event ends, and | |
| 6455 | +/// an event can now end without running JS at all — a budget overrun, a | |
| 6456 | +/// handler waiting on nothing — so the entry carries the claim rather than | |
| 6457 | +/// the caller that made it. | |
| 6458 | +struct AlarmClaim { | |
| 6459 | + /// The instant the dispatch was judged due against, so the outcome is | |
| 6460 | + /// recorded against the same one. | |
| 6461 | + now_ms: i64, | |
| 6462 | +} | |
| 6463 | + | |
| 6464 | +/// Start one cell event: the half that runs before the handler can suspend. | |
| 6465 | +/// | |
| 6466 | +/// Every cell event does the same four things — name the cell it belongs to, | |
| 6467 | +/// sample the writes its answer will be gated on, open an event context, and | |
| 6468 | +/// keep the promise the dispatcher returned. Only the call and the shape of | |
| 6469 | +/// the answer differ, which is what the arguments say. | |
| 6470 | +fn start_cell_event<'s>( | |
| 6471 | + tc: &mut v8::PinScope<'s, '_>, | |
| 6472 | + scope: &str, | |
| 6473 | + answer: Answer, | |
| 6474 | + request_id: Option<RequestId>, | |
| 6475 | + body_stream_id: Option<u64>, | |
| 6476 | + capture_frames: bool, | |
| 6477 | + call: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>>, | |
| 6478 | +) -> Begun { | |
| 6479 | + let runtime_state = actor_runtime_state(tc); | |
| 6480 | + let context = IoContext::tracked(&runtime_state); | |
| 6481 | + if let Some(stream_id) = body_stream_id { | |
| 6482 | + context.own_body_stream(stream_id); | |
| 6483 | + } | |
| 6484 | + let guard = CurrentGuard::enter(context.clone()); | |
| 6485 | + let previous_io_context = install_io_context(tc, &context); | |
| 6486 | + // Sampled before the handler runs so the output gate can tell a write | |
| 6487 | + // this event made from celld's own activation writes. The first sample of | |
| 6488 | + // an activation is also the baseline a read-only answer observes above. | |
| 6489 | + let writes_before = storage::event_start_position(scope); | |
| 6490 | + // No guard: this frame is the context's outermost one and the context | |
| 6491 | + // ends with the event, so there is nothing to pop it before. | |
| 6492 | + context.egress.lock().unwrap().push(EgressFrame { | |
| 6493 | + storage: scope.to_string(), | |
| 6494 | + before: writes_before.unwrap_or(0), | |
| 6495 | + // A facet event stores here and gates on the cell that owns the root | |
| 6496 | + // database. Read once, with the position, so no later effect can take | |
| 6497 | + // one without the other. | |
| 6498 | + root: storage::embedded_root_gate(scope), | |
| 6499 | + }); | |
| 6500 | + if capture_frames { | |
| 6501 | + ws_capture_begin(); | |
| 6502 | + } | |
| 6503 | + let event_started = Instant::now(); | |
| 6504 | + let started = (|| { | |
| 6505 | + begin_event_context(tc)?; | |
| 6506 | + let ret = call(tc)?; | |
| 6507 | + match ret.try_cast::<v8::Promise>() { | |
| 6508 | + Ok(promise) => Ok(promise), | |
| 6509 | + Err(_) => resolved_promise(tc, ret), | |
| 6510 | + } | |
| 6511 | + })(); | |
| 6512 | + match started { | |
| 6513 | + Ok(promise) => { | |
| 6514 | + tc.perform_microtask_checkpoint(); | |
| 6515 | + let entry = InFlight { | |
| 6516 | + runtime_state: runtime_state.clone(), | |
| 6517 | + promise: v8::Global::new(tc, promise), | |
| 6518 | + context, | |
| 6519 | + scope: Some(scope.to_string()), | |
| 6520 | + writes_before, | |
| 6521 | + request_id, | |
| 6522 | + // A cell's dispatcher registers the incoming request itself, | |
| 6523 | + // so there is nothing for the shell to finish; `cancel` | |
| 6524 | + // aborts by the job's own id. | |
| 6525 | + active_request_id: None, | |
| 6526 | + reply: Some(answer), | |
| 6527 | + gated_reply: None, | |
| 6528 | + background: None, | |
| 6529 | + ops: std::collections::HashSet::new(), | |
| 6530 | + io_context_ops: std::collections::HashSet::new(), | |
| 6531 | + alarm: None, | |
| 6532 | + started: event_started, | |
| 6533 | + trace: None, | |
| 6534 | + failure: None, | |
| 6535 | + }; | |
| 6536 | + restore_io_context(tc, previous_io_context); | |
| 6537 | + drop(guard); | |
| 6538 | + Begun::Running(Box::new(entry)) | |
| 6539 | + } | |
| 6540 | + Err(error) => { | |
| 6541 | + // A V8 termination has a concrete stored cause. The dispatcher | |
| 6542 | + // wrapper can only report that its call returned no value, so do | |
| 6543 | + // not replace process.exit or actor-abort with that generic seam. | |
| 6544 | + let error = take_execution_termination(tc).unwrap_or(error); | |
| 6545 | + // The handler ran synchronously before it threw, and a | |
| 6546 | + // synchronous storage call both commits and reads, so the error | |
| 6547 | + // carries the positions it reached like a rejection does. | |
| 6548 | + let error = fail_in_turn_error(error, gate_positions(scope, writes_before)); | |
| 6549 | + let background = end_event_context(tc) | |
| 6550 | + .ok() | |
| 6551 | + .flatten() | |
| 6552 | + .map(|promise| v8::Global::new(tc, promise)); | |
| 6553 | + let failure = crate::telemetry::cap_error(format!("{error:#}")); | |
| 6554 | + let gated_reply = answer.fail_with_arm_gates(error, context.take_arm_gates()); | |
| 6555 | + let begun = if gated_reply.is_none() && background.is_none() { | |
| 6556 | + Begun::Nothing | |
| 6557 | + } else { | |
| 6558 | + let undefined = v8::undefined(tc).into(); | |
| 6559 | + let promise = resolved_promise(tc, undefined) | |
| 6560 | + .expect("a finishing cell event can create a resolved promise"); | |
| 6561 | + Begun::Running(Box::new(InFlight { | |
| 6562 | + runtime_state, | |
| 6563 | + promise: v8::Global::new(tc, promise), | |
| 6564 | + context, | |
| 6565 | + scope: Some(scope.to_string()), | |
| 6566 | + writes_before, | |
| 6567 | + request_id, | |
| 6568 | + active_request_id: None, | |
| 6569 | + reply: None, | |
| 6570 | + gated_reply, | |
| 6571 | + background, | |
| 6572 | + ops: std::collections::HashSet::new(), | |
| 6573 | + io_context_ops: std::collections::HashSet::new(), | |
| 6574 | + alarm: None, | |
| 6575 | + started: event_started, | |
| 6576 | + trace: None, | |
| 6577 | + failure: Some(failure), | |
| 6578 | + })) | |
| 6579 | + }; | |
| 6580 | + restore_io_context(tc, previous_io_context); | |
| 6581 | + drop(guard); | |
| 6582 | + begun | |
| 6583 | + } | |
| 6584 | + } | |
| 6585 | +} | |
| 6586 | + | |
| 6587 | +/// Look one of the harness dispatchers up on the current realm's global. | |
| 6588 | +fn dispatcher<'s>( | |
| 6589 | + tc: &mut v8::PinScope<'s, '_>, | |
| 6590 | + name: &str, | |
| 6591 | +) -> Result<v8::Local<'s, v8::Function>> { | |
| 6592 | + let global = tc.get_current_context().global(tc); | |
| 6593 | + let key = v8::String::new(tc, name).unwrap(); | |
| 6594 | + global | |
| 6595 | + .get(tc, key.into()) | |
| 6596 | + .ok_or_else(|| anyhow!("no {name}"))? | |
| 6597 | + .try_into() | |
| 6598 | + .map_err(|_| anyhow!("{name} is not a function")) | |
| 6599 | +} | |
| 6600 | + | |
| 6601 | +/// Start a cell event's first turn. | |
| 6602 | +/// | |
| 6603 | +/// The counterpart of `begin` for the events a cell receives. Where the | |
| 6604 | +/// blocking loop ran each of these to completion inside one call — and | |
| 6605 | +/// serviced other cells' events inside *that* — each is now an entry a tokio | |
| 6606 | +/// task drives, so two events of one cell interleave by suspending rather | |
| 6607 | +/// than by nesting. | |
| 6608 | +fn begin_cell(tc: &mut v8::PinScope, job: CellJob) -> Begun { | |
| 6609 | + match job { | |
| 6610 | + CellJob::Fetch { | |
| 6611 | + request_id, | |
| 6612 | + scope, | |
| 6613 | + name, | |
| 6614 | + url, | |
| 6615 | + method, | |
| 6616 | + body, | |
| 6617 | + headers, | |
| 6618 | + reply, | |
| 6619 | + order: _, | |
| 6620 | + } => { | |
| 6621 | + if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) { | |
| 6622 | + let _ = reply.send(Err(error)); | |
| 6623 | + return Begun::Nothing; | |
| 6624 | + } | |
| 6625 | + let body_stream_id = body.stream_id(); | |
| 6626 | + start_cell_event( | |
| 6627 | + tc, | |
| 6628 | + &scope, | |
| 6629 | + Answer::Fetch(reply), | |
| 6630 | + request_id, | |
| 6631 | + body_stream_id, | |
| 6632 | + false, | |
| 6633 | + |tc| { | |
| 6634 | + let f = dispatcher(tc, "__dispatchTo")?; | |
| 6635 | + // A held body crosses as its bytes; a streamed body crosses as | |
| 6636 | + // its host stream id, so the handler reads it in parts instead | |
| 6637 | + // of the routing seam collecting it first. | |
| 6638 | + let (body_value, stream_id) = match body { | |
| 6639 | + RequestBody::Bytes(bytes) => { | |
| 6640 | + (bytes_value(tc, bytes.into()), v8::null(tc).into()) | |
| 6641 | + } | |
| 6642 | + RequestBody::Stream(id) => ( | |
| 6643 | + v8::undefined(tc).into(), | |
| 6644 | + v8::Number::new(tc, id as f64).into(), | |
| 6645 | + ), | |
| 6646 | + }; | |
| 6647 | + let arguments = [ | |
| 6648 | + v8::String::new(tc, &scope).unwrap().into(), | |
| 6649 | + v8::String::new(tc, &url).unwrap().into(), | |
| 6650 | + v8::String::new(tc, &method).unwrap().into(), | |
| 6651 | + body_value, | |
| 6652 | + v8::String::new(tc, &serde_json::to_string(&headers)?) | |
| 6653 | + .unwrap() | |
| 6654 | + .into(), | |
| 6655 | + match request_id { | |
| 6656 | + Some(id) => v8::String::new(tc, &request_id_string(id)).unwrap().into(), | |
| 6657 | + None => v8::null(tc).into(), | |
| 6658 | + }, | |
| 6659 | + stream_id, | |
| 6660 | + ]; | |
| 6661 | + let recv = v8::undefined(tc).into(); | |
| 6662 | + f.call(tc, recv, &arguments) | |
| 6663 | + .ok_or_else(|| anyhow!("dispatchTo threw")) | |
| 6664 | + }, | |
| 6665 | + ) | |
| 6666 | + } | |
| 6667 | + CellJob::Rpc { | |
| 6668 | + request_id, | |
| 6669 | + scope, | |
| 6670 | + name, | |
| 6671 | + method, | |
| 6672 | + args, | |
| 6673 | + reply, | |
| 6674 | + } => { | |
| 6675 | + if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) { | |
| 6676 | + let _ = reply.send(Err(error)); | |
| 6677 | + return Begun::Nothing; | |
| 6678 | + } | |
| 6679 | + start_cell_event( | |
| 6680 | + tc, | |
| 6681 | + &scope, | |
| 6682 | + Answer::CellRpc(reply), | |
| 6683 | + request_id, | |
| 6684 | + None, | |
| 6685 | + false, | |
| 6686 | + |tc| { | |
| 6687 | + let f = dispatcher(tc, "__dispatchRpc")?; | |
| 6688 | + let arguments = [ | |
| 6689 | + v8::String::new(tc, &scope).unwrap().into(), | |
| 6690 | + v8::String::new(tc, &method).unwrap().into(), | |
| 6691 | + rpc_data_value(tc, args), | |
| 6692 | + ]; | |
| 6693 | + let recv = v8::undefined(tc).into(); | |
| 6694 | + f.call(tc, recv, &arguments) | |
| 6695 | + .ok_or_else(|| anyhow!("dispatchRpc threw")) | |
| 6696 | + }, | |
| 6697 | + ) | |
| 6698 | + } | |
| 6699 | + CellJob::WsOpen { | |
| 6700 | + scope, | |
| 6701 | + ws_id, | |
| 6702 | + protocol, | |
| 6703 | + reply, | |
| 6704 | + } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| { | |
| 6705 | + let f = dispatcher(tc, "__wsOpen")?; | |
| 6706 | + let arguments = [ | |
| 6707 | + v8::String::new(tc, &scope).unwrap().into(), | |
| 6708 | + v8::Number::new(tc, ws_id as f64).into(), | |
| 6709 | + v8::String::new(tc, &protocol).unwrap().into(), | |
| 6710 | + ]; | |
| 6711 | + let recv = v8::undefined(tc).into(); | |
| 6712 | + f.call(tc, recv, &arguments) | |
| 6713 | + .ok_or_else(|| anyhow!("wsOpen threw")) | |
| 6714 | + }), | |
| 6715 | + CellJob::WsMessage { | |
| 6716 | + scope, | |
| 6717 | + ws_id, | |
| 6718 | + data, | |
| 6719 | + reply, | |
| 6720 | + } => start_cell_event( | |
| 6721 | + tc, | |
| 6722 | + &scope, | |
| 6723 | + Answer::WsMessage(reply), | |
| 6724 | + None, | |
| 6725 | + None, | |
| 6726 | + true, | |
| 6727 | + |tc| { | |
| 6728 | + let (name, data) = match data { | |
| 6729 | + WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()), | |
| 6730 | + WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)), | |
| 6731 | + }; | |
| 6732 | + let f = dispatcher(tc, name)?; | |
| 6733 | + let arguments = [ | |
| 6734 | + v8::String::new(tc, &scope).unwrap().into(), | |
| 6735 | + v8::Number::new(tc, ws_id as f64).into(), | |
| 6736 | + data, | |
| 6737 | + ]; | |
| 6738 | + let recv = v8::undefined(tc).into(); | |
| 6739 | + f.call(tc, recv, &arguments) | |
| 6740 | + .ok_or_else(|| anyhow!("WebSocket message dispatch threw")) | |
| 6741 | + }, | |
| 6742 | + ), | |
| 6743 | + CellJob::WsClosed { | |
| 6744 | + scope, | |
| 6745 | + ws_id, | |
| 6746 | + code, | |
| 6747 | + reason, | |
| 6748 | + was_clean, | |
| 6749 | + reply, | |
| 6750 | + } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| { | |
| 6751 | + let f = dispatcher(tc, "__wsClosed")?; | |
| 6752 | + let arguments = [ | |
| 6753 | + v8::String::new(tc, &scope).unwrap().into(), | |
| 6754 | + v8::Number::new(tc, ws_id as f64).into(), | |
| 6755 | + v8::Number::new(tc, f64::from(code)).into(), | |
| 6756 | + v8::String::new(tc, &reason).unwrap().into(), | |
| 6757 | + v8::Boolean::new(tc, was_clean).into(), | |
| 6758 | + ]; | |
| 6759 | + let recv = v8::undefined(tc).into(); | |
| 6760 | + f.call(tc, recv, &arguments) | |
| 6761 | + .ok_or_else(|| anyhow!("wsClosed threw")) | |
| 6762 | + }), | |
| 6763 | + CellJob::Alarm { | |
| 6764 | + request_id, | |
| 6765 | + scope, | |
| 6766 | + scheduled_ms, | |
| 6767 | + claim, | |
| 6768 | + reply, | |
| 6769 | + } => begin_alarm(tc, &scope, scheduled_ms, claim, request_id, reply), | |
| 6770 | + #[cfg(celld_internal_tests)] | |
| 6771 | + CellJob::SyncErrorForTest { | |
| 6772 | + scope, | |
| 6773 | + gate, | |
| 6774 | + socket_id, | |
| 6775 | + terminate, | |
| 6776 | + reply, | |
| 6777 | + } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| { | |
| 6778 | + register_arm_gate_with_current_event(gate, installed_context()); | |
| 6779 | + if let Some(socket_id) = socket_id { | |
| 6780 | + current_context().sockets.lock().unwrap().push(socket_id); | |
| 6781 | + } | |
| 6782 | + if terminate { | |
| 6783 | + let state = actor_runtime_state(tc); | |
| 6784 | + *state.termination.lock().expect("termination lock poisoned") = | |
| 6785 | + Some(ExecutionTermination { | |
| 6786 | + error: "synchronous V8 termination sentinel".to_string(), | |
| 6787 | + actor_scope: None, | |
| 6788 | + context_id: None, | |
| 6789 | + }); | |
| 6790 | + tc.terminate_execution(); | |
| 6791 | + Err(anyhow!("generic synchronous dispatch failure")) | |
| 6792 | + } else { | |
| 6793 | + Err(anyhow!("synchronous cell dispatch sentinel")) | |
| 6794 | + } | |
| 6795 | + }), | |
| 6796 | + } | |
| 6797 | +} | |
| 6798 | + | |
| 6799 | +/// Start an alarm, claiming the due entry so nothing else fires it. | |
| 6800 | +/// | |
| 6801 | +/// The claim is recorded on the entry rather than closed here, because the | |
| 6802 | +/// handler has not run yet: the outcome is known only when the event ends, | |
| 6803 | +/// which is now many turns away. | |
| 6804 | +fn begin_alarm( | |
| 6805 | + tc: &mut v8::PinScope, | |
| 6806 | + scope: &str, | |
| 6807 | + scheduled_ms: i64, | |
| 6808 | + claim: AlarmDispatch, | |
| 6809 | + request_id: Option<RequestId>, | |
| 6810 | + reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 6811 | +) -> Begun { | |
| 6812 | + let now = unix_now_ms(); | |
| 6813 | + if now < scheduled_ms { | |
| 6814 | + let _ = reply.send(Err(anyhow!("alarm dispatched before its deadline"))); | |
| 6815 | + return Begun::Nothing; | |
| 6816 | + } | |
| 6817 | + #[cfg(celld_internal_tests)] | |
| 6818 | + if let AlarmDispatch::Claimed(retry) = claim { | |
| 6819 | + let Some(scheduled_at) = storage::active_alarm_scheduled_time(scope) else { | |
| 6820 | + let _ = reply.send(Err(anyhow!("alarm dispatched without a claim"))); | |
| 6821 | + return Begun::Nothing; | |
| 6822 | + }; | |
| 6823 | + return fire_alarm_handler(tc, scope, scheduled_at, retry, None, request_id, reply); | |
| 6824 | + } | |
| 6825 | + let due_by = match claim { | |
| 6826 | + #[cfg(celld_internal_tests)] | |
| 6827 | + AlarmDispatch::Armed => i64::MAX, | |
| 6828 | + AlarmDispatch::Due => now, | |
| 6829 | + #[cfg(celld_internal_tests)] | |
| 6830 | + AlarmDispatch::Claimed(_) => unreachable!("claimed alarms return above"), | |
| 6831 | + }; | |
| 6832 | + let Some((scheduled_at, retry)) = storage::due_alarm_entry(scope, due_by) else { | |
| 6833 | + // Nothing is due: another dispatch already ran it, or the handler | |
| 6834 | + // that armed it cleared it. Answer what stands now, with no delta — | |
| 6835 | + // no handler ran, so there is nothing written to prove. | |
| 6836 | + let _ = reply.send(Ok((storage::get_alarm(scope), None))); | |
| 6837 | + return Begun::Nothing; | |
| 6838 | + }; | |
| 6839 | + storage::begin_alarm_handler(scope, scheduled_at); | |
| 6840 | + fire_alarm_handler( | |
| 6841 | + tc, | |
| 6842 | + scope, | |
| 6843 | + scheduled_at, | |
| 6844 | + retry, | |
| 6845 | + Some(AlarmClaim { now_ms: now }), | |
| 6846 | + request_id, | |
| 6847 | + reply, | |
| 6848 | + ) | |
| 6849 | +} | |
| 6850 | + | |
| 6851 | +/// Call `alarm()`, carrying whatever claim its outcome must close. | |
| 6852 | +fn fire_alarm_handler( | |
| 6853 | + tc: &mut v8::PinScope, | |
| 6854 | + scope: &str, | |
| 6855 | + scheduled_at: i64, | |
| 6856 | + retry: i64, | |
| 6857 | + claim: Option<AlarmClaim>, | |
| 6858 | + request_id: Option<RequestId>, | |
| 6859 | + reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 6860 | +) -> Begun { | |
| 6861 | + let begun = start_cell_event( | |
| 6862 | + tc, | |
| 6863 | + scope, | |
| 6864 | + Answer::Alarm(reply), | |
| 6865 | + request_id, | |
| 6866 | + None, | |
| 6867 | + false, | |
| 6868 | + |tc| { | |
| 6869 | + let f = dispatcher(tc, "__fireAlarm")?; | |
| 6870 | + let arguments = [ | |
| 6871 | + v8::String::new(tc, scope).unwrap().into(), | |
| 6872 | + v8::Number::new(tc, scheduled_at as f64).into(), | |
| 6873 | + v8::Number::new(tc, retry as f64).into(), | |
| 6874 | + ]; | |
| 6875 | + let recv = v8::undefined(tc).into(); | |
| 6876 | + f.call(tc, recv, &arguments) | |
| 6877 | + .ok_or_else(|| anyhow!("alarm threw")) | |
| 6878 | + }, | |
| 6879 | + ); | |
| 6880 | + match begun { | |
| 6881 | + Begun::Running(mut entry) => { | |
| 6882 | + entry.alarm = claim; | |
| 6883 | + Begun::Running(entry) | |
| 6884 | + } | |
| 6885 | + // The dispatcher never ran, so nothing can have changed the alarm. | |
| 6886 | + // Give the claim back as a failure that does not count against the | |
| 6887 | + // retry limit: the handler is not what failed. | |
| 6888 | + begun => { | |
| 6889 | + if let Some(claim) = claim { | |
| 6890 | + storage::finish_alarm_handler_with_retry_policy(scope, false, claim.now_ms, false); | |
| 6891 | + } | |
| 6892 | + begun | |
| 6893 | + } | |
| 6894 | + } | |
| 6895 | +} | |
| 6896 | + | |
| 6897 | +/// Resolve one completed op and run the microtasks that follow, with the | |
| 6898 | +/// owning request's context current. | |
| 6899 | +/// | |
| 6900 | +/// The half of a turn that resumes a suspended request. It knows nothing | |
| 6901 | +/// about any other request: the caller has already established that this op | |
| 6902 | +/// is `entry`'s. | |
| 6903 | +fn deliver( | |
| 6904 | + tc: &mut v8::PinScope, | |
| 6905 | + entry: &mut InFlight, | |
| 6906 | + op: u64, | |
| 6907 | + res: Result<asyncrt::OpOut, String>, | |
| 6908 | +) { | |
| 6909 | + entry.ops.remove(&op); | |
| 6910 | + entry.io_context_ops.remove(&op); | |
| 6911 | + let guard = CurrentGuard::enter(entry.context.clone()); | |
| 6912 | + resolve_res(tc, op, res); | |
| 6913 | + tc.perform_microtask_checkpoint(); | |
| 6914 | + drop(guard); | |
| 6915 | +} | |
| 6916 | + | |
| 6917 | +/// End a request whose client has hung up, so its handler stops running. | |
| 6918 | +fn cancelled(tc: &mut v8::PinScope, entry: &mut InFlight) { | |
| 6919 | + if entry.reply.is_none() || !take_request_cancellation(entry.request_id) { | |
| 6920 | + return; | |
| 6921 | + } | |
| 6922 | + let shutdown = take_shutdown_cancellation(entry.request_id); | |
| 6923 | + cancel(tc, entry, shutdown); | |
| 6924 | +} | |
| 6925 | + | |
| 6926 | +/// End a request whose cancellation has already been taken. | |
| 6927 | +/// | |
| 6928 | +/// Split from [`cancelled`] because a suspended request observes the | |
| 6929 | +/// cancellation *outside* the isolate — the flag is host state and costs no | |
| 6930 | +/// V8 — and only then enters to act on it. | |
| 6931 | +fn cancel(tc: &mut v8::PinScope, entry: &mut InFlight, shutdown: bool) { | |
| 6932 | + let guard = CurrentGuard::enter(entry.context.clone()); | |
| 6933 | + // The id that names this request to the JS side. A stateless handler is | |
| 6934 | + // registered by the shell, and only once it suspends, so the shell holds | |
| 6935 | + // the id; a cell's dispatcher registers the request itself, so the job's | |
| 6936 | + // own id is the one to abort. Aborting the wrong one — or neither — | |
| 6937 | + // leaves the target's `request.signal` unfired while the caller is told | |
| 6938 | + // the client has gone. | |
| 6939 | + if let Some(id) = entry.active_request_id.or(entry.request_id) { | |
| 6940 | + let _ = abort_incoming_request(tc, id); | |
| 6941 | + } | |
| 6942 | + // Finishing is the shell's to undo only where the shell registered. | |
| 6943 | + if let Some(id) = entry.active_request_id { | |
| 6944 | + finish_incoming_request(tc, id); | |
| 6945 | + } | |
| 6946 | + let background = end_event_context(tc).ok().flatten(); | |
| 6947 | + entry.background = background.map(|promise| v8::Global::new(tc, promise)); | |
| 6948 | + if shutdown { | |
| 6949 | + finish_retired_input_gate_context(tc, &entry.context); | |
| 6950 | + } | |
| 6951 | + drop(guard); | |
| 6952 | + entry.fail_cancelled(anyhow!("The client has disconnected")); | |
| 6953 | + if shutdown { | |
| 6954 | + // A lifecycle cancellation can be consumed either between turns or | |
| 6955 | + // during an operation turn. Keep the background cleanup here so both | |
| 6956 | + // paths retire the same work. | |
| 6957 | + entry.retire_background_for_shutdown(); | |
| 6958 | + } | |
| 6959 | + // A cancelled handler with no waitUntil work has nothing left to drive. | |
| 6960 | + // Drop its host ops now, so their guards cancel routed work. Explicit | |
| 6961 | + // waitUntil work keeps its ops and continues after the client disconnects. | |
| 6962 | + // | |
| 6963 | + // So does a handler that holds or awaits the cell's input gate, or whose | |
| 6964 | + // cross-entry block can still use an operation started by this event. | |
| 6965 | + // Not at shutdown: nothing will run the block to its end, so its gate is | |
| 6966 | + // given up instead. | |
| 6967 | + if shutdown || !entry.keeps_native_ops_after_disconnect() { | |
| 6968 | + entry.abandon(); | |
| 6969 | + } | |
| 6970 | +} | |
| 6971 | + | |
| 6972 | +/// Answer a request whose handler promise has settled, and retire its | |
| 6973 | +/// `waitUntil` work once that settles too. | |
| 6974 | +fn settle(tc: &mut v8::PinScope, entry: &mut InFlight) { | |
| 6975 | + if entry.reply.is_some() { | |
| 6976 | + let promise = v8::Local::new(tc, &entry.promise); | |
| 6977 | + match promise.state() { | |
| 6978 | + v8::PromiseState::Pending => {} | |
| 6979 | + v8::PromiseState::Fulfilled => { | |
| 6980 | + let guard = CurrentGuard::enter(entry.context.clone()); | |
| 6981 | + let value = promise.result(tc); | |
| 6982 | + entry.answer_settled(tc, value); | |
| 6983 | + if let Some(request_id) = entry.active_request_id { | |
| 6984 | + finish_incoming_request(tc, request_id); | |
| 6985 | + } | |
| 6986 | + drop(guard); | |
| 6987 | + } | |
| 6988 | + v8::PromiseState::Rejected => { | |
| 6989 | + let guard = CurrentGuard::enter(entry.context.clone()); | |
| 6990 | + let reason = reject_reason(tc, promise); | |
| 6991 | + // The handler is what failed, so an alarm's failure here | |
| 6992 | + // counts against its retry limit — unlike a budget overrun | |
| 6993 | + // or a disconnect, which `fail` records as not counting. | |
| 6994 | + entry.settle_alarm(false, true); | |
| 6995 | + let _ = end_event_context(tc); | |
| 6996 | + if let Some(request_id) = entry.active_request_id { | |
| 6997 | + finish_incoming_request(tc, request_id); | |
| 6998 | + } | |
| 6999 | + drop(guard); | |
| 7000 | + entry.fail_in_turn(anyhow!("rejected: {reason}")); | |
| 7001 | + } | |
| 7002 | + } | |
| 7003 | + } | |
| 7004 | + if let Some(background) = &entry.background { | |
| 7005 | + let promise = v8::Local::new(tc, background); | |
| 7006 | + if !matches!(promise.state(), v8::PromiseState::Pending) { | |
| 7007 | + entry.background = None; | |
| 7008 | + } | |
| 7009 | + } | |
| 7010 | +} | |
| 7011 | + | |
| 7012 | +/// Begin a stateless request: build it, call the Worker's `fetch`, and hand | |
| 7013 | +/// back the promise it returned. | |
| 7014 | +/// | |
| 7015 | +/// The half of a request that runs *before* it can suspend. Split out from | |
| 7016 | +/// driving it to completion so a caller can start several and drive them | |
| 7017 | +/// together; the single-request path starts one and drives it immediately, | |
| 7018 | +/// which is what it always did. | |
| 7019 | +/// | |
| 7020 | +/// The caller owns the `IoContext` and must have it current: `__beginEvent` | |
| 7021 | +/// runs here, and the frame it pushes belongs to this request. | |
| 7022 | +fn start_fetch<'s>( | |
| 7023 | + tc: &mut v8::PinScope<'s, '_>, | |
| 7024 | + fetch: v8::Local<'s, v8::Function>, | |
| 7025 | + url: &str, | |
| 7026 | + method: &str, | |
| 7027 | + body: RequestBody, | |
| 7028 | + headers: &[(String, String)], | |
| 7029 | + request_id: Option<RequestId>, | |
| 7030 | +) -> Result<Started<'s>> { | |
| 7031 | + let req = match request_id { | |
| 7032 | + Some(_) => make_incoming_request(tc, url, method, body, headers), | |
| 7033 | + None => make_request(tc, url, method, body, headers), | |
| 7034 | + }?; | |
| 7035 | + let env = harness_env(tc)?; | |
| 7036 | + let recv = v8::undefined(tc).into(); | |
| 7037 | + let f = fetch; | |
| 7038 | + let execution_ctx = begin_event_context(tc)?; | |
| 7039 | + let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else { | |
| 7040 | + // The handler threw synchronously. Termination carries its own error; | |
| 7041 | + // otherwise the pending exception is on the caller's TryCatch, which | |
| 7042 | + // is the only scope that can read it, so it formats the message. | |
| 7043 | + let error = take_execution_termination(tc); | |
| 7044 | + let _ = end_event_context(tc); | |
| 7045 | + return match error { | |
| 7046 | + Some(error) => Err(error), | |
| 7047 | + None => Ok(Started::Threw), | |
| 7048 | + }; | |
| 7049 | + }; | |
| 7050 | + // A handler that suspends must be reachable by an abort: register it as an | |
| 7051 | + // incoming request so a client disconnect can cancel it. One that already | |
| 7052 | + // settled cannot be cancelled, so its registration is cleared instead. | |
| 7053 | + let active_request_id = match request_id { | |
| 7054 | + Some(request_id) | |
| 7055 | + if ret | |
| 7056 | + .try_cast::<v8::Promise>() | |
| 7057 | + .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) => | |
| 7058 | + { | |
| 7059 | + if let Err(error) = register_incoming_request(tc, request_id, req) { | |
| 7060 | + clear_request_cancellation(request_id); | |
| 7061 | + let _ = end_event_context(tc); | |
| 7062 | + return Err(error); | |
| 7063 | + } | |
| 7064 | + Some(request_id) | |
| 7065 | + } | |
| 7066 | + Some(request_id) => { | |
| 7067 | + clear_request_cancellation(request_id); | |
| 7068 | + None | |
| 7069 | + } | |
| 7070 | + None => None, | |
| 7071 | + }; | |
| 7072 | + Ok(Started::Running(ret, active_request_id)) | |
| 7073 | +} | |
| 7074 | + | |
| 7075 | +/// What `start_fetch` produced: a running handler, or a synchronous throw | |
| 7076 | +/// whose exception only the caller's `TryCatch` can read. | |
| 7077 | +enum Started<'s> { | |
| 7078 | + Running(v8::Local<'s, v8::Value>, Option<RequestId>), | |
| 7079 | + Threw, | |
| 7080 | +} | |
| 7081 | + | |
| 7082 | +impl Worker { | |
| 7083 | + /// Compile the worker module, wire the DO harness, and extract the entry | |
| 7084 | + /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding | |
| 7085 | + /// name to a DO class name (from wrangler metadata). | |
| 7086 | + /// | |
| 7087 | + /// The runtime builds a `WorkerConfig` directly. This cfg-gated helper | |
| 7088 | + /// constructs the same value from individual options. | |
| 7089 | + #[cfg(celld_internal_tests)] | |
| 7090 | + pub fn load(options: WorkerConfigOptions) -> Result<Worker> { | |
| 7091 | + Self::load_config(Arc::new(WorkerConfig::new(options))) | |
| 7092 | + } | |
| 7093 | + | |
| 7094 | + pub fn load_config(config: Arc<WorkerConfig>) -> Result<Worker> { | |
| 7095 | + let src = config.src.as_str(); | |
| 7096 | + let script_name = config.script_name.as_str(); | |
| 7097 | + let do_classes = config.do_classes.as_slice(); | |
| 7098 | + let node = config.node.as_str(); | |
| 7099 | + let compat = config.compat; | |
| 7100 | + let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes()); | |
| 7101 | + let mut isolate = v8::Isolate::new(params); | |
| 7102 | + // Dynamic `import()` of builtin specifiers; per-import()-call only. | |
| 7103 | + isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically); | |
| 7104 | + let original_heap_limit = isolate.get_heap_statistics().heap_size_limit(); | |
| 7105 | + let heap_limit_state = Arc::new(HeapLimitState { | |
| 7106 | + excessively_exceeded: AtomicBool::new(false), | |
| 7107 | + limit: original_heap_limit, | |
| 7108 | + last_gc_nudge: Mutex::new(None), | |
| 7109 | + #[cfg(celld_internal_tests)] | |
| 7110 | + forced_admission_refusal: AtomicBool::new(false), | |
| 7111 | + }); | |
| 7112 | + let runtime_state = Arc::new(ActorRuntimeState { | |
| 7113 | + promises: std::sync::Mutex::new(PromiseMap::new()), | |
| 7114 | + egress: config.egress, | |
| 7115 | + ..Default::default() | |
| 7116 | + }); | |
| 7117 | + let loader_owner = LoaderOwner::fresh(); | |
| 7118 | + let heap_limit_state_ptr = | |
| 7119 | + Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void; | |
| 7120 | + isolate.set_slot(heap_limit_state); | |
| 7121 | + isolate.set_slot(runtime_state.clone()); | |
| 7122 | + isolate.set_slot(Arc::new(ModuleRegistry::default())); | |
| 7123 | + isolate.set_slot(loader_owner); | |
| 7124 | + isolate.set_slot(crate::generation::GenerationTag(config.generation)); | |
| 7125 | + // Retains the config so `/bundle` can project it later. Nothing is | |
| 7126 | + // walked or copied here: a worker that never reads its own bundle pays | |
| 7127 | + // only this `Arc` clone. | |
| 7128 | + isolate.set_slot(Arc::new(BundleFs { | |
| 7129 | + config: config.clone(), | |
| 7130 | + tree: OnceLock::new(), | |
| 7131 | + })); | |
| 7132 | + isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr); | |
| 7133 | + let (context, fetch) = { | |
| 7134 | + v8::scope!(let hs, &mut isolate); | |
| 7135 | + let context = v8::Context::new(hs, Default::default()); | |
| 7136 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 7137 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 7138 | + let scope = &mut tc.init(); | |
| 7139 | + | |
| 7140 | + install_ops(scope, context); | |
| 7141 | + install_prelude(scope)?; // Web Platform APIs | |
| 7142 | + install_harness(scope)?; // DO object model + minimal Response | |
| 7143 | + install_lazy_globals(scope)?; | |
| 7144 | + // A global, so it must exist before the module evaluates: bundles | |
| 7145 | + // read Cloudflare.compatibilityFlags at module scope. | |
| 7146 | + inject_compatibility_flags(scope, compat)?; | |
| 7147 | + inject_storage_compatibility(scope, compat)?; | |
| 7148 | + | |
| 7149 | + let module = match compile_module(scope, ENTRY_MODULE_NAME, src) { | |
| 7150 | + Some(m) => m, | |
| 7151 | + None => return Err(anyhow!("compile: {}", exc!(scope))), | |
| 7152 | + }; | |
| 7153 | + register_stubs(scope, &config); // cloudflare:*/node:* + text modules | |
| 7154 | + register_wasm_modules(scope, &config.modules); | |
| 7155 | + register_loader_modules(scope, &config); | |
| 7156 | + module | |
| 7157 | + .instantiate_module(scope, resolve_external) | |
| 7158 | + .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?; | |
| 7159 | + let ev = match module.evaluate(scope) { | |
| 7160 | + Some(value) => value, | |
| 7161 | + None => { | |
| 7162 | + if let Some(error) = take_execution_termination(scope) { | |
| 7163 | + return Err(error); | |
| 7164 | + } | |
| 7165 | + return Err(anyhow!("evaluate: {}", exc!(scope))); | |
| 7166 | + } | |
| 7167 | + }; | |
| 7168 | + if let Some(error) = take_execution_termination(scope) { | |
| 7169 | + return Err(error); | |
| 7170 | + } | |
| 7171 | + if let Ok(p) = ev.try_cast::<v8::Promise>() { | |
| 7172 | + if p.state() == v8::PromiseState::Rejected { | |
| 7173 | + let r = p.result(scope); | |
| 7174 | + let stk = r | |
| 7175 | + .to_object(scope) | |
| 7176 | + .and_then(|o| { | |
| 7177 | + let k = v8::String::new(scope, "stack")?; | |
| 7178 | + o.get(scope, k.into()) | |
| 7179 | + }) | |
| 7180 | + .map(|s| s.to_rust_string_lossy(scope)) | |
| 7181 | + .unwrap_or_default(); | |
| 7182 | + return Err(anyhow!( | |
| 7183 | + "top-level rejected: {}\n{}", | |
| 7184 | + r.to_rust_string_lossy(scope), | |
| 7185 | + stk | |
| 7186 | + )); | |
| 7187 | + } | |
| 7188 | + } | |
| 7189 | + | |
| 7190 | + let ns = module | |
| 7191 | + .get_module_namespace() | |
| 7192 | + .to_object(scope) | |
| 7193 | + .ok_or_else(|| anyhow!("ns"))?; | |
| 7194 | + | |
| 7195 | + // register each exported DO class into the harness registry | |
| 7196 | + for cn in do_classes { | |
| 7197 | + // The D1 class is the runtime's own and is never a worker | |
| 7198 | + // export. It is in `do_classes` so that it gets a namespace | |
| 7199 | + // key; reading it off the module namespace would find | |
| 7200 | + // `undefined` and overwrite the harness's registration. | |
| 7201 | + if crate::deploy::is_reserved_class(cn) { | |
| 7202 | + continue; | |
| 7203 | + } | |
| 7204 | + let key = v8::String::new(scope, cn).unwrap(); | |
| 7205 | + let cls = ns | |
| 7206 | + .get(scope, key.into()) | |
| 7207 | + .ok_or_else(|| anyhow!("DO class {cn} not exported"))?; | |
| 7208 | + register_class(scope, cn, cls)?; | |
| 7209 | + } | |
| 7210 | + inject_namespace_keys(scope, script_name, do_classes)?; | |
| 7211 | + inject_crons(scope, &config.crons)?; | |
| 7212 | + inject_workflows(scope, script_name, &config.workflow_bindings)?; | |
| 7213 | + inject_kv_limits(scope)?; | |
| 7214 | + inject_queue_config(scope, &config)?; | |
| 7215 | + populate_cf_exports(scope, ns, do_classes)?; | |
| 7216 | + register_entrypoints(scope, ns)?; | |
| 7217 | + validate_workflow_classes(scope, ns, &config.workflow_bindings)?; | |
| 7218 | + // build env from bindings and stash it in the harness | |
| 7219 | + build_env(scope, &config)?; | |
| 7220 | + // tell the harness which cells are local (route the rest cross-node) | |
| 7221 | + inject_routing(scope, node)?; | |
| 7222 | + | |
| 7223 | + // entry fetch | |
| 7224 | + let dk = v8::String::new(scope, "default").unwrap(); | |
| 7225 | + let default = ns | |
| 7226 | + .get(scope, dk.into()) | |
| 7227 | + .ok_or_else(|| anyhow!("no default export"))? | |
| 7228 | + .to_object(scope) | |
| 7229 | + .ok_or_else(|| anyhow!("default not object"))?; | |
| 7230 | + let fk = v8::String::new(scope, "fetch").unwrap(); | |
| 7231 | + let fetch_value = default | |
| 7232 | + .get(scope, fk.into()) | |
| 7233 | + .ok_or_else(|| anyhow!("no fetch"))?; | |
| 7234 | + let default_is_entrypoint = | |
| 7235 | + default.is_function() && cell_registry_has(scope, "entrypoints", "default")?; | |
| 7236 | + let class_fetch = default_is_entrypoint | |
| 7237 | + && default | |
| 7238 | + .get(scope, v8::String::new(scope, "prototype").unwrap().into()) | |
| 7239 | + .and_then(|prototype| prototype.to_object(scope)) | |
| 7240 | + .and_then(|prototype| prototype.get(scope, fk.into())) | |
| 7241 | + .is_some_and(|handler| handler.is_function()); | |
| 7242 | + let qk = v8::String::new(scope, "queue").unwrap(); | |
| 7243 | + let own_queue = default | |
| 7244 | + .get(scope, qk.into()) | |
| 7245 | + .is_some_and(|handler| handler.is_function()); | |
| 7246 | + let class_queue = default_is_entrypoint | |
| 7247 | + && default | |
| 7248 | + .get(scope, v8::String::new(scope, "prototype").unwrap().into()) | |
| 7249 | + .and_then(|prototype| prototype.to_object(scope)) | |
| 7250 | + .and_then(|prototype| prototype.get(scope, qk.into())) | |
| 7251 | + .is_some_and(|handler| handler.is_function()); | |
| 7252 | + let has_queue_handler = own_queue || class_queue; | |
| 7253 | + anyhow::ensure!( | |
| 7254 | + !config.declares_queue_consumer || has_queue_handler, | |
| 7255 | + "queue consumer has no queue handler" | |
| 7256 | + ); | |
| 7257 | + let f: v8::Local<v8::Function> = if fetch_value.is_function() { | |
| 7258 | + fetch_value.try_into().expect("function casts to Function") | |
| 7259 | + } else if default_is_entrypoint && class_fetch { | |
| 7260 | + // A class-based default entrypoint (extends WorkerEntrypoint) | |
| 7261 | + // keeps fetch on the prototype, so route through the | |
| 7262 | + // harness's cached instance like a named entrypoint. Only a | |
| 7263 | + // registered entrypoint dispatches that way — any other | |
| 7264 | + // callable would load fine and then 500 on every request. | |
| 7265 | + compile_fn( | |
| 7266 | + scope, | |
| 7267 | + "(req) => globalThis.__dispatchEntrypointFetch('default', req)", | |
| 7268 | + )? | |
| 7269 | + } else if default.is_function() && cell_registry_has(scope, "doExports", "default")? { | |
| 7270 | + return Err(anyhow!( | |
| 7271 | + "the default export is a Durable Object class; export a fetch \ | |
| 7272 | + handler or a WorkerEntrypoint class as the default" | |
| 7273 | + )); | |
| 7274 | + } else if config.declares_queue_consumer { | |
| 7275 | + // A push-consumer Worker needs no HTTP handler. Keep the | |
| 7276 | + // stateless pool's fetch slot total, but fail closed if this | |
| 7277 | + // deployment becomes the fleet's HTTP entry point. Test the | |
| 7278 | + // prototype above before the entrypoint fallback below: a | |
| 7279 | + // queue-only class is still a registered entrypoint, but | |
| 7280 | + // routing fetch through it throws instead of returning 404. | |
| 7281 | + compile_fn(scope, "() => new Response('Not found', { status: 404 })")? | |
| 7282 | + } else if default_is_entrypoint { | |
| 7283 | + // Preserve an RPC-only default entrypoint. Its HTTP path | |
| 7284 | + // reports the harness's specific missing-fetch error, while | |
| 7285 | + // its named methods remain callable through RPC. | |
| 7286 | + compile_fn( | |
| 7287 | + scope, | |
| 7288 | + "(req) => globalThis.__dispatchEntrypointFetch('default', req)", | |
| 7289 | + )? | |
| 7290 | + } else { | |
| 7291 | + return Err(anyhow!("fetch not fn")); | |
| 7292 | + }; | |
| 7293 | + | |
| 7294 | + // Lets a self-targeted service binding invoke the handler in | |
| 7295 | + // this isolate instead of crossing to a pool thread. | |
| 7296 | + { | |
| 7297 | + let cell_key = static_key(scope, &v8_strings::CELL); | |
| 7298 | + if let Some(cell) = context | |
| 7299 | + .global(scope) | |
| 7300 | + .get(scope, cell_key.into()) | |
| 7301 | + .and_then(|value| value.to_object(scope)) | |
| 7302 | + { | |
| 7303 | + let key = v8::String::new(scope, "selfFetch").unwrap(); | |
| 7304 | + cell.set(scope, key.into(), f.into()); | |
| 7305 | + // Optional scheduled handler, reached by a self-targeted | |
| 7306 | + // service binding's scheduled(). | |
| 7307 | + let sk = v8::String::new(scope, "scheduled").unwrap(); | |
| 7308 | + let key_ = v8::String::new(scope, "selfScheduled").unwrap(); | |
| 7309 | + let own = default | |
| 7310 | + .get(scope, sk.into()) | |
| 7311 | + .filter(|handler| handler.is_function()); | |
| 7312 | + if let Some(handler) = own { | |
| 7313 | + cell.set(scope, key_.into(), handler); | |
| 7314 | + } else if default_is_entrypoint { | |
| 7315 | + // A class-based default entrypoint keeps scheduled on | |
| 7316 | + // the prototype; dispatch through the cached instance | |
| 7317 | + // like fetch above. | |
| 7318 | + let pk = v8::String::new(scope, "prototype").unwrap(); | |
| 7319 | + let proto_scheduled = default | |
| 7320 | + .get(scope, pk.into()) | |
| 7321 | + .and_then(|proto| proto.to_object(scope)) | |
| 7322 | + .and_then(|proto| proto.get(scope, sk.into())); | |
| 7323 | + if proto_scheduled.is_some_and(|handler| handler.is_function()) { | |
| 7324 | + let shim = compile_fn( | |
| 7325 | + scope, | |
| 7326 | + "(ctrl) => globalThis.__dispatchEntrypointScheduled('default', ctrl)", | |
| 7327 | + )?; | |
| 7328 | + cell.set(scope, key_.into(), shim.into()); | |
| 7329 | + } | |
| 7330 | + } | |
| 7331 | + } | |
| 7332 | + } | |
| 7333 | + (v8::Global::new(scope, context), v8::Global::new(scope, f)) | |
| 7334 | + }; | |
| 7335 | + Ok(Worker { | |
| 7336 | + inner: Some(WorkerIsolate { | |
| 7337 | + // Every setup scope above has closed, so nothing is entered | |
| 7338 | + // on top of this isolate and it can be handed over. | |
| 7339 | + // SAFETY: `into_shared` requires every piece of embedder | |
| 7340 | + // state hanging off this isolate to be `Send`, because it | |
| 7341 | + // migrates between threads and is dropped on whichever one | |
| 7342 | + // holds the lock last. This isolate carries exactly: | |
| 7343 | + // | |
| 7344 | + // - four slots, whose types the assertion below pins as | |
| 7345 | + // `Send + Sync`; | |
| 7346 | + // - `near_heap_limit`, a bare fn pointer whose only captured | |
| 7347 | + // state is a raw pointer into the `HeapLimitState` above; | |
| 7348 | + // - `host_import_module_dynamically`, a bare fn pointer that | |
| 7349 | + // captures nothing; | |
| 7350 | + // - a default `CreateParams` allocator, owned by V8. | |
| 7351 | + // | |
| 7352 | + // Nothing else is attached, and the assertion fails the build | |
| 7353 | + // if a slot type ever stops being thread-safe. | |
| 7354 | + // | |
| 7355 | + // 152.1.0 made this fallible. None of the four refusals can | |
| 7356 | + // hold here — this isolate is entered, is not a snapshot | |
| 7357 | + // creator, has no C++ heap, and has taken no weak handles — | |
| 7358 | + // so a refusal is a bug in the setup above, not a condition | |
| 7359 | + // to recover from. It panics with the reason named. | |
| 7360 | + isolate: unsafe { isolate.try_into_shared() } | |
| 7361 | + .unwrap_or_else(|error| panic!("cell isolate cannot be shared: {error}")), | |
| 7362 | + realm: Realm { context, fetch }, | |
| 7363 | + original_heap_limit, | |
| 7364 | + compat, | |
| 7365 | + loader_owner, | |
| 7366 | + cells: storage::Cells::default(), | |
| 7367 | + }), | |
| 7368 | + }) | |
| 7369 | + } | |
| 7370 | + | |
| 7371 | + /// Restore an idFromName() actor's human-readable identity before its | |
| 7372 | + /// constructor runs. The host calls this on activation and before a named | |
| 7373 | + /// request is dispatched. | |
| 7374 | + /// Take a cell into this isolate or give it back. | |
| 7375 | + /// | |
| 7376 | + /// Taking it opens the cell's SQLite -- which the isolate owns, not the | |
| 7377 | + /// caller -- and restores the persisted id name. Giving it back releases | |
| 7378 | + /// what the isolate holds for the residency and closes the database, so | |
| 7379 | + /// state cannot span two epochs. | |
| 7380 | + /// | |
| 7381 | + /// Dispatch does not depend on this: every cell call goes out through the | |
| 7382 | + /// host whichever isolate hosts the target. | |
| 7383 | + pub fn own_cell( | |
| 7384 | + &mut self, | |
| 7385 | + cell: &str, | |
| 7386 | + storage: Option<CellStorage<'_>>, | |
| 7387 | + ) -> Result<Option<i64>> { | |
| 7388 | + let compat = self.inner.as_ref().expect("live worker isolate").compat; | |
| 7389 | + let (mut locker, _cells) = self.lock(); | |
| 7390 | + v8::scope!(let hs, &mut *locker); | |
| 7391 | + let realm = self.realm(hs); | |
| 7392 | + let context = realm.context; | |
| 7393 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 7394 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 7395 | + adopt_cell(&mut tc.init(), cell, storage, compat) | |
| 7396 | + } | |
| 7397 | + | |
| 7398 | + fn own_embedded_cell( | |
| 7399 | + &mut self, | |
| 7400 | + cell: &str, | |
| 7401 | + parent: &storage::StorageIdentity, | |
| 7402 | + name: &str, | |
| 7403 | + id: &str, | |
| 7404 | + props_json: &str, | |
| 7405 | + ) -> Result<Option<i64>> { | |
| 7406 | + let compat = self.inner.as_ref().expect("live worker isolate").compat; | |
| 7407 | + let (mut locker, _cells) = self.lock(); | |
| 7408 | + if storage::activation_epoch(cell).is_some() { | |
| 7409 | + // The facet is already open, but this call carries a newer sample | |
| 7410 | + // of the root cell. Take it: the egress of this call must wait for | |
| 7411 | + // what the root cell had committed when the call left it, which | |
| 7412 | + // includes every image an earlier call flushed. | |
| 7413 | + storage::refresh_embedded_root(cell, parent); | |
| 7414 | + return Ok(None); | |
| 7415 | + } | |
| 7416 | + v8::scope!(let hs, &mut *locker); | |
| 7417 | + let realm = self.realm(hs); | |
| 7418 | + let context = realm.context; | |
| 7419 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 7420 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 7421 | + adopt_embedded_cell(&mut tc.init(), cell, parent, name, id, props_json, compat) | |
| 7422 | + } | |
| 7423 | + | |
| 7424 | + /// Drain the alarm moves the last turn committed in this isolate. | |
| 7425 | + /// | |
| 7426 | + /// An alarm move is a turn output, exactly like the ops a turn starts: | |
| 7427 | + /// the drive that ran the turn reports it to the host, so a handler | |
| 7428 | + /// that arms an alarm and then awaits it is schedulable immediately, | |
| 7429 | + /// not when the request ends. A separate call rather than part of the | |
| 7430 | + /// turn methods' return because stateless turns cannot move an alarm | |
| 7431 | + /// and never pay for it. | |
| 7432 | + pub fn take_alarm_moves(&mut self) -> Vec<(String, i64)> { | |
| 7433 | + let Some(inner) = self.inner.as_mut() else { | |
| 7434 | + return Vec::new(); | |
| 7435 | + }; | |
| 7436 | + let (_locker, _cells) = inner.lock(); | |
| 7437 | + storage::take_alarm_moves() | |
| 7438 | + } | |
| 7439 | + | |
| 7440 | + pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> { | |
| 7441 | + let (mut locker, _cells) = self.lock(); | |
| 7442 | + v8::scope!(let hs, &mut *locker); | |
| 7443 | + let realm = self.realm(hs); | |
| 7444 | + let context = realm.context; | |
| 7445 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 7446 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 7447 | + register_actor_name(&mut tc.init(), scope, Some(name)) | |
| 7448 | + } | |
| 7449 | + | |
| 7450 | + /// Start a cell event's first turn. | |
| 7451 | + /// | |
| 7452 | + /// The cell counterpart of `turn_begin`: it hands back what is now in | |
| 7453 | + /// flight for `runtime::drive_cell` to pump. | |
| 7454 | + pub fn turn_begin_cell( | |
| 7455 | + &mut self, | |
| 7456 | + job: CellJob, | |
| 7457 | + trace: Option<crate::telemetry::TraceContext>, | |
| 7458 | + ) -> (Option<InFlight>, Vec<Op>) { | |
| 7459 | + let Some(inner) = self.inner.as_mut() else { | |
| 7460 | + return (None, Vec::new()); | |
| 7461 | + }; | |
| 7462 | + let (mut locker, _cells) = inner.lock(); | |
| 7463 | + inner.recover_heap(&mut locker); | |
| 7464 | + v8::scope!(let hs, &mut *locker); | |
| 7465 | + let realm = inner.realm(hs); | |
| 7466 | + let context = realm.context; | |
| 7467 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 7468 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 7469 | + let tc = &mut tc.init(); | |
| 7470 | + | |
| 7471 | + advance_io_time(tc); | |
| 7472 | + let previous = install_trace(tc, trace.as_ref()); | |
| 7473 | + let out = match begin_cell(tc, job) { | |
| 7474 | + Begun::Running(mut entry) => { | |
| 7475 | + entry.trace = trace; | |
| 7476 | + let previous_io_context = install_io_context(tc, &entry.context); | |
| 7477 | + let ops = finish_turn(tc, &mut entry); | |
| 7478 | + restore_io_context(tc, previous_io_context); | |
| 7479 | + (Some(*entry), ops) | |
| 7480 | + } | |
| 7481 | + Begun::Threw(answer) => { | |
| 7482 | + answer.fail(anyhow!("cell event threw: {}", exc!(tc))); | |
| 7483 | + (None, Vec::new()) | |
| 7484 | + } | |
| 7485 | + Begun::Nothing => (None, Vec::new()), | |
| 7486 | + }; | |
| 7487 | + restore_trace(tc, previous); | |
| 7488 | + out | |
| 7489 | + } | |
| 7490 | + | |
| 7491 | + /// Enter the isolate solely to see whether another event settled this | |
| 7492 | + /// one's promise. | |
| 7493 | + /// | |
| 7494 | + /// A promise resolved by a different entry has no waker pointing here, | |
| 7495 | + /// so the driving task cannot be told and has to look. That is why this | |
| 7496 | + /// is a poll and not an event, and it is the same reason the blocking | |
| 7497 | + /// loop woke every 10 ms. | |
| 7498 | + pub fn turn_poll(&mut self, entry: &mut InFlight) -> Vec<Op> { | |
| 7499 | + let Some(inner) = self.inner.as_mut() else { | |
| 7500 | + return Vec::new(); | |
| 7501 | + }; | |
| 7502 | + let (mut locker, _cells) = inner.lock(); | |
| 7503 | + v8::scope!(let hs, &mut *locker); | |
| 7504 | + let realm = inner.realm(hs); | |
| 7505 | + let context = realm.context; | |
| 7506 | + let cs = &mut v8::ContextScope::new(hs, context); | |
| 7507 | + let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 7508 | + let tc = &mut tc.init(); | |
| 7509 | + | |
| 7510 | + let previous_io_context = install_io_context(tc, &entry.context); | |
| 7511 | + let previous = install_trace(tc, entry.trace.as_ref()); | |
| 7512 | + let ops = finish_turn(tc, entry); | |
| 7513 | + restore_trace(tc, previous); | |
| 7514 | + restore_io_context(tc, previous_io_context); | |
| 7515 | + ops | |
| 7516 | + } | |
| 7517 | + | |
| 7518 | + /// Enter the isolate solely to record how a claimed alarm ended. | |
| 7519 | + /// | |
| 7520 | + /// Reached only when the event ended without running JS again — a budget | |
| 7521 | + /// overrun, or a handler waiting on nothing — or threw before it could | |
| 7522 | + /// suspend. The bookkeeping is storage the isolate owns, so it cannot be | |
| 7523 | + /// done from the driving task. | |
| 7524 | + /// | |
| 7525 | + /// Answers the position the event's commits reached, sampled after the | |
| 7526 | + /// retry record is written: that record and whatever the handler wrote | |
| 7527 | + /// before it failed are unproven, and the error that already left carried | |
| 7528 | + /// at most the handler's part, so `fire_alarm` gates on this instead. | |
| 7529 | + pub fn turn_finish_alarm(&mut self, entry: &mut InFlight) -> Option<u64> { | |
| 7530 | + debug_assert!( | |
| 7531 | + self.inner.is_some(), | |
| 7532 | + "the final alarm turn runs on a live worker" | |
| 7533 | + ); | |
| 7534 | + let inner = self.inner.as_mut()?; | |
| 7535 | + let (_locker, _cells) = inner.lock(); | |
| 7536 | + entry.settle_alarm(false, false); | |
| 7537 | + entry.write_delta() | |
| 7538 | + } | |
| 7539 | +} | |
| 7540 | + | |
| 7541 | +// ---- native ops exposed to JS ---- | |
| 7542 | + | |
| 7543 | +/// Host ops, defined non-enumerable. They are runtime internals: a bundle | |
| 7544 | +/// walking `globalThis` must not find them, let alone `new` one — `for (const | |
| 7545 | +/// k in globalThis) new globalThis[k]()` used to reach `__actor_abort` and | |
| 7546 | +/// kill the actor. | |
| 7547 | +macro_rules! ops { | |
| 7548 | + ($scope:expr, $global:expr, $($name:literal => $op:path),* $(,)?) => { | |
| 7549 | + $({ | |
| 7550 | + let f = v8::Function::new($scope, $op).unwrap(); | |
| 7551 | + let k = v8::String::new($scope, $name).unwrap(); | |
| 7552 | + $global.define_own_property( | |
| 7553 | + $scope, k.into(), f.into(), v8::PropertyAttribute::DONT_ENUM); | |
| 7554 | + })* | |
| 7555 | + }; | |
| 7556 | +} | |
| 7557 | + | |
| 7558 | +fn install_ops(scope: &mut v8::PinScope, context: v8::Local<v8::Context>) { | |
| 7559 | + let global = context.global(scope); | |
| 7560 | + ops! { scope, global, | |
| 7561 | + "__heap_limit_excessively_exceeded" => | |
| 7562 | + op_heap_limit_excessively_exceeded, | |
| 7563 | + "__heap_over_admission_share" => op_heap_over_admission_share, | |
| 7564 | + "__ws_send" => websocket::op_ws_send, | |
| 7565 | + "__ws_send_binary" => websocket::op_ws_send_binary, | |
| 7566 | + "__ws_close" => websocket::op_ws_close, | |
| 7567 | + "__ws_alloc" => websocket::op_ws_alloc, | |
| 7568 | + "__ws_prepare_worker_handoff" => websocket::op_ws_prepare_worker_handoff, | |
| 7569 | + "__ws_accept" => websocket::op_ws_accept, | |
| 7570 | + "__ws_accept_regular" => websocket::op_ws_accept_regular, | |
| 7571 | + "__ws_list" => websocket::op_ws_list, | |
| 7572 | + "__ws_attachment_set" => websocket::op_ws_attachment_set, | |
| 7573 | + "__ws_auto_response_set" => websocket::op_ws_auto_response_set, | |
| 7574 | + "__ws_auto_response_get" => websocket::op_ws_auto_response_get, | |
| 7575 | + "__ws_auto_response_ts" => websocket::op_ws_auto_response_ts, | |
| 7576 | + "__ws_connect" => websocket::op_ws_connect, | |
| 7577 | + "__ws_bind_target" => websocket::op_ws_bind_target, | |
| 7578 | + "__ws_next" => websocket::op_ws_next, | |
| 7579 | + "__ws_upgrade" => websocket::op_ws_upgrade, | |
| 7580 | + "__hr_create" => html_rewriter::op_hr_create, | |
| 7581 | + "__hr_write" => html_rewriter::op_hr_write, | |
| 7582 | + "__hr_end" => html_rewriter::op_hr_end, | |
| 7583 | + "__hr_cmd" => html_rewriter::op_hr_cmd, | |
| 7584 | + "__hr_event" => html_rewriter::op_hr_event, | |
| 7585 | + "__hr_take" => html_rewriter::op_hr_take, | |
| 7586 | + "__hr_free" => html_rewriter::op_hr_free, | |
| 7587 | + "__tcp_connect" => tcp::op_tcp_connect, | |
| 7588 | + "__tcp_read" => tcp::op_tcp_read, | |
| 7589 | + "__tcp_write" => tcp::op_tcp_write, | |
| 7590 | + "__tcp_shutdown" => tcp::op_tcp_shutdown, | |
| 7591 | + "__tcp_close" => tcp::op_tcp_close, | |
| 7592 | + "__tcp_starttls" => tcp::op_tcp_starttls, | |
| 7593 | + "__storage_get" => storage_ops::op_storage_get, | |
| 7594 | + "__storage_get_many" => storage_ops::op_storage_get_many, | |
| 7595 | + "__sql_ingest" => storage_ops::op_sql_ingest, | |
| 7596 | + "__sql_cursor_start" => storage_ops::op_sql_cursor_start, | |
| 7597 | + "__sql_cursor_next" => storage_ops::op_sql_cursor_next, | |
| 7598 | + "__sql_cursor_close" => storage_ops::op_sql_cursor_close, | |
| 7599 | + "__sql_database_size" => storage_ops::op_sql_database_size, | |
| 7600 | + "__d1_run" => storage_ops::op_d1_run, | |
| 7601 | + "__storage_transaction_control" => storage_ops::op_storage_transaction_control, | |
| 7602 | + "__log" => op_log, | |
| 7603 | + "__storage_put" => storage_ops::op_storage_put, | |
| 7604 | + "__storage_put_many" => storage_ops::op_storage_put_many, | |
| 7605 | + "__storage_queue_put" => storage_ops::op_storage_queue_put, | |
| 7606 | + "__storage_queue_put_many" => storage_ops::op_storage_queue_put_many, | |
| 7607 | + "__storage_put_serialized" => storage_ops::op_storage_put_serialized, | |
| 7608 | + "__storage_queue_put_serialized" => storage_ops::op_storage_queue_put_serialized, | |
| 7609 | + "__storage_flush_pending_puts" => storage_ops::op_storage_flush_pending_puts, | |
| 7610 | + "__storage_sync" => storage_ops::op_storage_sync, | |
| 7611 | + "__storage_cancel_pending_puts" => storage_ops::op_storage_cancel_pending_puts, | |
| 7612 | + "__actor_abort" => op_actor_abort, | |
| 7613 | + "__cron_plan" => op_cron_plan, | |
| 7614 | + "__kv_blob" => op_kv_blob, | |
| 7615 | + "__process_exit" => op_process_exit, | |
| 7616 | + "__storage_delete" => storage_ops::op_storage_delete, | |
| 7617 | + "__storage_delete_many" => storage_ops::op_storage_delete_many, | |
| 7618 | + "__storage_list" => storage_ops::op_storage_list, | |
| 7619 | + "__storage_sync_list_start" => storage_ops::op_storage_sync_list_start, | |
| 7620 | + "__storage_sync_list_next" => storage_ops::op_storage_sync_list_next, | |
| 7621 | + "__storage_delete_all" => storage_ops::op_storage_delete_all, | |
| 7622 | + "$$urlParse" => op_url_parse, | |
| 7623 | + "$$urlPatternParse" => op_urlpattern_parse, | |
| 7624 | + "$$urlPatternMatchInput" => op_urlpattern_match_input, | |
| 7625 | + "$$atob" => op_atob, | |
| 7626 | + "$$btoa" => op_btoa, | |
| 7627 | + "$$textDecoderLabel" => op_text_decoder_label, | |
| 7628 | + "$$textDecoderNew" => op_text_decoder_new, | |
| 7629 | + "$$textDecoderDecode" => op_text_decoder_decode, | |
| 7630 | + "$$textDecoderDecodeOnce" => op_text_decoder_decode_once, | |
| 7631 | + "$$textDecoderFree" => op_text_decoder_free, | |
| 7632 | + "__alarm_set" => op_alarm_set, | |
| 7633 | + "__queue_alarm_set_wait" => op_queue_alarm_set_wait, | |
| 7634 | + "__alarm_get" => op_alarm_get, | |
| 7635 | + "__alarm_delete" => op_alarm_delete, | |
| 7636 | + "__loader_load" => op_loader_load, | |
| 7637 | + "__loader_fetch" => op_loader_fetch, | |
| 7638 | + "__loader_rpc" => op_loader_rpc, | |
| 7639 | + "__loader_drop" => op_loader_drop, | |
| 7640 | + "__facet_fetch" => op_facet_fetch, | |
| 7641 | + "__facet_rpc" => op_facet_rpc, | |
| 7642 | + "__facet_abort" => op_facet_abort, | |
| 7643 | + "__facet_delete" => op_facet_delete, | |
| 7644 | + "__do_call" => op_do_call, | |
| 7645 | + "__svc_call" => op_svc_call, | |
| 7646 | + "__svc_call_cancellable" => op_svc_call_cancellable, | |
| 7647 | + "__svc_rpc" => op_svc_rpc, | |
| 7648 | + "__queue_dispatch" => op_queue_dispatch, | |
| 7649 | + "__queue_policy" => op_queue_policy, | |
| 7650 | + "__do_call_cancellable" => op_do_call_cancellable, | |
| 7651 | + "__do_call_cancel" => op_do_call_cancel, | |
| 7652 | + "__do_id" => op_do_id, | |
| 7653 | + "__rpc_call" => op_rpc_call, | |
| 7654 | + "__sc_encode" => storage_ops::op_sc_encode, | |
| 7655 | + "__sc_decode" => storage_ops::op_sc_decode, | |
| 7656 | + "__structured_clone" => storage_ops::op_structured_clone, | |
| 7657 | + "__op_fetch" => op_fetch, | |
| 7658 | + "__r2_head" => r2_ops::op_r2_head, | |
| 7659 | + "__r2_get" => r2_ops::op_r2_get, | |
| 7660 | + "__r2_put" => r2_ops::op_r2_put, | |
| 7661 | + "__r2_put_begin" => r2_ops::op_r2_put_begin, | |
| 7662 | + "__r2_put_chunk" => r2_ops::op_r2_put_chunk, | |
| 7663 | + "__r2_put_end" => r2_ops::op_r2_put_end, | |
| 7664 | + "__r2_delete" => r2_ops::op_r2_delete, | |
| 7665 | + "__r2_list" => r2_ops::op_r2_list, | |
| 7666 | + "__r2_mp_begin" => r2_ops::op_r2_mp_begin, | |
| 7667 | + "__r2_mp_resume" => r2_ops::op_r2_mp_resume, | |
| 7668 | + "__r2_mp_part" => r2_ops::op_r2_mp_part, | |
| 7669 | + "__r2_mp_complete" => r2_ops::op_r2_mp_complete, | |
| 7670 | + "__r2_mp_abort" => r2_ops::op_r2_mp_abort, | |
| 7671 | + "__asset_fetch" => op_asset_fetch, | |
| 7672 | + "__http_stream_read" => op_http_stream_read, | |
| 7673 | + "__http_stream_cancel" => op_http_stream_cancel, | |
| 7674 | + "__http_stream_tee" => op_http_stream_tee, | |
| 7675 | + "__response_stream_create" => op_response_stream_create, | |
| 7676 | + "__response_stream_write" => op_response_stream_write, | |
| 7677 | + "__response_stream_closed" => op_response_stream_closed, | |
| 7678 | + "__response_stream_close" => op_response_stream_close, | |
| 7679 | + "__op_timer" => op_timer, | |
| 7680 | + "__timer_alloc" => op_timer_alloc, | |
| 7681 | + "__io_context_id" => op_io_context_id, | |
| 7682 | + "__gate_acquire" => op_gate_acquire, | |
| 7683 | + "__gate_wait" => op_gate_wait, | |
| 7684 | + "__gate_release" => op_gate_release, | |
| 7685 | + "__timer_cancel" => op_timer_cancel, | |
| 7686 | + "__crypto_operation" => crypto::op_crypto_operation, | |
| 7687 | + "$$randomValues" => crypto::op_webcrypto_random, | |
| 7688 | + "$$digest" => crypto::op_webcrypto_digest, | |
| 7689 | + "$$hmacSign" => crypto::op_webcrypto_hmac_sign, | |
| 7690 | + "$$hmacVerify" => crypto::op_webcrypto_hmac_verify, | |
| 7691 | + "$$aesEncrypt" => crypto::op_webcrypto_aes_encrypt, | |
| 7692 | + "$$aesDecrypt" => crypto::op_webcrypto_aes_decrypt, | |
| 7693 | + "$$pbkdf2" => crypto::op_node_pbkdf2, | |
| 7694 | + "$$hkdf" => crypto::op_node_hkdf, | |
| 7695 | + "$$timingSafeEqual" => crypto::op_timing_safe_equal, | |
| 7696 | + "__event_begin" => op_event_begin, | |
| 7697 | + "__event_end" => op_event_end, | |
| 7698 | + "__vfs_mkdir" => op_vfs_mkdir, | |
| 7699 | + "__vfs_read_file" => op_vfs_read_file, | |
| 7700 | + "__vfs_stat" => op_vfs_stat, | |
| 7701 | + "__wait_until" => op_wait_until, | |
| 7702 | + "__event_depth" => op_event_depth, | |
| 7703 | + "__als_get" => op_als_get, | |
| 7704 | + "__als_set" => op_als_set, | |
| 7705 | + "__util_type_flags" => op_util_type_flags, | |
| 7706 | + "__util_constructor_name" => op_util_constructor_name, | |
| 7707 | + "__util_proxy_details" => op_util_proxy_details, | |
| 7708 | + "__util_promise_details" => op_util_promise_details, | |
| 7709 | + "__util_preview_entries" => op_util_preview_entries, | |
| 7710 | + "__builtin_module" => op_builtin_module, | |
| 7711 | + "__zlib" => zlib::op_zlib, | |
| 7712 | + "__zlib_stream_new" => zlib::op_zlib_stream_new, | |
| 7713 | + "__zlib_stream_push" => zlib::op_zlib_stream_push, | |
| 7714 | + "__zlib_stream_end" => zlib::op_zlib_stream_end, | |
| 7715 | + "__zlib_stream_drop" => zlib::op_zlib_stream_drop, | |
| 7716 | + } | |
| 7717 | + #[cfg(celld_internal_tests)] | |
| 7718 | + ops! { scope, global, | |
| 7719 | + "__test_gc" => op_test_gc, | |
| 7720 | + "__loader_count" => op_loader_count, | |
| 7721 | + "__test_set_heap_limit_excessively_exceeded" => | |
| 7722 | + op_test_set_heap_limit_excessively_exceeded, | |
| 7723 | + "__test_force_heap_admission_refusal" => | |
| 7724 | + op_test_force_heap_admission_refusal, | |
| 7725 | + "__test_heap_share" => op_test_heap_share, | |
| 7726 | + "__test_external_memory" => op_test_external_memory, | |
| 7727 | + "__test_workflow_event_consumed" => op_test_workflow_event_consumed, | |
| 7728 | + "__test_workflow_meta_created" => op_test_workflow_meta_created, | |
| 7729 | + "__test_workflow_alarm_deleted" => op_test_workflow_alarm_deleted, | |
| 7730 | + "__test_queue_dlq_accepted" => op_test_queue_dlq_accepted, | |
| 7731 | + "__test_queue_metrics_materialized" => op_test_queue_metrics_materialized, | |
| 7732 | + "__test_queue_producer_group" => op_test_queue_producer_group, | |
| 7733 | + "__test_queue_rearm_bounded" => op_test_queue_rearm_bounded, | |
| 7734 | + "__test_queue_lease_lookup_plan" => op_test_queue_lease_lookup_plan, | |
| 7735 | + "__sql_set_max_page_count_for_test" => | |
| 7736 | + storage_ops::op_sql_set_max_page_count_for_test, | |
| 7737 | + "__sql_set_write_fault_for_test" => storage_ops::op_sql_set_write_fault_for_test, | |
| 7738 | + "__sql_set_cache_size_for_test" => storage_ops::op_sql_set_cache_size_for_test, | |
| 7739 | + "__sql_set_interrupt_fault_for_test" => | |
| 7740 | + storage_ops::op_sql_set_interrupt_fault_for_test, | |
| 7741 | + "__sql_register_nomem_function_for_test" => | |
| 7742 | + storage_ops::op_sql_register_nomem_function_for_test, | |
| 7743 | + } | |
| 7744 | +} | |
| 7745 | + | |
| 7746 | +/// `__kv_blob(requestJson, bytes?)` -> Promise<string | Uint8Array>. | |
| 7747 | +/// | |
| 7748 | +/// One op for the whole large-value path, following `__d1_run` rather than | |
| 7749 | +/// exposing get, put and sweep as three. A put copies one typed view into Rust, | |
| 7750 | +/// and a successful get resolves directly to a `Uint8Array`. JSON arrays would | |
| 7751 | +/// turn a valid 25 MiB value into millions of heap objects and crash the | |
| 7752 | +/// isolate before the bucket I/O began. | |
| 7753 | +/// | |
| 7754 | +/// JSON remains the control envelope for an absent get and a swept count. The | |
| 7755 | +/// cell scope is host-derived, so JavaScript cannot read or collect another | |
| 7756 | +/// namespace's objects by changing the request. | |
| 7757 | +fn op_kv_blob( | |
| 7758 | + scope: &mut v8::PinScope, | |
| 7759 | + args: v8::FunctionCallbackArguments, | |
| 7760 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 7761 | +) { | |
| 7762 | + let request = args.get(0).to_rust_string_lossy(scope); | |
| 7763 | + let value = view_bytes(args.get(1)); | |
| 7764 | + // Bucket I/O is egress, so it waits on the same gate a service call does | |
| 7765 | + // rather than escaping the shed the node applies under pressure. | |
| 7766 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service); | |
| 7767 | + // Blob authority follows the storage installed for this exact cell | |
| 7768 | + // activation. Capturing it before enqueue prevents a later ownership | |
| 7769 | + // lookup from lending a deposed collector the new owner's epoch. | |
| 7770 | + let authority = gate | |
| 7771 | + .cell_scope() | |
| 7772 | + .and_then(|cell| storage::activation_epoch(cell).map(|epoch| (cell.to_string(), epoch))); | |
| 7773 | + let id = asyncrt::enqueue(async move { | |
| 7774 | + let (cell, activation_epoch) = | |
| 7775 | + authority.ok_or_else(|| "KV blob I/O requires active cell storage".to_string())?; | |
| 7776 | + let request: serde_json::Value = | |
| 7777 | + serde_json::from_str(&request).map_err(|error| format!("invalid request: {error}"))?; | |
| 7778 | + let field = |name: &str| -> std::result::Result<String, String> { | |
| 7779 | + request | |
| 7780 | + .get(name) | |
| 7781 | + .and_then(serde_json::Value::as_str) | |
| 7782 | + .map(str::to_string) | |
| 7783 | + .ok_or_else(|| format!("request has no {name}")) | |
| 7784 | + }; | |
| 7785 | + let mode = field("mode")?; | |
| 7786 | + await_egress_gate(gate).await?; | |
| 7787 | + let reply = match mode.as_str() { | |
| 7788 | + "prepare" => { | |
| 7789 | + let digest = field("digest")?; | |
| 7790 | + let reference = celld_logic::kv::BlobRef::v2(activation_epoch, &digest) | |
| 7791 | + .map_err(|error| error.to_string())? | |
| 7792 | + .encode(); | |
| 7793 | + serde_json::json!({ "reference": reference }) | |
| 7794 | + } | |
| 7795 | + "get" => { | |
| 7796 | + let reference = field("reference")?; | |
| 7797 | + let reference = celld_logic::kv::BlobRef::parse(&reference) | |
| 7798 | + .map_err(|error| error.to_string())?; | |
| 7799 | + if !reference.readable_by(activation_epoch) { | |
| 7800 | + return Err("a KV row references a later ownership epoch".to_string()); | |
| 7801 | + } | |
| 7802 | + let key = reference.object_key(&cell); | |
| 7803 | + match kv_blob_store()? | |
| 7804 | + .get(&key) | |
| 7805 | + .await | |
| 7806 | + .map_err(|error| error.to_string())? | |
| 7807 | + { | |
| 7808 | + Some((bytes, _etag)) => { | |
| 7809 | + return Ok(asyncrt::OpOut::Bytes(bytes.to_vec())); | |
| 7810 | + } | |
| 7811 | + None => serde_json::json!({ "found": false }), | |
| 7812 | + } | |
| 7813 | + } | |
| 7814 | + "put" => { | |
| 7815 | + let bytes = value.ok_or_else(|| "request has no byte view".to_string())?; | |
| 7816 | + let reference = field("reference")?; | |
| 7817 | + let reference = celld_logic::kv::BlobRef::parse(&reference) | |
| 7818 | + .map_err(|error| error.to_string())?; | |
| 7819 | + if !reference.writable_by(activation_epoch) { | |
| 7820 | + return Err("a new KV blob must use the active ownership epoch".to_string()); | |
| 7821 | + } | |
| 7822 | + let key = reference.object_key(&cell); | |
| 7823 | + kv_blob_store()? | |
| 7824 | + .put(&key, bytes) | |
| 7825 | + .await | |
| 7826 | + .map_err(|error| error.to_string())?; | |
| 7827 | + serde_json::json!({ "ok": true }) | |
| 7828 | + } | |
| 7829 | + "sweep" => { | |
| 7830 | + let values = request | |
| 7831 | + .get("live") | |
| 7832 | + .and_then(serde_json::Value::as_array) | |
| 7833 | + .ok_or_else(|| "request has no live blob reference list".to_string())?; | |
| 7834 | + let mut live = HashSet::new(); | |
| 7835 | + for value in values { | |
| 7836 | + let reference = value.as_str().ok_or_else(|| { | |
| 7837 | + "the live blob reference list contains a non-string".to_string() | |
| 7838 | + })?; | |
| 7839 | + let reference = celld_logic::kv::BlobRef::parse(reference) | |
| 7840 | + .map_err(|error| error.to_string())?; | |
| 7841 | + if !reference.readable_by(activation_epoch) { | |
| 7842 | + return Err( | |
| 7843 | + "the live blob reference list contains a later epoch".to_string() | |
| 7844 | + ); | |
| 7845 | + } | |
| 7846 | + if matches!(reference, celld_logic::kv::BlobRef::V2 { .. }) { | |
| 7847 | + live.insert(reference.encode()); | |
| 7848 | + } | |
| 7849 | + } | |
| 7850 | + // Mark and sweep, and the model says why it is not a refcount: | |
| 7851 | + // a crash between the blob write and the row commit leaves | |
| 7852 | + // bytes no count ever counted. The caller includes its pending | |
| 7853 | + // references because this end only needs "do not delete these". | |
| 7854 | + // Legacy blobs live outside this prefix and remain retained as | |
| 7855 | + // the safe migration cost. | |
| 7856 | + let prefix = celld_logic::kv::BlobRef::v2_object_prefix(&cell); | |
| 7857 | + let listed = kv_blob_store()? | |
| 7858 | + .list(&prefix) | |
| 7859 | + .await | |
| 7860 | + .map_err(|error| error.to_string())?; | |
| 7861 | + // Validate the complete listing before issuing one delete. A | |
| 7862 | + // malformed key must fail closed instead of turning a parsing | |
| 7863 | + // error into partial collection. | |
| 7864 | + let mut doomed = Vec::new(); | |
| 7865 | + for object in listed { | |
| 7866 | + let key = object.location.as_ref().to_string(); | |
| 7867 | + let suffix = key.strip_prefix(&prefix).ok_or_else(|| { | |
| 7868 | + "the KV blob listing returned a key outside its prefix".to_string() | |
| 7869 | + })?; | |
| 7870 | + let reference = celld_logic::kv::BlobRef::parse_object_suffix(suffix) | |
| 7871 | + .map_err(|error| error.to_string())?; | |
| 7872 | + if reference.collectable_by(activation_epoch) | |
| 7873 | + && !live.contains(&reference.encode()) | |
| 7874 | + { | |
| 7875 | + doomed.push(key); | |
| 7876 | + } | |
| 7877 | + } | |
| 7878 | + let gone = kv_blob_store()?.delete_many(&doomed).await; | |
| 7879 | + if gone.len() != doomed.len() { | |
| 7880 | + return Err(format!( | |
| 7881 | + "{} blob(s) refused deletion", | |
| 7882 | + doomed.len().saturating_sub(gone.len()) | |
| 7883 | + )); | |
| 7884 | + } | |
| 7885 | + serde_json::json!({ "removed": gone.len() }) | |
| 7886 | + } | |
| 7887 | + other => return Err(format!("unknown mode {other}")), | |
| 7888 | + }; | |
| 7889 | + Ok(asyncrt::OpOut::Str(reply.to_string())) | |
| 7890 | + }); | |
| 7891 | + rv.set(promise_for(scope, id)); | |
| 7892 | +} | |
| 7893 | + | |
| 7894 | +/// Create a JS promise for an async op `id` and return it to JS. | |
| 7895 | +fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> { | |
| 7896 | + let resolver = v8::PromiseResolver::new(scope).unwrap(); | |
| 7897 | + let promise = resolver.get_promise(scope); | |
| 7898 | + promise_store(scope, id, v8::Global::new(scope, resolver)); | |
| 7899 | + promise.into() | |
| 7900 | +} | |
| 7901 | + | |
| 7902 | +#[derive(serde::Deserialize)] | |
| 7903 | +#[serde(rename_all = "camelCase")] | |
| 7904 | +struct QueueDispatchEnvelope { | |
| 7905 | + lease_id: String, | |
| 7906 | + leases: Vec<QueueLeaseRef>, | |
| 7907 | + messages: Vec<QueueWireMessage>, | |
| 7908 | + metrics: QueueWireMetrics, | |
| 7909 | +} | |
| 7910 | + | |
| 7911 | +#[derive(serde::Deserialize)] | |
| 7912 | +#[serde(rename_all = "camelCase")] | |
| 7913 | +struct QueueWireMessage { | |
| 7914 | + id: String, | |
| 7915 | + timestamp_ms: i64, | |
| 7916 | + body_base64: String, | |
| 7917 | + content_type: String, | |
| 7918 | + attempts: u16, | |
| 7919 | +} | |
| 7920 | + | |
| 7921 | +#[derive(serde::Deserialize)] | |
| 7922 | +#[serde(rename_all = "camelCase")] | |
| 7923 | +struct QueueWireMetrics { | |
| 7924 | + backlog_count: f64, | |
| 7925 | + backlog_bytes: f64, | |
| 7926 | + oldest_message_timestamp_ms: Option<i64>, | |
| 7927 | +} | |
| 7928 | + | |
| 7929 | +/// `__queue_dispatch(script, queue, envelopeJson)` persists no state itself. | |
| 7930 | +/// The Queue cell has already installed each lease; this op gates that write, | |
| 7931 | +/// then hands the batch to the host and returns. Settlement comes back as a | |
| 7932 | +/// new call to the broker, so the alarm event does not spend the consumer's | |
| 7933 | +/// admission or handler budget and several leases can run concurrently. | |
| 7934 | +fn op_queue_dispatch( | |
| 7935 | + scope: &mut v8::PinScope, | |
| 7936 | + args: v8::FunctionCallbackArguments, | |
| 7937 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 7938 | +) { | |
| 7939 | + let script = args.get(0).to_rust_string_lossy(scope); | |
| 7940 | + let queue = args.get(1).to_rust_string_lossy(scope); | |
| 7941 | + let envelope: QueueDispatchEnvelope = | |
| 7942 | + match serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)) { | |
| 7943 | + Ok(envelope) => envelope, | |
| 7944 | + Err(error) => { | |
| 7945 | + return loader_throw(scope, &format!("invalid Queue dispatch envelope: {error}")) | |
| 7946 | + } | |
| 7947 | + }; | |
| 7948 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Queue); | |
| 7949 | + let cell = gate.cell_scope().map(str::to_string); | |
| 7950 | + let mut messages = Vec::with_capacity(envelope.messages.len()); | |
| 7951 | + for message in envelope.messages { | |
| 7952 | + let content_type = match message.content_type.as_str() { | |
| 7953 | + "text" => QueueContentType::Text, | |
| 7954 | + "bytes" => QueueContentType::Bytes, | |
| 7955 | + "json" => QueueContentType::Json, | |
| 7956 | + "v8" => QueueContentType::V8, | |
| 7957 | + other => return loader_throw(scope, &format!("invalid Queue content type {other:?}")), | |
| 7958 | + }; | |
| 7959 | + let body = match base64::engine::general_purpose::STANDARD.decode(&message.body_base64) { | |
| 7960 | + Ok(body) => body, | |
| 7961 | + Err(error) => { | |
| 7962 | + return loader_throw(scope, &format!("invalid Queue message body: {error}")) | |
| 7963 | + } | |
| 7964 | + }; | |
| 7965 | + messages.push(QueueMessage { | |
| 7966 | + id: message.id, | |
| 7967 | + timestamp_ms: message.timestamp_ms, | |
| 7968 | + body, | |
| 7969 | + content_type, | |
| 7970 | + attempts: message.attempts, | |
| 7971 | + }); | |
| 7972 | + } | |
| 7973 | + if messages.len() != envelope.leases.len() | |
| 7974 | + || messages | |
| 7975 | + .iter() | |
| 7976 | + .zip(&envelope.leases) | |
| 7977 | + .any(|(message, lease)| message.id != lease.message_id) | |
| 7978 | + { | |
| 7979 | + return loader_throw( | |
| 7980 | + scope, | |
| 7981 | + "a Queue dispatch must carry one matching lease per message", | |
| 7982 | + ); | |
| 7983 | + } | |
| 7984 | + let request = QueueDispatchReq { | |
| 7985 | + generation: current_generation(scope), | |
| 7986 | + scope: cell.unwrap_or_default(), | |
| 7987 | + script, | |
| 7988 | + lease_id: envelope.lease_id, | |
| 7989 | + leases: envelope.leases, | |
| 7990 | + batch: QueueBatch { | |
| 7991 | + queue, | |
| 7992 | + messages, | |
| 7993 | + metrics: QueueMetrics { | |
| 7994 | + backlog_count: envelope.metrics.backlog_count, | |
| 7995 | + backlog_bytes: envelope.metrics.backlog_bytes, | |
| 7996 | + oldest_message_timestamp_ms: envelope.metrics.oldest_message_timestamp_ms, | |
| 7997 | + }, | |
| 7998 | + }, | |
| 7999 | + }; | |
| 8000 | + let id = asyncrt::enqueue(async move { | |
| 8001 | + if request.scope.is_empty() { | |
| 8002 | + return Err("Queue dispatch requires a cell event".to_string()); | |
| 8003 | + } | |
| 8004 | + gated_channel_send( | |
| 8005 | + gate, | |
| 8006 | + &QUEUE_DISPATCH_TX, | |
| 8007 | + request, | |
| 8008 | + "no Queue dispatch channel", | |
| 8009 | + ) | |
| 8010 | + .await?; | |
| 8011 | + Ok(asyncrt::OpOut::Str(String::new())) | |
| 8012 | + }); | |
| 8013 | + rv.set(promise_for(scope, id)); | |
| 8014 | +} | |
| 8015 | + | |
| 8016 | +/// One synchronous boundary for Queue policy owned by `celld-logic`. | |
| 8017 | +/// | |
| 8018 | +/// The JavaScript cell owns SQL and presentation. It sends row facts here so | |
| 8019 | +/// alarm selection, concurrency admission, generation advancement, settlement | |
| 8020 | +/// fencing, purge classification, retry precedence, and exhaustion have one | |
| 8021 | +/// production implementation rather than a tested Rust copy beside a different | |
| 8022 | +/// shipped JavaScript copy. | |
| 8023 | +fn op_queue_policy( | |
| 8024 | + scope: &mut v8::PinScope, | |
| 8025 | + args: v8::FunctionCallbackArguments, | |
| 8026 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8027 | +) { | |
| 8028 | + let request: serde_json::Value = | |
| 8029 | + match serde_json::from_str(&args.get(0).to_rust_string_lossy(scope)) { | |
| 8030 | + Ok(request) => request, | |
| 8031 | + Err(error) => { | |
| 8032 | + return loader_throw(scope, &format!("invalid Queue policy input: {error}")) | |
| 8033 | + } | |
| 8034 | + }; | |
| 8035 | + let integer = |object: &serde_json::Value, name: &str| -> Result<i64> { | |
| 8036 | + object | |
| 8037 | + .get(name) | |
| 8038 | + .and_then(serde_json::Value::as_i64) | |
| 8039 | + .ok_or_else(|| anyhow!("Queue policy input has no integer {name}")) | |
| 8040 | + }; | |
| 8041 | + let optional_integer = |object: &serde_json::Value, name: &str| -> Result<Option<i64>> { | |
| 8042 | + match object.get(name) { | |
| 8043 | + None | Some(serde_json::Value::Null) => Ok(None), | |
| 8044 | + Some(value) => value | |
| 8045 | + .as_i64() | |
| 8046 | + .map(Some) | |
| 8047 | + .ok_or_else(|| anyhow!("Queue policy input {name} is not an integer")), | |
| 8048 | + } | |
| 8049 | + }; | |
| 8050 | + let result = (|| -> Result<serde_json::Value> { | |
| 8051 | + match request.get("op").and_then(serde_json::Value::as_str) { | |
| 8052 | + Some("rearm") => Ok(serde_json::json!(celld_logic::queue::rearm( | |
| 8053 | + integer(&request, "now")?, | |
| 8054 | + optional_integer(&request, "batchDeadline")?, | |
| 8055 | + optional_integer(&request, "earliestVisible")?, | |
| 8056 | + optional_integer(&request, "earliestLeaseExpiry")?, | |
| 8057 | + optional_integer(&request, "nextSweep")?, | |
| 8058 | + ))), | |
| 8059 | + Some("capacity") => { | |
| 8060 | + let active = usize::try_from(integer(&request, "active")?) | |
| 8061 | + .map_err(|_| anyhow!("Queue active concurrency is out of range"))?; | |
| 8062 | + let maximum = u16::try_from(integer(&request, "maximum")?) | |
| 8063 | + .map_err(|_| anyhow!("Queue max concurrency is out of range"))?; | |
| 8064 | + Ok(serde_json::json!(celld_logic::queue::can_install_lease( | |
| 8065 | + active, maximum, | |
| 8066 | + ))) | |
| 8067 | + } | |
| 8068 | + Some("retries") => { | |
| 8069 | + let now = integer(&request, "now")?; | |
| 8070 | + let entries = request | |
| 8071 | + .get("entries") | |
| 8072 | + .and_then(serde_json::Value::as_array) | |
| 8073 | + .ok_or_else(|| anyhow!("Queue retry policy has no entries"))?; | |
| 8074 | + let mut results = Vec::with_capacity(entries.len()); | |
| 8075 | + for entry in entries { | |
| 8076 | + let seconds = |name: &str| -> Result<Option<u32>> { | |
| 8077 | + optional_integer(entry, name)? | |
| 8078 | + .map(|value| { | |
| 8079 | + u32::try_from(value) | |
| 8080 | + .map_err(|_| anyhow!("Queue retry {name} is out of range")) | |
| 8081 | + }) | |
| 8082 | + .transpose() | |
| 8083 | + }; | |
| 8084 | + let attempt = u16::try_from(integer(entry, "attempt")?) | |
| 8085 | + .map_err(|_| anyhow!("Queue retry attempt is out of range"))?; | |
| 8086 | + let max_retries = u16::try_from(integer(entry, "maxRetries")?) | |
| 8087 | + .map_err(|_| anyhow!("Queue maxRetries is out of range"))?; | |
| 8088 | + results.push(serde_json::json!({ | |
| 8089 | + "at": celld_logic::queue::retry_at( | |
| 8090 | + now, | |
| 8091 | + seconds("explicitSeconds")?, | |
| 8092 | + seconds("configuredSeconds")?, | |
| 8093 | + ), | |
| 8094 | + "exhausted": celld_logic::queue::exhausted(attempt, max_retries), | |
| 8095 | + })); | |
| 8096 | + } | |
| 8097 | + Ok(serde_json::Value::Array(results)) | |
| 8098 | + } | |
| 8099 | + Some("expiry") => { | |
| 8100 | + let now = integer(&request, "now")?; | |
| 8101 | + let entries = request | |
| 8102 | + .get("entries") | |
| 8103 | + .and_then(serde_json::Value::as_array) | |
| 8104 | + .ok_or_else(|| anyhow!("Queue expiry policy has no entries"))?; | |
| 8105 | + let mut results = Vec::with_capacity(entries.len()); | |
| 8106 | + for entry in entries { | |
| 8107 | + let prior_failures = u16::try_from(integer(entry, "priorFailures")?) | |
| 8108 | + .map_err(|_| anyhow!("Queue priorFailures is out of range"))?; | |
| 8109 | + let max_retries = u16::try_from(integer(entry, "maxRetries")?) | |
| 8110 | + .map_err(|_| anyhow!("Queue maxRetries is out of range"))?; | |
| 8111 | + let configured = optional_integer(entry, "configuredSeconds")? | |
| 8112 | + .map(|value| { | |
| 8113 | + u32::try_from(value) | |
| 8114 | + .map_err(|_| anyhow!("Queue retry delay is out of range")) | |
| 8115 | + }) | |
| 8116 | + .transpose()?; | |
| 8117 | + let purge = entry | |
| 8118 | + .get("purgeOnSettle") | |
| 8119 | + .and_then(serde_json::Value::as_bool) | |
| 8120 | + .ok_or_else(|| anyhow!("Queue expiry has no purgeOnSettle"))?; | |
| 8121 | + let expired = celld_logic::queue::expire_lease( | |
| 8122 | + now, | |
| 8123 | + prior_failures, | |
| 8124 | + max_retries, | |
| 8125 | + configured, | |
| 8126 | + purge, | |
| 8127 | + ); | |
| 8128 | + let action = match expired.action { | |
| 8129 | + celld_logic::queue::ExpiredLeaseAction::RetryAt(at) => { | |
| 8130 | + serde_json::json!({ "kind": "retry", "at": at }) | |
| 8131 | + } | |
| 8132 | + celld_logic::queue::ExpiredLeaseAction::Exhausted => { | |
| 8133 | + serde_json::json!({ "kind": "exhausted" }) | |
| 8134 | + } | |
| 8135 | + celld_logic::queue::ExpiredLeaseAction::DeletePurged => { | |
| 8136 | + serde_json::json!({ "kind": "delete-purged" }) | |
| 8137 | + } | |
| 8138 | + }; | |
| 8139 | + results.push(serde_json::json!({ | |
| 8140 | + "attempt": expired.attempt, | |
| 8141 | + "action": action, | |
| 8142 | + })); | |
| 8143 | + } | |
| 8144 | + Ok(serde_json::Value::Array(results)) | |
| 8145 | + } | |
| 8146 | + Some("batch") => { | |
| 8147 | + let now = integer(&request, "now")?; | |
| 8148 | + let max_batch_size = usize::try_from(integer(&request, "maxBatchSize")?) | |
| 8149 | + .map_err(|_| anyhow!("Queue maxBatchSize is out of range"))?; | |
| 8150 | + let rows = request | |
| 8151 | + .get("rows") | |
| 8152 | + .and_then(serde_json::Value::as_array) | |
| 8153 | + .ok_or_else(|| anyhow!("Queue batch policy has no rows"))?; | |
| 8154 | + let rows = rows | |
| 8155 | + .iter() | |
| 8156 | + .map(|row| { | |
| 8157 | + let generation = row | |
| 8158 | + .get("leaseGeneration") | |
| 8159 | + .and_then(serde_json::Value::as_str) | |
| 8160 | + .ok_or_else(|| anyhow!("Queue row has no leaseGeneration"))? | |
| 8161 | + .parse::<u64>() | |
| 8162 | + .context("Queue leaseGeneration is invalid")?; | |
| 8163 | + Ok(celld_logic::queue::BatchRow { | |
| 8164 | + seq: integer(row, "seq")?, | |
| 8165 | + visible_at: integer(row, "visibleAt")?, | |
| 8166 | + lease_generation: generation, | |
| 8167 | + leased_until: optional_integer(row, "leasedUntil")?, | |
| 8168 | + purge_on_settle: row | |
| 8169 | + .get("purgeOnSettle") | |
| 8170 | + .and_then(serde_json::Value::as_bool) | |
| 8171 | + .ok_or_else(|| anyhow!("Queue row has no purgeOnSettle"))?, | |
| 8172 | + }) | |
| 8173 | + }) | |
| 8174 | + .collect::<Result<Vec<_>>>()?; | |
| 8175 | + let plan = celld_logic::queue::batch_plan(now, &rows, max_batch_size)?; | |
| 8176 | + Ok(serde_json::json!({ | |
| 8177 | + "leases": plan.leases.into_iter().map(|lease| serde_json::json!({ | |
| 8178 | + "seq": lease.seq, | |
| 8179 | + "generation": lease.generation.to_string(), | |
| 8180 | + "reclaimed": lease.reclaimed, | |
| 8181 | + })).collect::<Vec<_>>(), | |
| 8182 | + "deletePurged": plan.delete_purged, | |
| 8183 | + })) | |
| 8184 | + } | |
| 8185 | + Some("settlement") => { | |
| 8186 | + #[cfg(celld_internal_tests)] | |
| 8187 | + QUEUE_SETTLEMENT_POLICY_OBSERVED.with(|observed| observed.set(true)); | |
| 8188 | + | |
| 8189 | + let members = |name: &str| -> Result<Vec<celld_logic::queue::LeaseMember<'_>>> { | |
| 8190 | + request | |
| 8191 | + .get(name) | |
| 8192 | + .and_then(serde_json::Value::as_array) | |
| 8193 | + .ok_or_else(|| anyhow!("Queue settlement policy has no {name}"))? | |
| 8194 | + .iter() | |
| 8195 | + .map(|member| { | |
| 8196 | + let string = |field: &str| -> Result<&str> { | |
| 8197 | + member | |
| 8198 | + .get(field) | |
| 8199 | + .and_then(serde_json::Value::as_str) | |
| 8200 | + .ok_or_else(|| { | |
| 8201 | + anyhow!("Queue settlement member has no {field}") | |
| 8202 | + }) | |
| 8203 | + }; | |
| 8204 | + Ok(celld_logic::queue::LeaseMember { | |
| 8205 | + seq: string("seq")? | |
| 8206 | + .parse::<i64>() | |
| 8207 | + .context("Queue settlement sequence is invalid")?, | |
| 8208 | + message_id: string("messageId")?, | |
| 8209 | + generation: string("generation")? | |
| 8210 | + .parse::<u64>() | |
| 8211 | + .context("Queue settlement generation is invalid")?, | |
| 8212 | + }) | |
| 8213 | + }) | |
| 8214 | + .collect() | |
| 8215 | + }; | |
| 8216 | + let current = members("current")?; | |
| 8217 | + let submitted = members("submitted")?; | |
| 8218 | + Ok(serde_json::json!(celld_logic::queue::settlement_matches( | |
| 8219 | + ¤t, &submitted, | |
| 8220 | + ))) | |
| 8221 | + } | |
| 8222 | + Some("purge") => { | |
| 8223 | + let now = integer(&request, "now")?; | |
| 8224 | + let rows = request | |
| 8225 | + .get("rows") | |
| 8226 | + .and_then(serde_json::Value::as_array) | |
| 8227 | + .ok_or_else(|| anyhow!("Queue purge policy has no rows"))? | |
| 8228 | + .iter() | |
| 8229 | + .map(|row| { | |
| 8230 | + Ok(celld_logic::queue::PurgeRow { | |
| 8231 | + seq: row | |
| 8232 | + .get("seq") | |
| 8233 | + .and_then(serde_json::Value::as_str) | |
| 8234 | + .ok_or_else(|| anyhow!("Queue purge row has no sequence"))? | |
| 8235 | + .parse::<i64>() | |
| 8236 | + .context("Queue purge sequence is invalid")?, | |
| 8237 | + lease_id_present: row | |
| 8238 | + .get("leaseIdPresent") | |
| 8239 | + .and_then(serde_json::Value::as_bool) | |
| 8240 | + .ok_or_else(|| anyhow!("Queue purge row has no lease state"))?, | |
| 8241 | + leased_until: optional_integer(row, "leasedUntil")?, | |
| 8242 | + }) | |
| 8243 | + }) | |
| 8244 | + .collect::<Result<Vec<_>>>()?; | |
| 8245 | + let plan = celld_logic::queue::purge_plan(now, &rows); | |
| 8246 | + Ok(serde_json::json!({ | |
| 8247 | + "delete": plan.delete.into_iter().map(|seq| seq.to_string()).collect::<Vec<_>>(), | |
| 8248 | + "markForSettle": plan.mark_for_settle.into_iter().map(|seq| seq.to_string()).collect::<Vec<_>>(), | |
| 8249 | + })) | |
| 8250 | + } | |
| 8251 | + Some(other) => Err(anyhow!("unknown Queue policy operation {other:?}")), | |
| 8252 | + None => Err(anyhow!("Queue policy input has no op")), | |
| 8253 | + } | |
| 8254 | + })(); | |
| 8255 | + match result { | |
| 8256 | + Ok(value) => { | |
| 8257 | + let value = v8::String::new(scope, &value.to_string()).unwrap(); | |
| 8258 | + rv.set(value.into()); | |
| 8259 | + } | |
| 8260 | + Err(error) => loader_throw(scope, &error.to_string()), | |
| 8261 | + } | |
| 8262 | +} | |
| 8263 | + | |
| 8264 | +/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await | |
| 8265 | +/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON | |
| 8266 | +/// `{status, body, headers}` string the harness turns back into a Response. | |
| 8267 | +/// `__svc_rpc(script, entrypoint, method, argsSc)` -> Promise<Uint8Array>; | |
| 8268 | +/// arguments and result are V8 structured-clone bytes. | |
| 8269 | +/// The application generation the calling isolate was built for, from the | |
| 8270 | +/// slot `load_config` installs. Zero for an isolate built outside any | |
| 8271 | +/// generation, which the runtime resolves as the current one. | |
| 8272 | +fn current_generation(scope: &mut v8::PinScope) -> crate::generation::GenerationId { | |
| 8273 | + scope | |
| 8274 | + .get_slot::<crate::generation::GenerationTag>() | |
| 8275 | + .map(|tag| tag.0) | |
| 8276 | + .unwrap_or(0) | |
| 8277 | +} | |
| 8278 | + | |
| 8279 | +fn op_svc_rpc( | |
| 8280 | + scope: &mut v8::PinScope, | |
| 8281 | + args: v8::FunctionCallbackArguments, | |
| 8282 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8283 | +) { | |
| 8284 | + let script = args.get(0).to_rust_string_lossy(scope); | |
| 8285 | + let entrypoint = args.get(1).to_rust_string_lossy(scope); | |
| 8286 | + let method = args.get(2).to_rust_string_lossy(scope); | |
| 8287 | + let call_args = view_bytes(args.get(3)).unwrap_or_default(); | |
| 8288 | + let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 8289 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service); | |
| 8290 | + let request = SvcRpcReq { | |
| 8291 | + generation: current_generation(scope), | |
| 8292 | + script, | |
| 8293 | + entrypoint, | |
| 8294 | + method, | |
| 8295 | + args: call_args, | |
| 8296 | + reply: tx, | |
| 8297 | + }; | |
| 8298 | + let id = asyncrt::enqueue(async move { | |
| 8299 | + gated_channel_send(gate, &SVC_RPC_TX, request, "no service binding channel").await?; | |
| 8300 | + match rx.await { | |
| 8301 | + Ok(Ok(result)) => Ok(result), | |
| 8302 | + Ok(Err(error)) => Err(format!("{error}")), | |
| 8303 | + Err(error) => Err(format!("service dropped: {error}")), | |
| 8304 | + } | |
| 8305 | + }); | |
| 8306 | + rv.set(promise_for(scope, id)); | |
| 8307 | +} | |
| 8308 | + | |
| 8309 | +/// `__svc_call(script, url, method, body, headersJson)` -> Promise<json>. | |
| 8310 | +/// The service-binding equivalent of `__do_call`: no scope to resolve and no | |
| 8311 | +/// cancellation token, just a handoff to the target script's pool. | |
| 8312 | +fn op_svc_call( | |
| 8313 | + scope: &mut v8::PinScope, | |
| 8314 | + args: v8::FunctionCallbackArguments, | |
| 8315 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8316 | +) { | |
| 8317 | + op_svc_call_impl(scope, args, &mut rv, false); | |
| 8318 | +} | |
| 8319 | + | |
| 8320 | +fn op_svc_call_cancellable( | |
| 8321 | + scope: &mut v8::PinScope, | |
| 8322 | + args: v8::FunctionCallbackArguments, | |
| 8323 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8324 | +) { | |
| 8325 | + op_svc_call_impl(scope, args, &mut rv, true); | |
| 8326 | +} | |
| 8327 | + | |
| 8328 | +fn op_svc_call_impl( | |
| 8329 | + scope: &mut v8::PinScope, | |
| 8330 | + args: v8::FunctionCallbackArguments, | |
| 8331 | + rv: &mut v8::ReturnValue<v8::Value>, | |
| 8332 | + cancellable: bool, | |
| 8333 | +) { | |
| 8334 | + let script = args.get(0).to_rust_string_lossy(scope); | |
| 8335 | + let url = args.get(1).to_rust_string_lossy(scope); | |
| 8336 | + let method = args.get(2).to_rust_string_lossy(scope); | |
| 8337 | + let stream_arg = args.get(5); | |
| 8338 | + let body = if stream_arg.is_number() { | |
| 8339 | + RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64) | |
| 8340 | + } else { | |
| 8341 | + let Some(bytes) = view_bytes(args.get(3)) else { | |
| 8342 | + return loader_throw( | |
| 8343 | + scope, | |
| 8344 | + "service binding: the request body is not a typed array", | |
| 8345 | + ); | |
| 8346 | + }; | |
| 8347 | + RequestBody::Bytes(bytes.into()) | |
| 8348 | + }; | |
| 8349 | + let headers: Vec<(String, String)> = | |
| 8350 | + match serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)) { | |
| 8351 | + Ok(headers) => headers, | |
| 8352 | + Err(error) => { | |
| 8353 | + return loader_throw( | |
| 8354 | + scope, | |
| 8355 | + &format!( | |
| 8356 | + "service binding: the request headers are not a name/value list: {error}" | |
| 8357 | + ), | |
| 8358 | + ) | |
| 8359 | + } | |
| 8360 | + }; | |
| 8361 | + let body_guard = match body.stream_id() { | |
| 8362 | + Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 8363 | + Some(guard) => guard, | |
| 8364 | + None => return loader_throw(scope, "service binding: the body stream is not owned"), | |
| 8365 | + }, | |
| 8366 | + None => RequestBodyGuard::of(&body), | |
| 8367 | + }; | |
| 8368 | + let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 8369 | + // Shares the Durable Object cancel registry and the id encoding | |
| 8370 | + // `attach_cancel_id` writes, so `__do_call_cancel` works unchanged for a | |
| 8371 | + // service call. Only a cancellable call registers: a caller with no | |
| 8372 | + // AbortSignal has nothing that can cancel it, and the router already ends | |
| 8373 | + // the call when the reply sender drops. | |
| 8374 | + let (request_id, cancel, cancel_guard) = if cancellable { | |
| 8375 | + let request_id = next_do_request_id(); | |
| 8376 | + let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel(); | |
| 8377 | + do_call_cancels() | |
| 8378 | + .lock() | |
| 8379 | + .unwrap() | |
| 8380 | + .insert(request_id, cancel_sender); | |
| 8381 | + ( | |
| 8382 | + Some(request_id), | |
| 8383 | + Some(cancel_receiver), | |
| 8384 | + Some(DoCallCancelGuard::new(request_id)), | |
| 8385 | + ) | |
| 8386 | + } else { | |
| 8387 | + (None, None, None) | |
| 8388 | + }; | |
| 8389 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service); | |
| 8390 | + let request = SvcCallReq { | |
| 8391 | + cancel, | |
| 8392 | + generation: current_generation(scope), | |
| 8393 | + script, | |
| 8394 | + url, | |
| 8395 | + method, | |
| 8396 | + body, | |
| 8397 | + body_guard, | |
| 8398 | + headers, | |
| 8399 | + reply: tx, | |
| 8400 | + }; | |
| 8401 | + let stream_service = http_stream_service(); | |
| 8402 | + let id = asyncrt::enqueue(async move { | |
| 8403 | + let mut cancel_guard = cancel_guard; | |
| 8404 | + gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?; | |
| 8405 | + let result = match rx.await { | |
| 8406 | + Ok(Ok(response)) => encode_http_response(response, true, &stream_service), | |
| 8407 | + Ok(Err(error)) => Err(format!("{error}")), | |
| 8408 | + Err(error) => Err(format!("service dropped: {error}")), | |
| 8409 | + }; | |
| 8410 | + if let Some(cancel_guard) = cancel_guard.as_mut() { | |
| 8411 | + cancel_guard.disarm(); | |
| 8412 | + } | |
| 8413 | + result | |
| 8414 | + }); | |
| 8415 | + let promise = promise_for(scope, id); | |
| 8416 | + if let Some(request_id) = request_id { | |
| 8417 | + attach_cancel_id(scope, promise, request_id); | |
| 8418 | + } | |
| 8419 | + rv.set(promise); | |
| 8420 | +} | |
| 8421 | + | |
| 8422 | +// --- Worker Loader: dynamic isolates for Code Mode --- | |
| 8423 | +// A running Worker creates a fresh isolate from code it supplies at runtime | |
| 8424 | +// and invokes it. The loaded isolate uses the same turn driver as every | |
| 8425 | +// stateless Worker, so an awaited operation holds no thread or isolate. | |
| 8426 | + | |
| 8427 | +// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total | |
| 8428 | +// module bytes, 1 MiB env. Messages match so the conformance cases pass. | |
| 8429 | +const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024; | |
| 8430 | +const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024; | |
| 8431 | + | |
| 8432 | +#[derive(Clone)] | |
| 8433 | +enum LoaderState { | |
| 8434 | + Loading, | |
| 8435 | + Ready(Arc<crate::pool::Slot>), | |
| 8436 | + Failed(Arc<str>), | |
| 8437 | +} | |
| 8438 | + | |
| 8439 | +#[derive(Clone, Copy, Eq, PartialEq)] | |
| 8440 | +struct LoaderOwner(u64); | |
| 8441 | + | |
| 8442 | +impl LoaderOwner { | |
| 8443 | + fn fresh() -> Self { | |
| 8444 | + Self(LOADER_NEXT_OWNER.fetch_add(1, Ordering::Relaxed)) | |
| 8445 | + } | |
| 8446 | +} | |
| 8447 | + | |
| 8448 | +#[doc(hidden)] | |
| 8449 | +pub struct LoaderEntry { | |
| 8450 | + owner: LoaderOwner, | |
| 8451 | + state: tokio::sync::watch::Receiver<LoaderState>, | |
| 8452 | +} | |
| 8453 | + | |
| 8454 | +type LoaderRegistry = HashMap<u64, LoaderEntry>; | |
| 8455 | +static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new(); | |
| 8456 | +static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1); | |
| 8457 | +static LOADER_NEXT_OWNER: AtomicU64 = AtomicU64::new(1); | |
| 8458 | + | |
| 8459 | +#[doc(hidden)] | |
| 8460 | +pub fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> { | |
| 8461 | + LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 8462 | +} | |
| 8463 | + | |
| 8464 | +/// Remove the registry references for every child of `owner`. The caller | |
| 8465 | +/// chooses when to drop the returned states, because they can own V8 isolates | |
| 8466 | +/// and no other isolate can be entered on that thread at destruction time. | |
| 8467 | +fn take_loader_owner(owner: LoaderOwner) -> Vec<tokio::sync::watch::Receiver<LoaderState>> { | |
| 8468 | + let mut registry = loader_registry().lock().unwrap(); | |
| 8469 | + let ids: Vec<u64> = registry | |
| 8470 | + .iter() | |
| 8471 | + .filter_map(|(id, entry)| (entry.owner == owner).then_some(*id)) | |
| 8472 | + .collect(); | |
| 8473 | + ids.into_iter() | |
| 8474 | + .filter_map(|id| registry.remove(&id).map(|entry| entry.state)) | |
| 8475 | + .collect() | |
| 8476 | +} | |
| 8477 | + | |
| 8478 | +fn loader_throw(scope: &mut v8::PinScope, message: &str) { | |
| 8479 | + let message = v8::String::new(scope, message).unwrap(); | |
| 8480 | + let exception = v8::Exception::error(scope, message); | |
| 8481 | + scope.throw_exception(exception); | |
| 8482 | +} | |
| 8483 | + | |
| 8484 | +async fn loaded_worker_slot( | |
| 8485 | + mut state: tokio::sync::watch::Receiver<LoaderState>, | |
| 8486 | +) -> Result<Arc<crate::pool::Slot>, String> { | |
| 8487 | + loop { | |
| 8488 | + match state.borrow().clone() { | |
| 8489 | + LoaderState::Ready(slot) => return Ok(slot), | |
| 8490 | + LoaderState::Failed(error) => return Err(error.to_string()), | |
| 8491 | + LoaderState::Loading => {} | |
| 8492 | + } | |
| 8493 | + state | |
| 8494 | + .changed() | |
| 8495 | + .await | |
| 8496 | + .map_err(|_| "worker loader: load task dropped".to_string())?; | |
| 8497 | + } | |
| 8498 | +} | |
| 8499 | + | |
| 8500 | +/// `__loader_load(codeJson)` -> stub id. Builds a WorkerConfig from the | |
| 8501 | +/// supplied modules and registers its asynchronous load state. Compilation | |
| 8502 | +/// runs on Tokio's blocking pool. Calls wait for that result and then use the | |
| 8503 | +/// normal stateless turn driver. | |
| 8504 | +fn op_loader_load( | |
| 8505 | + scope: &mut v8::PinScope, | |
| 8506 | + args: v8::FunctionCallbackArguments, | |
| 8507 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8508 | +) { | |
| 8509 | + let code_json = args.get(0).to_rust_string_lossy(scope); | |
| 8510 | + let code: serde_json::Value = match serde_json::from_str(&code_json) { | |
| 8511 | + Ok(code) => code, | |
| 8512 | + Err(e) => return loader_throw(scope, &format!("worker loader: {e}")), | |
| 8513 | + }; | |
| 8514 | + let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else { | |
| 8515 | + return loader_throw(scope, "worker loader: missing mainModule"); | |
| 8516 | + }; | |
| 8517 | + let Some(src) = code | |
| 8518 | + .get("modules") | |
| 8519 | + .and_then(|m| m.get(main)) | |
| 8520 | + .and_then(|v| v.as_str()) | |
| 8521 | + .map(str::to_string) | |
| 8522 | + else { | |
| 8523 | + return loader_throw( | |
| 8524 | + scope, | |
| 8525 | + &format!("worker loader: module {main:?} missing or not a string"), | |
| 8526 | + ); | |
| 8527 | + }; | |
| 8528 | + // Every module other than the main one is a sibling the main module may | |
| 8529 | + // import. JS modules arrive in the JSON as strings; anything else there is | |
| 8530 | + // rejected — JSON.stringify would already have mangled it, and dropping it | |
| 8531 | + // silently leaves the loaded worker failing instantiation with an | |
| 8532 | + // unresolved specifier that never names the cause. Wasm modules arrive | |
| 8533 | + // out of band as the second argument, an array of `[name, Uint8Array]` | |
| 8534 | + // pairs, which keeps the blobs out of the JSON payload entirely. | |
| 8535 | + let mut modules: Vec<(String, ModuleSource)> = Vec::new(); | |
| 8536 | + if let Some(map) = code.get("modules").and_then(|m| m.as_object()) { | |
| 8537 | + for (name, value) in map.iter().filter(|(name, _)| name.as_str() != main) { | |
| 8538 | + let Some(source) = value.as_str() else { | |
| 8539 | + return loader_throw( | |
| 8540 | + scope, | |
| 8541 | + &format!("worker loader: module {name:?} must be a string or wasm bytes"), | |
| 8542 | + ); | |
| 8543 | + }; | |
| 8544 | + modules.push((name.clone(), ModuleSource::EsModule(source.to_string()))); | |
| 8545 | + } | |
| 8546 | + } | |
| 8547 | + let sideband = args.get(1); | |
| 8548 | + if !sideband.is_undefined() { | |
| 8549 | + let Ok(entries) = v8::Local::<v8::Array>::try_from(sideband) else { | |
| 8550 | + return loader_throw(scope, "worker loader: wasm modules must be an array"); | |
| 8551 | + }; | |
| 8552 | + for index in 0..entries.length() { | |
| 8553 | + let entry = entries | |
| 8554 | + .get_index(scope, index) | |
| 8555 | + .and_then(|entry| v8::Local::<v8::Array>::try_from(entry).ok()) | |
| 8556 | + .and_then(|pair| Some((pair.get_index(scope, 0)?, pair.get_index(scope, 1)?))) | |
| 8557 | + .filter(|(name, _)| name.is_string()) | |
| 8558 | + .and_then(|(name, value)| { | |
| 8559 | + let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?; | |
| 8560 | + Some((name.to_rust_string_lossy(scope), view)) | |
| 8561 | + }); | |
| 8562 | + let Some((name, view)) = entry else { | |
| 8563 | + return loader_throw(scope, "worker loader: malformed wasm module entry"); | |
| 8564 | + }; | |
| 8565 | + // A name carried by both the JSON map and the side-band would | |
| 8566 | + // silently shadow one module with the other in the registry; | |
| 8567 | + // refuse it the way a non-string JSON module is refused. | |
| 8568 | + if name == main || modules.iter().any(|(existing, _)| *existing == name) { | |
| 8569 | + return loader_throw( | |
| 8570 | + scope, | |
| 8571 | + &format!("worker loader: duplicate module name {name:?}"), | |
| 8572 | + ); | |
| 8573 | + } | |
| 8574 | + let mut bytes = vec![0u8; view.byte_length()]; | |
| 8575 | + view.copy_contents(&mut bytes); | |
| 8576 | + modules.push((name, ModuleSource::Wasm(bytes.into()))); | |
| 8577 | + } | |
| 8578 | + } | |
| 8579 | + // Total module bytes, checked before compiling anything (the oversized | |
| 8580 | + // module is never parsed) — the extra modules are not yet loaded but do | |
| 8581 | + // count against the ceiling, as upstream. | |
| 8582 | + let code_size: usize = src.len() | |
| 8583 | + + modules | |
| 8584 | + .iter() | |
| 8585 | + .map(|(_, source)| match source { | |
| 8586 | + ModuleSource::Text(source) | ModuleSource::EsModule(source) => source.len(), | |
| 8587 | + ModuleSource::Wasm(bytes) => bytes.len(), | |
| 8588 | + }) | |
| 8589 | + .sum::<usize>(); | |
| 8590 | + if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE { | |
| 8591 | + return loader_throw( | |
| 8592 | + scope, | |
| 8593 | + &format!( | |
| 8594 | + "Dynamic Worker code size ({code_size} bytes) exceeds the \ | |
| 8595 | + maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes." | |
| 8596 | + ), | |
| 8597 | + ); | |
| 8598 | + } | |
| 8599 | + // Plain JSON `env` values merge onto the loaded worker's env; capability | |
| 8600 | + // stubs are not yet supported and would fail to serialize upstream in JS. | |
| 8601 | + let loader_env = code | |
| 8602 | + .get("env") | |
| 8603 | + .filter(|v| !v.is_null()) | |
| 8604 | + .map(|v| v.to_string()); | |
| 8605 | + if let Some(env) = &loader_env { | |
| 8606 | + if env.len() > MAX_DYNAMIC_WORKER_ENV_SIZE { | |
| 8607 | + return loader_throw( | |
| 8608 | + scope, | |
| 8609 | + &format!( | |
| 8610 | + "Dynamic Worker env size ({} bytes) exceeds the maximum \ | |
| 8611 | + allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.", | |
| 8612 | + env.len() | |
| 8613 | + ), | |
| 8614 | + ); | |
| 8615 | + } | |
| 8616 | + } | |
| 8617 | + // globalOutbound: absent inherits the caller's authority, null denies | |
| 8618 | + // ambient egress, a Fetcher (broker) is not implemented yet. | |
| 8619 | + let egress = match code.get("globalOutbound") { | |
| 8620 | + None => actor_runtime_state(scope).egress, | |
| 8621 | + Some(v) if v.is_null() => EgressPolicy::Deny, | |
| 8622 | + Some(_) => { | |
| 8623 | + return loader_throw( | |
| 8624 | + scope, | |
| 8625 | + "worker loader: globalOutbound broker is not implemented yet", | |
| 8626 | + ); | |
| 8627 | + } | |
| 8628 | + }; | |
| 8629 | + let owner = *scope | |
| 8630 | + .get_slot::<LoaderOwner>() | |
| 8631 | + .expect("Worker isolate has a Loader owner"); | |
| 8632 | + // Bound live loaded workers so a runaway agent loop cannot exhaust | |
| 8633 | + // isolates. Evicted workers (dropped stubs) free their slot. | |
| 8634 | + let max = crate::env_vars::positive_or("CELLD_MAX_LOADED_WORKERS", 256) | |
| 8635 | + .expect("validated CELLD_MAX_LOADED_WORKERS"); | |
| 8636 | + if loader_registry().lock().unwrap().len() >= max { | |
| 8637 | + return loader_throw( | |
| 8638 | + scope, | |
| 8639 | + &format!("worker loader: too many loaded workers (limit {max})"), | |
| 8640 | + ); | |
| 8641 | + } | |
| 8642 | + // Honor the WorkerCode's declared compatibility (workerd worker_compat | |
| 8643 | + // reads snake_case keys); Code Mode workers keep RPC on regardless. | |
| 8644 | + let mut compat = crate::worker_compat(&serde_json::json!({ | |
| 8645 | + "compatibility_date": code.get("compatibilityDate"), | |
| 8646 | + "compatibility_flags": code.get("compatibilityFlags"), | |
| 8647 | + })); | |
| 8648 | + compat.js_rpc = true; | |
| 8649 | + let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed); | |
| 8650 | + let config = Arc::new( | |
| 8651 | + WorkerConfig::new(WorkerConfigOptions { | |
| 8652 | + src, | |
| 8653 | + script_name: format!("__loader:{id}"), | |
| 8654 | + do_classes: Vec::new(), | |
| 8655 | + bindings: Vec::new(), | |
| 8656 | + r2_bindings: Vec::new(), | |
| 8657 | + // A loaded worker reaches D1 only if its parent injects a stub; | |
| 8658 | + // ambient bindings are exactly what Code Mode withholds. | |
| 8659 | + d1_bindings: Vec::new(), | |
| 8660 | + kv_bindings: Vec::new(), | |
| 8661 | + queue_bindings: Vec::new(), | |
| 8662 | + queue_consumers: Vec::new(), | |
| 8663 | + workflow_bindings: Vec::new(), | |
| 8664 | + ai_binding: None, | |
| 8665 | + vars: Vec::new(), | |
| 8666 | + node: String::new(), | |
| 8667 | + modules, | |
| 8668 | + compat, | |
| 8669 | + }) | |
| 8670 | + .with_egress(egress) | |
| 8671 | + .with_loader_env(loader_env), | |
| 8672 | + ); | |
| 8673 | + let handle = match tokio::runtime::Handle::try_current() { | |
| 8674 | + Ok(handle) => handle, | |
| 8675 | + Err(error) => return loader_throw(scope, &format!("worker loader: {error}")), | |
| 8676 | + }; | |
| 8677 | + let (loaded, state) = tokio::sync::watch::channel(LoaderState::Loading); | |
| 8678 | + loader_registry() | |
| 8679 | + .lock() | |
| 8680 | + .unwrap() | |
| 8681 | + .insert(id, LoaderEntry { owner, state }); | |
| 8682 | + handle.spawn(async move { | |
| 8683 | + let state = match tokio::task::spawn_blocking(move || Worker::load_config(config)).await { | |
| 8684 | + Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::standalone(worker)), | |
| 8685 | + Ok(Err(error)) => LoaderState::Failed(Arc::from(format!("{error}"))), | |
| 8686 | + Err(error) => LoaderState::Failed(Arc::from(format!( | |
| 8687 | + "worker loader: load task failed: {error}" | |
| 8688 | + ))), | |
| 8689 | + }; | |
| 8690 | + loaded.send_replace(state); | |
| 8691 | + }); | |
| 8692 | + rv.set(v8::Number::new(scope, id as f64).into()); | |
| 8693 | +} | |
| 8694 | + | |
| 8695 | +/// `__loader_fetch(id, url, method, body, headersJson)` -> Promise<json>. The | |
| 8696 | +/// loaded-worker analog of `__svc_call`: encodes the response the same way. | |
| 8697 | +fn op_loader_fetch( | |
| 8698 | + scope: &mut v8::PinScope, | |
| 8699 | + args: v8::FunctionCallbackArguments, | |
| 8700 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8701 | +) { | |
| 8702 | + let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 8703 | + let url = args.get(1).to_rust_string_lossy(scope); | |
| 8704 | + let method = args.get(2).to_rust_string_lossy(scope); | |
| 8705 | + let stream_arg = args.get(5); | |
| 8706 | + let body = if stream_arg.is_number() { | |
| 8707 | + RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64) | |
| 8708 | + } else { | |
| 8709 | + let Some(bytes) = view_bytes(args.get(3)) else { | |
| 8710 | + return loader_throw( | |
| 8711 | + scope, | |
| 8712 | + "worker loader: the request body is not a typed array", | |
| 8713 | + ); | |
| 8714 | + }; | |
| 8715 | + RequestBody::Bytes(bytes.into()) | |
| 8716 | + }; | |
| 8717 | + let headers: Vec<(String, String)> = | |
| 8718 | + match serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)) { | |
| 8719 | + Ok(headers) => headers, | |
| 8720 | + Err(error) => { | |
| 8721 | + return loader_throw( | |
| 8722 | + scope, | |
| 8723 | + &format!( | |
| 8724 | + "worker loader: the request headers are not a name/value list: {error}" | |
| 8725 | + ), | |
| 8726 | + ) | |
| 8727 | + } | |
| 8728 | + }; | |
| 8729 | + let mut body_guard = match body.stream_id() { | |
| 8730 | + Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 8731 | + Some(guard) => guard, | |
| 8732 | + None => return loader_throw(scope, "worker loader: the body stream is not owned"), | |
| 8733 | + }, | |
| 8734 | + None => RequestBodyGuard::of(&body), | |
| 8735 | + }; | |
| 8736 | + let loaded = loader_registry() | |
| 8737 | + .lock() | |
| 8738 | + .unwrap() | |
| 8739 | + .get(&id) | |
| 8740 | + .map(|entry| entry.state.clone()); | |
| 8741 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service); | |
| 8742 | + let stream_service = http_stream_service(); | |
| 8743 | + let async_id = asyncrt::enqueue(async move { | |
| 8744 | + // The child's own `IoContext` has an empty egress stack, so nothing | |
| 8745 | + // inside it gates what it sends onward. Holding the call until the | |
| 8746 | + // caller's writes are proven makes every effect of the loaded worker | |
| 8747 | + // trail that proof, as a service-binding call already does. | |
| 8748 | + await_egress_gate(gate).await?; | |
| 8749 | + let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 8750 | + let slot = loaded_worker_slot(state).await?; | |
| 8751 | + let (reply, receive) = tokio::sync::oneshot::channel(); | |
| 8752 | + let job = crate::WorkerJob::Fetch { | |
| 8753 | + queued_at: Instant::now(), | |
| 8754 | + url, | |
| 8755 | + method, | |
| 8756 | + body, | |
| 8757 | + headers, | |
| 8758 | + // A loaded Worker receives an incoming request like a service | |
| 8759 | + // target does. The id selects the stream-aware construction path | |
| 8760 | + // and gives an abandoned request a lifecycle owner. | |
| 8761 | + request_id: Some(next_request_id()), | |
| 8762 | + reply, | |
| 8763 | + }; | |
| 8764 | + let driving = tokio::spawn(crate::runtime::drive(slot, job, None)); | |
| 8765 | + match receive.await { | |
| 8766 | + Ok(Ok(response)) => { | |
| 8767 | + // The response proves that the loaded Worker installed its | |
| 8768 | + // request context. That context owns an unread body tail | |
| 8769 | + // through its waitUntil work. | |
| 8770 | + body_guard.disarm(); | |
| 8771 | + encode_http_response(response, false, &stream_service) | |
| 8772 | + } | |
| 8773 | + Ok(Err(error)) => Err(format!("{error}")), | |
| 8774 | + Err(_) => match driving.await { | |
| 8775 | + Err(error) => Err(format!("loaded worker task died: {error}")), | |
| 8776 | + Ok(()) => Err("loaded worker dropped response".to_string()), | |
| 8777 | + }, | |
| 8778 | + } | |
| 8779 | + }); | |
| 8780 | + rv.set(promise_for(scope, async_id)); | |
| 8781 | +} | |
| 8782 | + | |
| 8783 | +/// Reclaims a streamed request body if a host dispatch fails before the | |
| 8784 | +/// target installs a request context. A successful dispatch disarms this | |
| 8785 | +/// fallback because the target context then owns the unread tail. | |
| 8786 | +pub struct RequestBodyGuard(Option<HttpStreamClaim>); | |
| 8787 | + | |
| 8788 | +impl RequestBodyGuard { | |
| 8789 | + pub fn of(body: &RequestBody) -> Self { | |
| 8790 | + Self(body.stream_id().and_then(claim_http_stream)) | |
| 8791 | + } | |
| 8792 | + | |
| 8793 | + fn transferred(claim: HttpStreamClaim) -> Self { | |
| 8794 | + Self(Some(claim)) | |
| 8795 | + } | |
| 8796 | + | |
| 8797 | + pub fn disarm(&mut self) { | |
| 8798 | + drop(self.0.take()); | |
| 8799 | + } | |
| 8800 | + | |
| 8801 | + fn take_stream(&mut self, stream_id: u64) -> Result<HttpChunkStream, String> { | |
| 8802 | + let Some(claim) = self.0.take() else { | |
| 8803 | + return Err(format!("body stream {stream_id} is not registered")); | |
| 8804 | + }; | |
| 8805 | + if claim.stream_id != stream_id { | |
| 8806 | + let claimed = claim.stream_id; | |
| 8807 | + self.0 = Some(claim); | |
| 8808 | + return Err(format!( | |
| 8809 | + "body stream {stream_id} does not match ownership claim {claimed}" | |
| 8810 | + )); | |
| 8811 | + } | |
| 8812 | + claim.take_source() | |
| 8813 | + } | |
| 8814 | +} | |
| 8815 | + | |
| 8816 | +impl Drop for RequestBodyGuard { | |
| 8817 | + fn drop(&mut self) { | |
| 8818 | + let claim = self.0.take(); | |
| 8819 | + run_http_cleanup_from_drop(|| drop(claim)); | |
| 8820 | + } | |
| 8821 | +} | |
| 8822 | + | |
| 8823 | +/// `__loader_rpc(id, entrypoint, method, argsSc)` -> Promise<Uint8Array>. The | |
| 8824 | +/// loaded-worker analog of `__svc_rpc`: a named-entrypoint method call whose | |
| 8825 | +/// args and result are V8 structured-clone bytes. | |
| 8826 | +fn op_loader_rpc( | |
| 8827 | + scope: &mut v8::PinScope, | |
| 8828 | + args: v8::FunctionCallbackArguments, | |
| 8829 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8830 | +) { | |
| 8831 | + let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 8832 | + let entrypoint = args.get(1).to_rust_string_lossy(scope); | |
| 8833 | + let method = args.get(2).to_rust_string_lossy(scope); | |
| 8834 | + let call_args = view_bytes(args.get(3)).unwrap_or_default(); | |
| 8835 | + let loaded = loader_registry() | |
| 8836 | + .lock() | |
| 8837 | + .unwrap() | |
| 8838 | + .get(&id) | |
| 8839 | + .map(|entry| entry.state.clone()); | |
| 8840 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service); | |
| 8841 | + let async_id = asyncrt::enqueue(async move { | |
| 8842 | + // The same rule as `op_loader_fetch`: the call carries cell state. | |
| 8843 | + await_egress_gate(gate).await?; | |
| 8844 | + let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 8845 | + let slot = loaded_worker_slot(state).await?; | |
| 8846 | + let (reply, receive) = tokio::sync::oneshot::channel(); | |
| 8847 | + let job = crate::WorkerJob::Rpc { | |
| 8848 | + entrypoint, | |
| 8849 | + method, | |
| 8850 | + args: call_args, | |
| 8851 | + reply, | |
| 8852 | + }; | |
| 8853 | + let driving = tokio::spawn(crate::runtime::drive(slot, job, None)); | |
| 8854 | + match receive.await { | |
| 8855 | + Ok(Ok(result)) => Ok(result), | |
| 8856 | + Ok(Err(error)) => Err(format!("{error}")), | |
| 8857 | + Err(_) => match driving.await { | |
| 8858 | + Err(error) => Err(format!("loaded worker task died: {error}")), | |
| 8859 | + Ok(()) => Err("loaded worker dropped RPC result".to_string()), | |
| 8860 | + }, | |
| 8861 | + } | |
| 8862 | + }); | |
| 8863 | + rv.set(promise_for(scope, async_id)); | |
| 8864 | +} | |
| 8865 | + | |
| 8866 | +fn facet_scope(class_name: &str, parent_scope: &str, owner: &str, name: &str) -> String { | |
| 8867 | + use sha2::Digest as _; | |
| 8868 | + let mut digest = sha2::Sha256::new(); | |
| 8869 | + digest.update(parent_scope.as_bytes()); | |
| 8870 | + digest.update([0]); | |
| 8871 | + digest.update(owner.as_bytes()); | |
| 8872 | + digest.update([0]); | |
| 8873 | + digest.update(name.as_bytes()); | |
| 8874 | + let digest: [u8; 32] = digest.finalize().into(); | |
| 8875 | + format!("{class_name}:{}", durable_object_id_hex(&digest)) | |
| 8876 | +} | |
| 8877 | + | |
| 8878 | +struct FacetStart { | |
| 8879 | + class_name: String, | |
| 8880 | + parent_scope: String, | |
| 8881 | + owner: String, | |
| 8882 | + name: String, | |
| 8883 | + id: String, | |
| 8884 | + props_json: String, | |
| 8885 | + parent: storage::StorageIdentity, | |
| 8886 | +} | |
| 8887 | + | |
| 8888 | +async fn prepare_loaded_facet( | |
| 8889 | + loaded: tokio::sync::watch::Receiver<LoaderState>, | |
| 8890 | + start: FacetStart, | |
| 8891 | +) -> Result<(Arc<crate::pool::Slot>, String), String> { | |
| 8892 | + let slot = loaded_worker_slot(loaded).await?; | |
| 8893 | + let scope = facet_scope( | |
| 8894 | + &start.class_name, | |
| 8895 | + &start.parent_scope, | |
| 8896 | + &start.owner, | |
| 8897 | + &start.name, | |
| 8898 | + ); | |
| 8899 | + slot.turn(|worker| { | |
| 8900 | + worker.own_embedded_cell( | |
| 8901 | + &scope, | |
| 8902 | + &start.parent, | |
| 8903 | + &start.name, | |
| 8904 | + &start.id, | |
| 8905 | + &start.props_json, | |
| 8906 | + ) | |
| 8907 | + }) | |
| 8908 | + .await | |
| 8909 | + .map_err(|error| format!("worker loader facet: {error}"))?; | |
| 8910 | + Ok((slot, scope)) | |
| 8911 | +} | |
| 8912 | + | |
| 8913 | +fn op_facet_rpc( | |
| 8914 | + scope: &mut v8::PinScope, | |
| 8915 | + args: v8::FunctionCallbackArguments, | |
| 8916 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8917 | +) { | |
| 8918 | + let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 8919 | + let class_name = args.get(1).to_rust_string_lossy(scope); | |
| 8920 | + let parent_scope = args.get(2).to_rust_string_lossy(scope); | |
| 8921 | + let owner = args.get(3).to_rust_string_lossy(scope); | |
| 8922 | + let name = args.get(4).to_rust_string_lossy(scope); | |
| 8923 | + let facet_id = args.get(5).to_rust_string_lossy(scope); | |
| 8924 | + let props_json = args.get(6).to_rust_string_lossy(scope); | |
| 8925 | + let method = args.get(7).to_rust_string_lossy(scope); | |
| 8926 | + let call_args = view_bytes(args.get(8)).unwrap_or_default(); | |
| 8927 | + let Some(parent) = storage::storage_identity(&parent_scope) else { | |
| 8928 | + return loader_throw( | |
| 8929 | + scope, | |
| 8930 | + "facets are available only inside a Durable Object event", | |
| 8931 | + ); | |
| 8932 | + }; | |
| 8933 | + let loaded = loader_registry() | |
| 8934 | + .lock() | |
| 8935 | + .unwrap() | |
| 8936 | + .get(&loader) | |
| 8937 | + .map(|entry| entry.state.clone()); | |
| 8938 | + let trace = current_trace_context(scope); | |
| 8939 | + let async_id = asyncrt::enqueue(async move { | |
| 8940 | + let loaded = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 8941 | + let (slot, facet_scope) = prepare_loaded_facet( | |
| 8942 | + loaded, | |
| 8943 | + FacetStart { | |
| 8944 | + class_name, | |
| 8945 | + parent_scope, | |
| 8946 | + owner, | |
| 8947 | + name, | |
| 8948 | + id: facet_id, | |
| 8949 | + props_json, | |
| 8950 | + parent, | |
| 8951 | + }, | |
| 8952 | + ) | |
| 8953 | + .await?; | |
| 8954 | + let (reply, receive) = tokio::sync::oneshot::channel(); | |
| 8955 | + let job = CellJob::Rpc { | |
| 8956 | + request_id: None, | |
| 8957 | + scope: facet_scope, | |
| 8958 | + name: None, | |
| 8959 | + method, | |
| 8960 | + args: RpcData::V8(call_args.into()), | |
| 8961 | + reply, | |
| 8962 | + }; | |
| 8963 | + let driving = tokio::spawn(crate::runtime::drive_cell( | |
| 8964 | + slot.affiliate(), | |
| 8965 | + job, | |
| 8966 | + None, | |
| 8967 | + trace, | |
| 8968 | + )); | |
| 8969 | + match receive.await { | |
| 8970 | + Ok(Ok(outcome)) => match outcome.data { | |
| 8971 | + RpcData::V8(bytes) => Ok(Vec::<u8>::from(bytes)), | |
| 8972 | + RpcData::Json(_) => Err("facet RPC answered JSON".to_string()), | |
| 8973 | + }, | |
| 8974 | + Ok(Err(error)) => Err(format!("{error}")), | |
| 8975 | + Err(_) => match driving.await { | |
| 8976 | + Err(error) => Err(format!("facet RPC task died: {error}")), | |
| 8977 | + Ok(()) => Err("facet dropped RPC result".to_string()), | |
| 8978 | + }, | |
| 8979 | + } | |
| 8980 | + }); | |
| 8981 | + rv.set(promise_for(scope, async_id)); | |
| 8982 | +} | |
| 8983 | + | |
| 8984 | +fn op_facet_fetch( | |
| 8985 | + scope: &mut v8::PinScope, | |
| 8986 | + args: v8::FunctionCallbackArguments, | |
| 8987 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 8988 | +) { | |
| 8989 | + let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 8990 | + let class_name = args.get(1).to_rust_string_lossy(scope); | |
| 8991 | + let parent_scope = args.get(2).to_rust_string_lossy(scope); | |
| 8992 | + let owner = args.get(3).to_rust_string_lossy(scope); | |
| 8993 | + let name = args.get(4).to_rust_string_lossy(scope); | |
| 8994 | + let facet_id = args.get(5).to_rust_string_lossy(scope); | |
| 8995 | + let props_json = args.get(6).to_rust_string_lossy(scope); | |
| 8996 | + let url = args.get(7).to_rust_string_lossy(scope); | |
| 8997 | + let method = args.get(8).to_rust_string_lossy(scope); | |
| 8998 | + let stream_arg = args.get(11); | |
| 8999 | + let body = if stream_arg.is_number() { | |
| 9000 | + RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64) | |
| 9001 | + } else { | |
| 9002 | + let Some(bytes) = view_bytes(args.get(9)) else { | |
| 9003 | + return loader_throw(scope, "facet: the request body is not a typed array"); | |
| 9004 | + }; | |
| 9005 | + RequestBody::Bytes(bytes.into()) | |
| 9006 | + }; | |
| 9007 | + let headers: Vec<(String, String)> = | |
| 9008 | + match serde_json::from_str(&args.get(10).to_rust_string_lossy(scope)) { | |
| 9009 | + Ok(headers) => headers, | |
| 9010 | + Err(error) => return loader_throw(scope, &format!("facet headers: {error}")), | |
| 9011 | + }; | |
| 9012 | + let mut body_guard = match body.stream_id() { | |
| 9013 | + Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 9014 | + Some(guard) => guard, | |
| 9015 | + None => return loader_throw(scope, "facet: the body stream is not owned"), | |
| 9016 | + }, | |
| 9017 | + None => RequestBodyGuard::of(&body), | |
| 9018 | + }; | |
| 9019 | + let Some(parent) = storage::storage_identity(&parent_scope) else { | |
| 9020 | + return loader_throw( | |
| 9021 | + scope, | |
| 9022 | + "facets are available only inside a Durable Object event", | |
| 9023 | + ); | |
| 9024 | + }; | |
| 9025 | + let loaded = loader_registry() | |
| 9026 | + .lock() | |
| 9027 | + .unwrap() | |
| 9028 | + .get(&loader) | |
| 9029 | + .map(|entry| entry.state.clone()); | |
| 9030 | + let trace = current_trace_context(scope); | |
| 9031 | + let stream_service = http_stream_service(); | |
| 9032 | + let async_id = asyncrt::enqueue(async move { | |
| 9033 | + let loaded = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 9034 | + let (slot, facet_scope) = prepare_loaded_facet( | |
| 9035 | + loaded, | |
| 9036 | + FacetStart { | |
| 9037 | + class_name, | |
| 9038 | + parent_scope, | |
| 9039 | + owner, | |
| 9040 | + name, | |
| 9041 | + id: facet_id, | |
| 9042 | + props_json, | |
| 9043 | + parent, | |
| 9044 | + }, | |
| 9045 | + ) | |
| 9046 | + .await?; | |
| 9047 | + let (reply, receive) = tokio::sync::oneshot::channel(); | |
| 9048 | + let job = CellJob::Fetch { | |
| 9049 | + request_id: None, | |
| 9050 | + scope: facet_scope, | |
| 9051 | + name: None, | |
| 9052 | + url, | |
| 9053 | + method, | |
| 9054 | + body, | |
| 9055 | + headers, | |
| 9056 | + reply, | |
| 9057 | + order: None, | |
| 9058 | + }; | |
| 9059 | + let driving = tokio::spawn(crate::runtime::drive_cell( | |
| 9060 | + slot.affiliate(), | |
| 9061 | + job, | |
| 9062 | + None, | |
| 9063 | + trace, | |
| 9064 | + )); | |
| 9065 | + match receive.await { | |
| 9066 | + Ok(Ok(response)) => { | |
| 9067 | + body_guard.disarm(); | |
| 9068 | + encode_http_response(response, false, &stream_service) | |
| 9069 | + } | |
| 9070 | + Ok(Err(error)) => Err(format!("{error}")), | |
| 9071 | + Err(_) => match driving.await { | |
| 9072 | + Err(error) => Err(format!("facet fetch task died: {error}")), | |
| 9073 | + Ok(()) => Err("facet dropped fetch response".to_string()), | |
| 9074 | + }, | |
| 9075 | + } | |
| 9076 | + }); | |
| 9077 | + rv.set(promise_for(scope, async_id)); | |
| 9078 | +} | |
| 9079 | + | |
| 9080 | +fn op_facet_abort( | |
| 9081 | + scope: &mut v8::PinScope, | |
| 9082 | + args: v8::FunctionCallbackArguments, | |
| 9083 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9084 | +) { | |
| 9085 | + let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 9086 | + let class_name = args.get(1).to_rust_string_lossy(scope); | |
| 9087 | + let parent_scope = args.get(2).to_rust_string_lossy(scope); | |
| 9088 | + let owner = args.get(3).to_rust_string_lossy(scope); | |
| 9089 | + let name = args.get(4).to_rust_string_lossy(scope); | |
| 9090 | + let loaded = loader_registry() | |
| 9091 | + .lock() | |
| 9092 | + .unwrap() | |
| 9093 | + .get(&loader) | |
| 9094 | + .map(|entry| entry.state.clone()); | |
| 9095 | + let facet_scope = facet_scope(&class_name, &parent_scope, &owner, &name); | |
| 9096 | + let async_id = asyncrt::enqueue(async move { | |
| 9097 | + let loaded = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 9098 | + let slot = loaded_worker_slot(loaded).await?; | |
| 9099 | + slot.turn(|worker| worker.own_cell(&facet_scope, None)) | |
| 9100 | + .await | |
| 9101 | + .map_err(|error| format!("abort facet: {error}"))?; | |
| 9102 | + Ok(Vec::new()) | |
| 9103 | + }); | |
| 9104 | + rv.set(promise_for(scope, async_id)); | |
| 9105 | +} | |
| 9106 | + | |
| 9107 | +fn op_facet_delete( | |
| 9108 | + scope: &mut v8::PinScope, | |
| 9109 | + args: v8::FunctionCallbackArguments, | |
| 9110 | + _rv: v8::ReturnValue<v8::Value>, | |
| 9111 | +) { | |
| 9112 | + let parent_scope = args.get(0).to_rust_string_lossy(scope); | |
| 9113 | + let name = args.get(1).to_rust_string_lossy(scope); | |
| 9114 | + let Some(parent) = storage::storage_identity(&parent_scope) else { | |
| 9115 | + return loader_throw( | |
| 9116 | + scope, | |
| 9117 | + "facets are available only inside a Durable Object event", | |
| 9118 | + ); | |
| 9119 | + }; | |
| 9120 | + if let Err(error) = storage::delete_embedded(&parent, &name) { | |
| 9121 | + loader_throw(scope, &format!("delete facet storage: {error}")); | |
| 9122 | + } | |
| 9123 | +} | |
| 9124 | + | |
| 9125 | +/// `__loader_drop(id)` — evict a loaded worker. Called from a | |
| 9126 | +/// FinalizationRegistry when its stub is GC'd. Removing the registry entry | |
| 9127 | +/// drops the isolate after any calls that already cloned its load state end. | |
| 9128 | +fn op_loader_drop( | |
| 9129 | + scope: &mut v8::PinScope, | |
| 9130 | + args: v8::FunctionCallbackArguments, | |
| 9131 | + _rv: v8::ReturnValue<v8::Value>, | |
| 9132 | +) { | |
| 9133 | + let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 9134 | + if let Some(entry) = loader_registry().lock().unwrap().remove(&id) { | |
| 9135 | + // This op runs while the parent isolate is entered. The load state can | |
| 9136 | + // own the loaded isolate, and V8 forbids dropping one isolate while a | |
| 9137 | + // different isolate is entered on the same thread. Hand the final | |
| 9138 | + // reference to the host scheduler so destruction happens after this | |
| 9139 | + // turn has left V8. | |
| 9140 | + asyncrt::op_handle().spawn(async move { drop(entry.state) }); | |
| 9141 | + } | |
| 9142 | +} | |
| 9143 | + | |
| 9144 | +fn op_do_call( | |
| 9145 | + scope: &mut v8::PinScope, | |
| 9146 | + args: v8::FunctionCallbackArguments, | |
| 9147 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9148 | +) { | |
| 9149 | + op_do_call_impl(scope, args, &mut rv, false); | |
| 9150 | +} | |
| 9151 | + | |
| 9152 | +fn op_do_call_cancellable( | |
| 9153 | + scope: &mut v8::PinScope, | |
| 9154 | + args: v8::FunctionCallbackArguments, | |
| 9155 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9156 | +) { | |
| 9157 | + op_do_call_impl(scope, args, &mut rv, true); | |
| 9158 | +} | |
| 9159 | + | |
| 9160 | +fn op_do_call_impl( | |
| 9161 | + scope: &mut v8::PinScope, | |
| 9162 | + args: v8::FunctionCallbackArguments, | |
| 9163 | + rv: &mut v8::ReturnValue<v8::Value>, | |
| 9164 | + cancellable: bool, | |
| 9165 | +) { | |
| 9166 | + let cell = args.get(0).to_rust_string_lossy(scope); | |
| 9167 | + let name_value = args.get(1); | |
| 9168 | + let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope)); | |
| 9169 | + let url = args.get(2).to_rust_string_lossy(scope); | |
| 9170 | + let method = args.get(3).to_rust_string_lossy(scope); | |
| 9171 | + // arg 4 is the held bytes; arg 6, when a number, is a host stream id for a | |
| 9172 | + // body that must not be collected here (a large or unbounded upload). The | |
| 9173 | + // owning cell reads that stream directly; only a cross-node hop collects it. | |
| 9174 | + let stream_arg = args.get(6); | |
| 9175 | + let body = if stream_arg.is_number() { | |
| 9176 | + RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64) | |
| 9177 | + } else { | |
| 9178 | + let Some(bytes) = view_bytes(args.get(4)) else { | |
| 9179 | + return loader_throw( | |
| 9180 | + scope, | |
| 9181 | + "durable object: the request body is not a typed array", | |
| 9182 | + ); | |
| 9183 | + }; | |
| 9184 | + RequestBody::Bytes(bytes.into()) | |
| 9185 | + }; | |
| 9186 | + let headers: Vec<(String, String)> = | |
| 9187 | + match serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)) { | |
| 9188 | + Ok(headers) => headers, | |
| 9189 | + Err(error) => { | |
| 9190 | + return loader_throw( | |
| 9191 | + scope, | |
| 9192 | + &format!( | |
| 9193 | + "durable object: the request headers are not a name/value list: {error}" | |
| 9194 | + ), | |
| 9195 | + ) | |
| 9196 | + } | |
| 9197 | + }; | |
| 9198 | + let body_guard = match body.stream_id() { | |
| 9199 | + Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 9200 | + Some(guard) => guard, | |
| 9201 | + None => return loader_throw(scope, "durable object: the body stream is not owned"), | |
| 9202 | + }, | |
| 9203 | + None => RequestBodyGuard::of(&body), | |
| 9204 | + }; | |
| 9205 | + let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 9206 | + // Taken here and nowhere later: this is the last point that still runs | |
| 9207 | + // in the order the script made the calls. | |
| 9208 | + let order = Some(enter_call_order(current_context(), &cell)); | |
| 9209 | + // Every host op needs an internal cancellation channel. A caller without | |
| 9210 | + // an AbortSignal cannot cancel from JavaScript, but its enclosing Worker | |
| 9211 | + // can still disappear and drop this op before routing completes. | |
| 9212 | + let request_id = next_do_request_id(); | |
| 9213 | + let (cancel_sender, cancel) = tokio::sync::oneshot::channel(); | |
| 9214 | + do_call_cancels() | |
| 9215 | + .lock() | |
| 9216 | + .unwrap() | |
| 9217 | + .insert(request_id, cancel_sender); | |
| 9218 | + let mut cancel_guard = DoCallCancelGuard::new(request_id); | |
| 9219 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::CellRpc); | |
| 9220 | + let request = DoCallReq { | |
| 9221 | + request_id: Some(request_id), | |
| 9222 | + cancel: Some(cancel), | |
| 9223 | + deliver_abort_to_handler: cancellable, | |
| 9224 | + scope: cell, | |
| 9225 | + name, | |
| 9226 | + url, | |
| 9227 | + method, | |
| 9228 | + body, | |
| 9229 | + body_guard, | |
| 9230 | + headers, | |
| 9231 | + reply: tx, | |
| 9232 | + order, | |
| 9233 | + parent: current_trace_context(scope), | |
| 9234 | + }; | |
| 9235 | + let stream_service = http_stream_service(); | |
| 9236 | + let id = asyncrt::enqueue(async move { | |
| 9237 | + gated_channel_send(gate, &DO_CALL_TX, request, "no proxy channel").await?; | |
| 9238 | + let result = match rx.await { | |
| 9239 | + Ok(Ok(response)) => encode_http_response(response, true, &stream_service), | |
| 9240 | + Ok(Err(e)) => Err(format!("{e}")), | |
| 9241 | + Err(e) => Err(format!("proxy dropped: {e}")), | |
| 9242 | + }; | |
| 9243 | + cancel_guard.disarm(); | |
| 9244 | + result | |
| 9245 | + }); | |
| 9246 | + let p = promise_for(scope, id); | |
| 9247 | + if cancellable { | |
| 9248 | + attach_cancel_id(scope, p, request_id); | |
| 9249 | + } | |
| 9250 | + rv.set(p); | |
| 9251 | +} | |
| 9252 | + | |
| 9253 | +fn op_do_call_cancel( | |
| 9254 | + scope: &mut v8::PinScope, | |
| 9255 | + args: v8::FunctionCallbackArguments, | |
| 9256 | + _rv: v8::ReturnValue<v8::Value>, | |
| 9257 | +) { | |
| 9258 | + let request_id = args.get(0).to_rust_string_lossy(scope); | |
| 9259 | + let Some(request_id) = parse_request_id(&request_id) else { | |
| 9260 | + return; | |
| 9261 | + }; | |
| 9262 | + if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) { | |
| 9263 | + let _ = cancel.send(()); | |
| 9264 | + } | |
| 9265 | +} | |
| 9266 | + | |
| 9267 | +/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>; | |
| 9268 | +/// arguments and result are V8 structured-clone bytes. | |
| 9269 | +fn op_rpc_call( | |
| 9270 | + scope: &mut v8::PinScope, | |
| 9271 | + args: v8::FunctionCallbackArguments, | |
| 9272 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9273 | +) { | |
| 9274 | + let cell = args.get(0).to_rust_string_lossy(scope); | |
| 9275 | + let name_value = args.get(1); | |
| 9276 | + let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope)); | |
| 9277 | + let method = args.get(2).to_rust_string_lossy(scope); | |
| 9278 | + let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default().into()); | |
| 9279 | + let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 9280 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::CellRpc); | |
| 9281 | + let request = RpcCallReq { | |
| 9282 | + scope: cell, | |
| 9283 | + name, | |
| 9284 | + method, | |
| 9285 | + args, | |
| 9286 | + reply: tx, | |
| 9287 | + }; | |
| 9288 | + let id = asyncrt::enqueue(async move { | |
| 9289 | + gated_channel_send(gate, &RPC_CALL_TX, request, "no RPC channel").await?; | |
| 9290 | + match rx.await { | |
| 9291 | + Ok(Ok(RpcData::V8(bytes))) => Ok(Vec::<u8>::from(bytes)), | |
| 9292 | + Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()), | |
| 9293 | + Ok(Err(e)) => Err(format!("{e}")), | |
| 9294 | + Err(e) => Err(format!("RPC proxy dropped: {e}")), | |
| 9295 | + } | |
| 9296 | + }); | |
| 9297 | + let p = promise_for(scope, id); | |
| 9298 | + rv.set(p); | |
| 9299 | +} | |
| 9300 | + | |
| 9301 | +/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON | |
| 9302 | +/// `{status, body, headers}` string. | |
| 9303 | +fn op_fetch( | |
| 9304 | + scope: &mut v8::PinScope, | |
| 9305 | + args: v8::FunctionCallbackArguments, | |
| 9306 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9307 | +) { | |
| 9308 | + // A loaded worker with globalOutbound: null has no ambient egress: it must | |
| 9309 | + // reach the world through `env` capabilities. Message matches workerd. | |
| 9310 | + if actor_runtime_state(scope).egress == EgressPolicy::Deny { | |
| 9311 | + return loader_throw( | |
| 9312 | + scope, | |
| 9313 | + "This worker is not permitted to access the internet via global \ | |
| 9314 | + functions like fetch(). It must use capabilities (such as \ | |
| 9315 | + bindings in 'env') to talk to the outside world.", | |
| 9316 | + ); | |
| 9317 | + } | |
| 9318 | + let method = args.get(0).to_rust_string_lossy(scope); | |
| 9319 | + let url = args.get(1).to_rust_string_lossy(scope); | |
| 9320 | + // A body is a typed array, as it is for `__svc_call`, `__do_call` and | |
| 9321 | + // `__loader_fetch`. `None` and an empty body are different requests — one | |
| 9322 | + // carries no `Content-Length` — so the absent case stays distinct. | |
| 9323 | + let body_arg = args.get(2); | |
| 9324 | + let stream_arg = args.get(5); | |
| 9325 | + let body: Option<RequestBody> = if body_arg.is_undefined() || body_arg.is_null() { | |
| 9326 | + None | |
| 9327 | + } else if stream_arg.is_number() { | |
| 9328 | + Some(RequestBody::Stream( | |
| 9329 | + stream_arg.number_value(scope).unwrap_or(0.0) as u64, | |
| 9330 | + )) | |
| 9331 | + } else { | |
| 9332 | + match view_bytes(body_arg) { | |
| 9333 | + Some(bytes) => Some(RequestBody::Bytes(bytes.into())), | |
| 9334 | + // Answering an unreadable argument with `None` sent the request | |
| 9335 | + // with no body at all: the peer saw something the Worker never | |
| 9336 | + // asked for, and nothing threw and nothing was logged. | |
| 9337 | + None => return loader_throw(scope, "fetch: the request body is not a typed array"), | |
| 9338 | + } | |
| 9339 | + }; | |
| 9340 | + let raw_headers = args.get(3).to_rust_string_lossy(scope); | |
| 9341 | + let mut headers: Vec<(String, String)> = match serde_json::from_str(&raw_headers) { | |
| 9342 | + Ok(headers) => headers, | |
| 9343 | + // Same failure as the body: dropping the headers silently sent an | |
| 9344 | + // unauthenticated, unrouted request in place of the real one. | |
| 9345 | + Err(error) => { | |
| 9346 | + return loader_throw( | |
| 9347 | + scope, | |
| 9348 | + &format!("fetch: the request headers are not a name/value list: {error}"), | |
| 9349 | + ) | |
| 9350 | + } | |
| 9351 | + }; | |
| 9352 | + let redirect = args.get(4).to_rust_string_lossy(scope); | |
| 9353 | + // The harness passes `true` only when the caller supplied an AbortSignal. | |
| 9354 | + // An absent argument is `false`, so a direct caller gets the uncancellable | |
| 9355 | + // request it asked for. | |
| 9356 | + let cancellable = args.get(6).boolean_value(scope); | |
| 9357 | + let mut body_guard = match body.as_ref().and_then(RequestBody::stream_id) { | |
| 9358 | + Some(stream_id) => match current_context().transfer_body_stream(stream_id) { | |
| 9359 | + Some(guard) => guard, | |
| 9360 | + None => return loader_throw(scope, "fetch: the body stream is not owned"), | |
| 9361 | + }, | |
| 9362 | + None => RequestBodyGuard(None), | |
| 9363 | + }; | |
| 9364 | + // Request validates this value in the harness, but the native op is a | |
| 9365 | + // separate trust boundary. Keep this match exhaustive so a future direct | |
| 9366 | + // caller cannot turn an unknown mode into redirect-following behavior. | |
| 9367 | + let client = match redirect.as_str() { | |
| 9368 | + "follow" => HTTP.with(|client| client.clone()), | |
| 9369 | + "manual" => HTTP_MANUAL.with(|client| client.clone()), | |
| 9370 | + "error" => HTTP_ERROR.with(|client| client.clone()), | |
| 9371 | + other => return loader_throw(scope, &format!("fetch: unknown redirect mode {other}")), | |
| 9372 | + }; | |
| 9373 | + // The creating context, read here while JS is still running: the op | |
| 9374 | + // future resolves on whatever worker polls it, far from any CPED. | |
| 9375 | + let trace = current_trace_context(scope); | |
| 9376 | + // The child's ids are minted before the request leaves so the | |
| 9377 | + // traceparent header carries them: whatever this fetch reaches can | |
| 9378 | + // join the trace celld is part of. | |
| 9379 | + let child = trace.as_ref().map(crate::telemetry::child_context); | |
| 9380 | + if let Some(child) = child.as_ref() { | |
| 9381 | + if !headers | |
| 9382 | + .iter() | |
| 9383 | + .any(|(name, _)| name.eq_ignore_ascii_case("traceparent")) | |
| 9384 | + { | |
| 9385 | + headers.push(("traceparent".into(), crate::telemetry::traceparent(child))); | |
| 9386 | + } | |
| 9387 | + } | |
| 9388 | + let recording = trace.and_then(crate::telemetry::TraceContext::recording_ids); | |
| 9389 | + let child_recording = child.and_then(crate::telemetry::TraceContext::recording_ids); | |
| 9390 | + let span_url = recording.map(|_| url.clone()); | |
| 9391 | + // Whatever this request can reveal must be durable before it leaves: a | |
| 9392 | + // third party that has acted on a write celld then loses cannot be told to | |
| 9393 | + // un-act. That covers a write this handler made and a value it only read, | |
| 9394 | + // because the third party cannot tell the two apart. | |
| 9395 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Fetch); | |
| 9396 | + // Shares the cancel registry, the id encoding and the `__do_call_cancel` | |
| 9397 | + // op that a Durable Object call and a service binding call already use. | |
| 9398 | + // Only a caller that supplied an AbortSignal registers: without one there | |
| 9399 | + // is nothing that can cancel, and the op then costs no registry entry. | |
| 9400 | + let (request_id, cancel, cancel_guard) = if cancellable { | |
| 9401 | + let request_id = next_do_request_id(); | |
| 9402 | + let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel(); | |
| 9403 | + do_call_cancels() | |
| 9404 | + .lock() | |
| 9405 | + .unwrap() | |
| 9406 | + .insert(request_id, cancel_sender); | |
| 9407 | + ( | |
| 9408 | + Some(request_id), | |
| 9409 | + Some(cancel_receiver), | |
| 9410 | + Some(DoCallCancelGuard::new(request_id)), | |
| 9411 | + ) | |
| 9412 | + } else { | |
| 9413 | + (None, None, None) | |
| 9414 | + }; | |
| 9415 | + let stream_service = http_stream_service(); | |
| 9416 | + let id = asyncrt::enqueue(async move { | |
| 9417 | + // Held, not disarmed: this op has several early returns, and the guard | |
| 9418 | + // removes its registry entry on every one of them when it drops. The | |
| 9419 | + // cancel it sends then reaches a receiver this block already consumed, | |
| 9420 | + // which is the same no-op as a disarm. | |
| 9421 | + let _cancel_guard = cancel_guard; | |
| 9422 | + let span_started = recording.map(|_| crate::telemetry::now_unix_us()); | |
| 9423 | + let mut span = recording.zip(child_recording).map(|(parent, child)| { | |
| 9424 | + let mut span = | |
| 9425 | + crate::telemetry::Span::new(child, "fetch", crate::telemetry::KIND_CLIENT); | |
| 9426 | + span.parent_span_id = Some(parent.span_id); | |
| 9427 | + span.parent_remote = Some(false); | |
| 9428 | + span.url = span_url; | |
| 9429 | + span | |
| 9430 | + }); | |
| 9431 | + let mut finish = |ok: bool, status: Option<u16>, error: Option<String>| { | |
| 9432 | + if let Some(mut span) = span.take() { | |
| 9433 | + span.start_unix_us = span_started.unwrap_or_default(); | |
| 9434 | + span.duration_us = crate::telemetry::now_unix_us() - span.start_unix_us; | |
| 9435 | + span.ok = ok; | |
| 9436 | + span.http_status = status; | |
| 9437 | + span.error = error; | |
| 9438 | + crate::telemetry::record(span); | |
| 9439 | + } | |
| 9440 | + }; | |
| 9441 | + await_egress_gate(gate).await.inspect_err(|error| { | |
| 9442 | + finish(false, None, Some(error.clone())); | |
| 9443 | + })?; | |
| 9444 | + let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET); | |
| 9445 | + // a timeout bounds a black-hole host: the future settles (Err) instead | |
| 9446 | + // of parking run_loop forever — the hang the Drop guard can't catch. | |
| 9447 | + let fetch_timeout = crate::env_vars::positive_or("CELLD_FETCH_TIMEOUT_S", 120) | |
| 9448 | + .expect("validated CELLD_FETCH_TIMEOUT_S"); | |
| 9449 | + let mut rb = client | |
| 9450 | + .request(m, &url) | |
| 9451 | + .timeout(std::time::Duration::from_secs(fetch_timeout)); | |
| 9452 | + // reqwest omits Content-Length for an empty Vec, which collapses the | |
| 9453 | + // wire representation of `Some([])` into the representation of | |
| 9454 | + // `None`. Install the zero length here unless the Worker supplied a | |
| 9455 | + // framing header, so the body distinction survives the HTTP client. | |
| 9456 | + let empty_body_needs_length = body | |
| 9457 | + .as_ref() | |
| 9458 | + .is_some_and(|body| matches!(body, RequestBody::Bytes(bytes) if bytes.is_empty())) | |
| 9459 | + && !headers.iter().any(|(name, _)| { | |
| 9460 | + name.eq_ignore_ascii_case("content-length") | |
| 9461 | + || name.eq_ignore_ascii_case("transfer-encoding") | |
| 9462 | + }); | |
| 9463 | + for (name, value) in headers { | |
| 9464 | + rb = rb.header(name, value); | |
| 9465 | + } | |
| 9466 | + if let Some(body) = body { | |
| 9467 | + rb = match body { | |
| 9468 | + RequestBody::Bytes(bytes) => rb.body(bytes), | |
| 9469 | + RequestBody::Stream(stream_id) => match body_guard.take_stream(stream_id) { | |
| 9470 | + Ok(stream) => rb.body(reqwest::Body::wrap_stream(stream)), | |
| 9471 | + Err(error) => { | |
| 9472 | + finish(false, None, Some(error.clone())); | |
| 9473 | + return Err(error); | |
| 9474 | + } | |
| 9475 | + }, | |
| 9476 | + }; | |
| 9477 | + } | |
| 9478 | + if empty_body_needs_length { | |
| 9479 | + rb = rb.header(reqwest::header::CONTENT_LENGTH, 0); | |
| 9480 | + } | |
| 9481 | + // The cancellable window is the request itself: connect, send, and wait | |
| 9482 | + // for the response head. Dropping the send future here closes the | |
| 9483 | + // connection, which is what tells the upstream to stop producing. After | |
| 9484 | + // this point the response body is a registered stream, and | |
| 9485 | + // `__http_stream_cancel` is what ends it. | |
| 9486 | + let sent = match cancel { | |
| 9487 | + Some(cancel) => crate::asyncrt::select_biased! { | |
| 9488 | + "a cancel that is ready wins a tie, so an aborted request never \ | |
| 9489 | + hands back a response and never leaves a body stream nobody reads"; | |
| 9490 | + _ = cancel => None, | |
| 9491 | + result = rb.send() => Some(result), | |
| 9492 | + }, | |
| 9493 | + None => Some(rb.send().await), | |
| 9494 | + }; | |
| 9495 | + let Some(sent) = sent else { | |
| 9496 | + let error = "fetch: the request was aborted".to_string(); | |
| 9497 | + finish(false, None, Some(error.clone())); | |
| 9498 | + return Err(error); | |
| 9499 | + }; | |
| 9500 | + match sent { | |
| 9501 | + Ok(resp) => { | |
| 9502 | + let status = resp.status().as_u16(); | |
| 9503 | + let headers = resp | |
| 9504 | + .headers() | |
| 9505 | + .iter() | |
| 9506 | + .map(|(name, value)| { | |
| 9507 | + ( | |
| 9508 | + name.as_str().to_string(), | |
| 9509 | + value.to_str().map(str::to_owned).unwrap_or_else(|_| { | |
| 9510 | + // Fetch exposes a response header value as a | |
| 9511 | + // byte string. UTF-8 conversion would merge a | |
| 9512 | + // multibyte sequence, so expand only the | |
| 9513 | + // uncommon header that contains a non-ASCII | |
| 9514 | + // byte. | |
| 9515 | + value | |
| 9516 | + .as_bytes() | |
| 9517 | + .iter() | |
| 9518 | + .map(|&byte| char::from(byte)) | |
| 9519 | + .collect::<String>() | |
| 9520 | + }), | |
| 9521 | + ) | |
| 9522 | + }) | |
| 9523 | + .collect::<Vec<_>>(); | |
| 9524 | + let Some(stream_id) = | |
| 9525 | + stream_service.register_source(HttpStreamSource::Response(resp)) | |
| 9526 | + else { | |
| 9527 | + let error = format!("fetch: {HTTP_STREAM_REGISTRATION_CLOSED}"); | |
| 9528 | + finish(false, Some(status), Some(error.clone())); | |
| 9529 | + return Err(error); | |
| 9530 | + }; | |
| 9531 | + finish(true, Some(status), None); | |
| 9532 | + Ok(serde_json::json!({ | |
| 9533 | + "status": status, "streamId": stream_id, "headers": headers, | |
| 9534 | + }) | |
| 9535 | + .to_string()) | |
| 9536 | + } | |
| 9537 | + Err(e) => { | |
| 9538 | + finish(false, None, Some(format!("fetch: {e}"))); | |
| 9539 | + Err(format!("fetch: {e}")) | |
| 9540 | + } | |
| 9541 | + } | |
| 9542 | + }); | |
| 9543 | + let p = promise_for(scope, id); | |
| 9544 | + if let Some(request_id) = request_id { | |
| 9545 | + attach_cancel_id(scope, p, request_id); | |
| 9546 | + } | |
| 9547 | + rv.set(p); | |
| 9548 | +} | |
| 9549 | + | |
| 9550 | +fn op_asset_fetch( | |
| 9551 | + scope: &mut v8::PinScope, | |
| 9552 | + args: v8::FunctionCallbackArguments, | |
| 9553 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9554 | +) { | |
| 9555 | + let script = args.get(0).to_rust_string_lossy(scope); | |
| 9556 | + let method = args.get(1).to_rust_string_lossy(scope); | |
| 9557 | + let url = args.get(2).to_rust_string_lossy(scope); | |
| 9558 | + let headers: Vec<(String, String)> = | |
| 9559 | + match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) { | |
| 9560 | + Ok(headers) => headers, | |
| 9561 | + Err(error) => { | |
| 9562 | + return loader_throw( | |
| 9563 | + scope, | |
| 9564 | + &format!("assets: the request headers are not a name/value list: {error}"), | |
| 9565 | + ) | |
| 9566 | + } | |
| 9567 | + }; | |
| 9568 | + let generation = current_generation(scope); | |
| 9569 | + let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 9570 | + let sent = ASSET_CALL_TX.get().is_some_and(|sender| { | |
| 9571 | + sender | |
| 9572 | + .send(AssetCallReq { | |
| 9573 | + generation, | |
| 9574 | + script, | |
| 9575 | + url, | |
| 9576 | + method, | |
| 9577 | + headers, | |
| 9578 | + reply: tx, | |
| 9579 | + }) | |
| 9580 | + .is_ok() | |
| 9581 | + }); | |
| 9582 | + let stream_service = http_stream_service(); | |
| 9583 | + let id = asyncrt::enqueue(async move { | |
| 9584 | + if !sent { | |
| 9585 | + return Err("no asset resolver channel".to_string()); | |
| 9586 | + } | |
| 9587 | + match rx.await { | |
| 9588 | + Ok(Ok(response)) => encode_http_response(response, false, &stream_service), | |
| 9589 | + Ok(Err(error)) => Err(format!("asset fetch: {error}")), | |
| 9590 | + Err(error) => Err(format!("asset resolver dropped: {error}")), | |
| 9591 | + } | |
| 9592 | + }); | |
| 9593 | + rv.set(promise_for(scope, id)); | |
| 9594 | +} | |
| 9595 | + | |
| 9596 | +/// Take exclusive ownership of a registered request source. | |
| 9597 | +/// | |
| 9598 | +/// The returned stream removes the registry hop, so its eventual consumer | |
| 9599 | +/// supplies the backpressure and dropping that consumer cancels the source. | |
| 9600 | +pub fn take_body_stream(stream_id: u64) -> Result<HttpChunkStream, String> { | |
| 9601 | + http_stream_service() | |
| 9602 | + .checkout_transfer(stream_id, None) | |
| 9603 | + .map(|source| Box::pin(source) as HttpChunkStream) | |
| 9604 | +} | |
| 9605 | + | |
| 9606 | +async fn next_http_stream_chunk(source: &mut HttpStreamSource) -> Result<Option<Vec<u8>>, String> { | |
| 9607 | + match source { | |
| 9608 | + HttpStreamSource::Response(response) => response | |
| 9609 | + .chunk() | |
| 9610 | + .await | |
| 9611 | + .map(|chunk| chunk.map(|bytes| bytes.to_vec())) | |
| 9612 | + .map_err(|error| format!("response stream: {error}")), | |
| 9613 | + HttpStreamSource::Receiver(receiver) => match receiver.recv().await { | |
| 9614 | + Some(Ok(bytes)) => Ok(Some(bytes)), | |
| 9615 | + Some(Err(error)) => Err(error), | |
| 9616 | + None => Ok(None), | |
| 9617 | + }, | |
| 9618 | + HttpStreamSource::Stream(stream) => stream.next().await.transpose(), | |
| 9619 | + } | |
| 9620 | +} | |
| 9621 | + | |
| 9622 | +fn settle_http_stream_read( | |
| 9623 | + mut lease: HttpSourceLease, | |
| 9624 | + source: HttpStreamSource, | |
| 9625 | + next: Option<Result<Option<Vec<u8>>, String>>, | |
| 9626 | +) -> Result<Option<Vec<u8>>, String> { | |
| 9627 | + lease.settled = true; | |
| 9628 | + let service = lease.service.clone(); | |
| 9629 | + let result = next.unwrap_or_else(|| { | |
| 9630 | + HttpStreamService::termination_result(lease.stream_id, lease.termination.reason()) | |
| 9631 | + }); | |
| 9632 | + service.complete_pull(&lease, source, result) | |
| 9633 | +} | |
| 9634 | + | |
| 9635 | +/// Build the future used by the JavaScript read op. | |
| 9636 | +/// | |
| 9637 | +/// Checkout stays synchronous because the op reserves the source before it | |
| 9638 | +/// enqueues asynchronous work. Internal tests call this constructor so they | |
| 9639 | +/// exercise the same checkout and completion transitions as the op. | |
| 9640 | +fn http_stream_read( | |
| 9641 | + service: Arc<HttpStreamService>, | |
| 9642 | + stream_id: u64, | |
| 9643 | +) -> impl std::future::Future<Output = Result<Option<Vec<u8>>, String>> + Send + 'static { | |
| 9644 | + let checkout = service.checkout_source(stream_id); | |
| 9645 | + async move { | |
| 9646 | + let (lease, source) = checkout?; | |
| 9647 | + let mut pull = HttpPull { lease, source }; | |
| 9648 | + let termination = pull.lease.termination.clone(); | |
| 9649 | + let next = crate::asyncrt::select! { | |
| 9650 | + result = next_http_stream_chunk(&mut pull.source) => Some(result), | |
| 9651 | + _ = futures_util::future::poll_fn(|context| termination.poll_reason(context)) => None, | |
| 9652 | + }; | |
| 9653 | + let HttpPull { lease, source } = pull; | |
| 9654 | + settle_http_stream_read(lease, source, next) | |
| 9655 | + } | |
| 9656 | +} | |
| 9657 | + | |
| 9658 | +#[cfg(all(test, celld_internal_tests))] | |
| 9659 | +fn http_stream_read_source_first_for_test( | |
| 9660 | + service: Arc<HttpStreamService>, | |
| 9661 | + stream_id: u64, | |
| 9662 | +) -> impl std::future::Future<Output = Result<Option<Vec<u8>>, String>> + Send + 'static { | |
| 9663 | + let checkout = service.checkout_source(stream_id); | |
| 9664 | + async move { | |
| 9665 | + let (lease, source) = checkout?; | |
| 9666 | + let mut pull = HttpPull { lease, source }; | |
| 9667 | + let termination = pull.lease.termination.clone(); | |
| 9668 | + let next = crate::asyncrt::select_biased! { | |
| 9669 | + "the source-first test probe makes a ready source win a termination tie"; | |
| 9670 | + result = next_http_stream_chunk(&mut pull.source) => Some(result), | |
| 9671 | + _ = futures_util::future::poll_fn(|context| termination.poll_reason(context)) => None, | |
| 9672 | + }; | |
| 9673 | + let HttpPull { lease, source } = pull; | |
| 9674 | + settle_http_stream_read(lease, source, next) | |
| 9675 | + } | |
| 9676 | +} | |
| 9677 | + | |
| 9678 | +async fn response_stream_write( | |
| 9679 | + service: Arc<HttpStreamService>, | |
| 9680 | + stream_id: u64, | |
| 9681 | + bytes: Option<Vec<u8>>, | |
| 9682 | +) -> Result<(), String> { | |
| 9683 | + let Some(bytes) = bytes else { | |
| 9684 | + return Err("response stream chunks must be ArrayBuffer views".into()); | |
| 9685 | + }; | |
| 9686 | + // Acquire on the first poll. Merely constructing and dropping this | |
| 9687 | + // future cannot read the Domain clock or create transient activity. | |
| 9688 | + let activity = service | |
| 9689 | + .begin_activity(stream_id, HttpStreamActivityKind::Write) | |
| 9690 | + .map_err(|error| error.write_message().to_string())?; | |
| 9691 | + if activity.writer.send(Ok(bytes)).await.is_err() { | |
| 9692 | + activity.lease.cancel_pair(); | |
| 9693 | + return Err(RESPONSE_STREAM_CONSUMER_CANCELED.into()); | |
| 9694 | + } | |
| 9695 | + activity.lease.succeed(false); | |
| 9696 | + Ok(()) | |
| 9697 | +} | |
| 9698 | + | |
| 9699 | +async fn response_stream_close( | |
| 9700 | + service: Arc<HttpStreamService>, | |
| 9701 | + stream_id: u64, | |
| 9702 | + error: String, | |
| 9703 | +) -> Result<(), String> { | |
| 9704 | + // Missing and expired writers preserve the producer harness's | |
| 9705 | + // idempotent close contract. A live close reservation is different: a | |
| 9706 | + // second terminal operation must not race the first one. | |
| 9707 | + let activity = match service.begin_activity(stream_id, HttpStreamActivityKind::Close) { | |
| 9708 | + Ok(activity) => activity, | |
| 9709 | + Err(HttpStreamActivityError::Closed) => return Err(HTTP_STREAM_REGISTRATION_CLOSED.into()), | |
| 9710 | + Err(HttpStreamActivityError::Gone) => return Ok(()), | |
| 9711 | + Err(HttpStreamActivityError::Closing) => { | |
| 9712 | + return Err(RESPONSE_STREAM_CLOSE_IN_PROGRESS.into()) | |
| 9713 | + } | |
| 9714 | + }; | |
| 9715 | + if error.is_empty() { | |
| 9716 | + let _ = activity.finished.send(true); | |
| 9717 | + } else { | |
| 9718 | + if activity.writer.send(Err(error)).await.is_err() { | |
| 9719 | + activity.lease.cancel_pair(); | |
| 9720 | + return Ok(()); | |
| 9721 | + } | |
| 9722 | + // A cancelled backpressured close must leave the producer watch | |
| 9723 | + // open. Publish completion only after the terminal item is queued. | |
| 9724 | + let _ = activity.finished.send(true); | |
| 9725 | + } | |
| 9726 | + activity.lease.succeed(true); | |
| 9727 | + Ok(()) | |
| 9728 | +} | |
| 9729 | + | |
| 9730 | +/// Move a host response source into a directly-polled stream. No pump task is | |
| 9731 | +/// needed: the eventual HTTP or JS consumer supplies the backpressure. | |
| 9732 | +fn http_chunk_stream(source: HttpStreamSource) -> HttpChunkStream { | |
| 9733 | + match source { | |
| 9734 | + HttpStreamSource::Response(response) => Box::pin(response.bytes_stream().map(|chunk| { | |
| 9735 | + chunk | |
| 9736 | + .map(|bytes| bytes.to_vec()) | |
| 9737 | + .map_err(|error| format!("response stream: {error}")) | |
| 9738 | + })), | |
| 9739 | + HttpStreamSource::Receiver(receiver) => { | |
| 9740 | + Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver)) | |
| 9741 | + } | |
| 9742 | + HttpStreamSource::Stream(stream) => stream, | |
| 9743 | + } | |
| 9744 | +} | |
| 9745 | + | |
| 9746 | +/// Host-native tee for an outbound response. Both branches are represented by | |
| 9747 | +/// stream IDs, so one can be returned through Axum while JS independently | |
| 9748 | +/// scans the other for observability or usage accounting. | |
| 9749 | +type HttpTeePump = Pin<Box<dyn std::future::Future<Output = ()> + Send>>; | |
| 9750 | + | |
| 9751 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 9752 | +enum HttpTeeSendOutcome { | |
| 9753 | + Sent, | |
| 9754 | + BranchClosed, | |
| 9755 | + SourceTerminated, | |
| 9756 | +} | |
| 9757 | + | |
| 9758 | +async fn reserve_http_tee_send( | |
| 9759 | + sender: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 9760 | + item: Result<Vec<u8>, String>, | |
| 9761 | + termination: &HttpStreamTermination, | |
| 9762 | +) -> HttpTeeSendOutcome { | |
| 9763 | + // Sender::send enqueues before it resolves, so a select cannot retract a | |
| 9764 | + // value after cancellation wins. Reserve capacity first, then recheck the | |
| 9765 | + // committed source reason before the permit makes the value visible. | |
| 9766 | + let reservation = asyncrt::select_biased! { | |
| 9767 | + "a capacity reservation wins a tie because termination is rechecked before the send"; | |
| 9768 | + reservation = sender.reserve() => Some(reservation), | |
| 9769 | + _ = futures_util::future::poll_fn(|context| termination.poll_reason(context)) => None, | |
| 9770 | + }; | |
| 9771 | + if termination.reason() != HttpStreamTerminationReason::Live { | |
| 9772 | + return HttpTeeSendOutcome::SourceTerminated; | |
| 9773 | + } | |
| 9774 | + match reservation { | |
| 9775 | + Some(Ok(permit)) => { | |
| 9776 | + permit.send(item); | |
| 9777 | + HttpTeeSendOutcome::Sent | |
| 9778 | + } | |
| 9779 | + Some(Err(_)) => HttpTeeSendOutcome::BranchClosed, | |
| 9780 | + None => HttpTeeSendOutcome::SourceTerminated, | |
| 9781 | + } | |
| 9782 | +} | |
| 9783 | + | |
| 9784 | +async fn fan_out_http_tee_item( | |
| 9785 | + tx1: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 9786 | + tx2: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 9787 | + item: Result<Vec<u8>, String>, | |
| 9788 | + termination: &HttpStreamTermination, | |
| 9789 | +) -> Option<(bool, bool)> { | |
| 9790 | + let first = reserve_http_tee_send(tx1, item.clone(), termination).await; | |
| 9791 | + if first == HttpTeeSendOutcome::SourceTerminated { | |
| 9792 | + return None; | |
| 9793 | + } | |
| 9794 | + let second = reserve_http_tee_send(tx2, item, termination).await; | |
| 9795 | + if second == HttpTeeSendOutcome::SourceTerminated { | |
| 9796 | + return None; | |
| 9797 | + } | |
| 9798 | + Some(( | |
| 9799 | + first == HttpTeeSendOutcome::Sent, | |
| 9800 | + second == HttpTeeSendOutcome::Sent, | |
| 9801 | + )) | |
| 9802 | +} | |
| 9803 | + | |
| 9804 | +async fn both_http_tee_receivers_closed( | |
| 9805 | + tx1: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 9806 | + tx2: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 9807 | +) { | |
| 9808 | + tx1.closed().await; | |
| 9809 | + tx2.closed().await; | |
| 9810 | +} | |
| 9811 | + | |
| 9812 | +fn prepare_http_stream_tee( | |
| 9813 | + service: &Arc<HttpStreamService>, | |
| 9814 | + mut source: HttpTransferredStream, | |
| 9815 | +) -> Result<((u64, u64), HttpTeePump), &'static str> { | |
| 9816 | + let (tx1, rx1) = tokio::sync::mpsc::channel(HTTP_TEE_BRANCH_CAPACITY); | |
| 9817 | + let (tx2, rx2) = tokio::sync::mpsc::channel(HTTP_TEE_BRANCH_CAPACITY); | |
| 9818 | + let Some(id1) = service.register_source(HttpStreamSource::Receiver(rx1)) else { | |
| 9819 | + return Err(HTTP_STREAM_REGISTRATION_CLOSED); | |
| 9820 | + }; | |
| 9821 | + let Some(id2) = service.register_source(HttpStreamSource::Receiver(rx2)) else { | |
| 9822 | + service.cancel_source(id1); | |
| 9823 | + return Err(HTTP_STREAM_REGISTRATION_CLOSED); | |
| 9824 | + }; | |
| 9825 | + let termination = source.termination_handle(); | |
| 9826 | + let pump = Box::pin(async move { | |
| 9827 | + loop { | |
| 9828 | + // A permanently pending source does not wake when its consumers | |
| 9829 | + // disappear. Observe both receivers in the same poll, and prefer | |
| 9830 | + // their committed closure when the source is also ready. | |
| 9831 | + let event = asyncrt::select_biased! { | |
| 9832 | + "closed tee consumers win a tie so the pump cannot read another source item"; | |
| 9833 | + _ = both_http_tee_receivers_closed(&tx1, &tx2) => None, | |
| 9834 | + event = futures_util::future::poll_fn(|context| source.poll_event(context)) => Some(event), | |
| 9835 | + }; | |
| 9836 | + let Some(event) = event else { | |
| 9837 | + break; | |
| 9838 | + }; | |
| 9839 | + match event { | |
| 9840 | + HttpTransferredEvent::Chunk(bytes) => { | |
| 9841 | + let Some((first, second)) = | |
| 9842 | + fan_out_http_tee_item(&tx1, &tx2, Ok(bytes), &termination).await | |
| 9843 | + else { | |
| 9844 | + break; | |
| 9845 | + }; | |
| 9846 | + if !first && !second { | |
| 9847 | + break; | |
| 9848 | + } | |
| 9849 | + } | |
| 9850 | + HttpTransferredEvent::Error(error) => { | |
| 9851 | + if fan_out_http_tee_item(&tx1, &tx2, Err(error), &termination) | |
| 9852 | + .await | |
| 9853 | + .is_some() | |
| 9854 | + { | |
| 9855 | + source.finish(HttpStreamTerminationReason::Finished); | |
| 9856 | + } | |
| 9857 | + break; | |
| 9858 | + } | |
| 9859 | + HttpTransferredEvent::End => { | |
| 9860 | + source.finish(HttpStreamTerminationReason::Finished); | |
| 9861 | + break; | |
| 9862 | + } | |
| 9863 | + HttpTransferredEvent::Terminated(_) => break, | |
| 9864 | + } | |
| 9865 | + } | |
| 9866 | + }); | |
| 9867 | + Ok(((id1, id2), pump)) | |
| 9868 | +} | |
| 9869 | + | |
| 9870 | +fn tee_http_stream( | |
| 9871 | + service: &Arc<HttpStreamService>, | |
| 9872 | + source: HttpTransferredStream, | |
| 9873 | +) -> Result<(u64, u64), &'static str> { | |
| 9874 | + let (ids, pump) = prepare_http_stream_tee(service, source)?; | |
| 9875 | + asyncrt::op_handle().spawn(pump); | |
| 9876 | + Ok(ids) | |
| 9877 | +} | |
| 9878 | + | |
| 9879 | +fn op_http_stream_read( | |
| 9880 | + scope: &mut v8::PinScope, | |
| 9881 | + args: v8::FunctionCallbackArguments, | |
| 9882 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9883 | +) { | |
| 9884 | + let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 9885 | + let service = http_stream_service(); | |
| 9886 | + let read = http_stream_read(service, stream_id); | |
| 9887 | + let id = asyncrt::enqueue(async move { | |
| 9888 | + match read.await? { | |
| 9889 | + Some(bytes) => Ok(asyncrt::OpOut::Bytes(bytes)), | |
| 9890 | + None => Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())), | |
| 9891 | + } | |
| 9892 | + }); | |
| 9893 | + rv.set(promise_for(scope, id)); | |
| 9894 | +} | |
| 9895 | + | |
| 9896 | +fn op_http_stream_tee( | |
| 9897 | + scope: &mut v8::PinScope, | |
| 9898 | + args: v8::FunctionCallbackArguments, | |
| 9899 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9900 | +) { | |
| 9901 | + let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 9902 | + let service = http_stream_service(); | |
| 9903 | + let source = service.checkout_transfer(stream_id, None).ok(); | |
| 9904 | + let Some(source) = source else { | |
| 9905 | + let message = v8::String::new(scope, "response stream is no longer available").unwrap(); | |
| 9906 | + let exception = v8::Exception::type_error(scope, message); | |
| 9907 | + scope.throw_exception(exception); | |
| 9908 | + return; | |
| 9909 | + }; | |
| 9910 | + let ids = match tee_http_stream(&service, source) { | |
| 9911 | + Ok(ids) => ids, | |
| 9912 | + Err(error) => { | |
| 9913 | + let message = v8::String::new(scope, error).unwrap(); | |
| 9914 | + let exception = v8::Exception::type_error(scope, message); | |
| 9915 | + scope.throw_exception(exception); | |
| 9916 | + return; | |
| 9917 | + } | |
| 9918 | + }; | |
| 9919 | + current_context().replace_body_stream(stream_id, &service, ids); | |
| 9920 | + let json = serde_json::to_string(&ids).unwrap(); | |
| 9921 | + rv.set(v8::String::new(scope, &json).unwrap().into()); | |
| 9922 | +} | |
| 9923 | + | |
| 9924 | +fn op_http_stream_cancel( | |
| 9925 | + scope: &mut v8::PinScope, | |
| 9926 | + args: v8::FunctionCallbackArguments, | |
| 9927 | + _rv: v8::ReturnValue<v8::Value>, | |
| 9928 | +) { | |
| 9929 | + let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 9930 | + http_stream_service().cancel_source(stream_id); | |
| 9931 | +} | |
| 9932 | + | |
| 9933 | +fn op_response_stream_create( | |
| 9934 | + scope: &mut v8::PinScope, | |
| 9935 | + _args: v8::FunctionCallbackArguments, | |
| 9936 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9937 | +) { | |
| 9938 | + let (writer, receiver) = tokio::sync::mpsc::channel(1); | |
| 9939 | + let (finished, _) = tokio::sync::watch::channel(false); | |
| 9940 | + let Some(stream_id) = http_stream_service() | |
| 9941 | + .register_response_pair(receiver, ResponseStreamWriter::new(writer, finished)) | |
| 9942 | + else { | |
| 9943 | + let message = v8::String::new(scope, HTTP_STREAM_REGISTRATION_CLOSED).unwrap(); | |
| 9944 | + let exception = v8::Exception::type_error(scope, message); | |
| 9945 | + scope.throw_exception(exception); | |
| 9946 | + return; | |
| 9947 | + }; | |
| 9948 | + rv.set(v8::Number::new(scope, stream_id as f64).into()); | |
| 9949 | +} | |
| 9950 | + | |
| 9951 | +fn op_response_stream_write( | |
| 9952 | + scope: &mut v8::PinScope, | |
| 9953 | + args: v8::FunctionCallbackArguments, | |
| 9954 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9955 | +) { | |
| 9956 | + let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 9957 | + let bytes = args | |
| 9958 | + .get(1) | |
| 9959 | + .try_cast::<v8::ArrayBufferView>() | |
| 9960 | + .ok() | |
| 9961 | + .map(|view| { | |
| 9962 | + let mut bytes = vec![0; view.byte_length()]; | |
| 9963 | + view.copy_contents(&mut bytes); | |
| 9964 | + bytes | |
| 9965 | + }); | |
| 9966 | + // A response is gated once, when it is released, but a body that streams | |
| 9967 | + // keeps producing after that. A later chunk can carry a commit that | |
| 9968 | + // another event made after the release, and that chunk leaves the process | |
| 9969 | + // as surely as the response head did. So each chunk takes its own ticket, | |
| 9970 | + // sampled here while JS still runs, exactly as `fetch` does. | |
| 9971 | + // | |
| 9972 | + // The pump in `__bridgeResponseStream` awaits each write before it asks | |
| 9973 | + // the producer for the next chunk, so one chunk is in flight at a time and | |
| 9974 | + // a held chunk cannot overtake a released one. The ticket is taken before | |
| 9975 | + // `response_stream_write` reserves the stream's write activity, so a long | |
| 9976 | + // wait for a proof holds no lease on the stream. The stream's inactivity | |
| 9977 | + // expiry still runs during the wait, so a proof that never lands ends the | |
| 9978 | + // body with an error rather than releasing the chunk, which is the | |
| 9979 | + // direction this gate exists to fail in. | |
| 9980 | + let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Response); | |
| 9981 | + let service = http_stream_service(); | |
| 9982 | + let id = asyncrt::enqueue(async move { | |
| 9983 | + await_egress_gate(gate).await?; | |
| 9984 | + response_stream_write(service, stream_id, bytes).await?; | |
| 9985 | + Ok(String::new()) | |
| 9986 | + }); | |
| 9987 | + rv.set(promise_for(scope, id)); | |
| 9988 | +} | |
| 9989 | + | |
| 9990 | +fn op_response_stream_closed( | |
| 9991 | + scope: &mut v8::PinScope, | |
| 9992 | + args: v8::FunctionCallbackArguments, | |
| 9993 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 9994 | +) { | |
| 9995 | + let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 9996 | + let (writer, mut finished) = http_stream_service() | |
| 9997 | + .writer_close_watch(stream_id) | |
| 9998 | + .map(|(writer, finished)| (Some(writer), Some(finished))) | |
| 9999 | + .unwrap_or((None, None)); | |
| 10000 | + let id = asyncrt::enqueue(async move { | |
| 10001 | + let cancelled = match (writer, finished.as_mut()) { | |
| 10002 | + (Some(writer), Some(finished)) => crate::asyncrt::select_biased! { | |
| 10003 | + "stream completion wins a tie so a completed response is not reported as cancelled"; | |
| 10004 | + result = finished.changed() => result.is_err(), | |
| 10005 | + _ = writer.closed() => true, | |
| 10006 | + }, | |
| 10007 | + _ => false, | |
| 10008 | + }; | |
| 10009 | + Ok(String::from(if cancelled { | |
| 10010 | + "cancelled" | |
| 10011 | + } else { | |
| 10012 | + "finished" | |
| 10013 | + })) | |
| 10014 | + }); | |
| 10015 | + rv.set(promise_for(scope, id)); | |
| 10016 | +} | |
| 10017 | + | |
| 10018 | +fn op_response_stream_close( | |
| 10019 | + scope: &mut v8::PinScope, | |
| 10020 | + args: v8::FunctionCallbackArguments, | |
| 10021 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10022 | +) { | |
| 10023 | + let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 10024 | + let error = args.get(1).to_rust_string_lossy(scope); | |
| 10025 | + let close = response_stream_close(http_stream_service(), stream_id, error); | |
| 10026 | + let id = asyncrt::enqueue(async move { | |
| 10027 | + close.await?; | |
| 10028 | + Ok(String::new()) | |
| 10029 | + }); | |
| 10030 | + rv.set(promise_for(scope, id)); | |
| 10031 | +} | |
| 10032 | + | |
| 10033 | +/// Hand a request body to the isolate as a stream rather than as bytes. | |
| 10034 | +/// The returned id names the stream for `__http_stream_read`, so the | |
| 10035 | +/// Worker pulls each chunk off the socket as it asks for it and the host | |
| 10036 | +/// never holds the whole body. | |
| 10037 | +pub fn register_body_stream(stream: HttpChunkStream) -> Result<u64, String> { | |
| 10038 | + register_http_stream(HttpStreamSource::Stream(stream)) | |
| 10039 | + .ok_or_else(|| HTTP_STREAM_REGISTRATION_CLOSED.to_string()) | |
| 10040 | +} | |
| 10041 | + | |
| 10042 | +/// How an incoming request body reaches the isolate. | |
| 10043 | +/// | |
| 10044 | +/// A small body crosses as bytes. This costs one copy and no asynchronous | |
| 10045 | +/// operations, so a common request pays nothing for a stream that it does | |
| 10046 | +/// not need. A large body, or a body of unknown length, crosses as a | |
| 10047 | +/// stream id. The peak cost of that body is one chunk, not its length. | |
| 10048 | +pub enum RequestBody { | |
| 10049 | + Bytes(bytes::Bytes), | |
| 10050 | + Stream(u64), | |
| 10051 | +} | |
| 10052 | + | |
| 10053 | +impl RequestBody { | |
| 10054 | + /// The bytes already in hand, for the paths that hold a whole body. | |
| 10055 | + pub fn bytes(&self) -> &[u8] { | |
| 10056 | + match self { | |
| 10057 | + Self::Bytes(bytes) => bytes, | |
| 10058 | + Self::Stream(_) => &[], | |
| 10059 | + } | |
| 10060 | + } | |
| 10061 | + | |
| 10062 | + pub fn stream_id(&self) -> Option<u64> { | |
| 10063 | + match self { | |
| 10064 | + Self::Bytes(_) => None, | |
| 10065 | + Self::Stream(id) => Some(*id), | |
| 10066 | + } | |
| 10067 | + } | |
| 10068 | + | |
| 10069 | + fn into_held_bytes(self) -> Option<Vec<u8>> { | |
| 10070 | + match self { | |
| 10071 | + Self::Bytes(bytes) => Some(bytes.into()), | |
| 10072 | + Self::Stream(_) => None, | |
| 10073 | + } | |
| 10074 | + } | |
| 10075 | +} | |
| 10076 | + | |
| 10077 | +impl From<Vec<u8>> for RequestBody { | |
| 10078 | + fn from(bytes: Vec<u8>) -> Self { | |
| 10079 | + Self::Bytes(bytes.into()) | |
| 10080 | + } | |
| 10081 | +} | |
| 10082 | + | |
| 10083 | +/// Timer op behind `setTimeout`: a promise resolving after `ms`. | |
| 10084 | +fn op_timer( | |
| 10085 | + scope: &mut v8::PinScope, | |
| 10086 | + args: v8::FunctionCallbackArguments, | |
| 10087 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10088 | +) { | |
| 10089 | + let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 10090 | + let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64; | |
| 10091 | + let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel(); | |
| 10092 | + timer_cancels().lock().unwrap().insert(timer_id, cancel_tx); | |
| 10093 | + let id = asyncrt::enqueue(async move { | |
| 10094 | + crate::asyncrt::select! { | |
| 10095 | + _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {} | |
| 10096 | + _ = &mut cancel_rx => {} | |
| 10097 | + } | |
| 10098 | + timer_cancels().lock().unwrap().remove(&timer_id); | |
| 10099 | + Ok(String::new()) | |
| 10100 | + }); | |
| 10101 | + let p = promise_for(scope, id); | |
| 10102 | + rv.set(p); | |
| 10103 | +} | |
| 10104 | + | |
| 10105 | +/// `__gate_acquire(scope)` — take the cell's input gate for a | |
| 10106 | +/// `blockConcurrencyWhile`, waiting if another block holds it. | |
| 10107 | +/// | |
| 10108 | +/// Answers a promise of the event id, not the id itself. It was synchronous, | |
| 10109 | +/// and that was right while a cell's events came off one channel: only one | |
| 10110 | +/// ran at a time, a delivery point had already found the gate open, and | |
| 10111 | +/// yielding even one microtask reopened a window in which a nested delivery | |
| 10112 | +/// could wait on a gate nothing would release. Neither half holds now — | |
| 10113 | +/// events are independent tasks, several run at once, and nothing nests — | |
| 10114 | +/// so two blocks can meet and the second must queue. | |
| 10115 | +fn op_io_context_id( | |
| 10116 | + scope: &mut v8::PinScope, | |
| 10117 | + _args: v8::FunctionCallbackArguments, | |
| 10118 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10119 | +) { | |
| 10120 | + let id = current_reaction_io_context(scope) | |
| 10121 | + .and_then(|context| context.continuation_id()) | |
| 10122 | + .map(|id| id.to_string()) | |
| 10123 | + .unwrap_or_default(); | |
| 10124 | + rv.set(v8::String::new(scope, &id).unwrap().into()); | |
| 10125 | +} | |
| 10126 | + | |
| 10127 | +fn return_gate_acquisition( | |
| 10128 | + scope: &mut v8::PinScope, | |
| 10129 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10130 | + event: celld_logic::gate::EventId, | |
| 10131 | + owner: Option<u64>, | |
| 10132 | + promise: v8::Local<v8::Value>, | |
| 10133 | +) { | |
| 10134 | + let event = v8::String::new(scope, &event.to_string()).unwrap(); | |
| 10135 | + let owner = | |
| 10136 | + v8::String::new(scope, &owner.map(|id| id.to_string()).unwrap_or_default()).unwrap(); | |
| 10137 | + let values = [event.into(), owner.into(), promise]; | |
| 10138 | + rv.set(v8::Array::new_with_elements(scope, &values).into()); | |
| 10139 | +} | |
| 10140 | + | |
| 10141 | +fn op_gate_acquire( | |
| 10142 | + scope: &mut v8::PinScope, | |
| 10143 | + args: v8::FunctionCallbackArguments, | |
| 10144 | + rv: v8::ReturnValue<v8::Value>, | |
| 10145 | +) { | |
| 10146 | + let cell = args.get(0).to_rust_string_lossy(scope); | |
| 10147 | + let event = NEXT_GATE_EVENT.fetch_add(1, Ordering::Relaxed); | |
| 10148 | + let Some(context) = current_reaction_io_context(scope) else { | |
| 10149 | + // A promise can retain user code after its event has retired. It must | |
| 10150 | + // not borrow the context of whichever event happens to run the stale | |
| 10151 | + // reaction's checkpoint. | |
| 10152 | + let id = | |
| 10153 | + asyncrt::enqueue(async move { Err::<String, String>(RETIRED_INPUT_GATE.to_string()) }); | |
| 10154 | + let promise = promise_for(scope, id); | |
| 10155 | + return_gate_acquisition(scope, rv, event, None, promise); | |
| 10156 | + return; | |
| 10157 | + }; | |
| 10158 | + // The turn owner is the entry that adopts the block's native operations, | |
| 10159 | + // as `CellGate` explains. A cancellation turn can have no tracked ambient | |
| 10160 | + // context, so the reaction context is the owner in that case. | |
| 10161 | + let active = current_context(); | |
| 10162 | + let owner_context = if active.continuation_id().is_some() { | |
| 10163 | + active | |
| 10164 | + } else { | |
| 10165 | + Arc::clone(&context) | |
| 10166 | + }; | |
| 10167 | + let owner = owner_context.continuation_id(); | |
| 10168 | + // Queued until taken or refused, either way once: the guard counts the | |
| 10169 | + // event out when the future ends, however it ends. | |
| 10170 | + struct Queued { | |
| 10171 | + cell: String, | |
| 10172 | + owner: Option<u64>, | |
| 10173 | + } | |
| 10174 | + impl Queued { | |
| 10175 | + fn new(cell: String, owner: Option<u64>) -> Self { | |
| 10176 | + if let Some(owner) = owner { | |
| 10177 | + *cell_gates() | |
| 10178 | + .lock() | |
| 10179 | + .unwrap() | |
| 10180 | + .entry(cell.clone()) | |
| 10181 | + .or_default() | |
| 10182 | + .queued | |
| 10183 | + .entry(owner) | |
| 10184 | + .or_default() += 1; | |
| 10185 | + GATE_ENGAGEMENTS.fetch_add(1, Ordering::Relaxed); | |
| 10186 | + } | |
| 10187 | + Self { cell, owner } | |
| 10188 | + } | |
| 10189 | + } | |
| 10190 | + impl Drop for Queued { | |
| 10191 | + fn drop(&mut self) { | |
| 10192 | + let Some(owner) = self.owner else { | |
| 10193 | + return; | |
| 10194 | + }; | |
| 10195 | + let mut gates = cell_gates().lock().unwrap(); | |
| 10196 | + let remove = if let Some(gate) = gates.get_mut(&self.cell) { | |
| 10197 | + if let Some(count) = gate.queued.get_mut(&owner) { | |
| 10198 | + *count -= 1; | |
| 10199 | + if *count == 0 { | |
| 10200 | + gate.queued.remove(&owner); | |
| 10201 | + } | |
| 10202 | + } | |
| 10203 | + gate.is_unused() | |
| 10204 | + } else { | |
| 10205 | + false | |
| 10206 | + }; | |
| 10207 | + if remove { | |
| 10208 | + gates.remove(&self.cell); | |
| 10209 | + } | |
| 10210 | + drop(gates); | |
| 10211 | + GATE_ENGAGEMENTS.fetch_sub(1, Ordering::Relaxed); | |
| 10212 | + } | |
| 10213 | + } | |
| 10214 | + let mut origin = if Arc::ptr_eq(&context, &owner_context) { | |
| 10215 | + None | |
| 10216 | + } else { | |
| 10217 | + let Some(claim) = context.claim_cross_entry_gate() else { | |
| 10218 | + let id = | |
| 10219 | + asyncrt::enqueue( | |
| 10220 | + async move { Err::<String, String>(RETIRED_INPUT_GATE.to_string()) }, | |
| 10221 | + ); | |
| 10222 | + let promise = promise_for(scope, id); | |
| 10223 | + return_gate_acquisition(scope, rv, event, owner, promise); | |
| 10224 | + return; | |
| 10225 | + }; | |
| 10226 | + Some(claim) | |
| 10227 | + }; | |
| 10228 | + let id = match acquire_cell_gate(&owner_context, &cell, event, owner, &mut origin) { | |
| 10229 | + CellGateAcquisition::Acquired => { | |
| 10230 | + asyncrt::enqueue_io_context(async move { Ok(String::new()) }) | |
| 10231 | + } | |
| 10232 | + CellGateAcquisition::Waiting { | |
| 10233 | + mut gate, | |
| 10234 | + mut retirement, | |
| 10235 | + } => { | |
| 10236 | + let queued = Queued::new(cell.clone(), owner); | |
| 10237 | + let context = Arc::downgrade(&owner_context); | |
| 10238 | + asyncrt::enqueue_io_context(async move { | |
| 10239 | + let _queued = queued; | |
| 10240 | + loop { | |
| 10241 | + let outcome = crate::asyncrt::select_biased! { | |
| 10242 | + "a settled gate failure remains visible when its event retires at the same instant"; | |
| 10243 | + outcome = &mut gate => Some(outcome), | |
| 10244 | + retired = retirement.wait_for(|retired| *retired) => { | |
| 10245 | + let _ = retired; | |
| 10246 | + None | |
| 10247 | + } | |
| 10248 | + }; | |
| 10249 | + let Some(outcome) = outcome else { | |
| 10250 | + return Err(RETIRED_INPUT_GATE.to_string()); | |
| 10251 | + }; | |
| 10252 | + match outcome { | |
| 10253 | + Ok(Ok(())) => {} | |
| 10254 | + // The block ahead failed and reset the actor. This event | |
| 10255 | + // was sent to that old actor, so it cannot compete for the | |
| 10256 | + // fresh gate. | |
| 10257 | + Ok(Err(failure)) => return Err(failure), | |
| 10258 | + Err(_) => { | |
| 10259 | + return Err("cell stopped while waiting for its input gate".to_string()) | |
| 10260 | + } | |
| 10261 | + } | |
| 10262 | + let Some(context) = context.upgrade() else { | |
| 10263 | + return Err(RETIRED_INPUT_GATE.to_string()); | |
| 10264 | + }; | |
| 10265 | + match acquire_cell_gate(&context, &cell, event, owner, &mut origin) { | |
| 10266 | + CellGateAcquisition::Acquired => { | |
| 10267 | + return Ok(String::new()); | |
| 10268 | + } | |
| 10269 | + CellGateAcquisition::Waiting { | |
| 10270 | + gate: next_gate, | |
| 10271 | + retirement: next_retirement, | |
| 10272 | + } => { | |
| 10273 | + gate = next_gate; | |
| 10274 | + retirement = next_retirement; | |
| 10275 | + } | |
| 10276 | + CellGateAcquisition::Retired => return Err(RETIRED_INPUT_GATE.to_string()), | |
| 10277 | + } | |
| 10278 | + } | |
| 10279 | + }) | |
| 10280 | + } | |
| 10281 | + CellGateAcquisition::Retired => asyncrt::enqueue_io_context(async move { | |
| 10282 | + Err::<String, String>(RETIRED_INPUT_GATE.to_string()) | |
| 10283 | + }), | |
| 10284 | + }; | |
| 10285 | + let promise = promise_for(scope, id); | |
| 10286 | + return_gate_acquisition(scope, rv, event, owner, promise); | |
| 10287 | +} | |
| 10288 | + | |
| 10289 | +/// `__gate_wait(scope)` — settle when the cell's input gate is open. | |
| 10290 | +/// | |
| 10291 | +/// The gate's other side. `op_gate_acquire` is for something that wants to | |
| 10292 | +/// *hold* the gate; this is for something that only has to arrive after it, | |
| 10293 | +/// which is every event the gate exists to hold back. A drive does this in | |
| 10294 | +/// Rust before it begins a turn; an RPC stub op does it here, because it is | |
| 10295 | +/// dispatched inside the isolate and never becomes a drive. | |
| 10296 | +/// | |
| 10297 | +/// Rejecting matters as much as resolving: a critical section that failed | |
| 10298 | +/// reset the cell, so what waited behind it is refused with the reason | |
| 10299 | +/// rather than run against state that no longer exists. | |
| 10300 | +fn op_gate_wait( | |
| 10301 | + scope: &mut v8::PinScope, | |
| 10302 | + args: v8::FunctionCallbackArguments, | |
| 10303 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10304 | +) { | |
| 10305 | + let cell = args.get(0).to_rust_string_lossy(scope); | |
| 10306 | + let id = asyncrt::enqueue(async move { | |
| 10307 | + loop { | |
| 10308 | + match cell_gate_wait(&cell) { | |
| 10309 | + None => return Ok(String::new()), | |
| 10310 | + Some(open) => match open.await { | |
| 10311 | + Ok(Ok(())) => {} | |
| 10312 | + Ok(Err(failure)) => return Err(failure), | |
| 10313 | + Err(_) => { | |
| 10314 | + return Err("cell stopped while waiting for its input gate".to_string()) | |
| 10315 | + } | |
| 10316 | + }, | |
| 10317 | + } | |
| 10318 | + } | |
| 10319 | + }); | |
| 10320 | + rv.set(promise_for(scope, id)); | |
| 10321 | +} | |
| 10322 | + | |
| 10323 | +/// `__gate_release(scope, event, owner)` — the block is over. The next | |
| 10324 | +/// delivery point to run takes whatever queued behind it. | |
| 10325 | +fn op_gate_release( | |
| 10326 | + scope: &mut v8::PinScope, | |
| 10327 | + args: v8::FunctionCallbackArguments, | |
| 10328 | + _rv: v8::ReturnValue<v8::Value>, | |
| 10329 | +) { | |
| 10330 | + let cell = args.get(0).to_rust_string_lossy(scope); | |
| 10331 | + let event = args.get(1).number_value(scope).unwrap_or_default() as celld_logic::gate::EventId; | |
| 10332 | + let owner = args.get(2).to_rust_string_lossy(scope).parse::<u64>().ok(); | |
| 10333 | + // A fourth argument means the block failed and the actor was reset, so | |
| 10334 | + // what queued behind it is refused with that reason rather than | |
| 10335 | + // delivered to a cell whose state is gone. | |
| 10336 | + let failure = args.get(3); | |
| 10337 | + let outcome = if failure.is_null_or_undefined() { | |
| 10338 | + Ok(()) | |
| 10339 | + } else { | |
| 10340 | + Err(failure.to_rust_string_lossy(scope)) | |
| 10341 | + }; | |
| 10342 | + let Some(owner) = owner else { | |
| 10343 | + return; | |
| 10344 | + }; | |
| 10345 | + let active = current_context(); | |
| 10346 | + let context = if active.continuation_id() == Some(owner) { | |
| 10347 | + Some(active) | |
| 10348 | + } else { | |
| 10349 | + actor_runtime_state(scope).io_context(owner) | |
| 10350 | + }; | |
| 10351 | + let Some(context) = context else { | |
| 10352 | + return; | |
| 10353 | + }; | |
| 10354 | + if !context.release_input_gate(&cell, event) { | |
| 10355 | + return; | |
| 10356 | + } | |
| 10357 | + release_cell_gate(&cell, event, outcome); | |
| 10358 | +} | |
| 10359 | + | |
| 10360 | +fn op_timer_alloc( | |
| 10361 | + scope: &mut v8::PinScope, | |
| 10362 | + _args: v8::FunctionCallbackArguments, | |
| 10363 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10364 | +) { | |
| 10365 | + let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64); | |
| 10366 | + rv.set(id.into()); | |
| 10367 | +} | |
| 10368 | + | |
| 10369 | +fn op_timer_cancel( | |
| 10370 | + scope: &mut v8::PinScope, | |
| 10371 | + args: v8::FunctionCallbackArguments, | |
| 10372 | + _rv: v8::ReturnValue<v8::Value>, | |
| 10373 | +) { | |
| 10374 | + let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 10375 | + if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) { | |
| 10376 | + let _ = cancel.send(()); | |
| 10377 | + } | |
| 10378 | +} | |
| 10379 | + | |
| 10380 | +fn durable_object_id_key(namespace_key: &str) -> [u8; 32] { | |
| 10381 | + DO_ID_KEYS.with(|keys| { | |
| 10382 | + if let Some(key) = keys.borrow().get(namespace_key) { | |
| 10383 | + return *key; | |
| 10384 | + } | |
| 10385 | + use sha2::Digest; | |
| 10386 | + let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into(); | |
| 10387 | + keys.borrow_mut().insert(namespace_key.to_string(), key); | |
| 10388 | + key | |
| 10389 | + }) | |
| 10390 | +} | |
| 10391 | + | |
| 10392 | +fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> { | |
| 10393 | + use hmac::Mac; | |
| 10394 | + let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key) | |
| 10395 | + .expect("SHA-256 accepts any HMAC key"); | |
| 10396 | + mac.update(input); | |
| 10397 | + mac | |
| 10398 | +} | |
| 10399 | + | |
| 10400 | +/// Ids already derived on this thread, keyed by namespace and name. | |
| 10401 | +/// | |
| 10402 | +/// `getByName` costs two HMAC-SHA256 rounds, and a profile of `/c/hello` | |
| 10403 | +/// found them among the largest terms the stateless path does not have — | |
| 10404 | +/// the same name resolving to the same id, recomputed on every request. | |
| 10405 | +/// | |
| 10406 | +/// Per thread and unsynchronised, which is sound because the derivation is | |
| 10407 | +/// a pure function of its inputs: a worker that has not seen a name pays | |
| 10408 | +/// for it once, and no answer can differ between threads. Bounded because | |
| 10409 | +/// names come from the application, and cleared wholesale at the cap rather | |
| 10410 | +/// than evicted one at a time — a cache this cheap to refill does not earn | |
| 10411 | +/// an LRU. | |
| 10412 | +const DO_ID_CACHE_MAX: usize = 4096; | |
| 10413 | + | |
| 10414 | +fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] { | |
| 10415 | + use hmac::Mac; | |
| 10416 | + | |
| 10417 | + thread_local! { | |
| 10418 | + static IDS: RefCell<HashMap<(String, String), [u8; 32]>> = | |
| 10419 | + RefCell::new(HashMap::new()); | |
| 10420 | + } | |
| 10421 | + let cached = IDS.with(|ids| { | |
| 10422 | + ids.borrow() | |
| 10423 | + .get(&(namespace_key.to_string(), name.to_string())) | |
| 10424 | + .copied() | |
| 10425 | + }); | |
| 10426 | + if let Some(id) = cached { | |
| 10427 | + return id; | |
| 10428 | + } | |
| 10429 | + | |
| 10430 | + let key = durable_object_id_key(namespace_key); | |
| 10431 | + let mut id = [0_u8; 32]; | |
| 10432 | + let digest = durable_object_id_hmac(&key, name.as_bytes()) | |
| 10433 | + .finalize() | |
| 10434 | + .into_bytes(); | |
| 10435 | + id[..16].copy_from_slice(&digest[..16]); | |
| 10436 | + let digest = durable_object_id_hmac(&key, &id[..16]) | |
| 10437 | + .finalize() | |
| 10438 | + .into_bytes(); | |
| 10439 | + id[16..].copy_from_slice(&digest[..16]); | |
| 10440 | + | |
| 10441 | + IDS.with(|ids| { | |
| 10442 | + let mut ids = ids.borrow_mut(); | |
| 10443 | + if ids.len() >= DO_ID_CACHE_MAX { | |
| 10444 | + ids.clear(); | |
| 10445 | + } | |
| 10446 | + ids.insert((namespace_key.to_string(), name.to_string()), id); | |
| 10447 | + }); | |
| 10448 | + id | |
| 10449 | +} | |
| 10450 | + | |
| 10451 | +/// The key a Durable Object namespace derives its IDs from. D1 uses one | |
| 10452 | +/// fleet-wide namespace because the database is a resource that several | |
| 10453 | +/// Workers can bind, and a Worker rename must not rename that database. | |
| 10454 | +const D1_NAMESPACE_KEY: &str = "cells:v1:d1:__D1Database"; | |
| 10455 | + | |
| 10456 | +/// The same, for a KV namespace, and for the same reason: several Workers can | |
| 10457 | +/// bind one namespace, and they must reach one set of cells. | |
| 10458 | +/// | |
| 10459 | +/// Written out rather than derived from the class name, because these two | |
| 10460 | +/// strings are addresses. A scheme that computed them would be free to change, | |
| 10461 | +/// and changing one renames every cell it ever addressed. | |
| 10462 | +const KV_NAMESPACE_KEY: &str = "cells:v1:kv:__KvNamespace"; | |
| 10463 | + | |
| 10464 | +/// The fleet-wide namespace for Queue broker cells. The queue name is the | |
| 10465 | +/// durable resource identity, so a producer and a consumer in different | |
| 10466 | +/// scripts must derive the same cell id. | |
| 10467 | +const QUEUE_NAMESPACE_KEY: &str = "cells:v1:queue:__Queue"; | |
| 10468 | + | |
| 10469 | +/// A shared reserved class addresses one set of cells for the whole fleet; every | |
| 10470 | +/// other class, reserved or not, is scoped to the script that exports it. | |
| 10471 | +/// | |
| 10472 | +/// The question is asked once, through `deploy::is_shared_reserved_class`, and | |
| 10473 | +/// not as a chain of `==` against class names. A reserved class declared shared | |
| 10474 | +/// there and script-scoped here would silently give each script its own copy of | |
| 10475 | +/// a resource the configuration says they share -- which is what happened to KV | |
| 10476 | +/// between its manifest landing and this line being written. | |
| 10477 | +fn shared_namespace_key(class_name: &str) -> Option<&'static str> { | |
| 10478 | + match class_name { | |
| 10479 | + crate::deploy::D1_CLASS => Some(D1_NAMESPACE_KEY), | |
| 10480 | + crate::deploy::KV_CLASS => Some(KV_NAMESPACE_KEY), | |
| 10481 | + crate::deploy::QUEUE_CLASS => Some(QUEUE_NAMESPACE_KEY), | |
| 10482 | + _ => { | |
| 10483 | + debug_assert!( | |
| 10484 | + !crate::deploy::is_shared_reserved_class(class_name), | |
| 10485 | + "a shared reserved class needs a fleet-wide namespace key: {class_name}" | |
| 10486 | + ); | |
| 10487 | + None | |
| 10488 | + } | |
| 10489 | + } | |
| 10490 | +} | |
| 10491 | + | |
| 10492 | +pub(crate) fn namespace_key(script_name: &str, class_name: &str) -> String { | |
| 10493 | + match shared_namespace_key(class_name) { | |
| 10494 | + Some(shared) => shared.to_string(), | |
| 10495 | + None => format!("cells:v1:{}:{script_name}:{class_name}", script_name.len()), | |
| 10496 | + } | |
| 10497 | +} | |
| 10498 | + | |
| 10499 | +/// The cell scope a D1 database lives at, for a caller outside any isolate. | |
| 10500 | +/// `celld d1` addresses a database over the operator route, which takes a | |
| 10501 | +/// scope, so this derives what `getByName` derives in the harness, from the | |
| 10502 | +/// same key and the same HMAC. | |
| 10503 | +pub fn d1_cell_scope(database_identity: &str) -> String { | |
| 10504 | + let id = durable_object_id_for_name(D1_NAMESPACE_KEY, database_identity); | |
| 10505 | + format!("{}:{}", crate::deploy::D1_CLASS, durable_object_id_hex(&id)) | |
| 10506 | +} | |
| 10507 | + | |
| 10508 | +/// The cell scope one shard of a KV namespace lives at, for a caller outside | |
| 10509 | +/// any isolate. `celld kv` addresses a namespace over the operator route, and | |
| 10510 | +/// this derives what `getByName` derives in the harness -- from the same key, | |
| 10511 | +/// the same name, and the same HMAC. | |
| 10512 | +/// | |
| 10513 | +/// The name comes from `celld_logic::kv::cell_name`, which is also what the | |
| 10514 | +/// binding is handed at `build_env`. Neither side formats it, because a | |
| 10515 | +/// formatting disagreement here does not fail: it silently addresses a second, | |
| 10516 | +/// empty namespace. | |
| 10517 | +pub fn kv_cell_scope(namespace_id: &str, shard: u32) -> String { | |
| 10518 | + let name = celld_logic::kv::cell_name(namespace_id, shard); | |
| 10519 | + let id = durable_object_id_for_name(KV_NAMESPACE_KEY, &name); | |
| 10520 | + format!("{}:{}", crate::deploy::KV_CLASS, durable_object_id_hex(&id)) | |
| 10521 | +} | |
| 10522 | + | |
| 10523 | +/// The Queue broker scope for callers outside a Worker isolate. | |
| 10524 | +pub fn queue_cell_scope(queue: &str) -> String { | |
| 10525 | + let name = celld_logic::queue::cell_name(queue); | |
| 10526 | + let id = durable_object_id_for_name(QUEUE_NAMESPACE_KEY, name); | |
| 10527 | + format!( | |
| 10528 | + "{}:{}", | |
| 10529 | + crate::deploy::QUEUE_CLASS, | |
| 10530 | + durable_object_id_hex(&id) | |
| 10531 | + ) | |
| 10532 | +} | |
| 10533 | + | |
| 10534 | +#[cfg(celld_internal_tests)] | |
| 10535 | +#[doc(hidden)] | |
| 10536 | +pub fn workflow_cell_scope_for_test( | |
| 10537 | + script_name: &str, | |
| 10538 | + workflow_name: &str, | |
| 10539 | + instance_id: &str, | |
| 10540 | +) -> String { | |
| 10541 | + let class = crate::deploy::workflow_class(script_name); | |
| 10542 | + let namespace = namespace_key(script_name, &class); | |
| 10543 | + let name = format!("{workflow_name}/{instance_id}"); | |
| 10544 | + let id = durable_object_id_for_name(&namespace, &name); | |
| 10545 | + format!("{class}:{}", durable_object_id_hex(&id)) | |
| 10546 | +} | |
| 10547 | + | |
| 10548 | +fn durable_object_id_hex(bytes: &[u8; 32]) -> String { | |
| 10549 | + const HEX: &[u8; 16] = b"0123456789abcdef"; | |
| 10550 | + let mut output = String::with_capacity(64); | |
| 10551 | + for byte in bytes { | |
| 10552 | + output.push(HEX[(byte >> 4) as usize] as char); | |
| 10553 | + output.push(HEX[(byte & 0x0f) as usize] as char); | |
| 10554 | + } | |
| 10555 | + output | |
| 10556 | +} | |
| 10557 | + | |
| 10558 | +fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> { | |
| 10559 | + if value.len() != 64 { | |
| 10560 | + return None; | |
| 10561 | + } | |
| 10562 | + let mut output = [0_u8; 32]; | |
| 10563 | + for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() { | |
| 10564 | + let nibble = |byte| match byte { | |
| 10565 | + b'0'..=b'9' => Some(byte - b'0'), | |
| 10566 | + b'a'..=b'f' => Some(byte - b'a' + 10), | |
| 10567 | + b'A'..=b'F' => Some(byte - b'A' + 10), | |
| 10568 | + _ => None, | |
| 10569 | + }; | |
| 10570 | + output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?; | |
| 10571 | + } | |
| 10572 | + Some(output) | |
| 10573 | +} | |
| 10574 | + | |
| 10575 | +fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) { | |
| 10576 | + let message = v8::String::new(scope, message).unwrap(); | |
| 10577 | + let exception = v8::Exception::type_error(scope, message); | |
| 10578 | + scope.throw_exception(exception); | |
| 10579 | +} | |
| 10580 | + | |
| 10581 | +fn register_actor_name( | |
| 10582 | + scope: &mut v8::PinScope, | |
| 10583 | + actor_scope: &str, | |
| 10584 | + name: Option<&str>, | |
| 10585 | +) -> Result<()> { | |
| 10586 | + let Some(name) = name else { | |
| 10587 | + return Ok(()); | |
| 10588 | + }; | |
| 10589 | + let context = scope.get_current_context(); | |
| 10590 | + let global = context.global(scope); | |
| 10591 | + let cell_key = static_key(scope, &v8_strings::CELL); | |
| 10592 | + let cell = global | |
| 10593 | + .get(scope, cell_key.into()) | |
| 10594 | + .and_then(|value| value.to_object(scope)) | |
| 10595 | + .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 10596 | + let names_key = v8::String::new(scope, "idNames").unwrap(); | |
| 10597 | + let names = cell | |
| 10598 | + .get(scope, names_key.into()) | |
| 10599 | + .and_then(|value| value.to_object(scope)) | |
| 10600 | + .ok_or_else(|| anyhow!("missing Durable Object name registry"))?; | |
| 10601 | + let actor_scope_key = v8::String::new(scope, actor_scope).unwrap(); | |
| 10602 | + if let Some(existing) = names.get(scope, actor_scope_key.into()) { | |
| 10603 | + if !existing.is_undefined() { | |
| 10604 | + if existing.to_rust_string_lossy(scope) == name { | |
| 10605 | + return Ok(()); | |
| 10606 | + } | |
| 10607 | + anyhow::bail!("actor name conflicts with active identity for {actor_scope}"); | |
| 10608 | + } | |
| 10609 | + } | |
| 10610 | + | |
| 10611 | + let (class_name, id) = actor_scope | |
| 10612 | + .split_once(':') | |
| 10613 | + .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?; | |
| 10614 | + let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap(); | |
| 10615 | + let namespace_keys = cell | |
| 10616 | + .get(scope, namespace_keys_key.into()) | |
| 10617 | + .and_then(|value| value.to_object(scope)) | |
| 10618 | + .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?; | |
| 10619 | + let class_name_key = v8::String::new(scope, class_name).unwrap(); | |
| 10620 | + let namespace_key = namespace_keys | |
| 10621 | + .get(scope, class_name_key.into()) | |
| 10622 | + .filter(|value| value.is_string()) | |
| 10623 | + .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))? | |
| 10624 | + .to_rust_string_lossy(scope); | |
| 10625 | + let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name)); | |
| 10626 | + if id != expected { | |
| 10627 | + anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}"); | |
| 10628 | + } | |
| 10629 | + storage::set_actor_name(actor_scope, name)?; | |
| 10630 | + | |
| 10631 | + let name_value = v8::String::new(scope, name).unwrap(); | |
| 10632 | + if !names | |
| 10633 | + .set(scope, actor_scope_key.into(), name_value.into()) | |
| 10634 | + .unwrap_or(false) | |
| 10635 | + { | |
| 10636 | + anyhow::bail!("could not register Durable Object name"); | |
| 10637 | + } | |
| 10638 | + Ok(()) | |
| 10639 | +} | |
| 10640 | + | |
| 10641 | +fn op_do_id( | |
| 10642 | + scope: &mut v8::PinScope, | |
| 10643 | + args: v8::FunctionCallbackArguments, | |
| 10644 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10645 | +) { | |
| 10646 | + use hmac::Mac; | |
| 10647 | + | |
| 10648 | + let namespace_key = args.get(0).to_rust_string_lossy(scope); | |
| 10649 | + let operation = args.get(1).to_rust_string_lossy(scope); | |
| 10650 | + let input = args.get(2).to_rust_string_lossy(scope); | |
| 10651 | + let key = durable_object_id_key(&namespace_key); | |
| 10652 | + let mut id = [0_u8; 32]; | |
| 10653 | + | |
| 10654 | + match operation.as_str() { | |
| 10655 | + "name" => { | |
| 10656 | + id = durable_object_id_for_name(&namespace_key, &input); | |
| 10657 | + rv.set( | |
| 10658 | + v8::String::new(scope, &durable_object_id_hex(&id)) | |
| 10659 | + .unwrap() | |
| 10660 | + .into(), | |
| 10661 | + ); | |
| 10662 | + return; | |
| 10663 | + } | |
| 10664 | + "unique" => { | |
| 10665 | + if getrandom::fill(&mut id[..16]).is_err() { | |
| 10666 | + throw_durable_object_id_error(scope, "secure random generation failed"); | |
| 10667 | + return; | |
| 10668 | + } | |
| 10669 | + } | |
| 10670 | + "validate" => { | |
| 10671 | + let Some(decoded) = decode_durable_object_id(&input) else { | |
| 10672 | + throw_durable_object_id_error( | |
| 10673 | + scope, | |
| 10674 | + "Invalid Durable Object ID: must be 64 hex digits", | |
| 10675 | + ); | |
| 10676 | + return; | |
| 10677 | + }; | |
| 10678 | + if durable_object_id_hmac(&key, &decoded[..16]) | |
| 10679 | + .verify_truncated_left(&decoded[16..]) | |
| 10680 | + .is_err() | |
| 10681 | + { | |
| 10682 | + throw_durable_object_id_error( | |
| 10683 | + scope, | |
| 10684 | + "Durable Object ID is not valid for this namespace", | |
| 10685 | + ); | |
| 10686 | + return; | |
| 10687 | + } | |
| 10688 | + rv.set( | |
| 10689 | + v8::String::new(scope, &input.to_ascii_lowercase()) | |
| 10690 | + .unwrap() | |
| 10691 | + .into(), | |
| 10692 | + ); | |
| 10693 | + return; | |
| 10694 | + } | |
| 10695 | + _ => { | |
| 10696 | + throw_durable_object_id_error(scope, "unknown Durable Object ID operation"); | |
| 10697 | + return; | |
| 10698 | + } | |
| 10699 | + } | |
| 10700 | + | |
| 10701 | + let digest = durable_object_id_hmac(&key, &id[..16]) | |
| 10702 | + .finalize() | |
| 10703 | + .into_bytes(); | |
| 10704 | + id[16..].copy_from_slice(&digest[..16]); | |
| 10705 | + rv.set( | |
| 10706 | + v8::String::new(scope, &durable_object_id_hex(&id)) | |
| 10707 | + .unwrap() | |
| 10708 | + .into(), | |
| 10709 | + ); | |
| 10710 | +} | |
| 10711 | + | |
| 10712 | +fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> { | |
| 10713 | + let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?; | |
| 10714 | + let mut bytes = vec![0_u8; view.byte_length()]; | |
| 10715 | + view.copy_contents(&mut bytes); | |
| 10716 | + Some(bytes) | |
| 10717 | +} | |
| 10718 | + | |
| 10719 | +fn webcrypto_return_bytes( | |
| 10720 | + scope: &mut v8::PinScope, | |
| 10721 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10722 | + bytes: &[u8], | |
| 10723 | +) { | |
| 10724 | + let buffer = v8::ArrayBuffer::new(scope, bytes.len()); | |
| 10725 | + if !bytes.is_empty() { | |
| 10726 | + let store = buffer.get_backing_store(); | |
| 10727 | + let destination = unsafe { | |
| 10728 | + std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len()) | |
| 10729 | + }; | |
| 10730 | + destination.copy_from_slice(bytes); | |
| 10731 | + } | |
| 10732 | + let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap(); | |
| 10733 | + rv.set(view.into()); | |
| 10734 | +} | |
| 10735 | + | |
| 10736 | +mod crypto; | |
| 10737 | +mod html_rewriter; | |
| 10738 | +mod tcp; | |
| 10739 | +#[cfg(celld_internal_tests)] | |
| 10740 | +pub use tcp::test_extra_tls_root; | |
| 10741 | +mod zlib; | |
| 10742 | + | |
| 10743 | +fn op_actor_abort( | |
| 10744 | + scope: &mut v8::PinScope, | |
| 10745 | + args: v8::FunctionCallbackArguments, | |
| 10746 | + _rv: v8::ReturnValue<v8::Value>, | |
| 10747 | +) { | |
| 10748 | + let Some(context) = current_reaction_io_context(scope) else { | |
| 10749 | + return; | |
| 10750 | + }; | |
| 10751 | + let cell = args.get(0).to_rust_string_lossy(scope); | |
| 10752 | + let reason = args.get(1).to_rust_string_lossy(scope); | |
| 10753 | + let state = actor_runtime_state(scope); | |
| 10754 | + state | |
| 10755 | + .pending_puts | |
| 10756 | + .lock() | |
| 10757 | + .expect("pending puts lock poisoned") | |
| 10758 | + .remove(&cell); | |
| 10759 | + *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination { | |
| 10760 | + error: format!("__CELLD_ACTOR_ABORT__:{reason}"), | |
| 10761 | + actor_scope: Some(cell), | |
| 10762 | + context_id: context.continuation_id(), | |
| 10763 | + }); | |
| 10764 | + scope.terminate_execution(); | |
| 10765 | +} | |
| 10766 | + | |
| 10767 | +fn op_process_exit( | |
| 10768 | + scope: &mut v8::PinScope, | |
| 10769 | + args: v8::FunctionCallbackArguments, | |
| 10770 | + _rv: v8::ReturnValue<v8::Value>, | |
| 10771 | +) { | |
| 10772 | + let code = args.get(0).integer_value(scope).unwrap_or(0); | |
| 10773 | + let Some(context) = current_reaction_or_untracked_io_context(scope) else { | |
| 10774 | + tracing::warn!( | |
| 10775 | + code, | |
| 10776 | + "process.exit called without an active request; ignoring" | |
| 10777 | + ); | |
| 10778 | + return; | |
| 10779 | + }; | |
| 10780 | + if context.depth() == 0 { | |
| 10781 | + tracing::warn!( | |
| 10782 | + code, | |
| 10783 | + "process.exit called without an active request; ignoring" | |
| 10784 | + ); | |
| 10785 | + return; | |
| 10786 | + } | |
| 10787 | + let actor_scope = args.get(1).to_rust_string_lossy(scope); | |
| 10788 | + let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope); | |
| 10789 | + let state = actor_runtime_state(scope); | |
| 10790 | + if let Some(actor_scope) = actor_scope.as_deref() { | |
| 10791 | + state | |
| 10792 | + .pending_puts | |
| 10793 | + .lock() | |
| 10794 | + .expect("pending puts lock poisoned") | |
| 10795 | + .remove(actor_scope); | |
| 10796 | + } | |
| 10797 | + *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination { | |
| 10798 | + error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."), | |
| 10799 | + actor_scope, | |
| 10800 | + context_id: context.continuation_id(), | |
| 10801 | + }); | |
| 10802 | + scope.terminate_execution(); | |
| 10803 | +} | |
| 10804 | + | |
| 10805 | +fn op_log( | |
| 10806 | + scope: &mut v8::PinScope, | |
| 10807 | + args: v8::FunctionCallbackArguments, | |
| 10808 | + _rv: v8::ReturnValue<v8::Value>, | |
| 10809 | +) { | |
| 10810 | + let msg: Vec<String> = (0..args.length()) | |
| 10811 | + .map(|i| args.get(i).to_rust_string_lossy(scope)) | |
| 10812 | + .collect(); | |
| 10813 | + let body = msg.join(" "); | |
| 10814 | + // Correlated by CPED, so a continuation logging after an await — or | |
| 10815 | + // another entry's continuation running in this turn's checkpoint — | |
| 10816 | + // lands on the trace that owns it, not on whoever holds the isolate. | |
| 10817 | + if crate::telemetry::active() { | |
| 10818 | + if let Some(ids) = | |
| 10819 | + current_trace_context(scope).and_then(crate::telemetry::TraceContext::recording_ids) | |
| 10820 | + { | |
| 10821 | + crate::telemetry::record_log(crate::telemetry::Log { | |
| 10822 | + trace_id: Some(ids.trace_id), | |
| 10823 | + span_id: Some(ids.span_id), | |
| 10824 | + time_unix_us: crate::telemetry::now_unix_us(), | |
| 10825 | + body: body.clone(), | |
| 10826 | + }); | |
| 10827 | + } | |
| 10828 | + } | |
| 10829 | + tracing::info!(target: "cell_console", "{}", body); | |
| 10830 | +} | |
| 10831 | +fn op_heap_limit_excessively_exceeded( | |
| 10832 | + scope: &mut v8::PinScope, | |
| 10833 | + _args: v8::FunctionCallbackArguments, | |
| 10834 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10835 | +) { | |
| 10836 | + let exceeded = scope | |
| 10837 | + .get_slot::<Arc<HeapLimitState>>() | |
| 10838 | + .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed)); | |
| 10839 | + rv.set(v8::Boolean::new(scope, exceeded).into()); | |
| 10840 | +} | |
| 10841 | +/// Whether this isolate is too close to its heap limit to retain more state. | |
| 10842 | +fn op_heap_over_admission_share( | |
| 10843 | + scope: &mut v8::PinScope, | |
| 10844 | + _args: v8::FunctionCallbackArguments, | |
| 10845 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 10846 | +) { | |
| 10847 | + let state = scope.get_slot::<Arc<HeapLimitState>>().cloned(); | |
| 10848 | + let over = match state { | |
| 10849 | + // A condemned isolate admits nothing, whatever the heap now reads. | |
| 10850 | + Some(state) | |
| 10851 | + if state.excessively_exceeded.load(Ordering::Relaxed) | |
| 10852 | + || admission_refusal_forced(&state) => | |
| 10853 | + { | |
| 10854 | + true | |
| 10855 | + } | |
| 10856 | + Some(state) => heap_share(scope, state.limit) >= HEAP_ADMISSION_SHARE, | |
| 10857 | + None => false, | |
| 10858 | + }; | |
| 10859 | + rv.set(v8::Boolean::new(scope, over).into()); | |
| 10860 | +} | |
| 10861 | +#[cfg(celld_internal_tests)] | |
| 10862 | +fn op_test_set_heap_limit_excessively_exceeded( | |
| 10863 | + scope: &mut v8::PinScope, | |
| 10864 | + args: v8::FunctionCallbackArguments, | |
| 10865 | + _rv: v8::ReturnValue<v8::Value>, | |
| 10866 | +) { | |
| 10867 | + if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() { | |
| 10868 | + state | |
| 10869 | + .excessively_exceeded | |
| 10870 | + .store(args.get(0).boolean_value(scope), Ordering::Relaxed); | |
| 10871 | + } | |
| 10872 | +} | |
| 10873 | +#[cfg(celld_internal_tests)] | |
| 10874 | +fn op_test_force_heap_admission_refusal( | |
| 10875 | + scope: &mut v8::PinScope, | |
| 10876 | + args: v8::FunctionCallbackArguments, | |
| 10877 | + _rv: v8::ReturnValue<v8::Value>, | |
| 10878 | +) { | |
| 10879 | + if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() { | |
| 10880 | + state | |
| 10881 | + .forced_admission_refusal | |
| 10882 | + .store(args.get(0).boolean_value(scope), Ordering::Relaxed); | |
| 10883 | + } | |
| 10884 | +} | |
| 10885 | +#[cfg(celld_internal_tests)] | |
| 10886 | +fn op_test_gc( | |
| 10887 | + scope: &mut v8::PinScope, | |
| 10888 | + _args: v8::FunctionCallbackArguments, | |
| 10889 | + _rv: v8::ReturnValue<v8::Value>, | |
| 10890 | +) { | |
| 10891 | + scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full); | |
| 10892 | +} | |
| 10893 | + | |
| 10894 | +#[cfg(celld_internal_tests)] | |
| 10895 | +thread_local! { | |
| 10896 | + static FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION: std::cell::Cell<bool> = const { | |
| 10897 | + std::cell::Cell::new(false) | |
| 10898 | + }; | |
| 10899 | + static FAIL_NEXT_WORKFLOW_META_CREATION: std::cell::Cell<bool> = const { | |
| 10900 | + std::cell::Cell::new(false) | |
| 10901 | + }; | |
| 10902 | + static FAIL_NEXT_WORKFLOW_ALARM_DELETION: std::cell::Cell<bool> = const { | |
| 10903 | + std::cell::Cell::new(false) | |
| 10904 | + }; | |
| 10905 | + static FAIL_NEXT_QUEUE_DLQ_ACCEPT: std::cell::Cell<bool> = const { | |
| 10906 | + std::cell::Cell::new(false) | |
| 10907 | + }; | |
| 10908 | + static QUEUE_DLQ_ACCEPT_CALLS: std::cell::Cell<usize> = const { | |
| 10909 | + std::cell::Cell::new(0) | |
| 10910 | + }; | |
| 10911 | + static QUEUE_METRICS_MATERIALIZED: std::cell::Cell<bool> = const { | |
| 10912 | + std::cell::Cell::new(false) | |
| 10913 | + }; | |
| 10914 | + static QUEUE_PRODUCER_GROUPS: std::cell::RefCell<Vec<(usize, usize)>> = const { | |
| 10915 | + std::cell::RefCell::new(Vec::new()) | |
| 10916 | + }; | |
| 10917 | + static QUEUE_PRODUCER_WRITE_POSITIONS: std::cell::RefCell<Vec<Option<u64>>> = const { | |
| 10918 | + std::cell::RefCell::new(Vec::new()) | |
| 10919 | + }; | |
| 10920 | + static QUEUE_REARM_OBSERVED: std::cell::Cell<bool> = const { | |
| 10921 | + std::cell::Cell::new(false) | |
| 10922 | + }; | |
| 10923 | + static QUEUE_REARM_POSITIVE: std::cell::Cell<bool> = const { | |
| 10924 | + std::cell::Cell::new(false) | |
| 10925 | + }; | |
| 10926 | + static QUEUE_REARM_BOUND_VIOLATED: std::cell::Cell<bool> = const { | |
| 10927 | + std::cell::Cell::new(false) | |
| 10928 | + }; | |
| 10929 | + static QUEUE_SETTLEMENT_POLICY_OBSERVED: std::cell::Cell<bool> = const { | |
| 10930 | + std::cell::Cell::new(false) | |
| 10931 | + }; | |
| 10932 | + static QUEUE_LEASE_LOOKUP_PLANS: std::cell::RefCell<Vec<String>> = const { | |
| 10933 | + std::cell::RefCell::new(Vec::new()) | |
| 10934 | + }; | |
| 10935 | +} | |
| 10936 | + | |
| 10937 | +#[cfg(celld_internal_tests)] | |
| 10938 | +#[doc(hidden)] | |
| 10939 | +pub fn fail_next_workflow_event_consumption_for_test() { | |
| 10940 | + FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION.with(|fail| fail.set(true)); | |
| 10941 | +} | |
| 10942 | + | |
| 10943 | +#[cfg(celld_internal_tests)] | |
| 10944 | +#[doc(hidden)] | |
| 10945 | +pub fn fail_next_workflow_meta_creation_for_test() { | |
| 10946 | + FAIL_NEXT_WORKFLOW_META_CREATION.with(|fail| fail.set(true)); | |
| 10947 | +} | |
| 10948 | + | |
| 10949 | +#[cfg(celld_internal_tests)] | |
| 10950 | +#[doc(hidden)] | |
| 10951 | +pub fn fail_next_workflow_alarm_deletion_for_test() { | |
| 10952 | + FAIL_NEXT_WORKFLOW_ALARM_DELETION.with(|fail| fail.set(true)); | |
| 10953 | +} | |
| 10954 | + | |
| 10955 | +#[cfg(celld_internal_tests)] | |
| 10956 | +#[doc(hidden)] | |
| 10957 | +pub fn fail_next_queue_dlq_accept_for_test() { | |
| 10958 | + FAIL_NEXT_QUEUE_DLQ_ACCEPT.with(|fail| fail.set(true)); | |
| 10959 | +} | |
| 10960 | + | |
| 10961 | +#[cfg(celld_internal_tests)] | |
| 10962 | +pub fn reset_queue_dlq_accept_calls_for_test() { | |
| 10963 | + QUEUE_DLQ_ACCEPT_CALLS.with(|calls| calls.set(0)); | |
| 10964 | +} | |
| 10965 | + | |
| 10966 | +#[cfg(celld_internal_tests)] | |
| 10967 | +#[doc(hidden)] | |
| 10968 | +pub fn queue_dlq_accept_calls_for_test() -> usize { | |
| 10969 | + QUEUE_DLQ_ACCEPT_CALLS.with(std::cell::Cell::get) | |
| 10970 | +} | |
| 10971 | + | |
| 10972 | +#[cfg(celld_internal_tests)] | |
| 10973 | +pub fn reset_queue_hot_path_observations_for_test() { | |
| 10974 | + QUEUE_METRICS_MATERIALIZED.with(|observed| observed.set(false)); | |
| 10975 | + QUEUE_REARM_OBSERVED.with(|observed| observed.set(false)); | |
| 10976 | + QUEUE_REARM_POSITIVE.with(|observed| observed.set(false)); | |
| 10977 | + QUEUE_REARM_BOUND_VIOLATED.with(|violated| violated.set(false)); | |
| 10978 | +} | |
| 10979 | + | |
| 10980 | +#[cfg(celld_internal_tests)] | |
| 10981 | +#[doc(hidden)] | |
| 10982 | +pub fn queue_hot_path_observations_for_test() -> (bool, bool, bool) { | |
| 10983 | + let materialized = QUEUE_METRICS_MATERIALIZED.with(std::cell::Cell::get); | |
| 10984 | + let bounded = QUEUE_REARM_OBSERVED.with(std::cell::Cell::get) | |
| 10985 | + && QUEUE_REARM_POSITIVE.with(std::cell::Cell::get) | |
| 10986 | + && !QUEUE_REARM_BOUND_VIOLATED.with(std::cell::Cell::get); | |
| 10987 | + let violated = QUEUE_REARM_BOUND_VIOLATED.with(std::cell::Cell::get); | |
| 10988 | + (materialized, bounded, violated) | |
| 10989 | +} | |
| 10990 | + | |
| 10991 | +#[cfg(celld_internal_tests)] | |
| 10992 | +pub fn reset_queue_producer_groups_for_test() { | |
| 10993 | + QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow_mut().clear()); | |
| 10994 | + QUEUE_PRODUCER_WRITE_POSITIONS.with(|positions| positions.borrow_mut().clear()); | |
| 10995 | +} | |
| 10996 | + | |
| 10997 | +#[cfg(celld_internal_tests)] | |
| 10998 | +#[doc(hidden)] | |
| 10999 | +pub fn queue_producer_groups_for_test() -> Vec<(usize, usize)> { | |
| 11000 | + QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow().clone()) | |
| 11001 | +} | |
| 11002 | + | |
| 11003 | +#[cfg(celld_internal_tests)] | |
| 11004 | +#[doc(hidden)] | |
| 11005 | +pub fn queue_producer_write_positions_for_test() -> Vec<Option<u64>> { | |
| 11006 | + QUEUE_PRODUCER_WRITE_POSITIONS.with(|positions| positions.borrow().clone()) | |
| 11007 | +} | |
| 11008 | + | |
| 11009 | +#[cfg(celld_internal_tests)] | |
| 11010 | +#[doc(hidden)] | |
| 11011 | +pub fn reset_queue_lease_lookup_plans_for_test() { | |
| 11012 | + QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow_mut().clear()); | |
| 11013 | +} | |
| 11014 | + | |
| 11015 | +#[cfg(celld_internal_tests)] | |
| 11016 | +#[doc(hidden)] | |
| 11017 | +pub fn queue_lease_lookup_plans_for_test() -> Vec<String> { | |
| 11018 | + QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow().clone()) | |
| 11019 | +} | |
| 11020 | + | |
| 11021 | +#[cfg(celld_internal_tests)] | |
| 11022 | +#[doc(hidden)] | |
| 11023 | +pub fn reset_queue_settlement_policy_observation_for_test() { | |
| 11024 | + QUEUE_SETTLEMENT_POLICY_OBSERVED.with(|observed| observed.set(false)); | |
| 11025 | +} | |
| 11026 | + | |
| 11027 | +#[cfg(celld_internal_tests)] | |
| 11028 | +#[doc(hidden)] | |
| 11029 | +pub fn queue_settlement_policy_observed_for_test() -> bool { | |
| 11030 | + QUEUE_SETTLEMENT_POLICY_OBSERVED.with(std::cell::Cell::get) | |
| 11031 | +} | |
| 11032 | + | |
| 11033 | +#[cfg(celld_internal_tests)] | |
| 11034 | +fn op_test_workflow_event_consumed( | |
| 11035 | + scope: &mut v8::PinScope, | |
| 11036 | + _args: v8::FunctionCallbackArguments, | |
| 11037 | + _rv: v8::ReturnValue<v8::Value>, | |
| 11038 | +) { | |
| 11039 | + let fail = FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION.with(|fail| fail.replace(false)); | |
| 11040 | + if fail { | |
| 11041 | + throw_storage_error( | |
| 11042 | + scope, | |
| 11043 | + "workflow event consumption", | |
| 11044 | + "injected failure after workflow event delete", | |
| 11045 | + ); | |
| 11046 | + } | |
| 11047 | +} | |
| 11048 | + | |
| 11049 | +#[cfg(celld_internal_tests)] | |
| 11050 | +fn op_test_workflow_meta_created( | |
| 11051 | + scope: &mut v8::PinScope, | |
| 11052 | + _args: v8::FunctionCallbackArguments, | |
| 11053 | + _rv: v8::ReturnValue<v8::Value>, | |
| 11054 | +) { | |
| 11055 | + let fail = FAIL_NEXT_WORKFLOW_META_CREATION.with(|fail| fail.replace(false)); | |
| 11056 | + if fail { | |
| 11057 | + throw_storage_error( | |
| 11058 | + scope, | |
| 11059 | + "workflow creation", | |
| 11060 | + "injected failure after workflow metadata write", | |
| 11061 | + ); | |
| 11062 | + } | |
| 11063 | +} | |
| 11064 | + | |
| 11065 | +#[cfg(celld_internal_tests)] | |
| 11066 | +fn op_test_workflow_alarm_deleted( | |
| 11067 | + scope: &mut v8::PinScope, | |
| 11068 | + _args: v8::FunctionCallbackArguments, | |
| 11069 | + _rv: v8::ReturnValue<v8::Value>, | |
| 11070 | +) { | |
| 11071 | + let fail = FAIL_NEXT_WORKFLOW_ALARM_DELETION.with(|fail| fail.replace(false)); | |
| 11072 | + if fail { | |
| 11073 | + throw_storage_error( | |
| 11074 | + scope, | |
| 11075 | + "workflow alarm deletion", | |
| 11076 | + "injected failure after workflow alarm delete", | |
| 11077 | + ); | |
| 11078 | + } | |
| 11079 | +} | |
| 11080 | + | |
| 11081 | +#[cfg(celld_internal_tests)] | |
| 11082 | +fn op_test_queue_dlq_accepted( | |
| 11083 | + scope: &mut v8::PinScope, | |
| 11084 | + _args: v8::FunctionCallbackArguments, | |
| 11085 | + _rv: v8::ReturnValue<v8::Value>, | |
| 11086 | +) { | |
| 11087 | + QUEUE_DLQ_ACCEPT_CALLS.with(|calls| calls.set(calls.get() + 1)); | |
| 11088 | + let fail = FAIL_NEXT_QUEUE_DLQ_ACCEPT.with(|fail| fail.replace(false)); | |
| 11089 | + if fail { | |
| 11090 | + throw_storage_error( | |
| 11091 | + scope, | |
| 11092 | + "Queue DLQ transfer", | |
| 11093 | + "injected failure after the target accepted the message", | |
| 11094 | + ); | |
| 11095 | + } | |
| 11096 | +} | |
| 11097 | + | |
| 11098 | +#[cfg(celld_internal_tests)] | |
| 11099 | +fn op_test_queue_metrics_materialized( | |
| 11100 | + _scope: &mut v8::PinScope, | |
| 11101 | + _args: v8::FunctionCallbackArguments, | |
| 11102 | + _rv: v8::ReturnValue<v8::Value>, | |
| 11103 | +) { | |
| 11104 | + QUEUE_METRICS_MATERIALIZED.with(|observed| observed.set(true)); | |
| 11105 | +} | |
| 11106 | + | |
| 11107 | +#[cfg(celld_internal_tests)] | |
| 11108 | +fn op_test_queue_producer_group( | |
| 11109 | + scope: &mut v8::PinScope, | |
| 11110 | + args: v8::FunctionCallbackArguments, | |
| 11111 | + _rv: v8::ReturnValue<v8::Value>, | |
| 11112 | +) { | |
| 11113 | + let calls = args.get(0).integer_value(scope).unwrap_or(0).max(0) as usize; | |
| 11114 | + let messages = args.get(1).integer_value(scope).unwrap_or(0).max(0) as usize; | |
| 11115 | + QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow_mut().push((calls, messages))); | |
| 11116 | +} | |
| 11117 | + | |
| 11118 | +#[cfg(celld_internal_tests)] | |
| 11119 | +fn op_test_queue_lease_lookup_plan( | |
| 11120 | + scope: &mut v8::PinScope, | |
| 11121 | + args: v8::FunctionCallbackArguments, | |
| 11122 | + _rv: v8::ReturnValue<v8::Value>, | |
| 11123 | +) { | |
| 11124 | + let plan = args.get(0).to_rust_string_lossy(scope); | |
| 11125 | + QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow_mut().push(plan)); | |
| 11126 | +} | |
| 11127 | + | |
| 11128 | +#[cfg(celld_internal_tests)] | |
| 11129 | +fn op_test_queue_rearm_bounded( | |
| 11130 | + scope: &mut v8::PinScope, | |
| 11131 | + args: v8::FunctionCallbackArguments, | |
| 11132 | + _rv: v8::ReturnValue<v8::Value>, | |
| 11133 | +) { | |
| 11134 | + QUEUE_REARM_OBSERVED.with(|observed| observed.set(true)); | |
| 11135 | + QUEUE_REARM_POSITIVE.with(|observed| observed.set(observed.get() || args.get(1).is_true())); | |
| 11136 | + if !args.get(0).boolean_value(scope) { | |
| 11137 | + QUEUE_REARM_BOUND_VIOLATED.with(|violated| violated.set(true)); | |
| 11138 | + } | |
| 11139 | +} | |
| 11140 | +mod r2_ops; | |
| 11141 | +mod storage_ops; | |
| 11142 | +use storage_ops::{actor_runtime_state, throw_storage_error}; | |
| 11143 | + | |
| 11144 | +/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href} | |
| 11145 | +/// Backed by the WHATWG-conformant `url` crate. | |
| 11146 | +fn op_url_parse( | |
| 11147 | + scope: &mut v8::PinScope, | |
| 11148 | + args: v8::FunctionCallbackArguments, | |
| 11149 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 11150 | +) { | |
| 11151 | + let input = args.get(0).to_rust_string_lossy(scope); | |
| 11152 | + let base = args.get(1); | |
| 11153 | + let parsed = if base.is_undefined() { | |
| 11154 | + url::Url::parse(&input) | |
| 11155 | + } else { | |
| 11156 | + url::Url::options() | |
| 11157 | + .base_url( | |
| 11158 | + url::Url::parse(&base.to_rust_string_lossy(scope)) | |
| 11159 | + .ok() | |
| 11160 | + .as_ref(), | |
| 11161 | + ) | |
| 11162 | + .parse(&input) | |
| 11163 | + }; | |
| 11164 | + let u = match parsed { | |
| 11165 | + Ok(u) => u, | |
| 11166 | + Err(e) => { | |
| 11167 | + let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap(); | |
| 11168 | + let exc = v8::Exception::type_error(scope, msg); | |
| 11169 | + scope.throw_exception(exc); | |
| 11170 | + return; | |
| 11171 | + } | |
| 11172 | + }; | |
| 11173 | + let o = v8::Object::new(scope); | |
| 11174 | + // The nine keys are fixed, so they come from the constant table rather | |
| 11175 | + // than from nine fresh `v8::String`s per `new URL(...)`. | |
| 11176 | + // | |
| 11177 | + // A set can still fail — a throwing setter on `Object.prototype` reaches | |
| 11178 | + // this plain object — and a URL record missing a component is worse than | |
| 11179 | + // no record at all, so the first refusal stops the build. | |
| 11180 | + let port = u.port().map(|p| p.to_string()).unwrap_or_default(); | |
| 11181 | + let fields: [(&'static v8::OneByteConst, &str); 9] = [ | |
| 11182 | + (&v8_strings::URL_PROTOCOL, u.scheme()), | |
| 11183 | + (&v8_strings::URL_USERNAME, u.username()), | |
| 11184 | + (&v8_strings::URL_PASSWORD, u.password().unwrap_or("")), | |
| 11185 | + (&v8_strings::URL_HOST, u.host_str().unwrap_or("")), | |
| 11186 | + (&v8_strings::URL_PORT, &port), | |
| 11187 | + (&v8_strings::URL_PATHNAME, u.path()), | |
| 11188 | + (&v8_strings::URL_SEARCH, u.query().unwrap_or("")), | |
| 11189 | + (&v8_strings::URL_HASH, u.fragment().unwrap_or("")), | |
| 11190 | + (&v8_strings::URL_HREF, u.as_str()), | |
| 11191 | + ]; | |
| 11192 | + for (k, v) in fields { | |
| 11193 | + let key = static_key(scope, k); | |
| 11194 | + let val = v8::String::new(scope, v).unwrap(); | |
| 11195 | + match o.set(scope, key.into(), val.into()) { | |
| 11196 | + Some(true) => {} | |
| 11197 | + // The setter threw. Its exception is already pending, and it names | |
| 11198 | + // the real cause, so it propagates unchanged. Throwing a generic | |
| 11199 | + // TypeError here would overwrite it and hide that cause. | |
| 11200 | + None => return, | |
| 11201 | + // A refusal that does not throw — a non-writable inherited data | |
| 11202 | + // property, in sloppy mode — leaves no pending exception, so this | |
| 11203 | + // path has to raise one of its own. | |
| 11204 | + Some(false) => { | |
| 11205 | + let name = key.to_rust_string_lossy(scope); | |
| 11206 | + let msg = v8::String::new( | |
| 11207 | + scope, | |
| 11208 | + &format!("Invalid URL: the {name} property of the URL record was refused"), | |
| 11209 | + ) | |
| 11210 | + .unwrap(); | |
| 11211 | + let exc = v8::Exception::type_error(scope, msg); | |
| 11212 | + scope.throw_exception(exc); | |
| 11213 | + return; | |
| 11214 | + } | |
| 11215 | + } | |
| 11216 | + } | |
| 11217 | + rv.set(o.into()); | |
| 11218 | +} | |
| 11219 | + | |
| 11220 | +// URLPattern host seam, split like Deno's: pattern parsing and match-input | |
| 11221 | +// canonicalization run in Rust via the `urlpattern` crate; per-match regex | |
| 11222 | +// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the | |
| 11223 | +// boundary — both ops run at construct/match-canonicalize time only. | |
| 11224 | + | |
| 11225 | +/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a | |
| 11226 | +/// pattern string or an init object of string components. Returns | |
| 11227 | +/// per-component `{ patternString, regexpString, groupNameList }` plus | |
| 11228 | +/// `hasRegexpGroups`. Throws TypeError on an invalid pattern. | |
| 11229 | +fn op_urlpattern_parse( | |
| 11230 | + scope: &mut v8::PinScope, | |
| 11231 | + args: v8::FunctionCallbackArguments, | |
| 11232 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 11233 | +) { | |
| 11234 | + use urlpattern::quirks; | |
| 11235 | + let input = args.get(0).to_rust_string_lossy(scope); | |
| 11236 | + let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap(); | |
| 11237 | + let base = args.get(1); | |
| 11238 | + let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope)); | |
| 11239 | + let options = urlpattern::UrlPatternOptions { | |
| 11240 | + ignore_case: args.get(2).boolean_value(scope), | |
| 11241 | + }; | |
| 11242 | + let pattern = quirks::process_construct_pattern_input(input, base.as_deref()) | |
| 11243 | + .and_then(|init| quirks::parse_pattern(init, options)); | |
| 11244 | + let p = match pattern { | |
| 11245 | + Ok(p) => p, | |
| 11246 | + Err(e) => { | |
| 11247 | + let msg = v8::String::new(scope, &e.to_string()).unwrap(); | |
| 11248 | + let exc = v8::Exception::type_error(scope, msg); | |
| 11249 | + scope.throw_exception(exc); | |
| 11250 | + return; | |
| 11251 | + } | |
| 11252 | + }; | |
| 11253 | + let component = |c: &quirks::UrlPatternComponent| { | |
| 11254 | + serde_json::json!({ | |
| 11255 | + "patternString": c.pattern_string, | |
| 11256 | + "regexpString": c.regexp_string, | |
| 11257 | + "groupNameList": c.group_name_list, | |
| 11258 | + }) | |
| 11259 | + }; | |
| 11260 | + let out = serde_json::json!({ | |
| 11261 | + "protocol": component(&p.protocol), | |
| 11262 | + "username": component(&p.username), | |
| 11263 | + "password": component(&p.password), | |
| 11264 | + "hostname": component(&p.hostname), | |
| 11265 | + "port": component(&p.port), | |
| 11266 | + "pathname": component(&p.pathname), | |
| 11267 | + "search": component(&p.search), | |
| 11268 | + "hash": component(&p.hash), | |
| 11269 | + "hasRegexpGroups": p.has_regexp_groups, | |
| 11270 | + }); | |
| 11271 | + rv.set(v8::String::new(scope, &out.to_string()).unwrap().into()); | |
| 11272 | +} | |
| 11273 | + | |
| 11274 | +/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in | |
| 11275 | +/// component order (protocol..hash), or `null` when the input does not parse | |
| 11276 | +/// as a URL. Throws TypeError for an init combined with a baseURL argument. | |
| 11277 | +fn op_urlpattern_match_input( | |
| 11278 | + scope: &mut v8::PinScope, | |
| 11279 | + args: v8::FunctionCallbackArguments, | |
| 11280 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 11281 | +) { | |
| 11282 | + use urlpattern::quirks; | |
| 11283 | + let input = args.get(0).to_rust_string_lossy(scope); | |
| 11284 | + let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap(); | |
| 11285 | + let base = args.get(1); | |
| 11286 | + let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope)); | |
| 11287 | + let null = v8::null(scope).into(); | |
| 11288 | + let m = match quirks::process_match_input(input, base.as_deref()) { | |
| 11289 | + Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) { | |
| 11290 | + Some(m) => m, | |
| 11291 | + None => return rv.set(null), | |
| 11292 | + }, | |
| 11293 | + Ok(None) => return rv.set(null), | |
| 11294 | + Err(e) => { | |
| 11295 | + let msg = v8::String::new(scope, &e.to_string()).unwrap(); | |
| 11296 | + let exc = v8::Exception::type_error(scope, msg); | |
| 11297 | + scope.throw_exception(exc); | |
| 11298 | + return; | |
| 11299 | + } | |
| 11300 | + }; | |
| 11301 | + let out = serde_json::json!([ | |
| 11302 | + m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash, | |
| 11303 | + ]); | |
| 11304 | + rv.set(v8::String::new(scope, &out.to_string()).unwrap().into()); | |
| 11305 | +} | |
| 11306 | + | |
| 11307 | +fn op_atob( | |
| 11308 | + scope: &mut v8::PinScope, | |
| 11309 | + args: v8::FunctionCallbackArguments, | |
| 11310 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 11311 | +) { | |
| 11312 | + use base64::Engine; | |
| 11313 | + let input = args.get(0).to_rust_string_lossy(scope); | |
| 11314 | + let cleaned: String = input.chars().filter(|c| !c.is_whitespace()).collect(); | |
| 11315 | + match base64::engine::general_purpose::STANDARD.decode(cleaned) { | |
| 11316 | + Ok(bytes) => { | |
| 11317 | + // The public `atob()` wrapper omits this argument and keeps the | |
| 11318 | + // required binary-string result. The KV operator protocol asks | |
| 11319 | + // for a typed view, so a 25 MiB value does not become 25 million | |
| 11320 | + // JavaScript numbers before the cell can store it. | |
| 11321 | + if args.get(1).boolean_value(scope) { | |
| 11322 | + rv.set(bytes_value(scope, bytes)); | |
| 11323 | + return; | |
| 11324 | + } | |
| 11325 | + // atob returns a binary string (latin1) | |
| 11326 | + let s: String = bytes.iter().map(|&b| b as char).collect(); | |
| 11327 | + rv.set(v8::String::new(scope, &s).unwrap().into()); | |
| 11328 | + } | |
| 11329 | + Err(_) => { | |
| 11330 | + let msg = v8::String::new(scope, "Invalid base64").unwrap(); | |
| 11331 | + let exc = v8::Exception::error(scope, msg); | |
| 11332 | + scope.throw_exception(exc); | |
| 11333 | + } | |
| 11334 | + } | |
| 11335 | +} | |
| 11336 | + | |
| 11337 | +// node:util introspection seam: V8-level queries that JS cannot perform, | |
| 11338 | +// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy | |
| 11339 | +// node:async_hooks prelude calls these. The value is V8's | |
| 11340 | +// continuation-preserved embedder data — the primitive Workerd's | |
| 11341 | +// AsyncContextFrame rides — which V8 itself captures and restores | |
| 11342 | +// around every promise reaction. No promise hooks are installed. A stateless | |
| 11343 | +// isolate that never touches AsyncLocalStorage leaves the frame absent; a cell | |
| 11344 | +// event still carries the separate native context token described below. | |
| 11345 | + | |
| 11346 | +#[derive(Default)] | |
| 11347 | +struct IoEventFrame { | |
| 11348 | + wait_until: Vec<v8::Global<v8::Promise>>, | |
| 11349 | + arm_gates: Vec<ArmGateRx>, | |
| 11350 | +} | |
| 11351 | + | |
| 11352 | +#[derive(Default)] | |
| 11353 | +struct IoEventState { | |
| 11354 | + frames: Vec<IoEventFrame>, | |
| 11355 | + ended_arm_gates: Vec<ArmGateRx>, | |
| 11356 | + arm_gates_sealed: bool, | |
| 11357 | +} | |
| 11358 | + | |
| 11359 | +/// The writable directory subset of Workerd's per-request virtual filesystem. | |
| 11360 | +/// | |
| 11361 | +/// The first compatibility slice stores directories only. Keeping the tree on | |
| 11362 | +/// `IoContext` is the isolation mechanism: async continuations for one request | |
| 11363 | +/// share it, while a concurrent or later request receives a different tree. | |
| 11364 | +/// No path can escape into the host filesystem. | |
| 11365 | +struct RequestVfs { | |
| 11366 | + nodes: HashMap<String, VfsNode>, | |
| 11367 | +} | |
| 11368 | + | |
| 11369 | +/// Keep the node kind in the tree, even while the first slice can only create | |
| 11370 | +/// directories. Deno's VFS uses the same entry-typed shape; a path-only set | |
| 11371 | +/// would make a later file node indistinguishable from its parent directory. | |
| 11372 | +enum VfsNode { | |
| 11373 | + Directory { writable: bool }, | |
| 11374 | +} | |
| 11375 | + | |
| 11376 | +/// The read-only `/bundle` projection of a worker's own modules. | |
| 11377 | +/// | |
| 11378 | +/// This is isolate state, not request state. The bytes are immutable and | |
| 11379 | +/// identical for every request the isolate serves, so building the tree per | |
| 11380 | +/// request would repeat the work and re-copy every module body. `BundleFs` | |
| 11381 | +/// below keeps one `Arc` and hands a clone to each reader. | |
| 11382 | +struct BundleTree { | |
| 11383 | + nodes: HashMap<String, BundleNode>, | |
| 11384 | +} | |
| 11385 | + | |
| 11386 | +/// A projected node. A file owns `Bytes` so a read is a refcount bump rather | |
| 11387 | +/// than a copy, and so a wasm module's bytes are shared with the config | |
| 11388 | +/// instead of duplicated. | |
| 11389 | +enum BundleNode { | |
| 11390 | + Directory, | |
| 11391 | + File(bytes::Bytes), | |
| 11392 | +} | |
| 11393 | + | |
| 11394 | +/// The bundle tree and the config it projects, materialized on first use. | |
| 11395 | +/// | |
| 11396 | +/// Workerd builds `/bundle` through a lazy directory for the same reason (see | |
| 11397 | +/// `getBundleDirectory` in `src/workerd/io/bundle-fs.c++`): a worker that never | |
| 11398 | +/// calls `node:fs` must not pay to walk its module list or to copy a module | |
| 11399 | +/// body into the filesystem. Holding the `Arc<WorkerConfig>` keeps the source | |
| 11400 | +/// alive, so materialization does not need its own copy of a module name. | |
| 11401 | +struct BundleFs { | |
| 11402 | + config: Arc<WorkerConfig>, | |
| 11403 | + tree: OnceLock<Arc<BundleTree>>, | |
| 11404 | +} | |
| 11405 | + | |
| 11406 | +impl BundleFs { | |
| 11407 | + /// Materialize once, then share. Returns an `Arc` clone so a caller can | |
| 11408 | + /// read without holding an isolate borrow across the read. | |
| 11409 | + fn tree(&self) -> Arc<BundleTree> { | |
| 11410 | + self.tree | |
| 11411 | + .get_or_init(|| Arc::new(BundleTree::project(&self.config))) | |
| 11412 | + .clone() | |
| 11413 | + } | |
| 11414 | +} | |
| 11415 | + | |
| 11416 | +impl BundleTree { | |
| 11417 | + /// Project every bundle module into `/bundle`, keyed by its name as a path. | |
| 11418 | + /// | |
| 11419 | + /// A module name is a path, not a flat key: workerd parses it against | |
| 11420 | + /// `file:///`, so `a/esModule` becomes `/bundle/a/esModule` and creates the | |
| 11421 | + /// intervening directory. The entry module is projected under the name it | |
| 11422 | + /// compiles as, matching workerd's `mainScriptName` entry. | |
| 11423 | + fn project(config: &WorkerConfig) -> Self { | |
| 11424 | + let mut nodes = HashMap::new(); | |
| 11425 | + nodes.insert("/bundle".to_string(), BundleNode::Directory); | |
| 11426 | + let entry = std::iter::once(( | |
| 11427 | + ENTRY_MODULE_NAME, | |
| 11428 | + bytes::Bytes::copy_from_slice(config.src.as_bytes()), | |
| 11429 | + )); | |
| 11430 | + let modules = config.modules.iter().map(|(name, source)| { | |
| 11431 | + let bytes = match source { | |
| 11432 | + // A text or ES module body is a `String` in the config, so the | |
| 11433 | + // projection copies it once per isolate. A wasm body is already | |
| 11434 | + // `Bytes`, so it is shared rather than copied. | |
| 11435 | + ModuleSource::Text(source) | ModuleSource::EsModule(source) => { | |
| 11436 | + bytes::Bytes::copy_from_slice(source.as_bytes()) | |
| 11437 | + } | |
| 11438 | + ModuleSource::Wasm(bytes) => bytes.clone(), | |
| 11439 | + }; | |
| 11440 | + (name.as_str(), bytes) | |
| 11441 | + }); | |
| 11442 | + for (name, bytes) in entry.chain(modules) { | |
| 11443 | + // A leading or doubled separator would otherwise create an empty | |
| 11444 | + // segment, which no path can address. | |
| 11445 | + let segments: Vec<&str> = name.split('/').filter(|part| !part.is_empty()).collect(); | |
| 11446 | + let Some((file, directories)) = segments.split_last() else { | |
| 11447 | + continue; | |
| 11448 | + }; | |
| 11449 | + let mut path = String::from("/bundle"); | |
| 11450 | + for directory in directories { | |
| 11451 | + path.push('/'); | |
| 11452 | + path.push_str(directory); | |
| 11453 | + nodes.entry(path.clone()).or_insert(BundleNode::Directory); | |
| 11454 | + } | |
| 11455 | + path.push('/'); | |
| 11456 | + path.push_str(file); | |
| 11457 | + nodes.insert(path, BundleNode::File(bytes)); | |
| 11458 | + } | |
| 11459 | + Self { nodes } | |
| 11460 | + } | |
| 11461 | +} | |
| 11462 | + | |
| 11463 | +enum VfsMkdirResult { | |
| 11464 | + Created(Option<String>), | |
| 11465 | + Error(&'static str), | |
| 11466 | +} | |
| 11467 | + | |
| 11468 | +impl Default for RequestVfs { | |
| 11469 | + fn default() -> Self { | |
| 11470 | + Self { | |
| 11471 | + nodes: [ | |
| 11472 | + ("/", false), | |
| 11473 | + ("/bundle", false), | |
| 11474 | + ("/dev", false), | |
| 11475 | + ("/tmp", true), | |
| 11476 | + ] | |
| 11477 | + .into_iter() | |
| 11478 | + .map(|(path, writable)| (path.to_string(), VfsNode::Directory { writable })) | |
| 11479 | + .collect(), | |
| 11480 | + } | |
| 11481 | + } | |
| 11482 | +} | |
| 11483 | + | |
| 11484 | +struct InputGateClaims { | |
| 11485 | + /// Set before the turn owner releases its final `IoContext` owner. The | |
| 11486 | + /// watch wakes its pending gate acquisition even when the promise | |
| 11487 | + /// reaction that requested the gate belongs to another event. | |
| 11488 | + retired: bool, | |
| 11489 | + held: HashMap<celld_logic::gate::EventId, String>, | |
| 11490 | + retirement: tokio::sync::watch::Sender<bool>, | |
| 11491 | +} | |
| 11492 | + | |
| 11493 | +impl Default for InputGateClaims { | |
| 11494 | + fn default() -> Self { | |
| 11495 | + let (retirement, _) = tokio::sync::watch::channel(false); | |
| 11496 | + Self { | |
| 11497 | + retired: false, | |
| 11498 | + held: HashMap::new(), | |
| 11499 | + retirement, | |
| 11500 | + } | |
| 11501 | + } | |
| 11502 | +} | |
| 11503 | + | |
| 11504 | +impl RequestVfs { | |
| 11505 | + fn stat(&self, path: &str) -> Option<bool> { | |
| 11506 | + self.nodes.get(path).map(|node| match node { | |
| 11507 | + VfsNode::Directory { writable } => *writable, | |
| 11508 | + }) | |
| 11509 | + } | |
| 11510 | + | |
| 11511 | + fn mkdir(&mut self, path: &str, recursive: bool) -> VfsMkdirResult { | |
| 11512 | + if path != "/tmp" && !path.starts_with("/tmp/") { | |
| 11513 | + return VfsMkdirResult::Error("EPERM"); | |
| 11514 | + } | |
| 11515 | + if self.stat(path).is_some() { | |
| 11516 | + return VfsMkdirResult::Created(None); | |
| 11517 | + } | |
| 11518 | + if recursive { | |
| 11519 | + let mut current = "/tmp".to_string(); | |
| 11520 | + let mut first_created = None; | |
| 11521 | + for segment in path.trim_start_matches("/tmp/").split('/') { | |
| 11522 | + current.push('/'); | |
| 11523 | + current.push_str(segment); | |
| 11524 | + if self | |
| 11525 | + .nodes | |
| 11526 | + .insert(current.clone(), VfsNode::Directory { writable: true }) | |
| 11527 | + .is_none() | |
| 11528 | + && first_created.is_none() | |
| 11529 | + { | |
| 11530 | + first_created = Some(current.clone()); | |
| 11531 | + } | |
| 11532 | + } | |
| 11533 | + return VfsMkdirResult::Created(first_created); | |
| 11534 | + } | |
| 11535 | + let parent = | |
| 11536 | + path.rsplit_once('/').map_or( | |
| 11537 | + "/", | |
| 11538 | + |(parent, _)| { | |
| 11539 | + if parent.is_empty() { | |
| 11540 | + "/" | |
| 11541 | + } else { | |
| 11542 | + parent | |
| 11543 | + } | |
| 11544 | + }, | |
| 11545 | + ); | |
| 11546 | + if self.stat(parent).is_none() { | |
| 11547 | + return VfsMkdirResult::Error("ENOENT"); | |
| 11548 | + } | |
| 11549 | + self.nodes | |
| 11550 | + .insert(path.to_string(), VfsNode::Directory { writable: true }); | |
| 11551 | + VfsMkdirResult::Created(None) | |
| 11552 | + } | |
| 11553 | +} | |
| 11554 | + | |
| 11555 | +/// The per-request context: everything a request owns while it is in flight. | |
| 11556 | +/// | |
| 11557 | +/// Modelled on workerd's `IoContext`. The host owns it, not JS: a request's | |
| 11558 | +/// event frames and the `waitUntil` promises inside them live here, and JS | |
| 11559 | +/// reaches them only through ops that ask for the *current* context. That | |
| 11560 | +/// inversion is the point. While an isolate serves one request at a time, | |
| 11561 | +/// JS-side per-request state is indistinguishable from isolate-side state, | |
| 11562 | +/// and the two silently diverge the moment requests interleave — one | |
| 11563 | +/// request's `__endEvent` popping another's event, its `waitUntil` work | |
| 11564 | +/// attributed to a request that never asked for it. | |
| 11565 | +/// | |
| 11566 | +/// `current()` is a thread-local the host installs for the duration of a | |
| 11567 | +/// turn and restores on the way out, exactly as `threadLocalRequest` is set | |
| 11568 | +/// in `IoContext::runInContextScope` and restored by `SuppressIoContextScope`. | |
| 11569 | +/// An op that needs a context and finds none is a bug in the host, not in | |
| 11570 | +/// the script, so it says so rather than inventing one. | |
| 11571 | +/// | |
| 11572 | +/// **It is `Send + Sync`, and that is load-bearing.** Under D1 a request is | |
| 11573 | +/// a tokio task that suspends between turns and can resume on any worker, so | |
| 11574 | +/// the context it carries has to cross threads with it. `Rc` and `RefCell` | |
| 11575 | +/// would forbid that. The isolate keeps one narrow weak lookup from a CPED | |
| 11576 | +/// continuation token to this context, because a reaction can run during a | |
| 11577 | +/// different event's checkpoint. That lookup owns no context, operation, or | |
| 11578 | +/// resolver, and `IoContext::drop` removes it. It therefore attributes the | |
| 11579 | +/// running reaction without rebuilding the pump's lifetime-owning `idmap`. | |
| 11580 | +/// A cross-entry input gate is the narrow exception: it claims the originating | |
| 11581 | +/// context so the event and its resources stay active until the callback ends. | |
| 11582 | +/// The gate releases that claim when the block ends. The interiors are | |
| 11583 | +/// `Mutex`; only the isolate's holder reaches them. | |
| 11584 | +pub struct IoContext { | |
| 11585 | + /// A process-wide identity captured by V8 with each promise reaction. | |
| 11586 | + /// The process-wide cell-gate map also uses it, so another isolate must | |
| 11587 | + /// not reuse it. The isolate registry holds only a `Weak`, so a | |
| 11588 | + /// continuation does not extend the request lifetime by itself. A | |
| 11589 | + /// cross-entry input gate adds an explicit claim that prevents this | |
| 11590 | + /// context's `InFlight` from retiring while its callback still runs. | |
| 11591 | + continuation: Option<(u64, Weak<ActorRuntimeState>)>, | |
| 11592 | + /// This caller's delivery order for each cell it has called. See | |
| 11593 | + /// `CallOrder` — it is here rather than in a process-wide map because | |
| 11594 | + /// nothing outside this caller ever reads it. | |
| 11595 | + pub call_chains: Mutex<CallChains>, | |
| 11596 | + /// Event frames, innermost last. A frame collects the `waitUntil` | |
| 11597 | + /// promises registered while it is the innermost one. | |
| 11598 | + /// | |
| 11599 | + /// Nesting is per-request and strictly LIFO — a service-binding | |
| 11600 | + /// dispatch, an RPC entry, or a DO construction pushes its own frame so | |
| 11601 | + /// its `waitUntil` binds to that dispatch, matching workerd. | |
| 11602 | + events: Mutex<IoEventState>, | |
| 11603 | + /// Workerd gives every request an empty, memory-backed `/tmp`. Directory | |
| 11604 | + /// state belongs here so it follows the request across promise turns and | |
| 11605 | + /// disappears with the request instead of leaking across isolate reuse. | |
| 11606 | + /// The tree stays unallocated when the application does not use `node:fs`. | |
| 11607 | + vfs: OnceLock<Mutex<RequestVfs>>, | |
| 11608 | + /// Isolate-polled sockets this request opened. Dropping the request's | |
| 11609 | + /// pending ops aborts everything the isolate is waiting on, but a socket | |
| 11610 | + /// is a host-side resource that abort cannot reach: its connector task | |
| 11611 | + /// exits only when the isolate stops reading. So the request closes its | |
| 11612 | + /// own sockets, and [`IoContext::drop`] is what makes that unforgettable. | |
| 11613 | + /// | |
| 11614 | + /// Flat rather than a stack. Only sockets that belong to no cell land | |
| 11615 | + /// here, and one `IoContext` is one request, so there is nothing to nest: | |
| 11616 | + /// a service-binding dispatch or a Durable Object call gets a context of | |
| 11617 | + /// its own rather than a frame inside this one. | |
| 11618 | + sockets: Mutex<Vec<u64>>, | |
| 11619 | + /// HTMLRewriter instances this request created. Each holds a parked | |
| 11620 | + /// parser thread; freeing them at retirement is what reclaims the | |
| 11621 | + /// thread when a transform is abandoned unread — nothing else can, | |
| 11622 | + /// because the pending event promise roots the output stream. | |
| 11623 | + rewriters: Mutex<Vec<u64>>, | |
| 11624 | + /// Outbound TCP sockets this event opened. A socket cannot outlive | |
| 11625 | + /// its event: retirement drops the registry entries, which closes | |
| 11626 | + /// the connections. | |
| 11627 | + tcp_sockets: Mutex<Vec<u64>>, | |
| 11628 | + /// Input-gate holds and pending acquisitions for this event. | |
| 11629 | + /// | |
| 11630 | + /// The event owns the cell and host id together, and retirement wakes a | |
| 11631 | + /// pending acquisition. A timeout or cancellation can therefore abandon | |
| 11632 | + /// only its own hold and cannot resume after its event has gone away. | |
| 11633 | + input_gates: Mutex<InputGateClaims>, | |
| 11634 | + /// Blocks created by this event but run during another event's turn. | |
| 11635 | + /// These claims keep this event's native operations and resources alive; | |
| 11636 | + /// their watch wakes the drive when the final block ends. | |
| 11637 | + cross_entry_gates: CrossEntryGateClaims, | |
| 11638 | + /// Host-backed request bodies this handler owns. A subrequest transfers | |
| 11639 | + /// an id out before its target takes ownership, so only one request can | |
| 11640 | + /// reclaim an unread tail. | |
| 11641 | + body_streams: Mutex<HashMap<u64, HttpStreamClaim>>, | |
| 11642 | + /// Output-gate capture. While a `webSocketMessage` runs, the frames it | |
| 11643 | + /// sends are collected here instead of reaching the wire, so the shell | |
| 11644 | + /// can hold them until the message's write is durable. A stack, so a | |
| 11645 | + /// nested dispatch keeps its frames apart from the outer one's. | |
| 11646 | + /// | |
| 11647 | + /// On the event and not on the thread, because an event outlives the | |
| 11648 | + /// turn that began it: capture starts in one turn and is taken in a | |
| 11649 | + /// later one, which tokio may run on a different worker. | |
| 11650 | + ws_capture: Mutex<Vec<Vec<(u64, WsOut)>>>, | |
| 11651 | + /// What each running event's outbound effects gate against, innermost | |
| 11652 | + /// last. An outbound effect raised during the event consults this: if the | |
| 11653 | + /// handler has advanced the position, the effect waits for the output gate | |
| 11654 | + /// before it leaves the process. | |
| 11655 | + /// | |
| 11656 | + /// Empty for stateless Worker code, which owns no cell and gates | |
| 11657 | + /// nothing. | |
| 11658 | + egress: Mutex<Vec<EgressFrame>>, | |
| 11659 | +} | |
| 11660 | + | |
| 11661 | +impl IoContext { | |
| 11662 | + /// The continuation id this context is registered under, which names | |
| 11663 | + /// the event to the cell's gate. `None` for a context V8 never captures. | |
| 11664 | + fn continuation_id(&self) -> Option<u64> { | |
| 11665 | + self.continuation.as_ref().map(|(id, _)| *id) | |
| 11666 | + } | |
| 11667 | + | |
| 11668 | + #[allow(clippy::new_ret_no_self, clippy::new_without_default)] | |
| 11669 | + #[doc(hidden)] | |
| 11670 | + pub fn new() -> Arc<Self> { | |
| 11671 | + Arc::new(Self { | |
| 11672 | + continuation: None, | |
| 11673 | + call_chains: Mutex::new(CallChains::default()), | |
| 11674 | + events: Mutex::new(IoEventState::default()), | |
| 11675 | + vfs: OnceLock::new(), | |
| 11676 | + sockets: Mutex::new(Vec::new()), | |
| 11677 | + rewriters: Mutex::new(Vec::new()), | |
| 11678 | + tcp_sockets: Mutex::new(Vec::new()), | |
| 11679 | + input_gates: Mutex::new(InputGateClaims::default()), | |
| 11680 | + cross_entry_gates: CrossEntryGateClaims::default(), | |
| 11681 | + body_streams: Mutex::new(HashMap::new()), | |
| 11682 | + ws_capture: Mutex::new(Vec::new()), | |
| 11683 | + egress: Mutex::new(Vec::new()), | |
| 11684 | + }) | |
| 11685 | + } | |
| 11686 | + | |
| 11687 | + fn tracked(runtime_state: &Arc<ActorRuntimeState>) -> Arc<Self> { | |
| 11688 | + let id = allocate_io_context_id(); | |
| 11689 | + let context = Arc::new(Self { | |
| 11690 | + continuation: Some((id, Arc::downgrade(runtime_state))), | |
| 11691 | + call_chains: Mutex::new(CallChains::default()), | |
| 11692 | + events: Mutex::new(IoEventState::default()), | |
| 11693 | + vfs: OnceLock::new(), | |
| 11694 | + sockets: Mutex::new(Vec::new()), | |
| 11695 | + rewriters: Mutex::new(Vec::new()), | |
| 11696 | + tcp_sockets: Mutex::new(Vec::new()), | |
| 11697 | + input_gates: Mutex::new(InputGateClaims::default()), | |
| 11698 | + cross_entry_gates: CrossEntryGateClaims::default(), | |
| 11699 | + body_streams: Mutex::new(HashMap::new()), | |
| 11700 | + ws_capture: Mutex::new(Vec::new()), | |
| 11701 | + egress: Mutex::new(Vec::new()), | |
| 11702 | + }); | |
| 11703 | + runtime_state | |
| 11704 | + .io_contexts | |
| 11705 | + .lock() | |
| 11706 | + .unwrap() | |
| 11707 | + .insert(id, Arc::downgrade(&context)); | |
| 11708 | + context | |
| 11709 | + } | |
| 11710 | + | |
| 11711 | + fn begin_event(&self) { | |
| 11712 | + self.events | |
| 11713 | + .lock() | |
| 11714 | + .unwrap() | |
| 11715 | + .frames | |
| 11716 | + .push(IoEventFrame::default()); | |
| 11717 | + } | |
| 11718 | + | |
| 11719 | + fn release_input_gate(&self, cell: &str, event: celld_logic::gate::EventId) -> bool { | |
| 11720 | + let mut claims = self.input_gates.lock().unwrap(); | |
| 11721 | + if !claims.held.get(&event).is_some_and(|owned| owned == cell) { | |
| 11722 | + return false; | |
| 11723 | + } | |
| 11724 | + claims.held.remove(&event); | |
| 11725 | + true | |
| 11726 | + } | |
| 11727 | + | |
| 11728 | + fn retire_input_gates(&self) -> Vec<(String, celld_logic::gate::EventId)> { | |
| 11729 | + let mut claims = self.input_gates.lock().unwrap(); | |
| 11730 | + claims.retired = true; | |
| 11731 | + claims.retirement.send_replace(true); | |
| 11732 | + let mut held = claims | |
| 11733 | + .held | |
| 11734 | + .drain() | |
| 11735 | + .map(|(event, cell)| (cell, event)) | |
| 11736 | + .collect::<Vec<_>>(); | |
| 11737 | + held.sort_unstable(); | |
| 11738 | + held | |
| 11739 | + } | |
| 11740 | + | |
| 11741 | + /// Pop the innermost frame and hand back what it collected. `None` when | |
| 11742 | + /// there is no frame, which is a script calling `waitUntil` outside any | |
| 11743 | + /// event; the harness turns that into workerd's global-scope error. | |
| 11744 | + fn end_event(&self) -> Option<Vec<v8::Global<v8::Promise>>> { | |
| 11745 | + let mut events = self.events.lock().unwrap(); | |
| 11746 | + let mut frame = events.frames.pop()?; | |
| 11747 | + if events.arm_gates_sealed { | |
| 11748 | + drop(frame.arm_gates); | |
| 11749 | + } else if let Some(parent) = events.frames.last_mut() { | |
| 11750 | + parent.arm_gates.append(&mut frame.arm_gates); | |
| 11751 | + } else { | |
| 11752 | + events.ended_arm_gates.append(&mut frame.arm_gates); | |
| 11753 | + } | |
| 11754 | + Some(frame.wait_until) | |
| 11755 | + } | |
| 11756 | + | |
| 11757 | + fn register_wait_until(&self, promise: v8::Global<v8::Promise>) { | |
| 11758 | + if let Some(frame) = self.events.lock().unwrap().frames.last_mut() { | |
| 11759 | + frame.wait_until.push(promise); | |
| 11760 | + } | |
| 11761 | + } | |
| 11762 | + | |
| 11763 | + fn register_arm_gate(&self, gate: ArmGateRx) -> Result<(), ArmGateRx> { | |
| 11764 | + let mut events = self.events.lock().unwrap(); | |
| 11765 | + if events.arm_gates_sealed { | |
| 11766 | + return Err(gate); | |
| 11767 | + } | |
| 11768 | + if let Some(frame) = events.frames.last_mut() { | |
| 11769 | + frame.arm_gates.push(gate); | |
| 11770 | + } else { | |
| 11771 | + // `op_event_end` pops the final frame before `Promise.allSettled` | |
| 11772 | + // can invoke a user-defined `then`. A gate created during that | |
| 11773 | + // call still belongs to this event until `take_arm_gates` seals | |
| 11774 | + // the response boundary. | |
| 11775 | + events.ended_arm_gates.push(gate); | |
| 11776 | + } | |
| 11777 | + Ok(()) | |
| 11778 | + } | |
| 11779 | + | |
| 11780 | + /// Take every response gate that this event owns. | |
| 11781 | + /// | |
| 11782 | + /// The normal path takes gates moved out by `end_event`. Active frames | |
| 11783 | + /// cover failures that cannot run JavaScript again, such as a timeout or | |
| 11784 | + /// an isolate termination. | |
| 11785 | + fn take_arm_gates(&self) -> Vec<ArmGateRx> { | |
| 11786 | + let mut events = self.events.lock().unwrap(); | |
| 11787 | + if events.arm_gates_sealed { | |
| 11788 | + return Vec::new(); | |
| 11789 | + } | |
| 11790 | + events.arm_gates_sealed = true; | |
| 11791 | + let mut gates = std::mem::take(&mut events.ended_arm_gates); | |
| 11792 | + for frame in &mut events.frames { | |
| 11793 | + gates.append(&mut frame.arm_gates); | |
| 11794 | + } | |
| 11795 | + gates | |
| 11796 | + } | |
| 11797 | + | |
| 11798 | + fn depth(&self) -> usize { | |
| 11799 | + self.events.lock().unwrap().frames.len() | |
| 11800 | + } | |
| 11801 | + | |
| 11802 | + /// Close every isolate-polled socket this request opened. | |
| 11803 | + /// | |
| 11804 | + /// Draining makes the operation idempotent. The drive loop calls it when | |
| 11805 | + /// the request retires, and `drop` covers every earlier failure path. | |
| 11806 | + fn close_sockets(&self) { | |
| 11807 | + let opened = self.sockets.lock().unwrap().drain(..).collect(); | |
| 11808 | + ws_close_request_sockets(opened); | |
| 11809 | + let rewriters: Vec<u64> = self.rewriters.lock().unwrap().drain(..).collect(); | |
| 11810 | + for id in rewriters { | |
| 11811 | + html_rewriter::free(id); | |
| 11812 | + } | |
| 11813 | + let tcp: Vec<u64> = self.tcp_sockets.lock().unwrap().drain(..).collect(); | |
| 11814 | + for id in tcp { | |
| 11815 | + tcp::free(id); | |
| 11816 | + } | |
| 11817 | + } | |
| 11818 | + | |
| 11819 | + #[doc(hidden)] | |
| 11820 | + pub fn own_body_stream(&self, stream_id: u64) { | |
| 11821 | + let Some(claim) = claim_http_stream(stream_id) else { | |
| 11822 | + return; | |
| 11823 | + }; | |
| 11824 | + let replaced = self.body_streams.lock().unwrap().insert(stream_id, claim); | |
| 11825 | + // Releasing a claim can drop an arbitrary source. Keep that work out | |
| 11826 | + // of the request-ownership lock. | |
| 11827 | + drop(replaced); | |
| 11828 | + } | |
| 11829 | + | |
| 11830 | + fn transfer_body_stream(&self, stream_id: u64) -> Option<RequestBodyGuard> { | |
| 11831 | + let claim = self.body_streams.lock().unwrap().remove(&stream_id)?; | |
| 11832 | + // Move the exact service claim into the guard. A later asynchronous | |
| 11833 | + // drop cannot resolve through another ambient Domain. | |
| 11834 | + Some(RequestBodyGuard::transferred(claim)) | |
| 11835 | + } | |
| 11836 | + | |
| 11837 | + /// Replace one request-owned source with the two sources created by a | |
| 11838 | + /// native tee. Response streams are not request-owned, so they keep the | |
| 11839 | + /// registry's ordinary unowned lifecycle. | |
| 11840 | + fn replace_body_stream( | |
| 11841 | + &self, | |
| 11842 | + stream_id: u64, | |
| 11843 | + service: &Arc<HttpStreamService>, | |
| 11844 | + branches: (u64, u64), | |
| 11845 | + ) { | |
| 11846 | + let original = self.body_streams.lock().unwrap().remove(&stream_id); | |
| 11847 | + let Some(original) = original else { | |
| 11848 | + return; | |
| 11849 | + }; | |
| 11850 | + debug_assert!(Arc::ptr_eq(&original.service, service)); | |
| 11851 | + let mut branch_claims = Vec::new(); | |
| 11852 | + for branch in [branches.0, branches.1] { | |
| 11853 | + if let Some(claim) = service.claim(branch) { | |
| 11854 | + branch_claims.push((branch, claim)); | |
| 11855 | + } | |
| 11856 | + } | |
| 11857 | + let replaced = { | |
| 11858 | + let mut owned = self.body_streams.lock().unwrap(); | |
| 11859 | + branch_claims | |
| 11860 | + .into_iter() | |
| 11861 | + .filter_map(|(branch, claim)| owned.insert(branch, claim)) | |
| 11862 | + .collect::<Vec<_>>() | |
| 11863 | + }; | |
| 11864 | + // The original entry was consumed by tee, so releasing this claim is | |
| 11865 | + // a no-op. Replaced claims still release through their bound service. | |
| 11866 | + drop(original); | |
| 11867 | + drop(replaced); | |
| 11868 | + } | |
| 11869 | + | |
| 11870 | + #[cfg(celld_internal_tests)] | |
| 11871 | + #[doc(hidden)] | |
| 11872 | + pub fn begin_event_for_test(&self) { | |
| 11873 | + self.begin_event(); | |
| 11874 | + } | |
| 11875 | + | |
| 11876 | + #[cfg(celld_internal_tests)] | |
| 11877 | + #[doc(hidden)] | |
| 11878 | + pub fn end_event_for_test(&self) -> Option<()> { | |
| 11879 | + self.end_event().map(drop) | |
| 11880 | + } | |
| 11881 | + | |
| 11882 | + #[cfg(celld_internal_tests)] | |
| 11883 | + #[doc(hidden)] | |
| 11884 | + pub fn register_arm_gate_for_test( | |
| 11885 | + &self, | |
| 11886 | + gate: tokio::sync::oneshot::Receiver<Result<(), String>>, | |
| 11887 | + ) -> Result<(), tokio::sync::oneshot::Receiver<Result<(), String>>> { | |
| 11888 | + self.register_arm_gate(gate) | |
| 11889 | + } | |
| 11890 | + | |
| 11891 | + #[cfg(celld_internal_tests)] | |
| 11892 | + #[doc(hidden)] | |
| 11893 | + pub fn take_arm_gates_for_test( | |
| 11894 | + &self, | |
| 11895 | + ) -> Vec<tokio::sync::oneshot::Receiver<Result<(), String>>> { | |
| 11896 | + self.take_arm_gates() | |
| 11897 | + } | |
| 11898 | +} | |
| 11899 | + | |
| 11900 | +#[cfg(celld_internal_tests)] | |
| 11901 | +#[doc(hidden)] | |
| 11902 | +#[derive(Default)] | |
| 11903 | +pub struct IoContextRegistryForTest(Arc<ActorRuntimeState>); | |
| 11904 | + | |
| 11905 | +#[cfg(celld_internal_tests)] | |
| 11906 | +impl IoContextRegistryForTest { | |
| 11907 | + #[doc(hidden)] | |
| 11908 | + pub fn track(&self) -> (u64, Arc<IoContext>) { | |
| 11909 | + let context = IoContext::tracked(&self.0); | |
| 11910 | + let id = context | |
| 11911 | + .continuation | |
| 11912 | + .as_ref() | |
| 11913 | + .map(|(id, _)| *id) | |
| 11914 | + .expect("a tracked IoContext has a continuation id"); | |
| 11915 | + (id, context) | |
| 11916 | + } | |
| 11917 | + | |
| 11918 | + #[doc(hidden)] | |
| 11919 | + pub fn resolves_to(&self, id: u64, expected: &Arc<IoContext>) -> bool { | |
| 11920 | + self.0 | |
| 11921 | + .io_context(id) | |
| 11922 | + .is_some_and(|context| Arc::ptr_eq(&context, expected)) | |
| 11923 | + } | |
| 11924 | + | |
| 11925 | + #[doc(hidden)] | |
| 11926 | + pub fn contains(&self, id: u64) -> bool { | |
| 11927 | + self.0.io_contexts.lock().unwrap().contains_key(&id) | |
| 11928 | + } | |
| 11929 | + | |
| 11930 | + #[doc(hidden)] | |
| 11931 | + pub fn is_empty(&self) -> bool { | |
| 11932 | + self.0.io_contexts.lock().unwrap().is_empty() | |
| 11933 | + } | |
| 11934 | +} | |
| 11935 | + | |
| 11936 | +/// A Worker socket lives and dies with its request, exactly as it does on | |
| 11937 | +/// Cloudflare. Closing it here rather than at each of the drive loops' exits | |
| 11938 | +/// is the difference between a rule every exit path has to remember and one | |
| 11939 | +/// it cannot get wrong: a request that times out, that is abandoned as stuck, | |
| 11940 | +/// or whose client disconnects drops its context on a path of its own. | |
| 11941 | +impl Drop for IoContext { | |
| 11942 | + fn drop(&mut self) { | |
| 11943 | + let already_panicking = std::thread::panicking(); | |
| 11944 | + // The drive loop also abandons these while it still owns the isolate, | |
| 11945 | + // because that path resets the JavaScript actor state. Drop is the | |
| 11946 | + // final host-side invariant for an earlier exit: no request context | |
| 11947 | + // can leave a process-wide input gate active after it is gone. | |
| 11948 | + let _ = abandon_context_input_gates(self); | |
| 11949 | + self.close_sockets(); | |
| 11950 | + let mut claims = self | |
| 11951 | + .body_streams | |
| 11952 | + .get_mut() | |
| 11953 | + .unwrap() | |
| 11954 | + .drain() | |
| 11955 | + .collect::<Vec<_>>(); | |
| 11956 | + // A claim can drop an arbitrary source. Fix the first-panic order even | |
| 11957 | + // when the request map uses a different randomized hash seed. | |
| 11958 | + claims.sort_unstable_by_key(|(stream_id, _)| *stream_id); | |
| 11959 | + let mut first_panic = None; | |
| 11960 | + for (_, claim) in claims { | |
| 11961 | + retain_first_http_cleanup_panic( | |
| 11962 | + &mut first_panic, | |
| 11963 | + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(claim))), | |
| 11964 | + ); | |
| 11965 | + } | |
| 11966 | + if let Some((id, runtime_state)) = &self.continuation { | |
| 11967 | + if let Some(runtime_state) = runtime_state.upgrade() { | |
| 11968 | + runtime_state.io_contexts.lock().unwrap().remove(id); | |
| 11969 | + } | |
| 11970 | + } | |
| 11971 | + if let Some(payload) = first_panic { | |
| 11972 | + if already_panicking { | |
| 11973 | + std::mem::forget(payload); | |
| 11974 | + } else { | |
| 11975 | + std::panic::resume_unwind(payload); | |
| 11976 | + } | |
| 11977 | + } | |
| 11978 | + } | |
| 11979 | +} | |
| 11980 | + | |
| 11981 | +/// What `OwnedIsolate::into_shared` demands of us: every slot value on a | |
| 11982 | +/// shared isolate is reachable, and droppable, from whichever thread holds | |
| 11983 | +/// the lock. The type system cannot check it at the call site, so it is | |
| 11984 | +/// checked here instead. | |
| 11985 | +const _: fn() = || { | |
| 11986 | + fn assert_send_sync<T: Send + Sync>() {} | |
| 11987 | + assert_send_sync::<HeapLimitState>(); | |
| 11988 | + assert_send_sync::<ActorRuntimeState>(); | |
| 11989 | + assert_send_sync::<ModuleRegistry>(); | |
| 11990 | + assert_send_sync::<LoaderOwner>(); | |
| 11991 | +}; | |
| 11992 | + | |
| 11993 | +/// A request must be able to carry its own context across a suspension. A | |
| 11994 | +/// compile-time check, because losing it would surface as an unrelated | |
| 11995 | +/// `Send` error wherever the request task is spawned. | |
| 11996 | +const _: fn() = || { | |
| 11997 | + fn assert_send_sync<T: Send + Sync>() {} | |
| 11998 | + assert_send_sync::<Arc<IoContext>>(); | |
| 11999 | +}; | |
| 12000 | + | |
| 12001 | +thread_local! { | |
| 12002 | + /// The request whose turn is running on this thread, or none between | |
| 12003 | + /// turns. Never set by JS. | |
| 12004 | + static CURRENT: RefCell<Option<Arc<IoContext>>> = | |
| 12005 | + const { RefCell::new(None) }; | |
| 12006 | +} | |
| 12007 | + | |
| 12008 | +/// Install `context` for the duration of a turn, restoring whatever was | |
| 12009 | +/// current when the guard drops. | |
| 12010 | +/// | |
| 12011 | +/// Restoring rather than clearing is what makes nested host dispatch safe: a | |
| 12012 | +/// service binding runs a second handler inside the first one's turn, and the | |
| 12013 | +/// outer request must still be current when it returns. | |
| 12014 | +pub struct CurrentGuard(Option<Arc<IoContext>>); | |
| 12015 | + | |
| 12016 | +impl CurrentGuard { | |
| 12017 | + pub fn enter(context: Arc<IoContext>) -> Self { | |
| 12018 | + CurrentGuard(CURRENT.with(|current| current.borrow_mut().replace(context))) | |
| 12019 | + } | |
| 12020 | +} | |
| 12021 | + | |
| 12022 | +impl Drop for CurrentGuard { | |
| 12023 | + fn drop(&mut self) { | |
| 12024 | + CURRENT.with(|current| *current.borrow_mut() = self.0.take()); | |
| 12025 | + } | |
| 12026 | +} | |
| 12027 | + | |
| 12028 | +/// The context this turn belongs to. | |
| 12029 | +/// | |
| 12030 | +/// A thread that has not had one installed gets a default: every path that | |
| 12031 | +/// runs JS without an explicit request context — a cell isolate, which the | |
| 12032 | +/// DO contract already serializes, an RPC entry, a DO constructor — keeps | |
| 12033 | +/// exactly the semantics it had when the stack lived in JS, one per isolate. | |
| 12034 | +/// Isolation is a property of *installing* a context, so it arrives with the | |
| 12035 | +/// paths that need it rather than being retrofitted to every caller at once. | |
| 12036 | +fn current_context() -> Arc<IoContext> { | |
| 12037 | + CURRENT.with(|current| { | |
| 12038 | + let mut current = current.borrow_mut(); | |
| 12039 | + current.get_or_insert_with(IoContext::new).clone() | |
| 12040 | + }) | |
| 12041 | +} | |
| 12042 | + | |
| 12043 | +#[cfg(celld_internal_tests)] | |
| 12044 | +fn installed_context() -> Option<Arc<IoContext>> { | |
| 12045 | + CURRENT.with(|current| current.borrow().clone()) | |
| 12046 | +} | |
| 12047 | + | |
| 12048 | +fn op_event_begin( | |
| 12049 | + scope: &mut v8::PinScope, | |
| 12050 | + _args: v8::FunctionCallbackArguments, | |
| 12051 | + _rv: v8::ReturnValue<v8::Value>, | |
| 12052 | +) { | |
| 12053 | + let _ = scope; | |
| 12054 | + current_context().begin_event(); | |
| 12055 | +} | |
| 12056 | + | |
| 12057 | +/// Pop the innermost event and return the aggregate of its `waitUntil` | |
| 12058 | +/// promises, or null when it collected none. The aggregate is built here | |
| 12059 | +/// rather than in JS because the promises live here: the host holds them for | |
| 12060 | +/// the request, and the request is what the frame belongs to. | |
| 12061 | +fn op_event_end<'s>( | |
| 12062 | + scope: &mut v8::PinScope<'s, '_>, | |
| 12063 | + _args: v8::FunctionCallbackArguments, | |
| 12064 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12065 | +) { | |
| 12066 | + let Some(frame) = current_context().end_event() else { | |
| 12067 | + rv.set_null(); | |
| 12068 | + return; | |
| 12069 | + }; | |
| 12070 | + if frame.is_empty() { | |
| 12071 | + rv.set_null(); | |
| 12072 | + return; | |
| 12073 | + } | |
| 12074 | + let promises: Vec<v8::Local<v8::Value>> = frame | |
| 12075 | + .iter() | |
| 12076 | + .map(|promise| v8::Local::new(scope, promise).into()) | |
| 12077 | + .collect(); | |
| 12078 | + let array = v8::Array::new_with_elements(scope, &promises); | |
| 12079 | + match all_settled(scope, array.into()) { | |
| 12080 | + Some(aggregate) => rv.set(aggregate), | |
| 12081 | + None => rv.set_null(), | |
| 12082 | + } | |
| 12083 | +} | |
| 12084 | + | |
| 12085 | +/// Create one directory in the current request's virtual `/tmp` tree. | |
| 12086 | +/// A created path starts with `/`, an error is a Node code, and an empty string | |
| 12087 | +/// means that no path must be returned. The disjoint representation keeps the | |
| 12088 | +/// result and its meaning together without allocating a JS object for each | |
| 12089 | +/// directory segment. | |
| 12090 | +fn op_vfs_mkdir( | |
| 12091 | + scope: &mut v8::PinScope, | |
| 12092 | + args: v8::FunctionCallbackArguments, | |
| 12093 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12094 | +) { | |
| 12095 | + let path = args.get(0).to_rust_string_lossy(scope); | |
| 12096 | + let recursive = args.get(1).boolean_value(scope); | |
| 12097 | + let result = current_context() | |
| 12098 | + .vfs | |
| 12099 | + .get_or_init(|| Mutex::new(RequestVfs::default())) | |
| 12100 | + .lock() | |
| 12101 | + .unwrap() | |
| 12102 | + .mkdir(&path, recursive); | |
| 12103 | + let result = match result { | |
| 12104 | + VfsMkdirResult::Created(Some(path)) => path, | |
| 12105 | + VfsMkdirResult::Created(None) => String::new(), | |
| 12106 | + VfsMkdirResult::Error(code) => code.to_string(), | |
| 12107 | + }; | |
| 12108 | + rv.set(v8::String::new(scope, &result).unwrap().into()); | |
| 12109 | +} | |
| 12110 | + | |
| 12111 | +/// Return `[kind, size]`, where kind is 0 for a missing path, 1 for a | |
| 12112 | +/// read-only directory, 2 for a writable directory, and 3 for a read-only | |
| 12113 | +/// file. Only a file has a size; a directory reports 0, matching workerd. | |
| 12114 | +/// | |
| 12115 | +/// The pair travels together because a caller that knows a path is a file | |
| 12116 | +/// always needs its size to build `Stats`, and a second lookup could observe a | |
| 12117 | +/// different tree. | |
| 12118 | +fn op_vfs_stat( | |
| 12119 | + scope: &mut v8::PinScope, | |
| 12120 | + args: v8::FunctionCallbackArguments, | |
| 12121 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12122 | +) { | |
| 12123 | + let path = args.get(0).to_rust_string_lossy(scope); | |
| 12124 | + let (kind, size) = match current_context() | |
| 12125 | + .vfs | |
| 12126 | + .get_or_init(|| Mutex::new(RequestVfs::default())) | |
| 12127 | + .lock() | |
| 12128 | + .unwrap() | |
| 12129 | + .stat(&path) | |
| 12130 | + { | |
| 12131 | + Some(writable) => (if writable { 2 } else { 1 }, 0), | |
| 12132 | + // Only a path the writable tree does not claim can be a bundle path, | |
| 12133 | + // so the request tree stays authoritative for `/tmp`. | |
| 12134 | + None => match bundle_node(scope, &path) { | |
| 12135 | + Some(BundleStat::Directory) => (1, 0), | |
| 12136 | + Some(BundleStat::File(size)) => (3, size), | |
| 12137 | + None => (0, 0), | |
| 12138 | + }, | |
| 12139 | + }; | |
| 12140 | + let pair = v8::Array::new(scope, 2); | |
| 12141 | + let kind = v8::Integer::new(scope, kind).into(); | |
| 12142 | + let size = v8::Number::new(scope, size as f64).into(); | |
| 12143 | + pair.set_index(scope, 0, kind); | |
| 12144 | + pair.set_index(scope, 1, size); | |
| 12145 | + rv.set(pair.into()); | |
| 12146 | +} | |
| 12147 | + | |
| 12148 | +/// What a bundle path is, without copying the bytes a stat does not need. | |
| 12149 | +enum BundleStat { | |
| 12150 | + Directory, | |
| 12151 | + File(usize), | |
| 12152 | +} | |
| 12153 | + | |
| 12154 | +/// Materializes `/bundle` on the first call that reaches it. | |
| 12155 | +fn bundle_node(scope: &mut v8::PinScope, path: &str) -> Option<BundleStat> { | |
| 12156 | + let bundle = scope.get_slot::<Arc<BundleFs>>().cloned()?; | |
| 12157 | + match bundle.tree().nodes.get(path)? { | |
| 12158 | + BundleNode::Directory => Some(BundleStat::Directory), | |
| 12159 | + BundleNode::File(bytes) => Some(BundleStat::File(bytes.len())), | |
| 12160 | + } | |
| 12161 | +} | |
| 12162 | + | |
| 12163 | +/// Read a whole bundle file. Returns an `ArrayBuffer` of the module's bytes, | |
| 12164 | +/// or `null` when the path is not a bundle file, so the caller raises the | |
| 12165 | +/// `ENOENT` that names the syscall it was performing. | |
| 12166 | +fn op_vfs_read_file( | |
| 12167 | + scope: &mut v8::PinScope, | |
| 12168 | + args: v8::FunctionCallbackArguments, | |
| 12169 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12170 | +) { | |
| 12171 | + let path = args.get(0).to_rust_string_lossy(scope); | |
| 12172 | + let Some(bundle) = scope.get_slot::<Arc<BundleFs>>().cloned() else { | |
| 12173 | + return; | |
| 12174 | + }; | |
| 12175 | + let tree = bundle.tree(); | |
| 12176 | + let Some(BundleNode::File(bytes)) = tree.nodes.get(&path) else { | |
| 12177 | + return; | |
| 12178 | + }; | |
| 12179 | + // One copy into the V8 heap. The projected `Bytes` stays shared, so a | |
| 12180 | + // second read of the same module does not re-copy the config's source. | |
| 12181 | + let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes.to_vec()).make_shared(); | |
| 12182 | + let buffer = v8::ArrayBuffer::with_backing_store(scope, &store); | |
| 12183 | + rv.set(buffer.into()); | |
| 12184 | +} | |
| 12185 | + | |
| 12186 | +fn op_wait_until<'s>( | |
| 12187 | + scope: &mut v8::PinScope<'s, '_>, | |
| 12188 | + args: v8::FunctionCallbackArguments<'s>, | |
| 12189 | + _rv: v8::ReturnValue<v8::Value>, | |
| 12190 | +) { | |
| 12191 | + let value = args.get(0); | |
| 12192 | + let promise = match value.try_cast::<v8::Promise>() { | |
| 12193 | + Ok(promise) => promise, | |
| 12194 | + Err(_) => match resolved_promise(scope, value) { | |
| 12195 | + Ok(promise) => promise, | |
| 12196 | + Err(_) => return, | |
| 12197 | + }, | |
| 12198 | + }; | |
| 12199 | + current_context().register_wait_until(v8::Global::new(scope, promise)); | |
| 12200 | +} | |
| 12201 | + | |
| 12202 | +/// How many events are open on the current request. The harness uses it for | |
| 12203 | +/// workerd's global-scope error, which fires when `waitUntil` is imported and | |
| 12204 | +/// called with no event in progress. | |
| 12205 | +fn op_event_depth( | |
| 12206 | + scope: &mut v8::PinScope, | |
| 12207 | + _args: v8::FunctionCallbackArguments, | |
| 12208 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12209 | +) { | |
| 12210 | + let depth = current_context().depth(); | |
| 12211 | + rv.set(v8::Integer::new(scope, depth as i32).into()); | |
| 12212 | +} | |
| 12213 | + | |
| 12214 | +/// `Promise.allSettled(values)`, from the context's own realm. | |
| 12215 | +fn all_settled<'s>( | |
| 12216 | + scope: &mut v8::PinScope<'s, '_>, | |
| 12217 | + values: v8::Local<'s, v8::Value>, | |
| 12218 | +) -> Option<v8::Local<'s, v8::Value>> { | |
| 12219 | + let global = scope.get_current_context().global(scope); | |
| 12220 | + let key = v8::String::new(scope, "Promise").unwrap(); | |
| 12221 | + let promise_ctor: v8::Local<v8::Object> = global.get(scope, key.into())?.try_into().ok()?; | |
| 12222 | + let key = v8::String::new(scope, "allSettled").unwrap(); | |
| 12223 | + let all_settled: v8::Local<v8::Function> = | |
| 12224 | + promise_ctor.get(scope, key.into())?.try_into().ok()?; | |
| 12225 | + all_settled.call(scope, promise_ctor.into(), &[values]) | |
| 12226 | +} | |
| 12227 | + | |
| 12228 | +fn op_als_get( | |
| 12229 | + scope: &mut v8::PinScope, | |
| 12230 | + _args: v8::FunctionCallbackArguments, | |
| 12231 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12232 | +) { | |
| 12233 | + rv.set(cped_frame(scope)); | |
| 12234 | +} | |
| 12235 | + | |
| 12236 | +fn op_als_set( | |
| 12237 | + scope: &mut v8::PinScope, | |
| 12238 | + args: v8::FunctionCallbackArguments, | |
| 12239 | + _rv: v8::ReturnValue<v8::Value>, | |
| 12240 | +) { | |
| 12241 | + let trace = cped_trace(scope); | |
| 12242 | + let io_context = cped_io_context(scope); | |
| 12243 | + set_cped(scope, args.get(0), trace, io_context); | |
| 12244 | +} | |
| 12245 | + | |
| 12246 | +// node:util prelude calls these; registration is the sole per-isolate cost. | |
| 12247 | + | |
| 12248 | +/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js. | |
| 12249 | +fn op_util_type_flags( | |
| 12250 | + _scope: &mut v8::PinScope, | |
| 12251 | + args: v8::FunctionCallbackArguments, | |
| 12252 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12253 | +) { | |
| 12254 | + let v = args.get(0); | |
| 12255 | + let checks: [bool; 27] = [ | |
| 12256 | + v.is_external(), | |
| 12257 | + v.is_date(), | |
| 12258 | + v.is_arguments_object(), | |
| 12259 | + v.is_big_int_object(), | |
| 12260 | + v.is_boolean_object(), | |
| 12261 | + v.is_number_object(), | |
| 12262 | + v.is_string_object(), | |
| 12263 | + v.is_symbol_object(), | |
| 12264 | + v.is_native_error(), | |
| 12265 | + v.is_reg_exp(), | |
| 12266 | + v.is_async_function(), | |
| 12267 | + v.is_generator_function(), | |
| 12268 | + v.is_generator_object(), | |
| 12269 | + v.is_promise(), | |
| 12270 | + v.is_map(), | |
| 12271 | + v.is_set(), | |
| 12272 | + v.is_map_iterator(), | |
| 12273 | + v.is_set_iterator(), | |
| 12274 | + v.is_weak_map(), | |
| 12275 | + v.is_weak_set(), | |
| 12276 | + v.is_array_buffer(), | |
| 12277 | + v.is_data_view(), | |
| 12278 | + v.is_shared_array_buffer(), | |
| 12279 | + v.is_proxy(), | |
| 12280 | + v.is_module_namespace_object(), | |
| 12281 | + v.is_typed_array(), | |
| 12282 | + v.is_array_buffer_view(), | |
| 12283 | + ]; | |
| 12284 | + let mut flags: u32 = 0; | |
| 12285 | + for (i, hit) in checks.iter().enumerate() { | |
| 12286 | + if *hit { | |
| 12287 | + flags |= 1 << i; | |
| 12288 | + } | |
| 12289 | + } | |
| 12290 | + rv.set_uint32(flags); | |
| 12291 | +} | |
| 12292 | + | |
| 12293 | +fn op_util_constructor_name( | |
| 12294 | + _scope: &mut v8::PinScope, | |
| 12295 | + args: v8::FunctionCallbackArguments, | |
| 12296 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12297 | +) { | |
| 12298 | + let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else { | |
| 12299 | + return; // undefined | |
| 12300 | + }; | |
| 12301 | + rv.set(obj.get_constructor_name().into()); | |
| 12302 | +} | |
| 12303 | + | |
| 12304 | +/// `[target, handler]` for a proxy, undefined otherwise. | |
| 12305 | +fn op_util_proxy_details( | |
| 12306 | + scope: &mut v8::PinScope, | |
| 12307 | + args: v8::FunctionCallbackArguments, | |
| 12308 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12309 | +) { | |
| 12310 | + let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else { | |
| 12311 | + return; | |
| 12312 | + }; | |
| 12313 | + let target = proxy.get_target(scope); | |
| 12314 | + let handler = proxy.get_handler(scope); | |
| 12315 | + rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into()); | |
| 12316 | +} | |
| 12317 | + | |
| 12318 | +/// `[state]` for a pending promise, `[state, result]` otherwise, | |
| 12319 | +/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected. | |
| 12320 | +fn op_util_promise_details( | |
| 12321 | + scope: &mut v8::PinScope, | |
| 12322 | + args: v8::FunctionCallbackArguments, | |
| 12323 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12324 | +) { | |
| 12325 | + let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else { | |
| 12326 | + return; | |
| 12327 | + }; | |
| 12328 | + let state = match promise.state() { | |
| 12329 | + v8::PromiseState::Pending => 0, | |
| 12330 | + v8::PromiseState::Fulfilled => 1, | |
| 12331 | + v8::PromiseState::Rejected => 2, | |
| 12332 | + }; | |
| 12333 | + let pending = state == 0; | |
| 12334 | + let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into(); | |
| 12335 | + let elements = if pending { | |
| 12336 | + vec![state] | |
| 12337 | + } else { | |
| 12338 | + vec![state, promise.result(scope)] | |
| 12339 | + }; | |
| 12340 | + rv.set(v8::Array::new_with_elements(scope, &elements).into()); | |
| 12341 | +} | |
| 12342 | + | |
| 12343 | +/// `[entries, isKeyValue]` for collections and their iterators (V8's | |
| 12344 | +/// PreviewEntries), undefined when V8 has no preview. | |
| 12345 | +fn op_util_preview_entries( | |
| 12346 | + scope: &mut v8::PinScope, | |
| 12347 | + args: v8::FunctionCallbackArguments, | |
| 12348 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12349 | +) { | |
| 12350 | + let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else { | |
| 12351 | + return; | |
| 12352 | + }; | |
| 12353 | + let (entries, is_key_value) = obj.preview_entries(scope); | |
| 12354 | + let Some(entries) = entries else { return }; | |
| 12355 | + let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into(); | |
| 12356 | + rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into()); | |
| 12357 | +} | |
| 12358 | + | |
| 12359 | +fn op_alarm_set( | |
| 12360 | + scope: &mut v8::PinScope, | |
| 12361 | + args: v8::FunctionCallbackArguments, | |
| 12362 | + _rv: v8::ReturnValue<v8::Value>, | |
| 12363 | +) { | |
| 12364 | + let s = args.get(0).to_rust_string_lossy(scope); | |
| 12365 | + let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64; | |
| 12366 | + let timing_started = (tracing::enabled!(target: "queue_timing", tracing::Level::DEBUG) | |
| 12367 | + && s.split_once(':') | |
| 12368 | + .is_some_and(|(class, _)| class == crate::deploy::QUEUE_CLASS)) | |
| 12369 | + .then(crate::asyncrt::mono_us); | |
| 12370 | + let result = storage::set_alarm(&s, at); | |
| 12371 | + if let Some(timing_started) = timing_started { | |
| 12372 | + tracing::debug!( | |
| 12373 | + target: "queue_timing", | |
| 12374 | + event = "queue_alarm_write_timing", | |
| 12375 | + total_us = crate::asyncrt::mono_us().saturating_sub(timing_started), | |
| 12376 | + ok = result.is_ok(), | |
| 12377 | + "Queue alarm write completed" | |
| 12378 | + ); | |
| 12379 | + } | |
| 12380 | + match result { | |
| 12381 | + Err(error) => throw_storage_error(scope, "setAlarm", error), | |
| 12382 | + // Committed immediately: register the wake-entry PUT against the | |
| 12383 | + // current event's output gate. Inside an explicit transaction (`Ok(None)`) | |
| 12384 | + // the gate registers at that transaction's commit instead. | |
| 12385 | + Ok(Some(committed)) if committed >= 0 => { | |
| 12386 | + spawn_arm_gate(&s, committed, current_reaction_io_context(scope)) | |
| 12387 | + } | |
| 12388 | + Ok(_) => {} | |
| 12389 | + } | |
| 12390 | +} | |
| 12391 | + | |
| 12392 | +/// Queue producer groups resolve promises from several cell events after one | |
| 12393 | +/// event rearms the broker. The ordinary event-local arm gate cannot migrate | |
| 12394 | +/// to those other events, so this internal variant awaits the wake-entry PUT | |
| 12395 | +/// before the shared promise resolves. The later output gate still proves the | |
| 12396 | +/// SQLite/LTX write; together they preserve the same acknowledgement boundary | |
| 12397 | +/// as an ungrouped `setAlarm` call. | |
| 12398 | +fn op_queue_alarm_set_wait( | |
| 12399 | + scope: &mut v8::PinScope, | |
| 12400 | + args: v8::FunctionCallbackArguments, | |
| 12401 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12402 | +) { | |
| 12403 | + let cell = args.get(0).to_rust_string_lossy(scope); | |
| 12404 | + let at_ms = args.get(1).number_value(scope).unwrap_or(0.0) as i64; | |
| 12405 | + let committed = match storage::set_alarm(&cell, at_ms) { | |
| 12406 | + Ok(committed) => committed, | |
| 12407 | + Err(error) => { | |
| 12408 | + throw_storage_error(scope, "Queue setAlarm", error); | |
| 12409 | + return; | |
| 12410 | + } | |
| 12411 | + }; | |
| 12412 | + let Some(committed) = committed.filter(|committed| *committed >= 0) else { | |
| 12413 | + return; | |
| 12414 | + }; | |
| 12415 | + let Some(gate) = launch_arm_gate(&cell, committed) else { | |
| 12416 | + return; | |
| 12417 | + }; | |
| 12418 | + let id = asyncrt::enqueue(async move { | |
| 12419 | + match gate.await { | |
| 12420 | + Ok(Ok(())) => Ok(String::new()), | |
| 12421 | + Ok(Err(error)) => Err(format!("Queue wake-entry gate: {error}")), | |
| 12422 | + Err(_) => Err("Queue wake-entry gate task dropped".to_string()), | |
| 12423 | + } | |
| 12424 | + }); | |
| 12425 | + rv.set(promise_for(scope, id)); | |
| 12426 | +} | |
| 12427 | +fn op_alarm_get( | |
| 12428 | + scope: &mut v8::PinScope, | |
| 12429 | + args: v8::FunctionCallbackArguments, | |
| 12430 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12431 | +) { | |
| 12432 | + let s = args.get(0).to_rust_string_lossy(scope); | |
| 12433 | + match storage::get_alarm(&s) { | |
| 12434 | + Some(at) => rv.set(v8::Number::new(scope, at as f64).into()), | |
| 12435 | + None => rv.set(v8::null(scope).into()), | |
| 12436 | + } | |
| 12437 | +} | |
| 12438 | +fn op_alarm_delete( | |
| 12439 | + scope: &mut v8::PinScope, | |
| 12440 | + args: v8::FunctionCallbackArguments, | |
| 12441 | + _rv: v8::ReturnValue<v8::Value>, | |
| 12442 | +) { | |
| 12443 | + let s = args.get(0).to_rust_string_lossy(scope); | |
| 12444 | + if let Err(error) = storage::delete_alarm(&s) { | |
| 12445 | + throw_storage_error(scope, "deleteAlarm", error); | |
| 12446 | + } | |
| 12447 | +} | |
| 12448 | + | |
| 12449 | +/// The reserved cron cell's whole schedule decision, in one call so the policy | |
| 12450 | +/// has one home in `celld_logic::cron` rather than a JavaScript copy that can | |
| 12451 | +/// drift from it. | |
| 12452 | +/// | |
| 12453 | +/// `firedMs` is the occurrence being handled, or negative when the cell is | |
| 12454 | +/// only arming. Returns `{ matching, armAt, armIsRetry }`: which expressions | |
| 12455 | +/// the occurrence belongs to, by index into the list passed in, when to arm | |
| 12456 | +/// next — `null` when the schedule is exhausted and the cell should retire — | |
| 12457 | +/// and whether that deadline is the failure backoff rather than the next | |
| 12458 | +/// occurrence. | |
| 12459 | +fn op_cron_plan( | |
| 12460 | + scope: &mut v8::PinScope, | |
| 12461 | + args: v8::FunctionCallbackArguments, | |
| 12462 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12463 | +) { | |
| 12464 | + let Ok(list) = v8::Local::<v8::Array>::try_from(args.get(0)) else { | |
| 12465 | + return; | |
| 12466 | + }; | |
| 12467 | + let mut crons = Vec::with_capacity(list.length() as usize); | |
| 12468 | + // Where each parsed expression sits in the list the caller passed. A | |
| 12469 | + // malformed expression is already refused by `celld deploy`, but the | |
| 12470 | + // control plane checks only the field count, so one can still arrive here. | |
| 12471 | + // Skipping it keeps one bad entry from silencing a script's other crons, | |
| 12472 | + // and this map is what keeps the skip from renumbering them: the caller | |
| 12473 | + // reports `controller.cron` by index, so a shifted index names the wrong | |
| 12474 | + // expression for every entry after the bad one. | |
| 12475 | + let mut positions = Vec::with_capacity(list.length() as usize); | |
| 12476 | + for index in 0..list.length() { | |
| 12477 | + let Some(value) = list.get_index(scope, index) else { | |
| 12478 | + continue; | |
| 12479 | + }; | |
| 12480 | + if let Ok(cron) = celld_logic::cron::parse(&value.to_rust_string_lossy(scope)) { | |
| 12481 | + crons.push(cron); | |
| 12482 | + positions.push(index as usize); | |
| 12483 | + } | |
| 12484 | + } | |
| 12485 | + let fired_ms = args.get(1).number_value(scope).unwrap_or(-1.0) as i64; | |
| 12486 | + let now_ms = args.get(2).number_value(scope).unwrap_or(0.0) as i64; | |
| 12487 | + let retry = args.get(3).number_value(scope).unwrap_or(0.0) as i64; | |
| 12488 | + let failed = args.get(4).boolean_value(scope); | |
| 12489 | + | |
| 12490 | + let matching = if fired_ms >= 0 { | |
| 12491 | + celld_logic::cron::matching(&crons, fired_ms) | |
| 12492 | + } else { | |
| 12493 | + Vec::new() | |
| 12494 | + }; | |
| 12495 | + let next = celld_logic::cron::next_across(&crons, now_ms); | |
| 12496 | + // The retry backoff is `alarm::alarm_retry`'s, not a second schedule: | |
| 12497 | + // a cron that fails behaves like any other failing alarm, except that | |
| 12498 | + // `cron_rearm` never lets the backoff outlast the next occurrence. | |
| 12499 | + let retry_at = failed | |
| 12500 | + .then(|| celld_logic::alarm::alarm_retry(now_ms, retry, retry, true)) | |
| 12501 | + .flatten(); | |
| 12502 | + let arm_at = celld_logic::cron::cron_rearm(next, retry_at); | |
| 12503 | + // Which of the two the deadline belongs to. `cron_rearm` takes the earlier | |
| 12504 | + // and gives a tie to the occurrence, so `armAt` alone cannot say — and the | |
| 12505 | + // caller has to know, because a retry owes the expressions of the | |
| 12506 | + // occurrence that failed, while a deadline that is an occurrence owes the | |
| 12507 | + // expressions that match it. | |
| 12508 | + let arm_is_retry = match (arm_at, next) { | |
| 12509 | + (Some(at), Some(occurrence)) => at < occurrence, | |
| 12510 | + (Some(_), None) => true, | |
| 12511 | + (None, _) => false, | |
| 12512 | + }; | |
| 12513 | + | |
| 12514 | + let indices = v8::Array::new(scope, matching.len() as i32); | |
| 12515 | + for (slot, index) in matching.iter().enumerate() { | |
| 12516 | + let value = v8::Number::new(scope, positions[*index] as f64); | |
| 12517 | + indices.set_index(scope, slot as u32, value.into()); | |
| 12518 | + } | |
| 12519 | + let result = v8::Object::new(scope); | |
| 12520 | + let key = v8::String::new(scope, "matching").unwrap(); | |
| 12521 | + result.set(scope, key.into(), indices.into()); | |
| 12522 | + let key = v8::String::new(scope, "armAt").unwrap(); | |
| 12523 | + let value: v8::Local<v8::Value> = match arm_at { | |
| 12524 | + Some(at) => v8::Number::new(scope, at as f64).into(), | |
| 12525 | + None => v8::null(scope).into(), | |
| 12526 | + }; | |
| 12527 | + result.set(scope, key.into(), value); | |
| 12528 | + let key = v8::String::new(scope, "armIsRetry").unwrap(); | |
| 12529 | + let value = v8::Boolean::new(scope, arm_is_retry); | |
| 12530 | + result.set(scope, key.into(), value.into()); | |
| 12531 | + rv.set(result.into()); | |
| 12532 | +} | |
| 12533 | + | |
| 12534 | +fn op_btoa( | |
| 12535 | + scope: &mut v8::PinScope, | |
| 12536 | + args: v8::FunctionCallbackArguments, | |
| 12537 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12538 | +) { | |
| 12539 | + use base64::Engine; | |
| 12540 | + // The public `btoa()` wrapper always supplies a string. The KV operator | |
| 12541 | + // protocol supplies a typed view directly, which avoids constructing a | |
| 12542 | + // second 25 MiB binary string only to encode it here. | |
| 12543 | + let bytes = view_bytes(args.get(0)).unwrap_or_else(|| { | |
| 12544 | + args.get(0) | |
| 12545 | + .to_rust_string_lossy(scope) | |
| 12546 | + .chars() | |
| 12547 | + .map(|c| c as u8) | |
| 12548 | + .collect() | |
| 12549 | + }); | |
| 12550 | + let s = base64::engine::general_purpose::STANDARD.encode(bytes); | |
| 12551 | + rv.set(v8::String::new(scope, &s).unwrap().into()); | |
| 12552 | +} | |
| 12553 | + | |
| 12554 | +// ---- WHATWG text decoders (encoding_rs) ---- | |
| 12555 | +// | |
| 12556 | +// These ops back every TextDecoder decode. src/js/text_encoding.js | |
| 12557 | +// resolves the label and owns the decoder's lifetime, and encoding_rs | |
| 12558 | +// does the decoding — for utf-8 and utf-16 as much as for every other | |
| 12559 | +// WHATWG label (windows-1252, Big5, GBK/GB18030, ISO-2022-JP, | |
| 12560 | +// x-user-defined, …). Previous utf-8 and utf-16 JS decoders were slower | |
| 12561 | +// than these ops at every measured size. | |
| 12562 | +// Streaming decoders live in a per-isolate table keyed by id; JS frees | |
| 12563 | +// one on the final decode (last=true), on a fatal error (encoding_rs | |
| 12564 | +// poisons an errored decoder), or via FinalizationRegistry when a | |
| 12565 | +// mid-stream decoder is abandoned. Ids are never reused, so a late | |
| 12566 | +// finalizer free of an already-closed id is a no-op. | |
| 12567 | + | |
| 12568 | +/// Live streaming decoders for one isolate, keyed by an id JS holds across | |
| 12569 | +/// awaits. | |
| 12570 | +/// | |
| 12571 | +/// An isolate slot rather than a process-wide `Mutex<HashMap<..>>` like | |
| 12572 | +/// [`zlib_streams`]. The reason that one is process-wide holds here too — a | |
| 12573 | +/// `TextDecoder` in streaming mode outlives the turn that made it, and the | |
| 12574 | +/// next turn can run on a different tokio worker — but it argues against a | |
| 12575 | +/// *thread-local*, not against this. A `TextDecoder` is a JS object, so it | |
| 12576 | +/// never leaves the isolate that made it, and every op that touches its | |
| 12577 | +/// decoder runs under that isolate's `v8::Locker`. The lock the embedder | |
| 12578 | +/// already holds is what makes the access exclusive, which `&mut Isolate` | |
| 12579 | +/// on the slot then proves. A second lock inside it buys nothing. | |
| 12580 | +/// | |
| 12581 | +/// This removes a ceiling rather than a measured regression, and the | |
| 12582 | +/// difference matters. In isolation the pattern does collapse: replayed on | |
| 12583 | +/// its own — remove, decode outside the lock, insert — 256-byte chunks | |
| 12584 | +/// peaked at two threads and then went *backwards*, 8 threads serving | |
| 12585 | +/// 0.46x what 1 thread served against 6.7x for the same decoding with no | |
| 12586 | +/// table. But celld end to end shows no difference between the two, at any | |
| 12587 | +/// concurrency this hardware can drive, because a chunk costs about 42us | |
| 12588 | +/// of stream and turn machinery around a lock held for about 100ns. So the | |
| 12589 | +/// mutex was not what any cell was waiting on. It was a process-wide | |
| 12590 | +/// serialisation point on a path that every stream now takes, and it went | |
| 12591 | +/// because it does not need to exist, not because it was costing anything | |
| 12592 | +/// yet. | |
| 12593 | +/// | |
| 12594 | +/// Dropping the isolate drops the table, so a decoder abandoned by a cell | |
| 12595 | +/// that goes away needs no finalizer to run. | |
| 12596 | +#[derive(Default)] | |
| 12597 | +struct TextDecoders(HashMap<u64, encoding_rs::Decoder>); | |
| 12598 | + | |
| 12599 | +static TEXT_DECODER_NEXT: AtomicU64 = AtomicU64::new(1); | |
| 12600 | + | |
| 12601 | +/// The calling isolate's decoder table, created on first use. | |
| 12602 | +fn text_decoders<'a>(scope: &'a mut v8::PinScope) -> &'a mut HashMap<u64, encoding_rs::Decoder> { | |
| 12603 | + if scope.get_slot::<TextDecoders>().is_none() { | |
| 12604 | + scope.set_slot(TextDecoders::default()); | |
| 12605 | + } | |
| 12606 | + &mut scope.get_slot_mut::<TextDecoders>().expect("just set").0 | |
| 12607 | +} | |
| 12608 | + | |
| 12609 | +/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined | |
| 12610 | +/// for unknown labels and the replacement encoding (RangeError in JS). | |
| 12611 | +fn op_text_decoder_label( | |
| 12612 | + scope: &mut v8::PinScope, | |
| 12613 | + args: v8::FunctionCallbackArguments, | |
| 12614 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12615 | +) { | |
| 12616 | + let label = args.get(0).to_rust_string_lossy(scope); | |
| 12617 | + if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) { | |
| 12618 | + let name = enc.name().to_ascii_lowercase(); | |
| 12619 | + rv.set(v8::String::new(scope, &name).unwrap().into()); | |
| 12620 | + } | |
| 12621 | +} | |
| 12622 | + | |
| 12623 | +/// `$$textDecoderNew(name, ignoreBOM)` -> id. | |
| 12624 | +fn op_text_decoder_new( | |
| 12625 | + scope: &mut v8::PinScope, | |
| 12626 | + args: v8::FunctionCallbackArguments, | |
| 12627 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12628 | +) { | |
| 12629 | + let name = args.get(0).to_rust_string_lossy(scope); | |
| 12630 | + let ignore_bom = args.get(1).boolean_value(scope); | |
| 12631 | + let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label"); | |
| 12632 | + let dec = if ignore_bom { | |
| 12633 | + enc.new_decoder_without_bom_handling() | |
| 12634 | + } else { | |
| 12635 | + enc.new_decoder_with_bom_removal() | |
| 12636 | + }; | |
| 12637 | + let id = TEXT_DECODER_NEXT.fetch_add(1, Ordering::Relaxed); | |
| 12638 | + text_decoders(scope).insert(id, dec); | |
| 12639 | + rv.set(v8::Number::new(scope, id as f64).into()); | |
| 12640 | +} | |
| 12641 | + | |
| 12642 | +/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the | |
| 12643 | +/// decoder when `last` is true or on a fatal malformed sequence | |
| 12644 | +/// (TypeError). | |
| 12645 | +fn op_text_decoder_decode( | |
| 12646 | + scope: &mut v8::PinScope, | |
| 12647 | + args: v8::FunctionCallbackArguments, | |
| 12648 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12649 | +) { | |
| 12650 | + let id = args.get(0).integer_value(scope).unwrap_or(0) as u64; | |
| 12651 | + let bytes = view_bytes(args.get(1)).unwrap_or_default(); | |
| 12652 | + let fatal = args.get(2).boolean_value(scope); | |
| 12653 | + let last = args.get(3).boolean_value(scope); | |
| 12654 | + // Per spec an empty streaming chunk is a no-op, but encoding_rs | |
| 12655 | + // 0.8 flushes a pending multibyte lead when fed an empty non-last | |
| 12656 | + // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead | |
| 12657 | + // of あ). Skip the decoder entirely. | |
| 12658 | + if bytes.is_empty() && !last { | |
| 12659 | + rv.set(v8::String::empty(scope).into()); | |
| 12660 | + return; | |
| 12661 | + } | |
| 12662 | + let mut dec = text_decoders(scope) | |
| 12663 | + .remove(&id) | |
| 12664 | + .expect("JS holds the only live id"); | |
| 12665 | + let Ok(out) = run_decoder(&mut dec, &bytes, fatal, last) else { | |
| 12666 | + throw_invalid_encoded_data(scope); | |
| 12667 | + return; | |
| 12668 | + }; | |
| 12669 | + if !last { | |
| 12670 | + text_decoders(scope).insert(id, dec); | |
| 12671 | + } | |
| 12672 | + rv.set(v8::String::new(scope, &out).unwrap().into()); | |
| 12673 | +} | |
| 12674 | + | |
| 12675 | +/// `$$textDecoderDecodeOnce(name, view, fatal, ignoreBOM)` -> string, for | |
| 12676 | +/// a complete buffer. | |
| 12677 | +/// | |
| 12678 | +/// The whole decode is one call, so the decoder never outlives it and | |
| 12679 | +/// never reaches [`text_decoders`]. That saves an insert and a remove, | |
| 12680 | +/// and it keeps every non-streaming decode on the node off a table that | |
| 12681 | +/// is one mutex for the whole process — which is most decodes, because | |
| 12682 | +/// `request.text()` and `response.text()` are not streams. A stream | |
| 12683 | +/// still takes that lock twice per chunk, which is a cost per chunk | |
| 12684 | +/// rather than per byte, and it has not been measured under load; | |
| 12685 | +/// sharding the table is the answer if it ever shows. | |
| 12686 | +fn op_text_decoder_decode_once( | |
| 12687 | + scope: &mut v8::PinScope, | |
| 12688 | + args: v8::FunctionCallbackArguments, | |
| 12689 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 12690 | +) { | |
| 12691 | + let name = args.get(0).to_rust_string_lossy(scope); | |
| 12692 | + let bytes = view_bytes(args.get(1)).unwrap_or_default(); | |
| 12693 | + let fatal = args.get(2).boolean_value(scope); | |
| 12694 | + let ignore_bom = args.get(3).boolean_value(scope); | |
| 12695 | + let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label"); | |
| 12696 | + let mut dec = if ignore_bom { | |
| 12697 | + enc.new_decoder_without_bom_handling() | |
| 12698 | + } else { | |
| 12699 | + enc.new_decoder_with_bom_removal() | |
| 12700 | + }; | |
| 12701 | + match run_decoder(&mut dec, &bytes, fatal, true) { | |
| 12702 | + Ok(out) => rv.set(v8::String::new(scope, &out).unwrap().into()), | |
| 12703 | + Err(()) => throw_invalid_encoded_data(scope), | |
| 12704 | + } | |
| 12705 | +} | |
| 12706 | + | |
| 12707 | +/// Feeds `bytes` to `dec` and answers the text. `Err` means `fatal` was | |
| 12708 | +/// set and the input was malformed. | |
| 12709 | +fn run_decoder( | |
| 12710 | + dec: &mut encoding_rs::Decoder, | |
| 12711 | + bytes: &[u8], | |
| 12712 | + fatal: bool, | |
| 12713 | + last: bool, | |
| 12714 | +) -> Result<String, ()> { | |
| 12715 | + let mut out = String::new(); | |
| 12716 | + if fatal { | |
| 12717 | + let cap = dec | |
| 12718 | + .max_utf8_buffer_length_without_replacement(bytes.len()) | |
| 12719 | + .unwrap(); | |
| 12720 | + out.reserve(cap); | |
| 12721 | + if !matches!( | |
| 12722 | + dec.decode_to_string_without_replacement(bytes, &mut out, last), | |
| 12723 | + (encoding_rs::DecoderResult::InputEmpty, _), | |
| 12724 | + ) { | |
| 12725 | + return Err(()); | |
| 12726 | + } | |
| 12727 | + } else { | |
| 12728 | + let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap(); | |
| 12729 | + out.reserve(cap); | |
| 12730 | + let _ = dec.decode_to_string(bytes, &mut out, last); | |
| 12731 | + } | |
| 12732 | + Ok(out) | |
| 12733 | +} | |
| 12734 | + | |
| 12735 | +fn throw_invalid_encoded_data(scope: &mut v8::PinScope) { | |
| 12736 | + let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap(); | |
| 12737 | + let exc = v8::Exception::type_error(scope, msg); | |
| 12738 | + scope.throw_exception(exc); | |
| 12739 | +} | |
| 12740 | + | |
| 12741 | +/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder | |
| 12742 | +/// abandoned mid-stream. | |
| 12743 | +fn op_text_decoder_free( | |
| 12744 | + scope: &mut v8::PinScope, | |
| 12745 | + args: v8::FunctionCallbackArguments, | |
| 12746 | + _rv: v8::ReturnValue<v8::Value>, | |
| 12747 | +) { | |
| 12748 | + let id = args.get(0).integer_value(scope).unwrap_or(0) as u64; | |
| 12749 | + text_decoders(scope).remove(&id); | |
| 12750 | +} | |
| 12751 | + | |
| 12752 | +// ---- the JS harness: Web API + the DO object model ---- | |
| 12753 | + | |
| 12754 | +#[doc(hidden)] | |
| 12755 | +pub mod bootstrap; | |
| 12756 | +pub mod modules; | |
| 12757 | +mod v8_strings; | |
| 12758 | +use bootstrap::{ | |
| 12759 | + adopt_cell, adopt_embedded_cell, begin_event_context, build_env, end_event_context, | |
| 12760 | + harness_env, inject_compatibility_flags, inject_crons, inject_kv_limits, inject_namespace_keys, | |
| 12761 | + inject_queue_config, inject_routing, inject_storage_compatibility, inject_workflows, | |
| 12762 | + install_harness, install_prelude, populate_cf_exports, register_class, register_entrypoints, | |
| 12763 | + validate_workflow_classes, | |
| 12764 | +}; | |
| 12765 | +use modules::{ | |
| 12766 | + compile_module, host_import_module_dynamically, install_lazy_globals, op_builtin_module, | |
| 12767 | + register_loader_modules, register_stubs, register_wasm_modules, resolve_external, | |
| 12768 | + ModuleRegistry, | |
| 12769 | +}; | |
| 12770 | +use v8_strings::key as static_key; | |
| 12771 | +/// Like `make_request`, but marks the request as incoming. Its signal is | |
| 12772 | +/// registered only if the handler actually suspends, preserving the | |
| 12773 | +/// synchronous request path. | |
| 12774 | +fn make_incoming_request<'s>( | |
| 12775 | + tc: &mut v8::PinScope<'s, '_>, | |
| 12776 | + url: &str, | |
| 12777 | + method: &str, | |
| 12778 | + body: RequestBody, | |
| 12779 | + headers: &[(String, String)], | |
| 12780 | +) -> Result<v8::Local<'s, v8::Value>> { | |
| 12781 | + let global = tc.get_current_context().global(tc); | |
| 12782 | + let key = v8::String::new(tc, "__makeIncomingRequest").unwrap(); | |
| 12783 | + let f: v8::Local<v8::Function> = global | |
| 12784 | + .get(tc, key.into()) | |
| 12785 | + .ok_or_else(|| anyhow!("no __makeIncomingRequest"))? | |
| 12786 | + .try_into() | |
| 12787 | + .map_err(|_| anyhow!("not fn"))?; | |
| 12788 | + let url = v8::String::new(tc, url).unwrap(); | |
| 12789 | + let method = v8::String::new(tc, method).unwrap(); | |
| 12790 | + let headers = v8::String::new( | |
| 12791 | + tc, | |
| 12792 | + &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()), | |
| 12793 | + ) | |
| 12794 | + .unwrap(); | |
| 12795 | + // A streamed body passes its id, and the harness builds the body | |
| 12796 | + // stream around that id. A held body passes the bytes. | |
| 12797 | + let stream_id = body.stream_id(); | |
| 12798 | + let (body, stream_id) = match stream_id { | |
| 12799 | + None => ( | |
| 12800 | + bytes_value(tc, body.into_held_bytes().unwrap()), | |
| 12801 | + v8::undefined(tc).into(), | |
| 12802 | + ), | |
| 12803 | + Some(id) => ( | |
| 12804 | + v8::undefined(tc).into(), | |
| 12805 | + v8::Number::new(tc, id as f64).into(), | |
| 12806 | + ), | |
| 12807 | + }; | |
| 12808 | + let recv = v8::undefined(tc).into(); | |
| 12809 | + f.call( | |
| 12810 | + tc, | |
| 12811 | + recv, | |
| 12812 | + &[url.into(), method.into(), body, headers.into(), stream_id], | |
| 12813 | + ) | |
| 12814 | + .ok_or_else(|| anyhow!("__makeIncomingRequest threw")) | |
| 12815 | +} | |
| 12816 | + | |
| 12817 | +fn register_incoming_request( | |
| 12818 | + tc: &mut v8::PinScope, | |
| 12819 | + request_id: RequestId, | |
| 12820 | + request: v8::Local<v8::Value>, | |
| 12821 | +) -> Result<()> { | |
| 12822 | + let global = tc.get_current_context().global(tc); | |
| 12823 | + let key = v8::String::new(tc, "__registerIncomingRequest").unwrap(); | |
| 12824 | + let function: v8::Local<v8::Function> = global | |
| 12825 | + .get(tc, key.into()) | |
| 12826 | + .ok_or_else(|| anyhow!("no __registerIncomingRequest"))? | |
| 12827 | + .try_into() | |
| 12828 | + .map_err(|_| anyhow!("__registerIncomingRequest is not a function"))?; | |
| 12829 | + let id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 12830 | + let recv = v8::undefined(tc).into(); | |
| 12831 | + function | |
| 12832 | + .call(tc, recv, &[id.into(), request]) | |
| 12833 | + .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?; | |
| 12834 | + Ok(()) | |
| 12835 | +} | |
| 12836 | + | |
| 12837 | +fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) { | |
| 12838 | + let global = tc.get_current_context().global(tc); | |
| 12839 | + let key = v8::String::new(tc, "__finishIncomingRequest").unwrap(); | |
| 12840 | + let Some(value) = global.get(tc, key.into()) else { | |
| 12841 | + return; | |
| 12842 | + }; | |
| 12843 | + let Ok(function) = value.try_cast::<v8::Function>() else { | |
| 12844 | + return; | |
| 12845 | + }; | |
| 12846 | + let id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 12847 | + let recv = v8::undefined(tc).into(); | |
| 12848 | + let _ = function.call(tc, recv, &[id.into()]); | |
| 12849 | +} | |
| 12850 | + | |
| 12851 | +fn make_request<'s>( | |
| 12852 | + tc: &mut v8::PinScope<'s, '_>, | |
| 12853 | + url: &str, | |
| 12854 | + method: &str, | |
| 12855 | + body: RequestBody, | |
| 12856 | + headers: &[(String, String)], | |
| 12857 | +) -> Result<v8::Local<'s, v8::Value>> { | |
| 12858 | + let g = tc.get_current_context().global(tc); | |
| 12859 | + let k = v8::String::new(tc, "__makeRequest").unwrap(); | |
| 12860 | + let f: v8::Local<v8::Function> = g.get(tc, k.into()).unwrap().try_into().unwrap(); | |
| 12861 | + let u = v8::String::new(tc, url).unwrap(); | |
| 12862 | + let m = v8::String::new(tc, method).unwrap(); | |
| 12863 | + let bytes = body.into_held_bytes().unwrap_or_default(); | |
| 12864 | + let b = bytes_value(tc, bytes); | |
| 12865 | + let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap(); | |
| 12866 | + let recv = v8::undefined(tc).into(); | |
| 12867 | + f.call(tc, recv, &[u.into(), m.into(), b, h.into()]) | |
| 12868 | + .ok_or_else(|| anyhow!("makeRequest threw")) | |
| 12869 | +} | |
| 12870 | + | |
| 12871 | +fn read_response(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> Result<HttpResponse> { | |
| 12872 | + let ctx = scope.get_current_context(); | |
| 12873 | + let global = ctx.global(scope); | |
| 12874 | + let key = v8::String::new(scope, "__readResponse").unwrap(); | |
| 12875 | + let f: v8::Local<v8::Function> = global | |
| 12876 | + .get(scope, key.into()) | |
| 12877 | + .ok_or_else(|| anyhow!("no __readResponse"))? | |
| 12878 | + .try_into() | |
| 12879 | + .map_err(|_| anyhow!("not fn"))?; | |
| 12880 | + let recv = v8::undefined(scope).into(); | |
| 12881 | + let out = f | |
| 12882 | + .call(scope, recv, &[ret]) | |
| 12883 | + .ok_or_else(|| anyhow!("readResponse threw"))?; | |
| 12884 | + // The harness response reader is synchronous. Keeping this assertion at | |
| 12885 | + // the native boundary prevents a future harness change from quietly | |
| 12886 | + // reintroducing a nested async runtime while an isolate is entered. | |
| 12887 | + if out.is_promise() { | |
| 12888 | + return Err(anyhow!("__readResponse returned a promise")); | |
| 12889 | + } | |
| 12890 | + let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?; | |
| 12891 | + let ek = v8::String::new(scope, "error").unwrap(); | |
| 12892 | + if let Some(error) = out.get(scope, ek.into()).filter(|value| value.is_string()) { | |
| 12893 | + return Err(anyhow!(error.to_rust_string_lossy(scope))); | |
| 12894 | + } | |
| 12895 | + let sk = v8::String::new(scope, "status").unwrap(); | |
| 12896 | + let bk = v8::String::new(scope, "bodyBytes").unwrap(); | |
| 12897 | + let tk = v8::String::new(scope, "bodyStreamId").unwrap(); | |
| 12898 | + let hk = v8::String::new(scope, "headersJson").unwrap(); | |
| 12899 | + let wk = v8::String::new(scope, "wsTargetJson").unwrap(); | |
| 12900 | + let worker_wk = v8::String::new(scope, "workerSocketId").unwrap(); | |
| 12901 | + let status = out | |
| 12902 | + .get(scope, sk.into()) | |
| 12903 | + .and_then(|v| v.uint32_value(scope)) | |
| 12904 | + .unwrap_or(200) as u16; | |
| 12905 | + // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON | |
| 12906 | + // number array (which was ~4x the bytes to serialize + parse per response). | |
| 12907 | + let body = out | |
| 12908 | + .get(scope, bk.into()) | |
| 12909 | + .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok()) | |
| 12910 | + .map(|view| { | |
| 12911 | + let mut buf = vec![0u8; view.byte_length()]; | |
| 12912 | + view.copy_contents(&mut buf); | |
| 12913 | + buf | |
| 12914 | + }) | |
| 12915 | + .unwrap_or_default(); | |
| 12916 | + let stream_id = out | |
| 12917 | + .get(scope, tk.into()) | |
| 12918 | + .and_then(|value| value.integer_value(scope)) | |
| 12919 | + .unwrap_or(0) | |
| 12920 | + .max(0) as u64; | |
| 12921 | + let stream = if stream_id == 0 { | |
| 12922 | + None | |
| 12923 | + } else { | |
| 12924 | + http_stream_service() | |
| 12925 | + .checkout_transfer(stream_id, None) | |
| 12926 | + .ok() | |
| 12927 | + .map(|source| Box::pin(source) as HttpChunkStream) | |
| 12928 | + }; | |
| 12929 | + if stream_id != 0 && stream.is_none() { | |
| 12930 | + return Err(anyhow!( | |
| 12931 | + "response stream {stream_id} is no longer available" | |
| 12932 | + )); | |
| 12933 | + } | |
| 12934 | + let headers = out | |
| 12935 | + .get(scope, hk.into()) | |
| 12936 | + .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok()) | |
| 12937 | + .unwrap_or_default(); | |
| 12938 | + let ws_json = out | |
| 12939 | + .get(scope, wk.into()) | |
| 12940 | + .map(|v| v.to_rust_string_lossy(scope)) | |
| 12941 | + .unwrap_or_else(|| "null".into()); | |
| 12942 | + let ws = serde_json::from_str(&ws_json).ok(); | |
| 12943 | + let worker_id = out | |
| 12944 | + .get(scope, worker_wk.into()) | |
| 12945 | + .and_then(|value| value.integer_value(scope)) | |
| 12946 | + .unwrap_or(0) | |
| 12947 | + .max(0) as u64; | |
| 12948 | + let worker_ws = if worker_id == 0 { | |
| 12949 | + None | |
| 12950 | + } else { | |
| 12951 | + Some( | |
| 12952 | + websocket::transfer_worker_websocket_handoff(worker_id) | |
| 12953 | + .ok_or_else(|| anyhow!("Worker WebSocket {worker_id} has no frame handoff"))?, | |
| 12954 | + ) | |
| 12955 | + }; | |
| 12956 | + if status == 101 { | |
| 12957 | + tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response"); | |
| 12958 | + } | |
| 12959 | + let websocket = match (ws, worker_ws) { | |
| 12960 | + (Some(target), None) => Some(HttpResponseWebSocket::Cell(target)), | |
| 12961 | + (None, Some(worker)) => Some(HttpResponseWebSocket::Worker(worker)), | |
| 12962 | + (None, None) => None, | |
| 12963 | + (Some(_), Some(_)) => return Err(anyhow!("Worker response has two WebSocket targets")), | |
| 12964 | + }; | |
| 12965 | + Ok(HttpResponse { | |
| 12966 | + status, | |
| 12967 | + body, | |
| 12968 | + stream, | |
| 12969 | + headers, | |
| 12970 | + websocket, | |
| 12971 | + write_position: None, | |
| 12972 | + observed_position: None, | |
| 9042 | 12973 | }) |
| 9043 | 12974 | } |
| 9044 | 12975 |
modifiedcrates/celld/js/bootstrap.rs+55−2View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/cache.js+105−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/crypto.js+252−60View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/crypto.rs+264−94View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/event_source.js+289−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/harness.js+10834−9522View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/html_rewriter.js+498−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/html_rewriter.rs+687−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/input_gate_lifecycle.rs+256−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/message_channel.js+111−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/modules.rs+33−7View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_crypto.js+11−14View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_diagnostics_channel.js+242−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/node_os.js+248−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/r2_ops.rs+4−2View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/sockets.js+231−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/storage_ops.rs+841−560View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/tcp.rs+289−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/websocket.rs+1266−926View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/kv_cli.rs+531−451View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/lib.rs+10−6View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ltx_repl.rs+4134−3320View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/machine.rs+178−125View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main.rs+5540−4729View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/cli.rs+382−369View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/peer_tunnel.rs+462−408View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/websocket.rs+1054−921View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/node_log.rs+5943−4869View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/node_log/recovery_progress.rs+150−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ownership_store.rs+1162−581View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/peer_auth.rs+239−246View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/pool.rs+750−624View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/protocol.rs+40−7View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/replication.rs+6−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/runtime.rs+3988−3431View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/startup.rs+3−12View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/storage.rs+4209−3700View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/telemetry.rs+943−726View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/wake.rs+159−51View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/drain.rs+123−100View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/durability.rs+76−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/format.rs+40−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/gate.rs+105−105View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/isolate.rs+22−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/lib.rs+6445−5486View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/log_tier.rs+213−150View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/output_gate.rs+335−222View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/peer.rs+8−6View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/rebalance.rs+163−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/schedule.rs+27−14View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/types.rs+1054−881View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/wake.rs+471−437View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/Cargo.toml+4−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/README.md+4−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/bundle.rs+115−109View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/client/epochs.rs+176−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/mod.rs+56−32View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/object_store.rs+1251−861View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/codec.rs+74−13View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/db.rs+2325−2076View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/error.rs+3−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/lib.rs+2−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/ltx.rs+27−47View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/paged.rs+546−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/paged_vfs.rs+681−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica_compactor.rs+72−61View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica_url.rs+294−295View file
Diff not rendered to keep this page fast. View the file
modifieddocs/README.md+924−694View file
Diff not rendered to keep this page fast. View the file
modifieddocs/cloudflare-compat.md+493−330View file
Diff not rendered to keep this page fast. View the file
modifieddocs/guarantees.md+277−212View file
Diff not rendered to keep this page fast. View the file
deleteddocs/library-api.md+0−60
Diff not rendered to keep this page fast. View the file
modifieddocs/limitations.md+4−2View file
Diff not rendered to keep this page fast. View the file
modifieddocs/telemetry.md+81−61View file
Diff not rendered to keep this page fast. View the file
modifieddocs/wasm.md+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/README.md+21−19View file
Diff not rendered to keep this page fast. View the file
addedexamples/opencode/README.md+35−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/opencode/index.js+144−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/opencode/package-lock.json+8679−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/opencode/package.json+10−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/opencode/wrangler.jsonc+10−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/pi/.gitignore+1−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/pi/README.md+43−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/pi/index.js+94−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/pi/package-lock.json+3011−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/pi/package.json+11−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/pi/wrangler.jsonc+24−0View file
Diff not rendered to keep this page fast. View the file