v0.4.0
Important upgrade note:
- A v0.3.0 fleet must stop completely before v0.4.0 is deployed. The two
versions cannot share a fleet because the peer tunnel protocol and large
Workers KV value references are incompatible.
Highlights:
- Add initial support for Workers KV, Queues, Workflows, and R2 bindings.
celld can deploy these bindings from the corresponding Wrangler
configuration.
- Add `celld dev` for local development. It rebuilds the application
automatically and uses a persistent local object store, so it does not
require Docker or a cloud bucket.
- Nodes can adopt a new deployment without restarting. Existing requests
finish on the old deployment, while new requests use the new deployment.
Durable Objects move at safe points and retain their storage and
hibernatable WebSockets.
- Strengthen the Durable Object output gate. It now applies one ordering
rule to responses, outbound calls, Queue deliveries, and WebSocket sends.
Read-only output waits for earlier request or alarm writes to become
durable.
- Route proxied fetch, RPC, and WebSocket calls through one versioned peer
tunnel. Request bodies stream to the owner. celld does not retry a call
after transmission starts because it does not retain a copy of the body.
- Improve graceful shutdown with batched handoffs, drain tokens, successor
acknowledgements, and full snapshots that reduce successor replay.
Configure the orchestrator stop grace to cover the drain-token wait,
handoff, and no-progress interval.
- Add commands to list cells and inspect or manage Workers KV namespaces
and Queues:
- `celld cell list`
- `celld kv get`, `celld kv put`, `celld kv delete`, `celld kv list`,
and `celld kv info`
- `celld kv bulk get`, `celld kv bulk put`, and
`celld kv bulk delete`
- `celld queue info`, `celld queue peek`, `celld queue purge`,
`celld queue pause`, `celld queue resume`, and
`celld queue redrive`
The cell and KV listings support pagination, full traversal, and
newline-delimited JSON.
- Move the public health endpoint from `/__celld/health` to
`/.well-known/celld/health`. Update load-balancer and readiness checks
when you upgrade.
- Add a configurable request-body limit, with a 1 GiB default, and a
per-cell concurrency limit. On Linux, memory-pressure handling now also
accounts for active cgroup memory.
- Add support for Amazon EKS Pod Identity credentials from the injected
environment variables and authorization-token file.
- Issues fixed:
- https://github.com/denoland/celld/issues/148
- https://github.com/denoland/celld/issues/161
- https://github.com/denoland/celld/issues/163
- https://github.com/denoland/celld/issues/165
- https://github.com/denoland/celld/issues/166
- https://github.com/denoland/celld/issues/167
- https://github.com/denoland/celld/issues/168
- https://github.com/denoland/celld/issues/170
Co-authored-by: Bartek Iwańczuk <[email protected]>
Co-authored-by: Divy Srivastava <[email protected]>
Co-authored-by: Kyle Kelley <[email protected]>
Co-authored-by: Nathan Whitaker <[email protected]>
Co-authored-by: Phil Renaud <[email protected]>
Co-authored-by: Yusuke Tanaka <[email protected]>Ryan Dahl authored signed1 parent 89e4ffccommit a52f9905425bc41134d817694bdc2c50bcc5e856Browse files
164 files changed+79829−58393
Files (164)
- .github/workflows/release.yml+3−4
- .gitignore+1−0
- Cargo.lock+190−132
- Cargo.toml+12−1
- LICENSE.tokio+21−0
- README.md+180−109
- clippy.toml+23−18
- crates/celld/Cargo.toml+10−2
- crates/celld/actor.rs+3904−2650
- crates/celld/actor/production.rs+5−7
- crates/celld/assets.rs+204−6
- crates/celld/asyncrt.rs+28−3
- crates/celld/bucket.rs+738−52
- crates/celld/cell_cli.rs+250−0
- crates/celld/cli_options.rs+142−0
- crates/celld/cli_output.rs+494−0
- crates/celld/control_plane.rs+121−116
- crates/celld/d1_cli.rs+161−261
- crates/celld/dead_node_gc.rs+4−6
- crates/celld/deploy.rs+754−43
- crates/celld/dev.rs+621−0
- crates/celld/drain_token.rs+223−0
- crates/celld/env_vars.rs+20−0
- crates/celld/fleet.rs+381−80
- crates/celld/generation.rs+420−0
- crates/celld/host_services.rs+8−56
- crates/celld/js.rs+9050−6260
- crates/celld/js/bootstrap.rs+999−491
- crates/celld/js/crypto.js+381−397
- crates/celld/js/crypto.rs+1168−1042
- crates/celld/js/harness.js+9844−5234
- crates/celld/js/headers.js+322−148
- crates/celld/js/modules.rs+600−570
- crates/celld/js/node_buffer.js+62−38
- crates/celld/js/node_events.js+1−2
- crates/celld/js/node_util.js+1−1
- crates/celld/js/r2_ops.rs+1286−0
- crates/celld/js/storage_ops.rs+277−175
- crates/celld/js/v8_strings.rs+65−0
- crates/celld/js/websocket.rs+1152−995
- crates/celld/kv_cli.rs+775−0
- crates/celld/lib.rs+517−237
- crates/celld/local_store.rs+557−0
- crates/celld/ltx_repl.rs+3494−1919
- crates/celld/machine.rs+123−137
- crates/celld/main.rs+4936−3233
- crates/celld/main/cli.rs+383−316
- crates/celld/main/peer_tunnel.rs+691−0
- crates/celld/main/websocket.rs+971−1117
- crates/celld/memory.rs+196−97
- crates/celld/node_log.rs+4925−2938
- crates/celld/operator_cell.rs+251−0
- crates/celld/otlp.rs+0−137
- crates/celld/ownership_store.rs+592−505
- crates/celld/peer_auth.rs+362−345
- crates/celld/peer_probe.rs+127−127
- crates/celld/pool.rs+649−419
- crates/celld/protocol.rs+330−108
- crates/celld/queue_cli.rs+221−0
- crates/celld/replication.rs+402−388
- crates/celld/runtime.rs+3419−2193
- crates/celld/startup.rs+0−6
- crates/celld/storage.rs+3822−3778
- crates/celld/telemetry.rs+1003−1254
- crates/celld/wake.rs+312−350
- crates/celld/ws_client.rs+1−1
- crates/logic/Cargo.toml+5−0
- crates/logic/drain.rs+154−0
- crates/logic/http.rs+227−0
- crates/logic/isolate.rs+7−5
- crates/logic/kv.rs+280−0
- crates/logic/lib.rs+5487−4680
- crates/logic/log_evict.rs+347−207
- crates/logic/log_tier.rs+94−53
- crates/logic/output_gate.rs+286−0
- crates/logic/pressure.rs+218−169
- crates/logic/queue.rs+365−0
- crates/logic/schedule.rs+2−2
- crates/logic/sqlite.rs+1−1
- crates/logic/sweep.rs+12−0
- crates/logic/types.rs+912−753
- crates/logic/wake.rs+1−1
- crates/ltx/Cargo.toml+29−29
- crates/ltx/README.md+59−76
- crates/ltx/reference/litestream-go/testdata/wal-reader/frame-checksum-mismatch/wal+0−0
- crates/ltx/reference/litestream-go/testdata/wal-reader/frame-salts/wal+0−0
- crates/ltx/reference/litestream-go/testdata/wal-reader/ok/wal+0−0
- crates/ltx/reference/litestream-go/testdata/wal-reader/salt-mismatch/wal+0−0
- crates/ltx/scripts/capture-golden.sh+0−74
- crates/ltx/scripts/db_equal.sh+0−72
- crates/ltx/src/bundle.rs+123−181
- crates/ltx/src/client/file.rs+0−36
- crates/ltx/src/client/mod.rs+63−171
- crates/ltx/src/client/object_store.rs+887−1083
- crates/ltx/src/compaction_level.rs+0−57
- crates/ltx/src/compactor.rs+0−240
- crates/ltx/src/db.rs+2131−2288
- crates/ltx/src/host.rs+321−317
- crates/ltx/src/lib.rs+399−389
- crates/ltx/src/ltx.rs+562−799
- crates/ltx/src/lz4_block.rs+8−59
- crates/ltx/src/replica.rs+1002−1336
- crates/ltx/src/replica_compactor.rs+46−195
- crates/ltx/src/replica_url.rs+0−278
- crates/ltx/src/wal.rs+547−843
- crates/ltx/tests/differential_xtool.rs+0−585
- crates/ltx/tests/faults_inject.rs+0−441
- crates/ltx/tests/fixtures/golden/.gitkeep+0−1
- crates/ltx/tests/fixtures/golden/MANIFEST.md+0−38
- crates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000001-0000000000000001.ltx+0−0
- crates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000002-0000000000000002.ltx+0−0
- crates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000003-0000000000000003.ltx+0−0
- crates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000004-0000000000000004.ltx+0−0
- crates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000005-0000000000000005.ltx+0−0
- crates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000006-0000000000000006.ltx+0−0
- crates/ltx/tests/fixtures/golden/sample.wal+0−0
- crates/ltx/tests/fuzz_bundle.rs+0−218
- crates/ltx/tests/fuzz_parsers.rs+0−539
- crates/ltx/tests/integration_file.rs+0−315
- crates/ltx/tests/integration_resilience.rs+0−449
- crates/ltx/tests/integration_s3.rs+0−397
- crates/ltx/tests/litestream_helpers.rs+0−525
- crates/ltx/tests/property_roundtrip.rs+0−243
- docs/README.md+705−391
- docs/cloudflare-compat.md+334−373
- docs/fencing.md+0−231
- docs/guarantees.md+228−0
- docs/library-api.md+60−0
- docs/limitations.md+46−53
- docs/security.md+150−126
- docs/telemetry.md+4−4
- docs/testing.md+73−63
- examples/README.md+33−18
- examples/alarm/index.js+29−21
- examples/alarm/wrangler.jsonc+3−1
- examples/async/index.js+17−29
- examples/async/wrangler.jsonc+4−2
- examples/body/index.js+21−21
- examples/counter/index.js+16−13
- examples/counter/wrangler.jsonc+3−1
- examples/cron/index.js+6−44
- examples/cron/wrangler.jsonc+1−6
- examples/d1/index.js+36−55
- examples/d1/wrangler.jsonc+0−4
- examples/hello/index.js+4−2
- examples/kv/index.js+21−0
- examples/kv/wrangler.jsonc+11−0
- examples/r2/index.js+33−0
- examples/r2/wrangler.jsonc+8−0
- examples/router/index.js+18−20
- examples/router/wrangler.jsonc+3−1
- examples/rpc/index.js+21−134
- examples/rpc/wrangler.jsonc+4−2
- examples/vectordb/index.js+37−24
- examples/vectordb/wrangler.jsonc+5−3
- examples/wasm/Cargo.toml+1−1
- examples/wasm/README.md+21−22
- examples/wasm/src/lib.rs+0−2
- examples/wasm/wrangler.jsonc+6−5
- examples/webapi/index.js+12−10
- examples/workflow/index.js+36−0
- examples/workflow/wrangler.jsonc+12−0
- examples/wsclient/index.js+23−35
- examples/wsecho/index.js+24−27
modified.github/workflows/release.yml+3−4View file
| @@ -140,8 +140,8 @@ | ||
| 140 | 140 | test -f "celld-$target.gz" |
| 141 | 141 | done |
| 142 | 142 | |
| 143 | - # Attestations require a public repository; until the visibility flip | |
| 144 | - # this step is skipped and drafts carry checksums only. | |
| 143 | + # Attestations require a public repository. Other repository visibilities | |
| 144 | + # skip this step and retain the release asset digests. | |
| 145 | 145 | - name: Attest build provenance |
| 146 | 146 | if: github.event.repository.visibility == 'public' |
| 147 | 147 | uses: actions/attest-build-provenance@v2 |
| @@ -296,8 +296,7 @@ | ||
| 296 | 296 | --format '{{json .Manifest.Digest}}' | tr -d '"') |
| 297 | 297 | echo "digest=$digest" >> "$GITHUB_OUTPUT" |
| 298 | 298 | |
| 299 | - # Attestations require a public repository; skipped until the | |
| 300 | - # visibility flip. | |
| 299 | + # Attestations require a public repository. | |
| 301 | 300 | - name: Attest image provenance |
| 302 | 301 | if: github.event.repository.visibility == 'public' |
| 303 | 302 | uses: actions/attest-build-provenance@v2 |
modified.gitignore+1−0View file
| @@ -1,2 +1,3 @@ | ||
| 1 | 1 | .DS_Store |
| 2 | +.celld/ | |
| 2 | 3 | /target/ |
modifiedCargo.lock+190−132View file
| @@ -193,7 +193,7 @@ | ||
| 193 | 193 | "bitflags", |
| 194 | 194 | "cexpr", |
| 195 | 195 | "clang-sys", |
| 196 | - "itertools", | |
| 196 | + "itertools 0.13.0", | |
| 197 | 197 | "log", |
| 198 | 198 | "prettyplease", |
| 199 | 199 | "proc-macro2", |
| @@ -205,21 +205,6 @@ | ||
| 205 | 205 | ] |
| 206 | 206 | |
| 207 | 207 | [[package]] |
| 208 | -name = "bit-set" | |
| 209 | -version = "0.8.0" | |
| 210 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 211 | -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" | |
| 212 | -dependencies = [ | |
| 213 | - "bit-vec", | |
| 214 | -] | |
| 215 | - | |
| 216 | -[[package]] | |
| 217 | -name = "bit-vec" | |
| 218 | -version = "0.8.0" | |
| 219 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 220 | -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" | |
| 221 | - | |
| 222 | -[[package]] | |
| 223 | 208 | name = "bitflags" |
| 224 | 209 | version = "2.13.1" |
| 225 | 210 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -288,7 +273,7 @@ | ||
| 288 | 273 | |
| 289 | 274 | [[package]] |
| 290 | 275 | name = "celld" |
| 291 | -version = "0.3.0" | |
| 276 | +version = "0.4.0" | |
| 292 | 277 | dependencies = [ |
| 293 | 278 | "aes", |
| 294 | 279 | "aes-gcm", |
| @@ -300,6 +285,7 @@ | ||
| 300 | 285 | "cbc", |
| 301 | 286 | "celld-logic", |
| 302 | 287 | "celld-ltx", |
| 288 | + "chrono", | |
| 303 | 289 | "crc", |
| 304 | 290 | "ctr", |
| 305 | 291 | "dsa", |
| @@ -309,6 +295,7 @@ | ||
| 309 | 295 | "flate2", |
| 310 | 296 | "futures-util", |
| 311 | 297 | "getrandom 0.3.4", |
| 298 | + "hkdf", | |
| 312 | 299 | "hmac", |
| 313 | 300 | "http-body-util", |
| 314 | 301 | "hyper", |
| @@ -317,11 +304,14 @@ | ||
| 317 | 304 | "lz4_flex", |
| 318 | 305 | "md-5", |
| 319 | 306 | "nix", |
| 307 | + "notify", | |
| 308 | + "nu-ansi-term", | |
| 320 | 309 | "object_store", |
| 321 | 310 | "p256", |
| 322 | 311 | "p384", |
| 323 | 312 | "p521", |
| 324 | 313 | "parquet", |
| 314 | + "pbkdf2", | |
| 325 | 315 | "percent-encoding", |
| 326 | 316 | "pkcs8", |
| 327 | 317 | "rand 0.8.7", |
| @@ -365,12 +355,9 @@ | ||
| 365 | 355 | "bytes", |
| 366 | 356 | "chrono", |
| 367 | 357 | "futures-util", |
| 368 | - "hex", | |
| 369 | 358 | "lz4_flex", |
| 370 | 359 | "object_store", |
| 371 | - "proptest", | |
| 372 | 360 | "rusqlite", |
| 373 | - "tempfile", | |
| 374 | 361 | "thiserror 2.0.19", |
| 375 | 362 | "tokio", |
| 376 | 363 | "tracing", |
| @@ -880,6 +867,15 @@ | ||
| 880 | 867 | ] |
| 881 | 868 | |
| 882 | 869 | [[package]] |
| 870 | +name = "fsevent-sys" | |
| 871 | +version = "4.1.0" | |
| 872 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 873 | +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" | |
| 874 | +dependencies = [ | |
| 875 | + "libc", | |
| 876 | +] | |
| 877 | + | |
| 878 | +[[package]] | |
| 883 | 879 | name = "fslock" |
| 884 | 880 | version = "0.2.1" |
| 885 | 881 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -1119,18 +1115,6 @@ | ||
| 1119 | 1115 | ] |
| 1120 | 1116 | |
| 1121 | 1117 | [[package]] |
| 1122 | -name = "heck" | |
| 1123 | -version = "0.5.0" | |
| 1124 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1125 | -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" | |
| 1126 | - | |
| 1127 | -[[package]] | |
| 1128 | -name = "hex" | |
| 1129 | -version = "0.4.3" | |
| 1130 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1131 | -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" | |
| 1132 | - | |
| 1133 | -[[package]] | |
| 1134 | 1118 | name = "hkdf" |
| 1135 | 1119 | version = "0.12.4" |
| 1136 | 1120 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -1454,6 +1438,26 @@ | ||
| 1454 | 1438 | ] |
| 1455 | 1439 | |
| 1456 | 1440 | [[package]] |
| 1441 | +name = "inotify" | |
| 1442 | +version = "0.11.5" | |
| 1443 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1444 | +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" | |
| 1445 | +dependencies = [ | |
| 1446 | + "bitflags", | |
| 1447 | + "inotify-sys", | |
| 1448 | + "libc", | |
| 1449 | +] | |
| 1450 | + | |
| 1451 | +[[package]] | |
| 1452 | +name = "inotify-sys" | |
| 1453 | +version = "0.1.8" | |
| 1454 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1455 | +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" | |
| 1456 | +dependencies = [ | |
| 1457 | + "libc", | |
| 1458 | +] | |
| 1459 | + | |
| 1460 | +[[package]] | |
| 1457 | 1461 | name = "inout" |
| 1458 | 1462 | version = "0.1.4" |
| 1459 | 1463 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -1479,6 +1483,15 @@ | ||
| 1479 | 1483 | ] |
| 1480 | 1484 | |
| 1481 | 1485 | [[package]] |
| 1486 | +name = "itertools" | |
| 1487 | +version = "0.14.0" | |
| 1488 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1489 | +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" | |
| 1490 | +dependencies = [ | |
| 1491 | + "either", | |
| 1492 | +] | |
| 1493 | + | |
| 1494 | +[[package]] | |
| 1482 | 1495 | name = "itoa" |
| 1483 | 1496 | version = "1.0.18" |
| 1484 | 1497 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -1512,6 +1525,26 @@ | ||
| 1512 | 1525 | ] |
| 1513 | 1526 | |
| 1514 | 1527 | [[package]] |
| 1528 | +name = "kqueue" | |
| 1529 | +version = "1.2.1" | |
| 1530 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1531 | +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" | |
| 1532 | +dependencies = [ | |
| 1533 | + "kqueue-sys", | |
| 1534 | + "libc", | |
| 1535 | +] | |
| 1536 | + | |
| 1537 | +[[package]] | |
| 1538 | +name = "kqueue-sys" | |
| 1539 | +version = "1.1.2" | |
| 1540 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1541 | +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" | |
| 1542 | +dependencies = [ | |
| 1543 | + "bitflags", | |
| 1544 | + "libc", | |
| 1545 | +] | |
| 1546 | + | |
| 1547 | +[[package]] | |
| 1515 | 1548 | name = "lazy_static" |
| 1516 | 1549 | version = "1.5.0" |
| 1517 | 1550 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -1661,6 +1694,7 @@ | ||
| 1661 | 1694 | checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" |
| 1662 | 1695 | dependencies = [ |
| 1663 | 1696 | "libc", |
| 1697 | + "log", | |
| 1664 | 1698 | "wasi", |
| 1665 | 1699 | "windows-sys 0.61.2", |
| 1666 | 1700 | ] |
| @@ -1705,6 +1739,33 @@ | ||
| 1705 | 1739 | ] |
| 1706 | 1740 | |
| 1707 | 1741 | [[package]] |
| 1742 | +name = "notify" | |
| 1743 | +version = "8.2.0" | |
| 1744 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1745 | +checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" | |
| 1746 | +dependencies = [ | |
| 1747 | + "bitflags", | |
| 1748 | + "fsevent-sys", | |
| 1749 | + "inotify", | |
| 1750 | + "kqueue", | |
| 1751 | + "libc", | |
| 1752 | + "log", | |
| 1753 | + "mio", | |
| 1754 | + "notify-types", | |
| 1755 | + "walkdir", | |
| 1756 | + "windows-sys 0.60.2", | |
| 1757 | +] | |
| 1758 | + | |
| 1759 | +[[package]] | |
| 1760 | +name = "notify-types" | |
| 1761 | +version = "2.1.0" | |
| 1762 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1763 | +checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" | |
| 1764 | +dependencies = [ | |
| 1765 | + "bitflags", | |
| 1766 | +] | |
| 1767 | + | |
| 1768 | +[[package]] | |
| 1708 | 1769 | name = "nu-ansi-term" |
| 1709 | 1770 | version = "0.50.3" |
| 1710 | 1771 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -1776,34 +1837,39 @@ | ||
| 1776 | 1837 | |
| 1777 | 1838 | [[package]] |
| 1778 | 1839 | name = "object_store" |
| 1779 | -version = "0.11.2" | |
| 1840 | +version = "0.12.5" | |
| 1780 | 1841 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1781 | -checksum = "3cfccb68961a56facde1163f9319e0d15743352344e7808a11795fb99698dcaf" | |
| 1842 | +checksum = "fbfbfff40aeccab00ec8a910b57ca8ecf4319b335c542f2edcd19dd25a1e2a00" | |
| 1782 | 1843 | dependencies = [ |
| 1783 | 1844 | "async-trait", |
| 1784 | 1845 | "base64 0.22.1", |
| 1785 | 1846 | "bytes", |
| 1786 | 1847 | "chrono", |
| 1848 | + "form_urlencoded", | |
| 1787 | 1849 | "futures", |
| 1850 | + "http", | |
| 1851 | + "http-body-util", | |
| 1788 | 1852 | "httparse", |
| 1789 | 1853 | "humantime", |
| 1790 | 1854 | "hyper", |
| 1791 | - "itertools", | |
| 1855 | + "itertools 0.14.0", | |
| 1792 | 1856 | "md-5", |
| 1793 | 1857 | "parking_lot", |
| 1794 | 1858 | "percent-encoding", |
| 1795 | 1859 | "quick-xml", |
| 1796 | - "rand 0.8.7", | |
| 1860 | + "rand 0.9.5", | |
| 1797 | 1861 | "reqwest", |
| 1798 | 1862 | "ring", |
| 1799 | 1863 | "rustls-pemfile", |
| 1800 | 1864 | "serde", |
| 1801 | 1865 | "serde_json", |
| 1802 | - "snafu", | |
| 1866 | + "serde_urlencoded", | |
| 1867 | + "thiserror 2.0.19", | |
| 1803 | 1868 | "tokio", |
| 1804 | 1869 | "tracing", |
| 1805 | 1870 | "url", |
| 1806 | - "walkdir", | |
| 1871 | + "wasm-bindgen-futures", | |
| 1872 | + "web-time", | |
| 1807 | 1873 | ] |
| 1808 | 1874 | |
| 1809 | 1875 | [[package]] |
| @@ -2072,35 +2138,10 @@ | ||
| 2072 | 2138 | ] |
| 2073 | 2139 | |
| 2074 | 2140 | [[package]] |
| 2075 | -name = "proptest" | |
| 2076 | -version = "1.11.0" | |
| 2077 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2078 | -checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" | |
| 2079 | -dependencies = [ | |
| 2080 | - "bit-set", | |
| 2081 | - "bit-vec", | |
| 2082 | - "bitflags", | |
| 2083 | - "num-traits", | |
| 2084 | - "rand 0.9.5", | |
| 2085 | - "rand_chacha 0.9.0", | |
| 2086 | - "rand_xorshift", | |
| 2087 | - "regex-syntax", | |
| 2088 | - "rusty-fork", | |
| 2089 | - "tempfile", | |
| 2090 | - "unarray", | |
| 2091 | -] | |
| 2092 | - | |
| 2093 | -[[package]] | |
| 2094 | -name = "quick-error" | |
| 2095 | -version = "1.2.3" | |
| 2096 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2097 | -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" | |
| 2098 | - | |
| 2099 | -[[package]] | |
| 2100 | 2141 | name = "quick-xml" |
| 2101 | -version = "0.37.5" | |
| 2142 | +version = "0.38.4" | |
| 2102 | 2143 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2103 | -checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" | |
| 2144 | +checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" | |
| 2104 | 2145 | dependencies = [ |
| 2105 | 2146 | "memchr", |
| 2106 | 2147 | "serde", |
| @@ -2269,15 +2310,6 @@ | ||
| 2269 | 2310 | ] |
| 2270 | 2311 | |
| 2271 | 2312 | [[package]] |
| 2272 | -name = "rand_xorshift" | |
| 2273 | -version = "0.4.0" | |
| 2274 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2275 | -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" | |
| 2276 | -dependencies = [ | |
| 2277 | - "rand_core 0.9.5", | |
| 2278 | -] | |
| 2279 | - | |
| 2280 | -[[package]] | |
| 2281 | 2313 | name = "redox_syscall" |
| 2282 | 2314 | version = "0.5.18" |
| 2283 | 2315 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -2531,18 +2563,6 @@ | ||
| 2531 | 2563 | checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" |
| 2532 | 2564 | |
| 2533 | 2565 | [[package]] |
| 2534 | -name = "rusty-fork" | |
| 2535 | -version = "0.3.1" | |
| 2536 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2537 | -checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" | |
| 2538 | -dependencies = [ | |
| 2539 | - "fnv", | |
| 2540 | - "quick-error", | |
| 2541 | - "tempfile", | |
| 2542 | - "wait-timeout", | |
| 2543 | -] | |
| 2544 | - | |
| 2545 | -[[package]] | |
| 2546 | 2566 | name = "ryu" |
| 2547 | 2567 | version = "1.0.23" |
| 2548 | 2568 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -2789,27 +2809,6 @@ | ||
| 2789 | 2809 | checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" |
| 2790 | 2810 | |
| 2791 | 2811 | [[package]] |
| 2792 | -name = "snafu" | |
| 2793 | -version = "0.8.9" | |
| 2794 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2795 | -checksum = "6e84b3f4eacbf3a1ce05eac6763b4d629d60cbc94d632e4092c54ade71f1e1a2" | |
| 2796 | -dependencies = [ | |
| 2797 | - "snafu-derive", | |
| 2798 | -] | |
| 2799 | - | |
| 2800 | -[[package]] | |
| 2801 | -name = "snafu-derive" | |
| 2802 | -version = "0.8.9" | |
| 2803 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2804 | -checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" | |
| 2805 | -dependencies = [ | |
| 2806 | - "heck", | |
| 2807 | - "proc-macro2", | |
| 2808 | - "quote", | |
| 2809 | - "syn 2.0.119", | |
| 2810 | -] | |
| 2811 | - | |
| 2812 | -[[package]] | |
| 2813 | 2812 | name = "socket2" |
| 2814 | 2813 | version = "0.6.5" |
| 2815 | 2814 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -3321,12 +3320,6 @@ | ||
| 3321 | 3320 | checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" |
| 3322 | 3321 | |
| 3323 | 3322 | [[package]] |
| 3324 | -name = "unarray" | |
| 3325 | -version = "0.1.4" | |
| 3326 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3327 | -checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" | |
| 3328 | - | |
| 3329 | -[[package]] | |
| 3330 | 3323 | name = "unicode-ident" |
| 3331 | 3324 | version = "1.0.24" |
| 3332 | 3325 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -3420,15 +3413,6 @@ | ||
| 3420 | 3413 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" |
| 3421 | 3414 | |
| 3422 | 3415 | [[package]] |
| 3423 | -name = "wait-timeout" | |
| 3424 | -version = "0.2.1" | |
| 3425 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3426 | -checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" | |
| 3427 | -dependencies = [ | |
| 3428 | - "libc", | |
| 3429 | -] | |
| 3430 | - | |
| 3431 | -[[package]] | |
| 3432 | 3416 | name = "walkdir" |
| 3433 | 3417 | version = "2.5.0" |
| 3434 | 3418 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| @@ -3667,7 +3651,7 @@ | ||
| 3667 | 3651 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3668 | 3652 | checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" |
| 3669 | 3653 | dependencies = [ |
| 3670 | - "windows-targets", | |
| 3654 | + "windows-targets 0.52.6", | |
| 3671 | 3655 | ] |
| 3672 | 3656 | |
| 3673 | 3657 | [[package]] |
| @@ -3676,11 +3660,20 @@ | ||
| 3676 | 3660 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3677 | 3661 | checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" |
| 3678 | 3662 | dependencies = [ |
| 3679 | - "windows-targets", | |
| 3663 | + "windows-targets 0.52.6", | |
| 3680 | 3664 | ] |
| 3681 | 3665 | |
| 3682 | 3666 | [[package]] |
| 3683 | 3667 | name = "windows-sys" |
| 3668 | +version = "0.60.2" | |
| 3669 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3670 | +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" | |
| 3671 | +dependencies = [ | |
| 3672 | + "windows-targets 0.53.5", | |
| 3673 | +] | |
| 3674 | + | |
| 3675 | +[[package]] | |
| 3676 | +name = "windows-sys" | |
| 3684 | 3677 | version = "0.61.2" |
| 3685 | 3678 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3686 | 3679 | checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" |
| @@ -3694,65 +3687,130 @@ | ||
| 3694 | 3687 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3695 | 3688 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" |
| 3696 | 3689 | dependencies = [ |
| 3697 | - "windows_aarch64_gnullvm", | |
| 3698 | - "windows_aarch64_msvc", | |
| 3699 | - "windows_i686_gnu", | |
| 3700 | - "windows_i686_gnullvm", | |
| 3701 | - "windows_i686_msvc", | |
| 3702 | - "windows_x86_64_gnu", | |
| 3703 | - "windows_x86_64_gnullvm", | |
| 3704 | - "windows_x86_64_msvc", | |
| 3690 | + "windows_aarch64_gnullvm 0.52.6", | |
| 3691 | + "windows_aarch64_msvc 0.52.6", | |
| 3692 | + "windows_i686_gnu 0.52.6", | |
| 3693 | + "windows_i686_gnullvm 0.52.6", | |
| 3694 | + "windows_i686_msvc 0.52.6", | |
| 3695 | + "windows_x86_64_gnu 0.52.6", | |
| 3696 | + "windows_x86_64_gnullvm 0.52.6", | |
| 3697 | + "windows_x86_64_msvc 0.52.6", | |
| 3705 | 3698 | ] |
| 3706 | 3699 | |
| 3707 | 3700 | [[package]] |
| 3701 | +name = "windows-targets" | |
| 3702 | +version = "0.53.5" | |
| 3703 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3704 | +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" | |
| 3705 | +dependencies = [ | |
| 3706 | + "windows-link", | |
| 3707 | + "windows_aarch64_gnullvm 0.53.1", | |
| 3708 | + "windows_aarch64_msvc 0.53.1", | |
| 3709 | + "windows_i686_gnu 0.53.1", | |
| 3710 | + "windows_i686_gnullvm 0.53.1", | |
| 3711 | + "windows_i686_msvc 0.53.1", | |
| 3712 | + "windows_x86_64_gnu 0.53.1", | |
| 3713 | + "windows_x86_64_gnullvm 0.53.1", | |
| 3714 | + "windows_x86_64_msvc 0.53.1", | |
| 3715 | +] | |
| 3716 | + | |
| 3717 | +[[package]] | |
| 3708 | 3718 | name = "windows_aarch64_gnullvm" |
| 3709 | 3719 | version = "0.52.6" |
| 3710 | 3720 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3711 | 3721 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" |
| 3712 | 3722 | |
| 3713 | 3723 | [[package]] |
| 3724 | +name = "windows_aarch64_gnullvm" | |
| 3725 | +version = "0.53.1" | |
| 3726 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3727 | +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" | |
| 3728 | + | |
| 3729 | +[[package]] | |
| 3714 | 3730 | name = "windows_aarch64_msvc" |
| 3715 | 3731 | version = "0.52.6" |
| 3716 | 3732 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3717 | 3733 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" |
| 3718 | 3734 | |
| 3719 | 3735 | [[package]] |
| 3736 | +name = "windows_aarch64_msvc" | |
| 3737 | +version = "0.53.1" | |
| 3738 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3739 | +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" | |
| 3740 | + | |
| 3741 | +[[package]] | |
| 3720 | 3742 | name = "windows_i686_gnu" |
| 3721 | 3743 | version = "0.52.6" |
| 3722 | 3744 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3723 | 3745 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" |
| 3724 | 3746 | |
| 3725 | 3747 | [[package]] |
| 3748 | +name = "windows_i686_gnu" | |
| 3749 | +version = "0.53.1" | |
| 3750 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3751 | +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" | |
| 3752 | + | |
| 3753 | +[[package]] | |
| 3726 | 3754 | name = "windows_i686_gnullvm" |
| 3727 | 3755 | version = "0.52.6" |
| 3728 | 3756 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3729 | 3757 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" |
| 3730 | 3758 | |
| 3731 | 3759 | [[package]] |
| 3760 | +name = "windows_i686_gnullvm" | |
| 3761 | +version = "0.53.1" | |
| 3762 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3763 | +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" | |
| 3764 | + | |
| 3765 | +[[package]] | |
| 3732 | 3766 | name = "windows_i686_msvc" |
| 3733 | 3767 | version = "0.52.6" |
| 3734 | 3768 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3735 | 3769 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" |
| 3736 | 3770 | |
| 3737 | 3771 | [[package]] |
| 3772 | +name = "windows_i686_msvc" | |
| 3773 | +version = "0.53.1" | |
| 3774 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3775 | +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" | |
| 3776 | + | |
| 3777 | +[[package]] | |
| 3738 | 3778 | name = "windows_x86_64_gnu" |
| 3739 | 3779 | version = "0.52.6" |
| 3740 | 3780 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3741 | 3781 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" |
| 3742 | 3782 | |
| 3743 | 3783 | [[package]] |
| 3784 | +name = "windows_x86_64_gnu" | |
| 3785 | +version = "0.53.1" | |
| 3786 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3787 | +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" | |
| 3788 | + | |
| 3789 | +[[package]] | |
| 3744 | 3790 | name = "windows_x86_64_gnullvm" |
| 3745 | 3791 | version = "0.52.6" |
| 3746 | 3792 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3747 | 3793 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" |
| 3748 | 3794 | |
| 3749 | 3795 | [[package]] |
| 3796 | +name = "windows_x86_64_gnullvm" | |
| 3797 | +version = "0.53.1" | |
| 3798 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3799 | +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" | |
| 3800 | + | |
| 3801 | +[[package]] | |
| 3750 | 3802 | name = "windows_x86_64_msvc" |
| 3751 | 3803 | version = "0.52.6" |
| 3752 | 3804 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3753 | 3805 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" |
| 3754 | 3806 | |
| 3755 | 3807 | [[package]] |
| 3808 | +name = "windows_x86_64_msvc" | |
| 3809 | +version = "0.53.1" | |
| 3810 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3811 | +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" | |
| 3812 | + | |
| 3813 | +[[package]] | |
| 3756 | 3814 | name = "winsafe" |
| 3757 | 3815 | version = "0.0.19" |
| 3758 | 3816 | source = "registry+https://github.com/rust-lang/crates.io-index" |
modifiedCargo.toml+12−1View file
| @@ -21,6 +21,10 @@ | ||
| 21 | 21 | lto = "thin" |
| 22 | 22 | codegen-units = 16 |
| 23 | 23 | incremental = true |
| 24 | +# The lab image keeps symbols so `perf` on a node attributes CPU by function; | |
| 25 | +# the shipped release profile stays stripped. | |
| 26 | +strip = false | |
| 27 | +debug = "line-tables-only" | |
| 24 | 28 | [profile.dev.package.sha2] |
| 25 | 29 | opt-level = 3 |
| 26 | 30 | [profile.dev.package.rsa] |
| @@ -57,7 +61,12 @@ | ||
| 57 | 61 | futures-util = "0.3" |
| 58 | 62 | getrandom = "0.3" |
| 59 | 63 | hex = "0.4" |
| 64 | +# The two node:crypto KDFs. Both crates already reach this build without a | |
| 65 | +# line here -- `pbkdf2` through `pkcs5`, `hkdf` through `elliptic-curve` -- | |
| 66 | +# so declaring them costs no compile time and adds no supply-chain surface. | |
| 67 | +hkdf = "0.12" | |
| 60 | 68 | hmac = "0.12" |
| 69 | +pbkdf2 = "0.12" | |
| 61 | 70 | http-body-util = "0.1" |
| 62 | 71 | hyper = { version = "1", features = ["client", "server", "http1"] } |
| 63 | 72 | hyper-util = { version = "0.1", features = ["tokio"] } |
| @@ -65,7 +74,9 @@ | ||
| 65 | 74 | lz4_flex = { version = "0.11", features = ["frame"] } |
| 66 | 75 | md-5 = "0.10" |
| 67 | 76 | nix = { version = "0.31", features = ["feature", "fs"] } |
| 68 | -object_store = { version = "0.11", default-features = false } | |
| 77 | +notify = "8" | |
| 78 | +nu-ansi-term = "0.50" | |
| 79 | +object_store = { version = "0.12", default-features = false } | |
| 69 | 80 | # The native column-writer API only: no `arrow` feature, so the arrow |
| 70 | 81 | # crate stack stays out of the binary. Revisit only if the telemetry |
| 71 | 82 | # schema ever grows nested columns. |
addedLICENSE.tokio+21−0View file
| @@ -1,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) Tokio Contributors | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
modifiedREADME.md+180−109View file
| @@ -3,31 +3,35 @@ | ||
| 3 | 3 | Self-hosted, distributed **Durable Objects**. |
| 4 | 4 | |
| 5 | 5 | celld is an open-source daemon that runs Cloudflare Workers and Durable |
| 6 | -Objects on your own machines. Each object is its own SQLite database. | |
| 7 | -celld addresses an object by name and replicates it to a bucket that you | |
| 8 | -own. The bucket can be S3-compatible, Google Cloud Storage, or Azure | |
| 9 | -Blob Storage. The nodes coordinate through that bucket alone, with no | |
| 10 | -control plane and no consensus. Because every object is its own small | |
| 11 | -database, applications shard by construction — the contention and | |
| 12 | -blast-radius failures of one shared database are designed out, not | |
| 13 | -managed. A cell that no node holds is inactive, and an inactive cell | |
| 14 | -costs nearly nothing. Learn more at | |
| 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 | |
| 8 | +that you own — S3-compatible, Google Cloud Storage, or Azure Blob | |
| 9 | +Storage — and needs no serving control plane and no consensus service. | |
| 10 | +A cell that nothing is serving costs almost nothing. Learn more at | |
| 15 | 11 | [celld.dev](https://celld.dev) or read the |
| 16 | 12 | [documentation](https://celld.dev/docs). |
| 17 | 13 | |
| 18 | 14 | ## How it works |
| 19 | 15 | |
| 20 | -Every `celld` node embeds V8 and executes Wrangler bundles. The fleet shares | |
| 21 | -one bucket, which contains deployments, cell state, and small ownership | |
| 22 | -records. The bucket can be S3-compatible, Google Cloud Storage, or Azure | |
| 23 | -Blob Storage. Object-storage compare-and-swap ensures that exactly one | |
| 24 | -node owns a cell at a time, without a membership protocol, failure | |
| 25 | -detector, or consensus service. | |
| 16 | +A node is one `celld` process, and you run one on each machine. Every | |
| 17 | +node embeds V8 and executes Wrangler bundles. The nodes that share one | |
| 18 | +bucket are a fleet, and that bucket holds the deployments, the cell | |
| 19 | +state, and small ownership records. A conditional bucket write gives a node the | |
| 20 | +ownership of a cell, so exactly one node owns a cell at a time — no | |
| 21 | +membership protocol, no failure detector, no consensus service. Signed | |
| 22 | +peer HTTP provides routing and replicated-log transport. | |
| 26 | 23 | |
| 27 | -celld continuously replicates each cell's SQLite database to the bucket. | |
| 28 | -When a cell moves, or when an inactive cell activates, its new owner restores | |
| 29 | -that database and resumes execution. The bucket is the durable source of | |
| 30 | -truth; nodes are replaceable. | |
| 24 | +celld captures each committed SQLite write as LTX data, the transaction | |
| 25 | +format the replication uses. A single node proves the write durable by | |
| 26 | +uploading that data to the bucket. A fleet of two or more nodes proves it | |
| 27 | +sooner: the owner sends the data to one or two other nodes, and the write | |
| 28 | +is durable as soon as they hold it on their disks. celld uploads the data | |
| 29 | +to the bucket afterwards. A single node has no other node to send to, so | |
| 30 | +each write waits for the bucket, and those writes are much slower. | |
| 31 | +Before a takeover restores a cell, celld recovers an open log from the | |
| 32 | +prior owner, so the bucket holds the long-term state and nodes stay | |
| 33 | +replaceable. See [what celld guarantees](docs/guarantees.md) for the | |
| 34 | +complete protocol. | |
| 31 | 35 | |
| 32 | 36 | ## Install |
| 33 | 37 | |
| @@ -85,10 +89,38 @@ | ||
| 85 | 89 | |
| 86 | 90 | ## Run it |
| 87 | 91 | |
| 88 | -celld uses the standard AWS credential chain. Deploy to an S3-compatible | |
| 89 | -bucket, then start celld against the same bucket: | |
| 92 | +Run an application locally without a cloud bucket: | |
| 90 | 93 | |
| 91 | 94 | ```sh |
| 95 | +celld dev | |
| 96 | +``` | |
| 97 | + | |
| 98 | +The command starts one celld node and uses a local object store. It does not | |
| 99 | +require Docker or a cloud bucket. The Worker listener uses | |
| 100 | +`http://127.0.0.1:9876`. Use `celld dev --port PORT` to select a different | |
| 101 | +Worker port. Use `celld dev --host IP` to select a different interface. A | |
| 102 | +non-loopback IP exposes the Worker listener to the network, and the internal | |
| 103 | +operator listener stays on loopback. The command keeps the application state | |
| 104 | +in `.celld/dev`, so a later invocation uses the same durable data. | |
| 105 | + | |
| 106 | +The default display highlights the application URL and hides the node | |
| 107 | +warning and information logs. Use `celld dev --logs` to show these logs. | |
| 108 | +The errors remain visible without this flag. Set `NO_COLOR` to disable color, | |
| 109 | +or set `FORCE_COLOR` to enable color when the output is not a terminal. | |
| 110 | +`NO_COLOR` always takes priority. | |
| 111 | + | |
| 112 | +The command watches the project and rebuilds the application after a | |
| 113 | +source or configuration change. It keeps the current application running | |
| 114 | +if a build fails, and a successful restart retains the durable state. See | |
| 115 | +the [documentation](docs/README.md#develop-an-application-locally) for | |
| 116 | +the complete local-development contract. | |
| 117 | + | |
| 118 | +celld uses the standard AWS credential chain. On Amazon EKS, celld reads the | |
| 119 | +Pod Identity credentials from the injected environment variables and the | |
| 120 | +authorization-token file. Deploy to an S3-compatible bucket, then start celld | |
| 121 | +against the same bucket: | |
| 122 | + | |
| 123 | +```sh | |
| 92 | 124 | celld deploy . \ |
| 93 | 125 | --bucket s3://my-cells-bucket |
| 94 | 126 | |
| @@ -99,11 +131,26 @@ | ||
| 99 | 131 | --advertise 10.0.0.12:8081 |
| 100 | 132 | ``` |
| 101 | 133 | |
| 134 | +One node proves each write through the bucket, so a write costs one storage | |
| 135 | +round trip. Start a second node against the same bucket, and celld sends each | |
| 136 | +write to it: the write then finishes as soon as the second node holds the data | |
| 137 | +on its disk, which is much faster than the round trip. | |
| 138 | + | |
| 139 | +Run two or more nodes if write latency matters to you. The second node needs | |
| 140 | +no extra configuration, because a node finds the other nodes through the | |
| 141 | +bucket. | |
| 142 | + | |
| 143 | +How much faster depends on how far your bucket is and how loaded the fleet | |
| 144 | +is. A write to a region-local store takes about 90 ms. One loaded lab fleet | |
| 145 | +measured about 600 ms against a store that was not region-local, and about | |
| 146 | +25 ms once a second node held the write. See | |
| 147 | +[what celld guarantees](docs/guarantees.md#the-ensemble-needs-two-nodes). | |
| 148 | + | |
| 102 | 149 | Use `--endpoint` for another S3-compatible service and `--region` when it |
| 103 | -cannot be inferred. A `gs://` bucket selects Google Cloud Storage. celld then | |
| 104 | -uses the Cloud Storage XML API with generation preconditions. Authentication | |
| 105 | -uses Application Default Credentials. celld rejects an S3 `--endpoint` for a | |
| 106 | -`gs://` bucket, and it ignores the storage region: | |
| 150 | +cannot be inferred. A `gs://` bucket selects Google Cloud Storage: celld then | |
| 151 | +uses the Cloud Storage XML API with generation preconditions and | |
| 152 | +authenticates with Application Default Credentials. celld rejects an S3 | |
| 153 | +`--endpoint` for a `gs://` bucket, and it ignores the storage region: | |
| 107 | 154 | |
| 108 | 155 | ```sh |
| 109 | 156 | celld deploy . --bucket gs://my-cells-bucket |
| @@ -112,18 +159,16 @@ | ||
| 112 | 159 | ``` |
| 113 | 160 | |
| 114 | 161 | An `az://` bucket selects Azure Blob Storage, where the NAME is the |
| 115 | -container. The storage account comes from `AZURE_STORAGE_ACCOUNT_NAME`. | |
| 116 | -celld requires exactly one storage account key, managed identity, or workload | |
| 117 | -identity. An AKS workload identity uses `AZURE_AUTHORITY_HOST`, | |
| 118 | -`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, and `AZURE_FEDERATED_TOKEN_FILE`. | |
| 119 | -The authority host must identify the public Azure cloud. A Microsoft Entra | |
| 120 | -identity needs data-plane permission to read, write, list, and delete blobs. | |
| 121 | -The `Storage Blob Data Contributor` role supplies these permissions. celld | |
| 122 | -rejects an S3 `--endpoint` for an `az://` bucket, and it ignores the storage | |
| 123 | -region. celld qualifies an `az://` bucket: the conditional-write contract and | |
| 124 | -the multipart upload path were tested against a live Azure account on | |
| 125 | -2026-08-18, under each of the three credential families named above. See | |
| 126 | -[ownership and fencing](docs/fencing.md): | |
| 162 | +container and `AZURE_STORAGE_ACCOUNT_NAME` names the storage account. | |
| 163 | +celld requires exactly one credential family: a storage account key, a | |
| 164 | +managed identity, or a workload identity. An AKS workload identity uses | |
| 165 | +`AZURE_AUTHORITY_HOST`, `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, and | |
| 166 | +`AZURE_FEDERATED_TOKEN_FILE`, and the authority host must identify the | |
| 167 | +public Azure cloud. A Microsoft Entra identity needs data-plane permission | |
| 168 | +to read, write, list, and delete blobs; the `Storage Blob Data Contributor` | |
| 169 | +role supplies these. celld rejects an S3 `--endpoint` for an `az://` bucket, | |
| 170 | +and it ignores the storage region. See | |
| 171 | +[what celld guarantees](docs/guarantees.md) for the qualification: | |
| 127 | 172 | |
| 128 | 173 | ```sh |
| 129 | 174 | export AZURE_STORAGE_ACCOUNT_NAME=myaccount |
| @@ -132,26 +177,27 @@ | ||
| 132 | 177 | --internal-listen 10.0.0.12:8081 --advertise 10.0.0.12:8081 |
| 133 | 178 | ``` |
| 134 | 179 | |
| 135 | -A fleet runs one application, and every node loads its | |
| 136 | -latest successfully committed deployment from `deploy/current.json`. Run | |
| 137 | -`celld --help` for the complete command line. | |
| 138 | -Deployment objects use the documented types in `crates/celld/protocol.rs`. `celld | |
| 139 | -deploy` invokes `esbuild` from `PATH` for Worker code, accepts the supported | |
| 140 | -Wrangler config subset—including co-deployed or asset-only static | |
| 141 | -assets—and writes those objects directly. Every node discovers owners and | |
| 142 | -peers from bucket leases; there is no account or join service. | |
| 180 | +A fleet runs one application, and every node loads its latest successfully | |
| 181 | +committed deployment from `deploy/current.json`. `celld deploy` invokes | |
| 182 | +`esbuild` from `PATH` for Worker code, accepts the supported Wrangler config | |
| 183 | +subset — including co-deployed or asset-only static assets — and writes the | |
| 184 | +deployment objects directly, using the documented types in | |
| 185 | +`crates/celld/protocol.rs`. Every node discovers owners and peers from | |
| 186 | +bucket leases; there is no account or join service. Run `celld --help` for | |
| 187 | +the complete command line. | |
| 143 | 188 | |
| 144 | -Peer HTTP and the operator API use the internal listener. Put every advertised | |
| 145 | -address on a trusted private network or an encrypted overlay such as WireGuard | |
| 146 | -or Tailscale. Do not publish the internal port. celld rejects a literal public | |
| 147 | -IP unless you supply `--unsafe-public-advertise`. An explicit advertised | |
| 148 | -address requires an explicit internal-listener address. celld cannot verify a | |
| 149 | -hostname or a translated port, so you must route the advertised address to the | |
| 150 | -internal listener. The first current node creates `fleet/peer-auth.json` in the | |
| 151 | -bucket. All peer requests are | |
| 152 | -protocol-versioned, body-bound, HMAC-authenticated, clock-bounded, and | |
| 153 | -replay-protected with that fleet secret. Treat access to the bucket and its | |
| 154 | -credentials as fleet administrator access. | |
| 189 | +Peer HTTP and the operator API use the internal listener. Put every | |
| 190 | +advertised address on a trusted private network or an encrypted overlay such | |
| 191 | +as WireGuard or Tailscale, and do not publish the internal port. celld | |
| 192 | +rejects a literal public IP unless you supply `--unsafe-public-advertise`. | |
| 193 | +An explicit advertised address requires an explicit internal-listener | |
| 194 | +address, and you must route the advertised address to the internal | |
| 195 | +listener — celld cannot verify a hostname or a translated port. The first | |
| 196 | +current node creates `fleet/peer-auth.json` in the bucket. Cell fetch and RPC | |
| 197 | +requests carry a protocol version and depend on the trusted private network. | |
| 198 | +Peer-control and reserved-cell operator requests use the fleet HMAC. This HMAC | |
| 199 | +binds each body and supplies a clock limit and replay protection. Treat access | |
| 200 | +to the bucket and its credentials as fleet administrator access. | |
| 155 | 201 | |
| 156 | 202 | ## Operate a fleet |
| 157 | 203 | |
| @@ -168,6 +214,23 @@ | ||
| 168 | 214 | WebSocket, RSS, CPU, file-descriptor, pressure, and shedding sample. Pass one |
| 169 | 215 | or more `--peer NODE_ID` options to restrict the check. |
| 170 | 216 | |
| 217 | +`celld cell list` lists the Durable Object instances in the fleet bucket: | |
| 218 | + | |
| 219 | +```sh | |
| 220 | +celld cell list --bucket s3://my-cells-bucket | |
| 221 | +``` | |
| 222 | + | |
| 223 | +The command prints one `Class:ID` cell scope per line. Give a class name to | |
| 224 | +list only the instances of that class, and pass `--json` for one JSON object | |
| 225 | +per line. An instance appears after the first event reaches it, because its | |
| 226 | +owner then writes an ownership record to the bucket. An ID that an application | |
| 227 | +only derives does not appear. | |
| 228 | + | |
| 229 | +The listing is bounded. One storage request returns at most 1000 instances, | |
| 230 | +so the command prints at most 1000 and reports on stderr that more exist. | |
| 231 | +Pass `--after SCOPE` to continue from the last instance printed, or `--all` | |
| 232 | +to read the whole listing. | |
| 233 | + | |
| 171 | 234 | `celld d1` runs SQL and migrations against a deployed D1 database. It finds a |
| 172 | 235 | node through the same node leases, and that node sends the work to the node |
| 173 | 236 | that owns the database: |
| @@ -176,6 +239,23 @@ | ||
| 176 | 239 | celld d1 migrations apply ledger --bucket s3://my-cells-bucket |
| 177 | 240 | ``` |
| 178 | 241 | |
| 242 | +`celld kv` reads and writes a deployed KV namespace. Its bulk commands use the | |
| 243 | +Wrangler file format, so a Wrangler export can migrate directly into celld: | |
| 244 | + | |
| 245 | +```sh | |
| 246 | +celld kv bulk put sessions wrangler-export.json \ | |
| 247 | + --bucket s3://my-cells-bucket | |
| 248 | +``` | |
| 249 | + | |
| 250 | +`celld queue` inspects and controls a deployed Queue. A queue can continue to | |
| 251 | +accept messages while delivery is paused: | |
| 252 | + | |
| 253 | +```sh | |
| 254 | +celld queue info jobs --bucket s3://my-cells-bucket | |
| 255 | +celld queue pause jobs --bucket s3://my-cells-bucket | |
| 256 | +celld queue resume jobs --bucket s3://my-cells-bucket | |
| 257 | +``` | |
| 258 | + | |
| 179 | 259 | Set a hard resident-cell limit on each loaded node: |
| 180 | 260 | |
| 181 | 261 | ```sh |
| @@ -184,60 +264,52 @@ | ||
| 184 | 264 | --internal-listen 10.0.0.12:8081 --advertise node-a.internal:8081 |
| 185 | 265 | ``` |
| 186 | 266 | |
| 187 | -celld enables a memory threshold at 80% of the available memory by default. Set | |
| 188 | -`CELLD_MAX_RSS_MB` to change the threshold, or set it to `0` to disable memory | |
| 189 | -pressure shedding. celld measures the memory that the cells hold, and not the | |
| 190 | -resident set size of the process. The two differ, because the memory allocator | |
| 191 | -keeps some freed pages instead of returning them to the operating system. | |
| 192 | -Shedding a cell cannot return those pages, so a threshold on the resident set | |
| 193 | -size holds a node in pressure after the node gives every cell back. The `/state` | |
| 194 | -route reports both numbers. | |
| 267 | +celld enables a memory-pressure threshold at 80% of the available memory by | |
| 268 | +default. Set `CELLD_MAX_RSS_MB` to change the threshold, or set it to `0` to | |
| 269 | +disable memory-pressure shedding. In a Linux cgroup, the threshold uses the | |
| 270 | +greater of the allocator-adjusted RSS and the active cgroup working set. celld | |
| 271 | +calculates the working set as `memory.current` less `inactive_file` from | |
| 272 | +`memory.stat`, then it removes the measured allocator slack. This calculation | |
| 273 | +includes active kernel charges that process RSS does not report, and it excludes | |
| 274 | +file pages and allocator pages that celld cannot return by shedding a cell. The | |
| 275 | +`/state` route reports all four input measurements. | |
| 195 | 276 | |
| 196 | -celld also applies an absolute cap to the resident set size of the process. The | |
| 197 | -cap is 95% of the available memory. It protects the node when the allocator | |
| 198 | -holds memory that shedding cannot return, because the operating system stops a | |
| 199 | -process that uses more memory than the machine has. The node logs a warning when | |
| 200 | -this cap applies. | |
| 277 | +A separate absolute cap applies to the complete cgroup charge at 95% of the | |
| 278 | +available memory. celld uses the process RSS when it cannot read a cgroup | |
| 279 | +charge. The cap protects the node when shedding cannot return a kernel charge. | |
| 280 | +The node logs a warning when the cap applies. The cap is a share of the | |
| 281 | +available memory, not a share of the threshold. Therefore, a | |
| 282 | +`CELLD_MAX_RSS_MB` value at or above 95% makes the cap the effective limit, and | |
| 283 | +celld reports the decision at startup. | |
| 284 | +`CELLD_MAX_RSS_MB=0` disables the threshold and the cap together. When celld | |
| 285 | +cannot read the size of the available memory, it applies a cap of 125% of an | |
| 286 | +explicit threshold. | |
| 201 | 287 | |
| 202 | -The cap is a share of the machine, and celld does not derive it from the | |
| 203 | -threshold. A `CELLD_MAX_RSS_MB` at or above 95% of the available memory therefore reaches | |
| 204 | -the cap. The cap is then the effective limit. The node decides on its resident | |
| 205 | -set size, and celld reports this at startup. `CELLD_MAX_RSS_MB=0` | |
| 206 | -disables the threshold and the cap together. When celld cannot read the size of | |
| 207 | -the available memory, it applies a cap of 125% of an explicit threshold. | |
| 288 | +Under pressure, celld durably replicates and fences the least-recently used | |
| 289 | +idle cells, publishes them as unowned without resetting their epochs, and | |
| 290 | +refuses to reacquire new unowned cells. It does not shed a cell with active | |
| 291 | +work or a live host WebSocket. A spare node receives no assignment; it | |
| 292 | +acquires a released cell through the same bucket protocol when normal | |
| 293 | +traffic reaches it. Each limit releases separately. The threshold releases at | |
| 294 | +80% of its value, and the cap releases at 80% of its value. Therefore, a | |
| 295 | +crossing of one limit does not hold the node against the other. | |
| 208 | 296 | |
| 209 | -Each isolate also has a V8 heap limit, and this limit is separate from the | |
| 210 | -memory of the node. The default is 128 MB, and it matches the limit of a | |
| 211 | -Durable Object on Cloudflare. Set `CELLD_V8_HEAP_LIMIT_MB` to change it. The | |
| 212 | -limit decides how much state one isolate can hold, so it decides how many | |
| 213 | -hibernatable WebSocket clients a cell can carry. Each client holds state in the | |
| 214 | -heap. A cell holds approximately 50,000 clients with the default limit, and it | |
| 215 | -needs approximately 512 MB to hold 100,000 clients. | |
| 297 | +Each isolate also has a V8 heap limit, separate from the memory of the node. | |
| 298 | +The default is 128 MB, and it matches the limit of a Durable Object on | |
| 299 | +Cloudflare; set `CELLD_V8_HEAP_LIMIT_MB` to change it. Each hibernatable | |
| 300 | +WebSocket client holds state in the heap, so the limit decides how many | |
| 301 | +clients a cell can carry: approximately 50,000 at the default, and | |
| 302 | +approximately 512 MB for 100,000. | |
| 216 | 303 | |
| 217 | -An isolate that uses more than 90% of this limit refuses a new hibernatable | |
| 218 | -WebSocket, and the error names the heap. The refusal is not permanent, and the | |
| 219 | -isolate accepts a WebSocket again when the use of the heap falls under 90%. | |
| 304 | +An isolate above 90% of this limit refuses a new hibernatable WebSocket, and | |
| 305 | +it accepts again when the use of the heap falls under 90%. An isolate that | |
| 306 | +reaches the limit also stops the materialization of a SQL result set; both | |
| 307 | +errors name the heap. celld measures the heap before each event, and the | |
| 308 | +isolate serves again when the use falls under 75% of the limit. An idle | |
| 309 | +isolate holds a dead heap until something allocates, so celld forces a | |
| 310 | +collection when a measurement is above that share. A restart of the process | |
| 311 | +is not necessary. | |
| 220 | 312 | |
| 221 | -An isolate that reaches the limit stops more than an accept. It also stops the | |
| 222 | -materialization of a SQL result set, and that error names the heap too. celld | |
| 223 | -measures the heap before each event, and the isolate serves again when the use | |
| 224 | -of the heap falls under 75% of the limit. An idle isolate holds a dead heap | |
| 225 | -until something allocates again, so celld forces a collection when a | |
| 226 | -measurement is above that share. A restart of the process is not necessary. | |
| 227 | - | |
| 228 | -Under pressure, celld durably replicates and fences the least-recently used idle | |
| 229 | -cells. It then publishes the cells as unowned without resetting their epochs. | |
| 230 | -Those cells become inactive, and celld refuses to reacquire new unowned cells. | |
| 231 | - | |
| 232 | -Each limit releases separately. The threshold releases when the memory in use | |
| 233 | -falls to 80% of the threshold. The cap releases when the resident set size falls | |
| 234 | -to 80% of the cap. A crossing of one limit therefore does not hold the node | |
| 235 | -against the other. | |
| 236 | - | |
| 237 | -A spare receives no assignment. It acquires a released cell through the same | |
| 238 | -bucket protocol when normal traffic reaches it. celld does not shed a cell with | |
| 239 | -active work or a live host WebSocket. | |
| 240 | - | |
| 241 | 313 | ## Contributions |
| 242 | 314 | |
| 243 | 315 | Pull requests are disabled. Coding agents make it too easy to send a large, |
| @@ -250,10 +322,9 @@ | ||
| 250 | 322 | Contributor License Agreement: By emailing a patch, you certify that you have |
| 251 | 323 | the right to submit it and assign to Deno Land Inc. all rights in the patch |
| 252 | 324 | that you can assign. Where a right cannot be assigned, you grant Deno Land |
| 253 | -Inc. a perpetual, irrevocable, | |
| 254 | -worldwide, royalty-free, transferable, sublicensable license to use, modify, | |
| 255 | -combine, relicense, redistribute, or publish the patch, in whole or in part, | |
| 256 | -with or without attribution. | |
| 325 | +Inc. a perpetual, irrevocable, worldwide, royalty-free, transferable, | |
| 326 | +sublicensable license to use, modify, combine, relicense, redistribute, or | |
| 327 | +publish the patch, in whole or in part, with or without attribution. | |
| 257 | 328 | |
| 258 | 329 | ## License |
| 259 | 330 |
modifiedclippy.toml+23−18View file
| @@ -1,20 +1,20 @@ | ||
| 1 | -# The execution boundary must use celld::asyncrt. Modules which never execute | |
| 2 | -# in the World carry an explicit lint allow and are listed in the S0 audit. | |
| 1 | +# The execution boundary must use celld::asyncrt. Modules outside that boundary | |
| 2 | +# carry an explicit lint allow. | |
| 3 | 3 | disallowed-methods = [ |
| 4 | - { path = "tokio::spawn", reason = "use celld::asyncrt::spawn inside the World boundary" }, | |
| 5 | - { path = "tokio::runtime::Handle::spawn", reason = "use celld::asyncrt::spawn inside the World boundary" }, | |
| 6 | - { path = "tokio::task::spawn_blocking", reason = "use celld::asyncrt::blocking inside the World boundary" }, | |
| 7 | - { path = "tokio::runtime::Handle::spawn_blocking", reason = "use celld::asyncrt::blocking inside the World boundary" }, | |
| 8 | - { path = "tokio::time::sleep", reason = "use celld::asyncrt::sleep inside the World boundary" }, | |
| 9 | - { path = "tokio::time::sleep_until", reason = "use celld::asyncrt::sleep_until inside the World boundary" }, | |
| 10 | - { path = "tokio::time::timeout", reason = "use celld::asyncrt::timeout inside the World boundary" }, | |
| 11 | - { path = "tokio::time::timeout_at", reason = "use celld::asyncrt::timeout_at inside the World boundary" }, | |
| 12 | - { path = "tokio::time::interval", reason = "use celld::asyncrt::interval inside the World boundary" }, | |
| 13 | - { path = "tokio::time::interval_at", reason = "use celld::asyncrt::interval_at inside the World boundary" }, | |
| 14 | - { path = "std::time::SystemTime::now", reason = "use the execution-domain wall clock inside the World boundary" }, | |
| 15 | - { path = "std::time::Instant::now", reason = "use the execution-domain monotonic clock inside the World boundary" }, | |
| 16 | - { path = "rand::random", reason = "use a labeled execution-domain RNG inside the World boundary" }, | |
| 17 | - { path = "std::process::id", reason = "use the execution-domain process tag inside the World boundary" }, | |
| 4 | + { path = "tokio::spawn", reason = "use celld::asyncrt::spawn inside the execution boundary" }, | |
| 5 | + { path = "tokio::runtime::Handle::spawn", reason = "use celld::asyncrt::spawn inside the execution boundary" }, | |
| 6 | + { path = "tokio::task::spawn_blocking", reason = "use celld::asyncrt::blocking inside the execution boundary" }, | |
| 7 | + { path = "tokio::runtime::Handle::spawn_blocking", reason = "use celld::asyncrt::blocking inside the execution boundary" }, | |
| 8 | + { path = "tokio::time::sleep", reason = "use celld::asyncrt::sleep inside the execution boundary" }, | |
| 9 | + { path = "tokio::time::sleep_until", reason = "use celld::asyncrt::sleep_until inside the execution boundary" }, | |
| 10 | + { path = "tokio::time::timeout", reason = "use celld::asyncrt::timeout inside the execution boundary" }, | |
| 11 | + { path = "tokio::time::timeout_at", reason = "use celld::asyncrt::timeout_at inside the execution boundary" }, | |
| 12 | + { path = "tokio::time::interval", reason = "use celld::asyncrt::interval inside the execution boundary" }, | |
| 13 | + { path = "tokio::time::interval_at", reason = "use celld::asyncrt::interval_at inside the execution boundary" }, | |
| 14 | + { path = "std::time::SystemTime::now", reason = "use the execution-domain wall clock inside the execution boundary" }, | |
| 15 | + { path = "std::time::Instant::now", reason = "use the execution-domain monotonic clock inside the execution boundary" }, | |
| 16 | + { path = "rand::random", reason = "use a labeled execution-domain RNG inside the execution boundary" }, | |
| 17 | + { path = "std::process::id", reason = "use the execution-domain process tag inside the execution boundary" }, | |
| 18 | 18 | { path = "std::fs::read", reason = "use the injected whole-node filesystem for celld node storage" }, |
| 19 | 19 | { path = "std::fs::read_to_string", reason = "use the injected whole-node filesystem for celld node storage" }, |
| 20 | 20 | { path = "std::fs::read_dir", reason = "use the injected whole-node filesystem for celld node storage" }, |
| @@ -76,10 +76,15 @@ | ||
| 76 | 76 | { path = "tokio::fs::set_permissions", reason = "use the injected whole-node filesystem for celld node storage" }, |
| 77 | 77 | ] |
| 78 | 78 | |
| 79 | +# The celld and celld-ltx packages forbid these macros, so no module can lower | |
| 80 | +# this policy. Clippy resolves imported and aliased macro calls in every | |
| 81 | +# target that Cargo compiles for these packages. | |
| 79 | 82 | disallowed-macros = [ |
| 80 | - { path = "tokio::select", reason = "use celld::asyncrt::select with a declared priority inside the World boundary" }, | |
| 83 | + { path = "tokio::select", reason = "use celld::asyncrt::select! for fair polling or select_biased! with a site reason for source-order priority; production uses a process-seeded cyclic start, and simulation uses Domain-derived ordering" }, | |
| 84 | + { path = "std::println", reason = "use celld::cli_output::Output for celld stdout data and note! for human-readable stderr messages" }, | |
| 85 | + { path = "std::print", reason = "use celld::cli_output::Output for celld stdout data and note! for human-readable stderr messages" }, | |
| 81 | 86 | ] |
| 82 | 87 | |
| 83 | 88 | disallowed-types = [ |
| 84 | - { path = "rand::rngs::OsRng", reason = "use a labeled execution-domain RNG inside the World boundary" }, | |
| 89 | + { path = "rand::rngs::OsRng", reason = "use a labeled execution-domain RNG inside the execution boundary" }, | |
| 85 | 90 | ] |
modifiedcrates/celld/Cargo.toml+10−2View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [package] |
| 2 | 2 | name = "celld" |
| 3 | -version = "0.3.0" | |
| 3 | +version = "0.4.0" | |
| 4 | 4 | edition = "2021" |
| 5 | 5 | rust-version = "1.94.1" |
| 6 | 6 | license = "Apache-2.0" |
| @@ -17,7 +17,12 @@ | ||
| 17 | 17 | level = "warn" |
| 18 | 18 | check-cfg = ["cfg(celld_internal_tests)", "cfg(celld_proxy_internals)"] |
| 19 | 19 | |
| 20 | +[lints.clippy] | |
| 21 | +disallowed_macros = "forbid" | |
| 22 | + | |
| 20 | 23 | [dependencies] |
| 24 | +async-trait.workspace = true | |
| 25 | +chrono.workspace = true | |
| 21 | 26 | aes.workspace = true |
| 22 | 27 | aes-gcm.workspace = true |
| 23 | 28 | cbc.workspace = true |
| @@ -34,13 +39,17 @@ | ||
| 34 | 39 | flate2.workspace = true |
| 35 | 40 | futures-util.workspace = true |
| 36 | 41 | getrandom.workspace = true |
| 42 | +hkdf.workspace = true | |
| 37 | 43 | hmac.workspace = true |
| 38 | 44 | http-body-util.workspace = true |
| 39 | 45 | hyper.workspace = true |
| 40 | 46 | hyper-util.workspace = true |
| 41 | 47 | md-5.workspace = true |
| 48 | +notify.workspace = true | |
| 49 | +nu-ansi-term.workspace = true | |
| 42 | 50 | object_store = { workspace = true, features = ["aws", "azure", "gcp"] } |
| 43 | 51 | parquet.workspace = true |
| 52 | +pbkdf2.workspace = true | |
| 44 | 53 | percent-encoding.workspace = true |
| 45 | 54 | p256.workspace = true |
| 46 | 55 | p384.workspace = true |
| @@ -81,5 +90,4 @@ | ||
| 81 | 90 | nix.workspace = true |
| 82 | 91 | |
| 83 | 92 | [dev-dependencies] |
| 84 | -async-trait.workspace = true | |
| 85 | 93 | lz4_flex.workspace = true |
modifiedcrates/celld/actor.rs+3904−2650View file
| @@ -2,2656 +2,3910 @@ | ||
| 2 | 2 | |
| 3 | 3 | //! The serial lifecycle executor and its shell-side request drivers. |
| 4 | 4 | |
| 5 | -#![warn(clippy::disallowed_macros)] | |
| 6 | - | |
| 7 | -use crate::assets::AssetResolver; | |
| 8 | -use crate::js::{HttpResponse, WsOut}; | |
| 9 | -use crate::machine::{ | |
| 10 | - ownership_on_evict_from_environment, pressure_config_from_environment, | |
| 11 | - random_process_generation, DEFAULT_MAX_OUTBOUND_WEBSOCKETS, | |
| 12 | -}; | |
| 13 | -use crate::ownership_store::{now_ms, BucketOwnership}; | |
| 14 | -use crate::peer_auth::{self, PeerAuth}; | |
| 15 | -use crate::runtime::{CellHost, RuntimeManager}; | |
| 16 | -use anyhow::Context as _; | |
| 17 | -use celld_logic::{ | |
| 18 | - on_event, CasGuard, CasOutcome, Config, Effect, Event, Failure, LeaseCasOutcome, | |
| 19 | - NodeLeaseRecord, NodeLeaseSpec, OpId, OwnerRecord, OwnershipOnEvict, Phase, RequestError, | |
| 20 | - Route, State, StopCause, Timer, WebSocketKind, WorkerRoute, | |
| 21 | -}; | |
| 22 | -use futures_util::stream::FuturesUnordered; | |
| 23 | -use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; | |
| 24 | -use std::future::Future; | |
| 25 | -use std::pin::Pin; | |
| 26 | -use std::sync::atomic::Ordering; | |
| 27 | -use std::sync::Arc; | |
| 28 | -use tokio::sync::{mpsc, oneshot, Mutex}; | |
| 29 | -use tokio_util::time::{delay_queue, DelayQueue}; | |
| 30 | - | |
| 31 | -mod production; | |
| 32 | - | |
| 33 | -const DEFAULT_OPERATION_DEADLINE_MS: u64 = 15_000; | |
| 34 | - | |
| 35 | -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] | |
| 36 | -pub enum TimerSlot { | |
| 37 | - NodeLeaseRenew, | |
| 38 | - NodeLeaseFence, | |
| 39 | - CellAlarm(String), | |
| 40 | - /// Keyed by operation, deliberately. Every other timer here coalesces | |
| 41 | - /// because only its newest arming matters; a deadline is the opposite -- | |
| 42 | - /// each watches a different outstanding operation, and a shared slot | |
| 43 | - /// would let arming one silently cancel another, leaving every activation | |
| 44 | - /// but the most recent with nothing watching it. | |
| 45 | - OperationDeadline(OpId), | |
| 46 | - /// Keyed by cell and generation for the same reason as the deadline | |
| 47 | - /// above: a node parks many cells at once, and one slot per cell would | |
| 48 | - /// let a later parking disarm an earlier one. | |
| 49 | - QueuedActivation(String, u64), | |
| 50 | -} | |
| 51 | - | |
| 52 | -impl TimerSlot { | |
| 53 | - pub fn of(timer: &Timer) -> Self { | |
| 54 | - match timer { | |
| 55 | - Timer::NodeLeaseRenew { .. } => Self::NodeLeaseRenew, | |
| 56 | - Timer::NodeLeaseFence { .. } => Self::NodeLeaseFence, | |
| 57 | - Timer::CellAlarm { cell, .. } => Self::CellAlarm(cell.clone()), | |
| 58 | - Timer::OperationDeadline { op } => Self::OperationDeadline(*op), | |
| 59 | - Timer::QueuedActivation { cell, generation } => { | |
| 60 | - Self::QueuedActivation(cell.clone(), *generation) | |
| 61 | - } | |
| 62 | - } | |
| 63 | - } | |
| 64 | -} | |
| 65 | - | |
| 66 | -/// One versioned timer arm emitted by an Actor step. | |
| 67 | -#[derive(Clone, Debug, PartialEq, Eq)] | |
| 68 | -pub struct TimerArm { | |
| 69 | - pub slot: TimerSlot, | |
| 70 | - pub ordinal: u64, | |
| 71 | - pub timer: Timer, | |
| 72 | - pub at_mono_ms: u64, | |
| 73 | -} | |
| 74 | - | |
| 75 | -/// The shared displacement discipline for production and deterministic timers. | |
| 76 | -pub struct TimerSlots<V> { | |
| 77 | - armed: BTreeMap<TimerSlot, (u64, V)>, | |
| 78 | - ordinals: BTreeMap<TimerSlot, u64>, | |
| 79 | -} | |
| 80 | - | |
| 81 | -impl<V> Default for TimerSlots<V> { | |
| 82 | - fn default() -> Self { | |
| 83 | - Self { | |
| 84 | - armed: BTreeMap::new(), | |
| 85 | - ordinals: BTreeMap::new(), | |
| 86 | - } | |
| 87 | - } | |
| 88 | -} | |
| 89 | - | |
| 90 | -impl<V> TimerSlots<V> { | |
| 91 | - /// Creates one arm, assigns its stable per-slot ordinal, and applies it. | |
| 92 | - pub fn arm(&mut self, timer: Timer, at_mono_ms: u64, value: V) -> (TimerArm, Option<V>) { | |
| 93 | - let slot = TimerSlot::of(&timer); | |
| 94 | - let ordinal = self.ordinals.entry(slot.clone()).or_default(); | |
| 95 | - let arm = TimerArm { | |
| 96 | - slot: slot.clone(), | |
| 97 | - ordinal: *ordinal, | |
| 98 | - timer, | |
| 99 | - at_mono_ms, | |
| 100 | - }; | |
| 101 | - *ordinal = ordinal.saturating_add(1); | |
| 102 | - let displaced = self.replace(&slot, arm.ordinal, value); | |
| 103 | - (arm, displaced) | |
| 104 | - } | |
| 105 | - | |
| 106 | - /// Applies an arm whose ordinal the Actor has already assigned. | |
| 107 | - pub fn install(&mut self, arm: &TimerArm, value: V) -> Option<V> { | |
| 108 | - self.replace(&arm.slot, arm.ordinal, value) | |
| 109 | - } | |
| 110 | - | |
| 111 | - fn replace(&mut self, slot: &TimerSlot, ordinal: u64, value: V) -> Option<V> { | |
| 112 | - let displaced = self | |
| 113 | - .armed | |
| 114 | - .insert(slot.clone(), (ordinal, value)) | |
| 115 | - .map(|(_, value)| value); | |
| 116 | - debug_assert!( | |
| 117 | - displaced.is_none() || !matches!(slot, TimerSlot::OperationDeadline(_)), | |
| 118 | - "an operation deadline displaced another: {slot:?}" | |
| 119 | - ); | |
| 120 | - displaced | |
| 121 | - } | |
| 122 | - | |
| 123 | - /// Removes the current arm only when both parts of its identity match. | |
| 124 | - pub fn fire(&mut self, slot: &TimerSlot, ordinal: u64) -> Option<V> { | |
| 125 | - if self | |
| 126 | - .armed | |
| 127 | - .get(slot) | |
| 128 | - .is_some_and(|(armed, _)| *armed == ordinal) | |
| 129 | - { | |
| 130 | - self.armed.remove(slot).map(|(_, value)| value) | |
| 131 | - } else { | |
| 132 | - None | |
| 133 | - } | |
| 134 | - } | |
| 135 | - | |
| 136 | - fn clear_slot(&mut self, slot: &TimerSlot) { | |
| 137 | - self.armed.remove(slot); | |
| 138 | - } | |
| 139 | -} | |
| 140 | - | |
| 141 | -pub struct MemoryOwnership { | |
| 142 | - node: String, | |
| 143 | - owners: BTreeMap<String, OwnerRecord>, | |
| 144 | - leases: BTreeMap<String, NodeLeaseRecord>, | |
| 145 | - next_etag: u64, | |
| 146 | -} | |
| 147 | - | |
| 148 | -#[derive(Clone)] | |
| 149 | -pub enum Ownership { | |
| 150 | - Memory(Arc<Mutex<MemoryOwnership>>), | |
| 151 | - Bucket(Arc<BucketOwnership>), | |
| 152 | -} | |
| 153 | - | |
| 154 | -impl Ownership { | |
| 155 | - async fn read_owner(&self, cell: &str) -> Result<Option<OwnerRecord>, Failure> { | |
| 156 | - match self { | |
| 157 | - Self::Memory(memory) => Ok(memory.lock().await.owners.get(cell).cloned()), | |
| 158 | - Self::Bucket(bucket) => bucket.read_owner(cell).await.map_err(|error| { | |
| 159 | - eprintln!("celld ownership read failed: {error:#}"); | |
| 160 | - Failure::Definite | |
| 161 | - }), | |
| 162 | - } | |
| 163 | - } | |
| 164 | - | |
| 165 | - async fn read_node_lease(&self, owner: &str) -> Result<Option<NodeLeaseRecord>, Failure> { | |
| 166 | - match self { | |
| 167 | - Self::Memory(memory) => Ok(memory.lock().await.leases.get(owner).cloned()), | |
| 168 | - Self::Bucket(bucket) => bucket.read_node_lease(owner).await.map_err(|error| { | |
| 169 | - eprintln!("celld node lease read failed: {error:#}"); | |
| 170 | - Failure::Definite | |
| 171 | - }), | |
| 172 | - } | |
| 173 | - } | |
| 174 | - | |
| 175 | - async fn read_capacity_peers(&self) -> Result<Vec<celld_logic::CapacityPeer>, Failure> { | |
| 176 | - match self { | |
| 177 | - // The in-memory adapter is a single-node development mode. It has | |
| 178 | - // no external membership enumeration to offer. | |
| 179 | - Self::Memory(_) => Ok(Vec::new()), | |
| 180 | - Self::Bucket(bucket) => bucket.read_capacity_peers().await.map_err(|error| { | |
| 181 | - eprintln!("celld capacity peer read failed: {error:#}"); | |
| 182 | - Failure::Definite | |
| 183 | - }), | |
| 184 | - } | |
| 185 | - } | |
| 186 | - | |
| 187 | - async fn read_self_node_lease(&self, node: &str) -> Result<Option<NodeLeaseRecord>, Failure> { | |
| 188 | - match self { | |
| 189 | - Self::Memory(memory) => Ok(memory.lock().await.leases.get(node).cloned()), | |
| 190 | - Self::Bucket(bucket) => bucket.read_self_node_lease(node).await.map_err(|error| { | |
| 191 | - eprintln!("celld self node lease read failed: {error:#}"); | |
| 192 | - Failure::Definite | |
| 193 | - }), | |
| 194 | - } | |
| 195 | - } | |
| 196 | - | |
| 197 | - async fn cas_owner( | |
| 198 | - &self, | |
| 199 | - cell: &str, | |
| 200 | - guard: CasGuard, | |
| 201 | - epoch: u64, | |
| 202 | - ) -> Result<CasOutcome, Failure> { | |
| 203 | - match self { | |
| 204 | - Self::Memory(memory) => { | |
| 205 | - let mut memory = memory.lock().await; | |
| 206 | - let allowed = match guard { | |
| 207 | - CasGuard::Absent => !memory.owners.contains_key(cell), | |
| 208 | - CasGuard::Match(expected) => memory | |
| 209 | - .owners | |
| 210 | - .get(cell) | |
| 211 | - .is_some_and(|owner| owner.etag == expected), | |
| 212 | - }; | |
| 213 | - if allowed { | |
| 214 | - let etag = format!("e{}", memory.next_etag); | |
| 215 | - memory.next_etag += 1; | |
| 216 | - let node = memory.node.clone(); | |
| 217 | - memory.owners.insert( | |
| 218 | - cell.into(), | |
| 219 | - OwnerRecord { | |
| 220 | - node: Some(node), | |
| 221 | - epoch, | |
| 222 | - etag, | |
| 223 | - }, | |
| 224 | - ); | |
| 225 | - } | |
| 226 | - Ok(if allowed { | |
| 227 | - CasOutcome::Applied | |
| 228 | - } else { | |
| 229 | - CasOutcome::Rejected | |
| 230 | - }) | |
| 231 | - } | |
| 232 | - Self::Bucket(bucket) => bucket.cas_owner(cell, guard, epoch).await.map_err(|error| { | |
| 233 | - // Any transport or 5xx failure may have happened after the | |
| 234 | - // store committed. The core reconciles by reading the owner | |
| 235 | - // again. | |
| 236 | - eprintln!("celld ownership CAS ambiguous: {error:#}"); | |
| 237 | - Failure::Ambiguous | |
| 238 | - }), | |
| 239 | - } | |
| 240 | - } | |
| 241 | - | |
| 242 | - async fn release_owner(&self, cell: &str, epoch: u64) -> Result<CasOutcome, Failure> { | |
| 243 | - match self { | |
| 244 | - Self::Memory(memory) => { | |
| 245 | - let mut memory = memory.lock().await; | |
| 246 | - let node = memory.node.clone(); | |
| 247 | - let releasable = memory.owners.get(cell).is_some_and(|owner| { | |
| 248 | - owner.node.as_deref() == Some(node.as_str()) && owner.epoch == epoch | |
| 249 | - }); | |
| 250 | - if releasable { | |
| 251 | - let etag = format!("e{}", memory.next_etag); | |
| 252 | - memory.next_etag += 1; | |
| 253 | - memory.owners.insert( | |
| 254 | - cell.into(), | |
| 255 | - OwnerRecord { | |
| 256 | - node: None, | |
| 257 | - epoch, | |
| 258 | - etag, | |
| 259 | - }, | |
| 260 | - ); | |
| 261 | - } | |
| 262 | - Ok(if releasable { | |
| 263 | - CasOutcome::Applied | |
| 264 | - } else { | |
| 265 | - CasOutcome::Rejected | |
| 266 | - }) | |
| 267 | - } | |
| 268 | - // A release that may or may not have committed needs no | |
| 269 | - // reconciliation: the record either still names this node, and the | |
| 270 | - // next eviction releases it again, or it does not, and the cell is | |
| 271 | - // already free. Either way nothing is owed. | |
| 272 | - Self::Bucket(bucket) => bucket.release_owner(cell, epoch).await.map_err(|error| { | |
| 273 | - eprintln!("celld ownership release failed: {error:#}"); | |
| 274 | - Failure::Definite | |
| 275 | - }), | |
| 276 | - } | |
| 277 | - } | |
| 278 | - | |
| 279 | - async fn cas_node_lease( | |
| 280 | - &self, | |
| 281 | - guard: CasGuard, | |
| 282 | - mut record: NodeLeaseRecord, | |
| 283 | - stamped: &mut Option<celld_logic::log_tier::LogState>, | |
| 284 | - ) -> Result<LeaseCasOutcome, Failure> { | |
| 285 | - match self { | |
| 286 | - Self::Memory(memory) => { | |
| 287 | - let mut memory = memory.lock().await; | |
| 288 | - let current = memory.leases.get(&record.node); | |
| 289 | - let allowed = match guard { | |
| 290 | - CasGuard::Absent => current.is_none(), | |
| 291 | - CasGuard::Match(expected) => { | |
| 292 | - current.is_some_and(|lease| lease.etag == expected) | |
| 293 | - } | |
| 294 | - }; | |
| 295 | - if !allowed { | |
| 296 | - return Ok(LeaseCasOutcome::Rejected); | |
| 297 | - } | |
| 298 | - let etag = format!("e{}", memory.next_etag); | |
| 299 | - memory.next_etag += 1; | |
| 300 | - record.etag = etag.clone(); | |
| 301 | - *stamped = record.log_state; | |
| 302 | - memory.leases.insert(record.node.clone(), record); | |
| 303 | - Ok(LeaseCasOutcome::Applied { etag }) | |
| 304 | - } | |
| 305 | - Self::Bucket(bucket) => bucket | |
| 306 | - .cas_node_lease(guard, &record, stamped) | |
| 307 | - .await | |
| 308 | - .map_err(|error| { | |
| 309 | - eprintln!("celld node-lease CAS ambiguous: {error:#}"); | |
| 310 | - Failure::Ambiguous | |
| 311 | - }), | |
| 312 | - } | |
| 313 | - } | |
| 314 | - | |
| 315 | - pub fn name(&self) -> &'static str { | |
| 316 | - match self { | |
| 317 | - Self::Memory(_) => "memory", | |
| 318 | - Self::Bucket(bucket) => bucket.storage_scheme(), | |
| 319 | - } | |
| 320 | - } | |
| 321 | -} | |
| 322 | - | |
| 323 | -pub enum Message { | |
| 324 | - /// A periodic resource sample. The measuring is the shell's job; every | |
| 325 | - /// decision that follows belongs to the core. | |
| 326 | - SampleLoad, | |
| 327 | - /// The log tier changed the folded log object the next lease write | |
| 328 | - /// must carry (lease-fold): renew now so the change becomes durable. | |
| 329 | - NudgeNodeLease, | |
| 330 | - /// Stop new internal routing while a clean same-node reload drains. The | |
| 331 | - /// request shell has already stopped admission; this closes wake and | |
| 332 | - /// service paths that do not pass through the HTTP gate. | |
| 333 | - BeginPreserve, | |
| 334 | - /// Graceful shutdown: release every owned cell's record so peers take | |
| 335 | - /// over immediately. The release writes run as effects inside the | |
| 336 | - /// shutdown drain window, and the drain waits for them to complete — | |
| 337 | - /// bounded by the drain deadline, so a wedged store still cannot hold | |
| 338 | - /// the exit hostage. | |
| 339 | - ReleaseAll, | |
| 340 | - /// Has the shutdown handoff finished? True once no cell occupies | |
| 341 | - /// capacity: nothing resident, restoring, or mid-eviction. The drain | |
| 342 | - /// loop polls this to exit as soon as the handoff completes instead of | |
| 343 | - /// sitting out the full drain window. | |
| 344 | - Drained { | |
| 345 | - reply: oneshot::Sender<DrainStatus>, | |
| 346 | - }, | |
| 347 | - Request { | |
| 348 | - request: u64, | |
| 349 | - cell: String, | |
| 350 | - capacity_handoff: bool, | |
| 351 | - reply: oneshot::Sender<Result<Routed, RequestError>>, | |
| 352 | - }, | |
| 353 | - /// A caller disappeared before routing finished. The request identity is | |
| 354 | - /// allocated by the shell, so the actor can remove it from either cold | |
| 355 | - /// admission queue immediately. | |
| 356 | - CancelRoute { | |
| 357 | - request: u64, | |
| 358 | - }, | |
| 359 | - WorkerRequest { | |
| 360 | - reply: oneshot::Sender<WorkerRouted>, | |
| 361 | - }, | |
| 362 | - ActivityFinished { | |
| 363 | - request: u64, | |
| 364 | - // The activity drop also observes the cell's alarm. Folded in here so a | |
| 365 | - // request's completion costs the serial core one message, not two — the | |
| 366 | - // hot path for every routed DO call. | |
| 367 | - cell: String, | |
| 368 | - alarm_at_ms: Option<i64>, | |
| 369 | - alarm_covered: bool, | |
| 370 | - }, | |
| 371 | - /// A local response is ready. A write opens a durability barrier, and a | |
| 372 | - /// read trails the newest barrier already open on its cell. | |
| 373 | - GateWrite { | |
| 374 | - request: u64, | |
| 375 | - position: Option<u64>, | |
| 376 | - reply: oneshot::Sender<Result<(), RequestError>>, | |
| 377 | - }, | |
| 378 | - /// A `webSocketMessage` finished; hand its captured outbound frames to the | |
| 379 | - /// cell's output gate. `write_position` present means the handler wrote, so | |
| 380 | - /// the frames are held behind that write until it is durable; absent means | |
| 381 | - /// flush them (behind any earlier still-pending write, else immediately). | |
| 382 | - WsOutput { | |
| 383 | - request: u64, | |
| 384 | - scope: String, | |
| 385 | - frames: Vec<(u64, WsOut)>, | |
| 386 | - write_position: Option<u64>, | |
| 387 | - reply: oneshot::Sender<()>, | |
| 388 | - }, | |
| 389 | - WebSocketOpened { | |
| 390 | - cell: String, | |
| 391 | - websocket: u64, | |
| 392 | - kind: WebSocketKind, | |
| 393 | - reply: oneshot::Sender<bool>, | |
| 394 | - }, | |
| 395 | - WebSocketClosed { | |
| 396 | - cell: String, | |
| 397 | - websocket: u64, | |
| 398 | - }, | |
| 399 | - AlarmObserved { | |
| 400 | - cell: String, | |
| 401 | - at_ms: Option<i64>, | |
| 402 | - covered: bool, | |
| 403 | - }, | |
| 404 | - WakeHint { | |
| 405 | - cell: String, | |
| 406 | - }, | |
| 407 | - Evict { | |
| 408 | - cell: String, | |
| 409 | - reply: oneshot::Sender<()>, | |
| 410 | - }, | |
| 411 | - InvalidateRemote { | |
| 412 | - cell: String, | |
| 413 | - node: String, | |
| 414 | - epoch: u64, | |
| 415 | - reply: oneshot::Sender<()>, | |
| 416 | - }, | |
| 417 | - Snapshot { | |
| 418 | - reply: oneshot::Sender<String>, | |
| 419 | - }, | |
| 420 | - Health { | |
| 421 | - reply: oneshot::Sender<bool>, | |
| 422 | - }, | |
| 423 | - Presence { | |
| 424 | - reply: oneshot::Sender<celld_logic::PresenceSnapshot>, | |
| 425 | - }, | |
| 426 | -} | |
| 427 | - | |
| 428 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 429 | -pub enum ShutdownMode { | |
| 430 | - /// The logical node is leaving. Release every owner record so another | |
| 431 | - /// node can take over without waiting for the node lease to expire. | |
| 432 | - Handoff, | |
| 433 | - /// The same logical node will start again at the same address. Drain the | |
| 434 | - /// request shell, but keep ownership and the local replica cache intact. | |
| 435 | - Preserve, | |
| 436 | -} | |
| 437 | - | |
| 438 | -pub struct Routed { | |
| 439 | - pub request: u64, | |
| 440 | - pub route: Route, | |
| 441 | -} | |
| 442 | - | |
| 443 | -#[derive(Clone, Copy, Default)] | |
| 444 | -pub struct DrainStatus { | |
| 445 | - pub occupied: usize, | |
| 446 | - pub activating: usize, | |
| 447 | - pub evicting: usize, | |
| 448 | - /// Ownership releases still in flight. A handoff drain waits for zero: | |
| 449 | - /// a released cell leaves `occupied` before its record write commits, | |
| 450 | - /// so exiting on occupancy alone can abort the write mid-flight and | |
| 451 | - /// leave a record the successor waits out the node lease for. | |
| 452 | - pub releasing: usize, | |
| 453 | -} | |
| 454 | - | |
| 455 | -// Read only by the orphaned `worker_route`; removed with the landing-cell | |
| 456 | -// machinery in the DO-dispatch refactor ([[designs/do-fast-path]]). | |
| 457 | -#[allow(dead_code)] | |
| 458 | -pub struct WorkerRouted { | |
| 459 | - pub request: u64, | |
| 460 | - pub route: Option<WorkerRoute>, | |
| 461 | -} | |
| 462 | - | |
| 463 | -/// Worker requests owned by one HTTP connection. Hyper can finish a failed | |
| 464 | -/// connection without dropping its service future, so the connection also | |
| 465 | -/// aborts these requests explicitly when its transport ends. | |
| 466 | -#[derive(Clone, Default)] | |
| 467 | -pub struct ConnectionWorkerRequests(Arc<std::sync::Mutex<BTreeSet<crate::js::RequestId>>>); | |
| 468 | - | |
| 469 | -impl ConnectionWorkerRequests { | |
| 470 | - pub fn register(&self, request: crate::js::RequestId) { | |
| 471 | - self.0.lock().unwrap().insert(request); | |
| 472 | - } | |
| 473 | - | |
| 474 | - pub fn complete(&self, request: crate::js::RequestId) { | |
| 475 | - self.0.lock().unwrap().remove(&request); | |
| 476 | - } | |
| 477 | - | |
| 478 | - pub fn abort_all(&self) { | |
| 479 | - let requests = std::mem::take(&mut *self.0.lock().unwrap()); | |
| 480 | - for request in requests { | |
| 481 | - crate::js::abort_request(request); | |
| 482 | - } | |
| 483 | - } | |
| 484 | -} | |
| 485 | - | |
| 486 | -pub struct IngressAbortGuard { | |
| 487 | - request: Option<crate::js::RequestId>, | |
| 488 | - connection: ConnectionWorkerRequests, | |
| 489 | -} | |
| 490 | - | |
| 491 | -impl IngressAbortGuard { | |
| 492 | - pub fn new(request: crate::js::RequestId, connection: ConnectionWorkerRequests) -> Self { | |
| 493 | - connection.register(request); | |
| 494 | - Self { | |
| 495 | - request: Some(request), | |
| 496 | - connection, | |
| 497 | - } | |
| 498 | - } | |
| 499 | - | |
| 500 | - pub fn disarm(&mut self) { | |
| 501 | - if let Some(request) = self.request.take() { | |
| 502 | - self.connection.complete(request); | |
| 503 | - } | |
| 504 | - } | |
| 505 | -} | |
| 506 | - | |
| 507 | -/// Cancels a core route when the future awaiting it is dropped. A normal | |
| 508 | -/// route disarms the guard before returning its result. | |
| 509 | -pub struct RouteCancelGuard { | |
| 510 | - tx: mpsc::UnboundedSender<Message>, | |
| 511 | - request: Option<u64>, | |
| 512 | -} | |
| 513 | - | |
| 514 | -impl RouteCancelGuard { | |
| 515 | - pub fn new(tx: mpsc::UnboundedSender<Message>, request: u64) -> Self { | |
| 516 | - Self { | |
| 517 | - tx, | |
| 518 | - request: Some(request), | |
| 519 | - } | |
| 520 | - } | |
| 521 | - | |
| 522 | - pub fn disarm(&mut self) { | |
| 523 | - self.request = None; | |
| 524 | - } | |
| 525 | -} | |
| 526 | - | |
| 527 | -impl Drop for RouteCancelGuard { | |
| 528 | - fn drop(&mut self) { | |
| 529 | - if let Some(request) = self.request { | |
| 530 | - let _ = self.tx.send(Message::CancelRoute { request }); | |
| 531 | - } | |
| 532 | - } | |
| 533 | -} | |
| 534 | - | |
| 535 | -impl Drop for IngressAbortGuard { | |
| 536 | - fn drop(&mut self) { | |
| 537 | - if let Some(request) = self.request.take() { | |
| 538 | - self.connection.complete(request); | |
| 539 | - crate::js::abort_request(request); | |
| 540 | - } | |
| 541 | - } | |
| 542 | -} | |
| 543 | - | |
| 544 | -pub struct ActivityGuard { | |
| 545 | - tx: mpsc::UnboundedSender<Message>, | |
| 546 | - request: u64, | |
| 547 | - runtime: Option<RuntimeManager>, | |
| 548 | - cell: String, | |
| 549 | -} | |
| 550 | - | |
| 551 | -impl Drop for ActivityGuard { | |
| 552 | - fn drop(&mut self) { | |
| 553 | - // Read and send under the registry lock (`with_alarm`), so this | |
| 554 | - // report cannot carry an alarm older than one the reporter already | |
| 555 | - // sent — a stale fold arriving later would unarm the core and | |
| 556 | - // delete the wake entry (`alarm_reporter` documents the ordering). | |
| 557 | - let send = |tx: &mpsc::UnboundedSender<Message>, at_ms, covered| { | |
| 558 | - let _ = tx.send(Message::ActivityFinished { | |
| 559 | - request: self.request, | |
| 560 | - cell: self.cell.clone(), | |
| 561 | - alarm_at_ms: at_ms, | |
| 562 | - alarm_covered: covered, | |
| 563 | - }); | |
| 564 | - }; | |
| 565 | - match &self.runtime { | |
| 566 | - Some(runtime) => runtime.with_alarm(&self.cell, |at_ms| { | |
| 567 | - let covered = runtime.alarm_covered(&self.cell, at_ms); | |
| 568 | - send(&self.tx, at_ms, covered); | |
| 569 | - }), | |
| 570 | - None => send(&self.tx, None, false), | |
| 571 | - } | |
| 572 | - } | |
| 573 | -} | |
| 574 | - | |
| 575 | -#[derive(Clone, Copy)] | |
| 576 | -enum RouteStage { | |
| 577 | - OwnershipRead, | |
| 578 | - NodeLeaseLookup, | |
| 579 | - CapacityLookup, | |
| 580 | - OwnershipAcquire, | |
| 581 | - Restore, | |
| 582 | - IsolateStartup, | |
| 583 | - RegistryInsert, | |
| 584 | -} | |
| 585 | - | |
| 586 | -struct EffectTiming { | |
| 587 | - cell: String, | |
| 588 | - stage: RouteStage, | |
| 589 | - elapsed_us: u64, | |
| 590 | -} | |
| 591 | - | |
| 592 | -pub struct CompletedEffect { | |
| 593 | - event: Event, | |
| 594 | - timing: Option<EffectTiming>, | |
| 595 | -} | |
| 596 | - | |
| 597 | -impl CompletedEffect { | |
| 598 | - fn plain(event: Event) -> Self { | |
| 599 | - Self { | |
| 600 | - event, | |
| 601 | - timing: None, | |
| 602 | - } | |
| 603 | - } | |
| 604 | - | |
| 605 | - fn timed(event: Event, cell: String, stage: RouteStage, started_mono_ms: u64) -> Self { | |
| 606 | - Self { | |
| 607 | - event, | |
| 608 | - timing: Some(EffectTiming { | |
| 609 | - cell, | |
| 610 | - stage, | |
| 611 | - elapsed_us: mono_elapsed_us(started_mono_ms), | |
| 612 | - }), | |
| 613 | - } | |
| 614 | - } | |
| 615 | -} | |
| 616 | - | |
| 617 | -struct CellRouteTiming { | |
| 618 | - started_mono_ms: u64, | |
| 619 | - activation_started: bool, | |
| 620 | - capacity_wait_started_mono_ms: Option<u64>, | |
| 621 | - latch_wait_us: u64, | |
| 622 | - ownership_read_us: u64, | |
| 623 | - node_lease_lookup_us: u64, | |
| 624 | - capacity_lookup_us: u64, | |
| 625 | - capacity_wait_us: u64, | |
| 626 | - activation_slot_wait_us: u64, | |
| 627 | - lease_permit_us: u64, | |
| 628 | - ownership_acquire_us: u64, | |
| 629 | - replica_discovery_us: u64, | |
| 630 | - restore_us: u64, | |
| 631 | - isolate_startup_us: u64, | |
| 632 | - registry_insert_us: u64, | |
| 633 | - fresh: Option<bool>, | |
| 634 | -} | |
| 635 | - | |
| 636 | -impl CellRouteTiming { | |
| 637 | - fn new() -> Self { | |
| 638 | - Self { | |
| 639 | - started_mono_ms: crate::asyncrt::mono_ms(), | |
| 640 | - activation_started: false, | |
| 641 | - capacity_wait_started_mono_ms: None, | |
| 642 | - latch_wait_us: 0, | |
| 643 | - ownership_read_us: 0, | |
| 644 | - node_lease_lookup_us: 0, | |
| 645 | - capacity_lookup_us: 0, | |
| 646 | - capacity_wait_us: 0, | |
| 647 | - activation_slot_wait_us: 0, | |
| 648 | - lease_permit_us: 0, | |
| 649 | - ownership_acquire_us: 0, | |
| 650 | - replica_discovery_us: 0, | |
| 651 | - restore_us: 0, | |
| 652 | - isolate_startup_us: 0, | |
| 653 | - registry_insert_us: 0, | |
| 654 | - fresh: None, | |
| 655 | - } | |
| 656 | - } | |
| 657 | - | |
| 658 | - fn effect_started(&mut self) { | |
| 659 | - if !self.activation_started { | |
| 660 | - self.activation_started = true; | |
| 661 | - self.activation_slot_wait_us = mono_elapsed_us(self.started_mono_ms); | |
| 662 | - } | |
| 663 | - if let Some(started) = self.capacity_wait_started_mono_ms.take() { | |
| 664 | - self.capacity_wait_us = self | |
| 665 | - .capacity_wait_us | |
| 666 | - .saturating_add(mono_elapsed_us(started)); | |
| 667 | - } | |
| 668 | - } | |
| 669 | - | |
| 670 | - fn record(&mut self, stage: RouteStage, elapsed_us: u64) { | |
| 671 | - let field = match stage { | |
| 672 | - RouteStage::OwnershipRead => &mut self.ownership_read_us, | |
| 673 | - RouteStage::NodeLeaseLookup => &mut self.node_lease_lookup_us, | |
| 674 | - RouteStage::CapacityLookup => &mut self.capacity_lookup_us, | |
| 675 | - RouteStage::OwnershipAcquire => &mut self.ownership_acquire_us, | |
| 676 | - RouteStage::Restore => &mut self.restore_us, | |
| 677 | - RouteStage::IsolateStartup => &mut self.isolate_startup_us, | |
| 678 | - RouteStage::RegistryInsert => &mut self.registry_insert_us, | |
| 679 | - }; | |
| 680 | - *field = field.saturating_add(elapsed_us); | |
| 681 | - } | |
| 682 | -} | |
| 683 | - | |
| 684 | -fn mono_elapsed_us(started_mono_ms: u64) -> u64 { | |
| 685 | - crate::asyncrt::mono_ms() | |
| 686 | - .saturating_sub(started_mono_ms) | |
| 687 | - .saturating_mul(1_000) | |
| 688 | -} | |
| 689 | - | |
| 690 | -pub type EffectFuture = Pin<Box<dyn Future<Output = CompletedEffect> + Send>>; | |
| 691 | -pub type ConnectionFuture = Pin<Box<dyn Future<Output = ()> + Send>>; | |
| 692 | -pub type DoCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>; | |
| 693 | -pub type AssetCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>; | |
| 694 | -pub type WebSocketFuture = Pin<Box<dyn Future<Output = ()> + Send>>; | |
| 695 | -pub type CachePruneFuture = Pin< | |
| 696 | - Box< | |
| 697 | - dyn Future< | |
| 698 | - Output = ( | |
| 699 | - u64, | |
| 700 | - Result<std::io::Result<(usize, usize, u64)>, crate::asyncrt::TaskPanic>, | |
| 701 | - ), | |
| 702 | - > + Send, | |
| 703 | - >, | |
| 704 | ->; | |
| 705 | - | |
| 706 | -/// One ready item selected for the serial Actor. | |
| 707 | -pub enum ActorInput { | |
| 708 | - Message(Message), | |
| 709 | - Completed(CompletedEffect), | |
| 710 | - TimerFired(Timer), | |
| 711 | -} | |
| 712 | - | |
| 713 | -/// Futures and timer arms emitted by one Actor transition. | |
| 714 | -#[derive(Default)] | |
| 715 | -pub struct StepOutput { | |
| 716 | - pub effects: Vec<EffectFuture>, | |
| 717 | - pub timers: Vec<TimerArm>, | |
| 718 | -} | |
| 719 | - | |
| 720 | -fn drain_step_output( | |
| 721 | - out: &mut StepOutput, | |
| 722 | - effects: &mut FuturesUnordered<EffectFuture>, | |
| 723 | - delays: &mut DelayQueue<TimerArm>, | |
| 724 | - timers: &mut TimerSlots<delay_queue::Key>, | |
| 725 | -) { | |
| 726 | - for effect in out.effects.drain(..) { | |
| 727 | - effects.push(effect); | |
| 728 | - } | |
| 729 | - for arm in out.timers.drain(..) { | |
| 730 | - let delay = std::time::Duration::from_millis( | |
| 731 | - arm.at_mono_ms.saturating_sub(crate::asyncrt::mono_ms()), | |
| 732 | - ); | |
| 733 | - let key = delays.insert(arm.clone(), delay); | |
| 734 | - if let Some(displaced) = timers.install(&arm, key) { | |
| 735 | - delays.remove(&displaced); | |
| 736 | - } | |
| 737 | - } | |
| 738 | -} | |
| 739 | - | |
| 740 | -#[derive(Clone)] | |
| 741 | -pub struct AppHandle { | |
| 742 | - pub tx: mpsc::UnboundedSender<Message>, | |
| 743 | - pub runtime: Option<RuntimeManager>, | |
| 744 | - pub assets: Arc<HashMap<String, AssetResolver>>, | |
| 745 | - pub asset_script: Option<Arc<str>>, | |
| 746 | - pub peer_http: reqwest::Client, | |
| 747 | - pub peer_auth: Arc<PeerAuth>, | |
| 748 | - pub advertise: String, | |
| 749 | - pub websockets: mpsc::UnboundedSender<WebSocketFuture>, | |
| 750 | - /// Whether the RPO=0 output gate is armed: hold a local write's response | |
| 751 | - /// until its cell is proven durable. On by default; set `CELLD_OUTPUT_GATE=0` | |
| 752 | - /// to acknowledge writes without proving them durable. The core and its DST | |
| 753 | - /// are unconditional. | |
| 754 | - pub output_gate: bool, | |
| 755 | - /// Concurrent outbound WebSockets one cell may hold, for the refusal | |
| 756 | - /// message; the core enforces it. | |
| 757 | - pub max_outbound_websockets: usize, | |
| 758 | - /// Set the instant a graceful shutdown begins, so `/__celld/health` reports | |
| 759 | - /// unhealthy and a load balancer stops routing here before teardown. | |
| 760 | - pub draining: Arc<std::sync::atomic::AtomicBool>, | |
| 761 | - /// The log tier's follower store: this node holds peers' log fragments | |
| 762 | - /// whatever its own durability posture. `None` without a bucket. | |
| 763 | - pub follower: Option<Arc<crate::node_log::FollowerStore>>, | |
| 764 | - /// Whether forwarded scheme and host headers can set `request.url`. | |
| 765 | - /// The default is false because a direct client controls both headers. | |
| 766 | - pub trust_forwarded_headers: bool, | |
| 767 | -} | |
| 768 | - | |
| 769 | -impl AppHandle { | |
| 770 | - pub async fn request(&self, cell: String) -> Result<Routed, RequestError> { | |
| 771 | - self.request_with_mode(cell, false).await | |
| 772 | - } | |
| 773 | - | |
| 774 | - pub async fn capacity_request(&self, cell: String) -> Result<Routed, RequestError> { | |
| 775 | - self.request_with_mode(cell, true).await | |
| 776 | - } | |
| 777 | - | |
| 778 | - async fn request_with_mode( | |
| 779 | - &self, | |
| 780 | - cell: String, | |
| 781 | - capacity_handoff: bool, | |
| 782 | - ) -> Result<Routed, RequestError> { | |
| 783 | - let request = crate::asyncrt::next_core_request(); | |
| 784 | - let (reply, receive) = oneshot::channel(); | |
| 785 | - if self | |
| 786 | - .tx | |
| 787 | - .send(Message::Request { | |
| 788 | - request, | |
| 789 | - cell, | |
| 790 | - capacity_handoff, | |
| 791 | - reply, | |
| 792 | - }) | |
| 793 | - .is_err() | |
| 794 | - { | |
| 795 | - return Err(RequestError::NodeFenced); | |
| 796 | - } | |
| 797 | - let mut cancel = RouteCancelGuard::new(self.tx.clone(), request); | |
| 798 | - let result = receive.await.unwrap_or(Err(RequestError::NodeFenced)); | |
| 799 | - cancel.disarm(); | |
| 800 | - result | |
| 801 | - } | |
| 802 | - | |
| 803 | - // Orphaned by the always-pool Worker entry below. The whole landing-cell | |
| 804 | - // machinery (this, `Message::WorkerRequest`, `WorkerRouted`, | |
| 805 | - // `fetch_worker_on_cell`, `CellJob::WorkerFetch`, the logic `worker_request`, | |
| 806 | - // and the inline co-hosted-write gate) is removed together in the DO-dispatch | |
| 807 | - // refactor ([[designs/do-fast-path]]) so the RPO=0 co-hosted path is reworked | |
| 808 | - // coherently rather than unpicked here. | |
| 809 | - #[allow(dead_code)] | |
| 810 | - async fn worker_route(&self) -> anyhow::Result<WorkerRouted> { | |
| 811 | - let (reply, receive) = oneshot::channel(); | |
| 812 | - self.tx | |
| 813 | - .send(Message::WorkerRequest { reply }) | |
| 814 | - .map_err(|_| anyhow::anyhow!("core stopped before Worker routing"))?; | |
| 815 | - receive | |
| 816 | - .await | |
| 817 | - .context("core stopped while routing Worker request") | |
| 818 | - } | |
| 819 | - | |
| 820 | - pub async fn fetch_worker( | |
| 821 | - &self, | |
| 822 | - url: String, | |
| 823 | - method: String, | |
| 824 | - body: crate::js::RequestBody, | |
| 825 | - headers: Vec<(String, String)>, | |
| 826 | - connection: ConnectionWorkerRequests, | |
| 827 | - ) -> anyhow::Result<HttpResponse> { | |
| 828 | - let runtime = self | |
| 829 | - .runtime | |
| 830 | - .as_ref() | |
| 831 | - .ok_or_else(|| anyhow::anyhow!("Worker runtime unavailable"))?; | |
| 832 | - // Admission happens in the runtime, against the pool that actually | |
| 833 | - // holds the requests. It used to be duplicated here against an empty | |
| 834 | - // `PoolLoad` — a snapshot with no isolates and no affiliations, which | |
| 835 | - // could only ever answer "yes" once pressure stopped refusing | |
| 836 | - // outright. A decision made against a fake reading is not a fast path. | |
| 837 | - let js_request = crate::js::next_request_id(); | |
| 838 | - // The Worker entry is stateless — run it in the pool, always. Routing it | |
| 839 | - // to a "landing cell" existed only to make an `env.NS.get(id)` call | |
| 840 | - // resolve inline; but a cell runs one fetch at a time, so under any real | |
| 841 | - // concurrency the entry can't be on the cell it calls, and the routing | |
| 842 | - // round-trip is paid for nothing — on top of the DO call's own routing. | |
| 843 | - // A DO call reaches its owning cell (with fencing and the output gate) on | |
| 844 | - // the host path, so one routing round-trip per request, never two. | |
| 845 | - let mut abort = IngressAbortGuard::new(js_request, connection); | |
| 846 | - let result = runtime | |
| 847 | - .fetch_worker_pool(url, method, body, headers, js_request) | |
| 848 | - .await; | |
| 849 | - abort.disarm(); | |
| 850 | - result | |
| 851 | - } | |
| 852 | - | |
| 853 | - pub fn activity(&self, request: u64, cell: String) -> ActivityGuard { | |
| 854 | - ActivityGuard { | |
| 855 | - tx: self.tx.clone(), | |
| 856 | - request, | |
| 857 | - runtime: self.runtime.clone(), | |
| 858 | - cell, | |
| 859 | - } | |
| 860 | - } | |
| 861 | - | |
| 862 | - /// Hold a response until every write it can reveal is durable. A write | |
| 863 | - /// supplies its ending position. A read supplies `None` and trails the | |
| 864 | - /// newest outstanding write on the same cell, if one exists. | |
| 865 | - pub async fn gate_output( | |
| 866 | - &self, | |
| 867 | - request: u64, | |
| 868 | - position: Option<u64>, | |
| 869 | - ) -> Result<(), RequestError> { | |
| 870 | - let started_mono_ms = crate::asyncrt::mono_ms(); | |
| 871 | - let (reply, receive) = oneshot::channel(); | |
| 872 | - if self | |
| 873 | - .tx | |
| 874 | - .send(Message::GateWrite { | |
| 875 | - request, | |
| 876 | - position, | |
| 877 | - reply, | |
| 878 | - }) | |
| 879 | - .is_err() | |
| 880 | - { | |
| 881 | - return Err(RequestError::NodeFenced); | |
| 882 | - } | |
| 883 | - let result = receive.await.unwrap_or(Err(RequestError::NodeFenced)); | |
| 884 | - tracing::debug!( | |
| 885 | - target: "timing", | |
| 886 | - event = "gate_write_timing", | |
| 887 | - request, | |
| 888 | - total_us = mono_elapsed_us(started_mono_ms), | |
| 889 | - "output gate resolved" | |
| 890 | - ); | |
| 891 | - result | |
| 892 | - } | |
| 893 | - | |
| 894 | - pub async fn gate_write(&self, request: u64, position: u64) -> Result<(), RequestError> { | |
| 895 | - self.gate_output(request, Some(position)).await | |
| 896 | - } | |
| 897 | - | |
| 898 | - /// Hand a finished `webSocketMessage`'s frames to the cell's output gate. | |
| 899 | - /// Awaited so the request stays pinned until the actor has registered the | |
| 900 | - /// gate (the core reads the still-active request when it opens); frames flush | |
| 901 | - /// or fail asynchronously as durability resolves, not here. | |
| 902 | - pub async fn ws_output( | |
| 903 | - &self, | |
| 904 | - request: u64, | |
| 905 | - scope: String, | |
| 906 | - frames: Vec<(u64, WsOut)>, | |
| 907 | - write_position: Option<u64>, | |
| 908 | - ) { | |
| 909 | - let (reply, receive) = oneshot::channel(); | |
| 910 | - if self | |
| 911 | - .tx | |
| 912 | - .send(Message::WsOutput { | |
| 913 | - request, | |
| 914 | - scope, | |
| 915 | - frames, | |
| 916 | - write_position, | |
| 917 | - reply, | |
| 918 | - }) | |
| 919 | - .is_ok() | |
| 920 | - { | |
| 921 | - let _ = receive.await; | |
| 922 | - } | |
| 923 | - } | |
| 924 | - | |
| 925 | - pub async fn websocket_opened( | |
| 926 | - &self, | |
| 927 | - cell: String, | |
| 928 | - websocket: u64, | |
| 929 | - kind: WebSocketKind, | |
| 930 | - ) -> anyhow::Result<()> { | |
| 931 | - let (reply, receive) = oneshot::channel(); | |
| 932 | - self.tx | |
| 933 | - .send(Message::WebSocketOpened { | |
| 934 | - cell, | |
| 935 | - websocket, | |
| 936 | - kind, | |
| 937 | - reply, | |
| 938 | - }) | |
| 939 | - .map_err(|_| anyhow::anyhow!("core stopped before WebSocket opened"))?; | |
| 940 | - let held = receive | |
| 941 | - .await | |
| 942 | - .context("core stopped while opening WebSocket")?; | |
| 943 | - anyhow::ensure!( | |
| 944 | - held, | |
| 945 | - "outbound WebSocket refused: a cell may hold at most {}, and a node \ | |
| 946 | - may pin at most {}% of its residency ceiling", | |
| 947 | - self.max_outbound_websockets, | |
| 948 | - celld_logic::pressure::MAX_OUTBOUND_PIN_PERCENT, | |
| 949 | - ); | |
| 950 | - Ok(()) | |
| 951 | - } | |
| 952 | - | |
| 953 | - pub fn websocket_closed(&self, cell: String, websocket: u64) { | |
| 954 | - let _ = self.tx.send(Message::WebSocketClosed { cell, websocket }); | |
| 955 | - } | |
| 956 | - | |
| 957 | - pub async fn evict(&self, cell: String) { | |
| 958 | - let (reply, receive) = oneshot::channel(); | |
| 959 | - if self.tx.send(Message::Evict { cell, reply }).is_ok() { | |
| 960 | - let _ = receive.await; | |
| 961 | - } | |
| 962 | - } | |
| 963 | - | |
| 964 | - pub async fn invalidate_remote(&self, cell: String, node: String, epoch: u64) { | |
| 965 | - let (reply, receive) = oneshot::channel(); | |
| 966 | - if self | |
| 967 | - .tx | |
| 968 | - .send(Message::InvalidateRemote { | |
| 969 | - cell, | |
| 970 | - node, | |
| 971 | - epoch, | |
| 972 | - reply, | |
| 973 | - }) | |
| 974 | - .is_ok() | |
| 975 | - { | |
| 976 | - let _ = receive.await; | |
| 977 | - } | |
| 978 | - } | |
| 979 | - | |
| 980 | - pub async fn snapshot(&self) -> String { | |
| 981 | - let (reply, receive) = oneshot::channel(); | |
| 982 | - if self.tx.send(Message::Snapshot { reply }).is_err() { | |
| 983 | - return "{\"error\":\"actor_stopped\"}".into(); | |
| 984 | - } | |
| 985 | - receive | |
| 986 | - .await | |
| 987 | - .unwrap_or_else(|_| "{\"error\":\"actor_stopped\"}".into()) | |
| 988 | - } | |
| 989 | - | |
| 990 | - pub fn is_draining(&self) -> bool { | |
| 991 | - self.draining.load(std::sync::atomic::Ordering::Relaxed) | |
| 992 | - } | |
| 993 | - | |
| 994 | - /// A dead actor has nothing left to hand off, so channel failure | |
| 995 | - /// reports drained rather than wedging shutdown. | |
| 996 | - pub async fn drain_status(&self) -> DrainStatus { | |
| 997 | - let (reply, receive) = oneshot::channel(); | |
| 998 | - if self.tx.send(Message::Drained { reply }).is_err() { | |
| 999 | - return DrainStatus::default(); | |
| 1000 | - } | |
| 1001 | - receive.await.unwrap_or_default() | |
| 1002 | - } | |
| 1003 | - | |
| 1004 | - pub async fn healthy(&self) -> bool { | |
| 1005 | - let (reply, receive) = oneshot::channel(); | |
| 1006 | - if self.tx.send(Message::Health { reply }).is_err() { | |
| 1007 | - return false; | |
| 1008 | - } | |
| 1009 | - receive.await.unwrap_or(false) | |
| 1010 | - } | |
| 1011 | - | |
| 1012 | - pub async fn presence(&self) -> Option<celld_logic::PresenceSnapshot> { | |
| 1013 | - let (reply, receive) = oneshot::channel(); | |
| 1014 | - self.tx.send(Message::Presence { reply }).ok()?; | |
| 1015 | - receive.await.ok() | |
| 1016 | - } | |
| 1017 | -} | |
| 1018 | - | |
| 1019 | -/// One cell's WebSocket output gate: an ordered queue of write barriers. | |
| 1020 | -#[derive(Default)] | |
| 1021 | -struct WsGate { | |
| 1022 | - barriers: VecDeque<WsBarrier>, | |
| 1023 | -} | |
| 1024 | - | |
| 1025 | -/// One `webSocketMessage` batch and the outbound frames held behind it. | |
| 1026 | -/// `settled` is `None` while the verdict is outstanding, `Some(true)` once the | |
| 1027 | -/// core proved every write the frames can reveal (they may flush when this | |
| 1028 | -/// barrier reaches the front), `Some(false)` on failure (the gate breaks). | |
| 1029 | -/// | |
| 1030 | -/// Every batch gets its own barrier, including one that wrote nothing: the core | |
| 1031 | -/// decides what it trails, because only the core knows the writes other | |
| 1032 | -/// channels have outstanding on this cell. The queue keeps them in arrival | |
| 1033 | -/// order and drains only from the front, so a barrier settled early cannot | |
| 1034 | -/// overtake one still waiting. | |
| 1035 | -struct WsBarrier { | |
| 1036 | - request: u64, | |
| 1037 | - settled: Option<bool>, | |
| 1038 | - frames: Vec<(u64, WsOut)>, | |
| 1039 | -} | |
| 1040 | - | |
| 1041 | -pub struct Actor { | |
| 1042 | - state: State, | |
| 1043 | - pub ownership: Ownership, | |
| 1044 | - host: Option<CellHost>, | |
| 1045 | - /// The node-log manager, filled at boot once the log tier exists: | |
| 1046 | - /// the executor's RecoverNodeLog effect runs through it directly. | |
| 1047 | - pub node_log: Arc<std::sync::Mutex<Option<Arc<crate::node_log::NodeLogManager>>>>, | |
| 1048 | - region: String, | |
| 1049 | - pending: BTreeMap<u64, oneshot::Sender<Result<Routed, RequestError>>>, | |
| 1050 | - request_cells: BTreeMap<u64, String>, | |
| 1051 | - route_timings: BTreeMap<String, CellRouteTiming>, | |
| 1052 | - pending_workers: BTreeMap<u64, oneshot::Sender<WorkerRouted>>, | |
| 1053 | - eviction_waiters: BTreeMap<String, Vec<oneshot::Sender<()>>>, | |
| 1054 | - durability_waiters: BTreeMap<u64, (String, Vec<oneshot::Sender<()>>)>, | |
| 1055 | - eviction_stops: BTreeMap<u64, Vec<oneshot::Sender<()>>>, | |
| 1056 | - /// Local write responses held open by the output gate, keyed by request, | |
| 1057 | - /// released when the core emits `ReleaseResponse`. | |
| 1058 | - gated_responses: BTreeMap<u64, oneshot::Sender<Result<(), RequestError>>>, | |
| 1059 | - /// Per-cell WebSocket output gate: a FIFO of write barriers, each holding | |
| 1060 | - /// the outbound frames produced up to it. The front drains in write order as | |
| 1061 | - /// durability proves, so no client ever sees a frame that trails an | |
| 1062 | - /// unproven write (the Cloudflare per-object output gate). | |
| 1063 | - ws_gates: BTreeMap<String, WsGate>, | |
| 1064 | - /// Gated `webSocketMessage` requests, mapping each to its cell so a | |
| 1065 | - /// `ReleaseResponse` routes to the WebSocket gate rather than an HTTP reply. | |
| 1066 | - ws_gated: BTreeMap<u64, String>, | |
| 1067 | - published: BTreeSet<String>, | |
| 1068 | - fail_publish_once: bool, | |
| 1069 | - publishes: u64, | |
| 1070 | - stops: u64, | |
| 1071 | - pub lease_spec: NodeLeaseSpec, | |
| 1072 | - /// Whether to re-check every core invariant after every event. | |
| 1073 | - /// | |
| 1074 | - /// The check is a full scan of the cell table, so its cost grows with | |
| 1075 | - /// residency: roughly 800us per event at ten thousand resident cells, | |
| 1076 | - /// which would cap a busy node at about a thousand events a second in | |
| 1077 | - /// assertion code alone. It is a model-checking assertion, and the place | |
| 1078 | - /// it earns its keep is simulation, which can afford to run it after | |
| 1079 | - /// every event over far more schedules than production will ever see. | |
| 1080 | - /// Debug builds keep it. Release builds rely on the deterministic model, | |
| 1081 | - /// because this full-table scan is too expensive for production traffic. | |
| 1082 | - validate_invariants: bool, | |
| 1083 | - /// The counters peers rank this node by, when there is a bucket to | |
| 1084 | - /// publish them to. | |
| 1085 | - live_load: Option<Arc<crate::ownership_store::LiveLoad>>, | |
| 1086 | - /// The shed reason last reported to the log, so a latch that holds for | |
| 1087 | - /// minutes is reported once rather than on every sample. | |
| 1088 | - logged_shed_reason: Option<&'static str>, | |
| 1089 | - fence: mpsc::UnboundedSender<i32>, | |
| 1090 | - timer_slots: TimerSlots<()>, | |
| 1091 | - started: bool, | |
| 1092 | - preserving: bool, | |
| 1093 | -} | |
| 1094 | - | |
| 1095 | -pub struct AdmissionLimits { | |
| 1096 | - pub resident: usize, | |
| 1097 | - pub activations: usize, | |
| 1098 | - pub evictions: usize, | |
| 1099 | - pub releases: usize, | |
| 1100 | -} | |
| 1101 | - | |
| 1102 | -pub struct ActorIdentity { | |
| 1103 | - pub node: String, | |
| 1104 | - pub advertise: String, | |
| 1105 | - pub region: String, | |
| 1106 | -} | |
| 1107 | - | |
| 1108 | -impl Actor { | |
| 1109 | - pub async fn from_environment( | |
| 1110 | - limits: AdmissionLimits, | |
| 1111 | - fail_publish_once: bool, | |
| 1112 | - fence: mpsc::UnboundedSender<i32>, | |
| 1113 | - runtime: Option<RuntimeManager>, | |
| 1114 | - ownership: Option<Ownership>, | |
| 1115 | - identity: ActorIdentity, | |
| 1116 | - resume_generation: Option<String>, | |
| 1117 | - ) -> anyhow::Result<Self> { | |
| 1118 | - Self::from_environment_with_cell_host( | |
| 1119 | - limits, | |
| 1120 | - fail_publish_once, | |
| 1121 | - fence, | |
| 1122 | - runtime.map(CellHost::V8), | |
| 1123 | - ownership, | |
| 1124 | - identity, | |
| 1125 | - resume_generation, | |
| 1126 | - ) | |
| 1127 | - .await | |
| 1128 | - } | |
| 1129 | - | |
| 1130 | - #[cfg(all(test, celld_internal_tests))] | |
| 1131 | - pub(crate) async fn from_environment_with_scripted_host( | |
| 1132 | - limits: AdmissionLimits, | |
| 1133 | - fail_publish_once: bool, | |
| 1134 | - fence: mpsc::UnboundedSender<i32>, | |
| 1135 | - host: crate::conformance_sim_cell_host::SimCellHost, | |
| 1136 | - ownership: Option<Ownership>, | |
| 1137 | - identity: ActorIdentity, | |
| 1138 | - resume_generation: Option<String>, | |
| 1139 | - ) -> anyhow::Result<Self> { | |
| 1140 | - Self::from_environment_with_cell_host( | |
| 1141 | - limits, | |
| 1142 | - fail_publish_once, | |
| 1143 | - fence, | |
| 1144 | - Some(CellHost::Scripted(host)), | |
| 1145 | - ownership, | |
| 1146 | - identity, | |
| 1147 | - resume_generation, | |
| 1148 | - ) | |
| 1149 | - .await | |
| 1150 | - } | |
| 1151 | - | |
| 1152 | - async fn from_environment_with_cell_host( | |
| 1153 | - limits: AdmissionLimits, | |
| 1154 | - fail_publish_once: bool, | |
| 1155 | - fence: mpsc::UnboundedSender<i32>, | |
| 1156 | - host: Option<CellHost>, | |
| 1157 | - ownership: Option<Ownership>, | |
| 1158 | - identity: ActorIdentity, | |
| 1159 | - resume_generation: Option<String>, | |
| 1160 | - ) -> anyhow::Result<Self> { | |
| 1161 | - let ActorIdentity { | |
| 1162 | - node, | |
| 1163 | - advertise, | |
| 1164 | - region, | |
| 1165 | - } = identity; | |
| 1166 | - let ownership = if let Some(ownership) = ownership { | |
| 1167 | - ownership | |
| 1168 | - } else { | |
| 1169 | - Ownership::Memory(Arc::new(Mutex::new(MemoryOwnership { | |
| 1170 | - node: node.clone(), | |
| 1171 | - owners: BTreeMap::new(), | |
| 1172 | - leases: BTreeMap::new(), | |
| 1173 | - next_etag: 1, | |
| 1174 | - }))) | |
| 1175 | - }; | |
| 1176 | - let live_load = match &ownership { | |
| 1177 | - Ownership::Bucket(bucket) => Some(bucket.live()), | |
| 1178 | - Ownership::Memory(_) => None, | |
| 1179 | - }; | |
| 1180 | - if let Some(live) = &live_load { | |
| 1181 | - crate::ownership_store::set_node_load(live.clone()); | |
| 1182 | - } | |
| 1183 | - let process_generation = match &ownership { | |
| 1184 | - Ownership::Bucket(bucket) => bucket | |
| 1185 | - .process_generation() | |
| 1186 | - .map(str::to_owned) | |
| 1187 | - .unwrap_or_else(random_process_generation), | |
| 1188 | - Ownership::Memory(_) => random_process_generation(), | |
| 1189 | - }; | |
| 1190 | - let ttl_ms = crate::env_vars::positive_or("CELLD_TTL_MS", 10_000)?; | |
| 1191 | - let lease_spec = NodeLeaseSpec { | |
| 1192 | - // Startup has already resolved the environment and CLI settings | |
| 1193 | - // into this validated internal address. Reading the environment | |
| 1194 | - // again would let CELLD_ADVERTISE override a later CLI option and | |
| 1195 | - // publish an address that the bound listener did not validate. | |
| 1196 | - addr: advertise, | |
| 1197 | - peer_protocol: peer_auth::PROTOCOL_VERSION, | |
| 1198 | - generation: std::env::var("CELLD_TEST_GENERATION").unwrap_or(process_generation), | |
| 1199 | - resume_generation, | |
| 1200 | - ttl_ms, | |
| 1201 | - }; | |
| 1202 | - Ok(Self { | |
| 1203 | - node_log: Arc::new(std::sync::Mutex::new(None)), | |
| 1204 | - state: State::new( | |
| 1205 | - node, | |
| 1206 | - Config { | |
| 1207 | - max_resident: limits.resident, | |
| 1208 | - max_activations: limits.activations, | |
| 1209 | - max_evictions: limits.evictions, | |
| 1210 | - max_releases: limits.releases, | |
| 1211 | - alarm_resident_ms: crate::wake::resident_ms().max(0) as u64, | |
| 1212 | - require_node_lease: true, | |
| 1213 | - peer_protocol: crate::peer_auth::PROTOCOL_VERSION, | |
| 1214 | - operation_deadline_ms: Some(crate::env_vars::positive_or( | |
| 1215 | - "CELLD_OPERATION_DEADLINE_MS", | |
| 1216 | - DEFAULT_OPERATION_DEADLINE_MS, | |
| 1217 | - )?), | |
| 1218 | - idle_evict_ms: crate::env_vars::positive::<u64>("CELLD_IDLE_EVICT_S")? | |
| 1219 | - .map(|seconds| seconds.saturating_mul(1_000)), | |
| 1220 | - pressure: pressure_config_from_environment()?, | |
| 1221 | - max_outbound_websockets: crate::env_vars::positive_or( | |
| 1222 | - "CELLD_MAX_OUTBOUND_WEBSOCKETS", | |
| 1223 | - DEFAULT_MAX_OUTBOUND_WEBSOCKETS, | |
| 1224 | - )?, | |
| 1225 | - ownership_on_evict: match &ownership { | |
| 1226 | - // Releasing a cell says "any node may take this | |
| 1227 | - // one", which is only true if some other node could | |
| 1228 | - // restore it. Without a bucket the sole copy is this | |
| 1229 | - // node's disk, keyed to an epoch a re-acquire will | |
| 1230 | - // step past, so releasing would lose the cell. | |
| 1231 | - Ownership::Memory(_) => OwnershipOnEvict::Sticky, | |
| 1232 | - Ownership::Bucket(_) => ownership_on_evict_from_environment()?, | |
| 1233 | - }, | |
| 1234 | - }, | |
| 1235 | - ), | |
| 1236 | - ownership, | |
| 1237 | - host, | |
| 1238 | - region, | |
| 1239 | - pending: BTreeMap::new(), | |
| 1240 | - request_cells: BTreeMap::new(), | |
| 1241 | - route_timings: BTreeMap::new(), | |
| 1242 | - pending_workers: BTreeMap::new(), | |
| 1243 | - eviction_waiters: BTreeMap::new(), | |
| 1244 | - durability_waiters: BTreeMap::new(), | |
| 1245 | - gated_responses: BTreeMap::new(), | |
| 1246 | - ws_gates: BTreeMap::new(), | |
| 1247 | - ws_gated: BTreeMap::new(), | |
| 1248 | - eviction_stops: BTreeMap::new(), | |
| 1249 | - published: BTreeSet::new(), | |
| 1250 | - fail_publish_once, | |
| 1251 | - publishes: 0, | |
| 1252 | - stops: 0, | |
| 1253 | - lease_spec, | |
| 1254 | - live_load, | |
| 1255 | - logged_shed_reason: None, | |
| 1256 | - validate_invariants: cfg!(debug_assertions), | |
| 1257 | - fence, | |
| 1258 | - timer_slots: TimerSlots::default(), | |
| 1259 | - started: false, | |
| 1260 | - preserving: false, | |
| 1261 | - }) | |
| 1262 | - } | |
| 1263 | - | |
| 1264 | - /// Emits the exactly-once pre-loop node-lease transition. | |
| 1265 | - pub fn start(&mut self, out: &mut StepOutput) { | |
| 1266 | - assert!(!self.started, "Actor::start was called more than once"); | |
| 1267 | - self.started = true; | |
| 1268 | - self.drive( | |
| 1269 | - Event::StartNodeLease { | |
| 1270 | - now_ms: now_ms(), | |
| 1271 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1272 | - spec: self.lease_spec.clone(), | |
| 1273 | - }, | |
| 1274 | - out, | |
| 1275 | - ); | |
| 1276 | - } | |
| 1277 | - | |
| 1278 | - /// Handles exactly one ready mailbox item, completion, or timer. | |
| 1279 | - pub fn step(&mut self, input: ActorInput, out: &mut StepOutput) { | |
| 1280 | - assert!(self.started, "Actor::step was called before Actor::start"); | |
| 1281 | - match input { | |
| 1282 | - ActorInput::Message(message) => self.handle_message(message, out), | |
| 1283 | - ActorInput::Completed(completed) => { | |
| 1284 | - #[cfg(all(test, celld_internal_tests))] | |
| 1285 | - if crate::asyncrt::sabotage_active( | |
| 1286 | - crate::host_services::EngineSabotage::SuppressReleasingDecrement, | |
| 1287 | - ) && matches!(&completed.event, Event::OwnerReleased { .. }) | |
| 1288 | - { | |
| 1289 | - return; | |
| 1290 | - } | |
| 1291 | - let route_cell = completed.timing.as_ref().map(|timing| timing.cell.clone()); | |
| 1292 | - if let Some(timing) = completed.timing { | |
| 1293 | - self.record_effect_timing(timing); | |
| 1294 | - } | |
| 1295 | - self.drive(completed.event, out); | |
| 1296 | - if let Some(cell) = route_cell { | |
| 1297 | - self.observe_capacity_wait(&cell); | |
| 1298 | - } | |
| 1299 | - } | |
| 1300 | - ActorInput::TimerFired(timer) => { | |
| 1301 | - self.timer_slots.clear_slot(&TimerSlot::of(&timer)); | |
| 1302 | - if self.preserving && matches!(timer, Timer::CellAlarm { .. }) { | |
| 1303 | - return; | |
| 1304 | - } | |
| 1305 | - self.drive( | |
| 1306 | - Event::TimerFired { | |
| 1307 | - timer, | |
| 1308 | - now_ms: now_ms(), | |
| 1309 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1310 | - }, | |
| 1311 | - out, | |
| 1312 | - ); | |
| 1313 | - } | |
| 1314 | - } | |
| 1315 | - } | |
| 1316 | - | |
| 1317 | - fn handle_message(&mut self, message: Message, out: &mut StepOutput) { | |
| 1318 | - match message { | |
| 1319 | - Message::BeginPreserve => { | |
| 1320 | - self.preserving = true; | |
| 1321 | - self.drive(Event::BeginPreserve, out); | |
| 1322 | - } | |
| 1323 | - Message::Request { reply, .. } if self.preserving => { | |
| 1324 | - let _ = reply.send(Err(RequestError::NodeFenced)); | |
| 1325 | - } | |
| 1326 | - Message::Request { | |
| 1327 | - request, | |
| 1328 | - cell, | |
| 1329 | - capacity_handoff, | |
| 1330 | - reply, | |
| 1331 | - } => { | |
| 1332 | - let retired_durability = match self.state.phase(&cell) { | |
| 1333 | - Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 1334 | - _ => None, | |
| 1335 | - }; | |
| 1336 | - self.pending.insert(request, reply); | |
| 1337 | - self.begin_route_if_cold(&cell); | |
| 1338 | - self.request_cells.insert(request, cell.clone()); | |
| 1339 | - self.drive( | |
| 1340 | - if capacity_handoff { | |
| 1341 | - Event::CapacityRequestAt { | |
| 1342 | - request, | |
| 1343 | - cell: cell.clone(), | |
| 1344 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1345 | - } | |
| 1346 | - } else { | |
| 1347 | - Event::RequestAt { | |
| 1348 | - request, | |
| 1349 | - cell: cell.clone(), | |
| 1350 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1351 | - } | |
| 1352 | - }, | |
| 1353 | - out, | |
| 1354 | - ); | |
| 1355 | - self.observe_capacity_wait(&cell); | |
| 1356 | - if let Some(op) = retired_durability { | |
| 1357 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 1358 | - for waiter in waiters { | |
| 1359 | - let _ = waiter.send(()); | |
| 1360 | - } | |
| 1361 | - } | |
| 1362 | - } | |
| 1363 | - } | |
| 1364 | - Message::CancelRoute { request } => { | |
| 1365 | - self.pending.remove(&request); | |
| 1366 | - if let Some(cell) = self.request_cells.remove(&request) { | |
| 1367 | - self.finish_route(&cell, "cancelled", "caller_disconnected", None); | |
| 1368 | - } | |
| 1369 | - self.drive(Event::Cancel { request }, out); | |
| 1370 | - } | |
| 1371 | - Message::WorkerRequest { reply } if self.preserving => { | |
| 1372 | - let _ = reply.send(WorkerRouted { | |
| 1373 | - request: crate::asyncrt::next_core_request(), | |
| 1374 | - route: None, | |
| 1375 | - }); | |
| 1376 | - } | |
| 1377 | - Message::WorkerRequest { reply } => { | |
| 1378 | - let request = crate::asyncrt::next_core_request(); | |
| 1379 | - self.pending_workers.insert(request, reply); | |
| 1380 | - self.drive(Event::WorkerRequest { request }, out); | |
| 1381 | - } | |
| 1382 | - Message::ReleaseAll => self.drive(Event::ReleaseAll, out), | |
| 1383 | - Message::Drained { reply } => { | |
| 1384 | - let _ = reply.send(DrainStatus { | |
| 1385 | - occupied: self.state.occupied(), | |
| 1386 | - activating: self.state.activating(), | |
| 1387 | - evicting: self.state.evicting(), | |
| 1388 | - releasing: self.state.releasing(), | |
| 1389 | - }); | |
| 1390 | - } | |
| 1391 | - Message::SampleLoad if self.preserving => {} | |
| 1392 | - Message::SampleLoad => { | |
| 1393 | - // Counted once: it is a walk of every cell, and the latch and | |
| 1394 | - // the number peers rank this node by must agree anyway. | |
| 1395 | - let occupied = self.state.occupied(); | |
| 1396 | - let metrics = crate::asyncrt::services().sample_metrics(); | |
| 1397 | - let cpu = metrics.cpu_percent_x100; | |
| 1398 | - let load = celld_logic::pressure::Load { | |
| 1399 | - resident_cells: occupied, | |
| 1400 | - rss_bytes: metrics.rss_bytes, | |
| 1401 | - in_use_bytes: metrics.in_use_bytes, | |
| 1402 | - }; | |
| 1403 | - let now_mono_ms = crate::asyncrt::mono_ms(); | |
| 1404 | - self.drive(Event::LoadSampled { load, now_mono_ms }, out); | |
| 1405 | - // Report a change of shed reason once. `rss-hard` is the one | |
| 1406 | - // that needs an operator: it says the resident set size crossed | |
| 1407 | - // the absolute cap, so the allocator is holding memory that | |
| 1408 | - // shedding may not return, and the process is near a kill. | |
| 1409 | - let reason = self.state.shed_reason(); | |
| 1410 | - if reason != self.logged_shed_reason { | |
| 1411 | - self.logged_shed_reason = reason; | |
| 1412 | - // How many V8 heaps the resident cells hold open. Most of | |
| 1413 | - // what a cell costs is its heap, and a heap comes back | |
| 1414 | - // only when its last cell goes, so cells alone do not say | |
| 1415 | - // how much a walk down can still return. | |
| 1416 | - let heaps = self | |
| 1417 | - .state | |
| 1418 | - .resident_isolates() | |
| 1419 | - .into_iter() | |
| 1420 | - .collect::<BTreeSet<_>>() | |
| 1421 | - .len(); | |
| 1422 | - match reason { | |
| 1423 | - Some(celld_logic::pressure::SHED_RSS_HARD) => tracing::warn!( | |
| 1424 | - rss_bytes = load.rss_bytes, | |
| 1425 | - in_use_bytes = load.in_use_bytes, | |
| 1426 | - heaps, | |
| 1427 | - "shedding on the absolute resident-set cap: the \ | |
| 1428 | - allocator holds memory that shedding cannot return" | |
| 1429 | - ), | |
| 1430 | - Some(reason) => tracing::info!( | |
| 1431 | - reason, | |
| 1432 | - rss_bytes = load.rss_bytes, | |
| 1433 | - in_use_bytes = load.in_use_bytes, | |
| 1434 | - heaps, | |
| 1435 | - "shedding" | |
| 1436 | - ), | |
| 1437 | - None => tracing::info!("no longer shedding"), | |
| 1438 | - } | |
| 1439 | - } | |
| 1440 | - // Republish what peers rank this node by. The same numbers the | |
| 1441 | - // latch just saw: a node that reports last tick's residency | |
| 1442 | - // attracts work it has already refused. | |
| 1443 | - if let Some(live) = &self.live_load { | |
| 1444 | - live.resident_cells.store(occupied, Ordering::Relaxed); | |
| 1445 | - live.host_websockets | |
| 1446 | - .store(self.state.host_websockets(), Ordering::Relaxed); | |
| 1447 | - live.pressured | |
| 1448 | - .store(self.state.shedding(), Ordering::Relaxed); | |
| 1449 | - live.cpu_percent_x100.store(cpu, Ordering::Relaxed); | |
| 1450 | - live.restoring | |
| 1451 | - .store(self.state.activation_backlog() as u64, Ordering::Relaxed); | |
| 1452 | - } | |
| 1453 | - } | |
| 1454 | - Message::GateWrite { | |
| 1455 | - request, | |
| 1456 | - position, | |
| 1457 | - reply, | |
| 1458 | - } => { | |
| 1459 | - self.gated_responses.insert(request, reply); | |
| 1460 | - self.drive( | |
| 1461 | - match position { | |
| 1462 | - Some(position) => Event::Wrote { request, position }, | |
| 1463 | - None => Event::ReadOutput { request }, | |
| 1464 | - }, | |
| 1465 | - out, | |
| 1466 | - ); | |
| 1467 | - } | |
| 1468 | - Message::WsOutput { | |
| 1469 | - request, | |
| 1470 | - scope, | |
| 1471 | - frames, | |
| 1472 | - write_position, | |
| 1473 | - reply, | |
| 1474 | - } => { | |
| 1475 | - // Open a barrier for every batch, then let the core decide | |
| 1476 | - // what it trails: its own write when the handler wrote, and | |
| 1477 | - // otherwise the newest write still outstanding on this cell, | |
| 1478 | - // whichever channel made it. The queue consulted here before | |
| 1479 | - // was filled in one place -- the arm below that writes -- so it | |
| 1480 | - // held only writes a `webSocketMessage` handler made itself, | |
| 1481 | - // and an HTTP, RPC, or peer write on the same cell was | |
| 1482 | - // invisible to a batch that only read. | |
| 1483 | - // | |
| 1484 | - // Both registrations happen before the drive, and must: `drive` | |
| 1485 | - // runs the effects it produces synchronously, so a read with no | |
| 1486 | - // barrier open on its cell is released inside the call below. | |
| 1487 | - // Moved after it, that `Effect::ReleaseResponse` would find no | |
| 1488 | - // `ws_gated` entry, fall through to the `gated_responses` map, | |
| 1489 | - // match nothing, and strand these frames behind a barrier that | |
| 1490 | - // nothing will ever settle. | |
| 1491 | - self.ws_gates | |
| 1492 | - .entry(scope.clone()) | |
| 1493 | - .or_default() | |
| 1494 | - .barriers | |
| 1495 | - .push_back(WsBarrier { | |
| 1496 | - request, | |
| 1497 | - settled: None, | |
| 1498 | - frames, | |
| 1499 | - }); | |
| 1500 | - self.ws_gated.insert(request, scope); | |
| 1501 | - self.drive( | |
| 1502 | - match write_position { | |
| 1503 | - Some(position) => Event::Wrote { request, position }, | |
| 1504 | - // A known gap remains on the other side of this | |
| 1505 | - // question: an alarm handler proves its own write | |
| 1506 | - // durable inline and registers no barrier with the | |
| 1507 | - // core, so a frame revealing one is released early. | |
| 1508 | - None => Event::ReadOutput { request }, | |
| 1509 | - }, | |
| 1510 | - out, | |
| 1511 | - ); | |
| 1512 | - let _ = reply.send(()); | |
| 1513 | - } | |
| 1514 | - Message::ActivityFinished { | |
| 1515 | - request, | |
| 1516 | - cell, | |
| 1517 | - alarm_at_ms, | |
| 1518 | - alarm_covered, | |
| 1519 | - } => { | |
| 1520 | - // Folded from the old AlarmObserved-then-ActivityFinished pair the | |
| 1521 | - // activity drop sent: observe the alarm and release any retired | |
| 1522 | - // durability waiters, then finish the activity — same events, same | |
| 1523 | - // order, one message instead of two. | |
| 1524 | - let retired_durability = match self.state.phase(&cell) { | |
| 1525 | - Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 1526 | - _ => None, | |
| 1527 | - }; | |
| 1528 | - self.drive( | |
| 1529 | - Event::AlarmObserved { | |
| 1530 | - cell, | |
| 1531 | - at_ms: alarm_at_ms, | |
| 1532 | - covered: alarm_covered, | |
| 1533 | - now_ms: now_ms(), | |
| 1534 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1535 | - }, | |
| 1536 | - out, | |
| 1537 | - ); | |
| 1538 | - if let Some(op) = retired_durability { | |
| 1539 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 1540 | - for waiter in waiters { | |
| 1541 | - let _ = waiter.send(()); | |
| 1542 | - } | |
| 1543 | - } | |
| 1544 | - } | |
| 1545 | - self.drive(Event::ActivityFinished { request }, out); | |
| 1546 | - } | |
| 1547 | - Message::WebSocketOpened { | |
| 1548 | - cell, | |
| 1549 | - websocket, | |
| 1550 | - kind, | |
| 1551 | - reply, | |
| 1552 | - } => { | |
| 1553 | - self.drive( | |
| 1554 | - Event::WebSocketOpened { | |
| 1555 | - cell: cell.clone(), | |
| 1556 | - websocket, | |
| 1557 | - kind, | |
| 1558 | - }, | |
| 1559 | - out, | |
| 1560 | - ); | |
| 1561 | - // The core may decline to hold the transport. Say so, rather | |
| 1562 | - // than acknowledging an open and closing the socket a moment | |
| 1563 | - // later: an application that hit a ceiling deserves to be | |
| 1564 | - // told which one, not left watching a socket disappear. | |
| 1565 | - // Only an outbound socket can be declined, and only for a | |
| 1566 | - // cell the core knows: an inbound transport is never refused, | |
| 1567 | - // and reporting one as refused fails opens that succeeded. | |
| 1568 | - let refused = kind == WebSocketKind::Outbound | |
| 1569 | - && !self.state.holds_websocket(&cell, websocket); | |
| 1570 | - let _ = reply.send(!refused); | |
| 1571 | - } | |
| 1572 | - Message::WebSocketClosed { cell, websocket } => { | |
| 1573 | - self.drive(Event::WebSocketClosed { cell, websocket }, out); | |
| 1574 | - } | |
| 1575 | - Message::AlarmObserved { | |
| 1576 | - cell, | |
| 1577 | - at_ms, | |
| 1578 | - covered, | |
| 1579 | - } => { | |
| 1580 | - let retired_durability = match self.state.phase(&cell) { | |
| 1581 | - Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 1582 | - _ => None, | |
| 1583 | - }; | |
| 1584 | - self.drive( | |
| 1585 | - Event::AlarmObserved { | |
| 1586 | - cell, | |
| 1587 | - at_ms, | |
| 1588 | - covered, | |
| 1589 | - now_ms: now_ms(), | |
| 1590 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1591 | - }, | |
| 1592 | - out, | |
| 1593 | - ); | |
| 1594 | - if let Some(op) = retired_durability { | |
| 1595 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 1596 | - for waiter in waiters { | |
| 1597 | - let _ = waiter.send(()); | |
| 1598 | - } | |
| 1599 | - } | |
| 1600 | - } | |
| 1601 | - } | |
| 1602 | - Message::NudgeNodeLease => { | |
| 1603 | - self.drive( | |
| 1604 | - Event::NudgeNodeLease { | |
| 1605 | - now_ms: now_ms(), | |
| 1606 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1607 | - }, | |
| 1608 | - out, | |
| 1609 | - ); | |
| 1610 | - } | |
| 1611 | - Message::WakeHint { .. } if self.preserving => {} | |
| 1612 | - Message::WakeHint { cell } => { | |
| 1613 | - self.drive( | |
| 1614 | - Event::WakeHintAt { | |
| 1615 | - cell, | |
| 1616 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1617 | - }, | |
| 1618 | - out, | |
| 1619 | - ); | |
| 1620 | - } | |
| 1621 | - Message::Evict { reply, .. } if self.preserving => { | |
| 1622 | - let _ = reply.send(()); | |
| 1623 | - } | |
| 1624 | - Message::Evict { cell, reply } if self.state.is_active(&cell) => { | |
| 1625 | - let _ = reply.send(()); | |
| 1626 | - } | |
| 1627 | - Message::Evict { cell, reply } => match self.state.phase(&cell) { | |
| 1628 | - Some(Phase::Resident { .. }) => { | |
| 1629 | - self.eviction_waiters | |
| 1630 | - .entry(cell.clone()) | |
| 1631 | - .or_default() | |
| 1632 | - .push(reply); | |
| 1633 | - self.drive(Event::Evict { cell }, out); | |
| 1634 | - } | |
| 1635 | - Some(Phase::EnsuringDurability { op, .. }) => { | |
| 1636 | - self.durability_waiters | |
| 1637 | - .entry(*op) | |
| 1638 | - .or_insert_with(|| (cell, Vec::new())) | |
| 1639 | - .1 | |
| 1640 | - .push(reply); | |
| 1641 | - } | |
| 1642 | - Some(Phase::Cleaning { | |
| 1643 | - op, | |
| 1644 | - cause: StopCause::Evict { .. }, | |
| 1645 | - .. | |
| 1646 | - }) => { | |
| 1647 | - self.eviction_stops.entry(*op).or_default().push(reply); | |
| 1648 | - } | |
| 1649 | - _ => { | |
| 1650 | - let _ = reply.send(()); | |
| 1651 | - } | |
| 1652 | - }, | |
| 1653 | - Message::InvalidateRemote { | |
| 1654 | - cell, | |
| 1655 | - node, | |
| 1656 | - epoch, | |
| 1657 | - reply, | |
| 1658 | - } => { | |
| 1659 | - self.drive(Event::InvalidateRemote { cell, node, epoch }, out); | |
| 1660 | - let _ = reply.send(()); | |
| 1661 | - } | |
| 1662 | - Message::Snapshot { reply } => { | |
| 1663 | - let _ = reply.send(self.state_json()); | |
| 1664 | - } | |
| 1665 | - Message::Health { reply } => { | |
| 1666 | - let _ = reply.send(self.state.ready_to_serve()); | |
| 1667 | - } | |
| 1668 | - Message::Presence { reply } => { | |
| 1669 | - let _ = reply.send(self.state.presence_snapshot()); | |
| 1670 | - } | |
| 1671 | - } | |
| 1672 | - } | |
| 1673 | - | |
| 1674 | - /// Settle a gated `webSocketMessage`'s durability. On success mark its | |
| 1675 | - /// barrier durable and flush the durable prefix in write order; on failure | |
| 1676 | - /// break the whole cell gate — drop every held frame and reset its sockets, | |
| 1677 | - /// since an unproven write must never leave an acknowledged trace. | |
| 1678 | - fn ws_release(&mut self, request: u64, ok: bool) { | |
| 1679 | - let Some(scope) = self.ws_gated.remove(&request) else { | |
| 1680 | - return; | |
| 1681 | - }; | |
| 1682 | - let mut flush = Vec::new(); | |
| 1683 | - let broke = { | |
| 1684 | - let Some(gate) = self.ws_gates.get_mut(&scope) else { | |
| 1685 | - return; | |
| 1686 | - }; | |
| 1687 | - if let Some(barrier) = gate.barriers.iter_mut().find(|b| b.request == request) { | |
| 1688 | - barrier.settled = Some(ok); | |
| 1689 | - } | |
| 1690 | - if gate.barriers.iter().any(|b| b.settled == Some(false)) { | |
| 1691 | - true | |
| 1692 | - } else { | |
| 1693 | - while gate | |
| 1694 | - .barriers | |
| 1695 | - .front() | |
| 1696 | - .is_some_and(|b| b.settled == Some(true)) | |
| 1697 | - { | |
| 1698 | - flush.push(gate.barriers.pop_front().unwrap().frames); | |
| 1699 | - } | |
| 1700 | - false | |
| 1701 | - } | |
| 1702 | - }; | |
| 1703 | - if broke { | |
| 1704 | - self.ws_gates.remove(&scope); | |
| 1705 | - self.ws_gated.retain(|_, s| *s != scope); | |
| 1706 | - crate::js::ws_close_scope(&scope, 1011, "durability unproven"); | |
| 1707 | - return; | |
| 1708 | - } | |
| 1709 | - for frames in flush { | |
| 1710 | - crate::js::ws_emit_batch(frames); | |
| 1711 | - } | |
| 1712 | - if self | |
| 1713 | - .ws_gates | |
| 1714 | - .get(&scope) | |
| 1715 | - .is_some_and(|g| g.barriers.is_empty()) | |
| 1716 | - { | |
| 1717 | - self.ws_gates.remove(&scope); | |
| 1718 | - } | |
| 1719 | - } | |
| 1720 | - | |
| 1721 | - fn drive(&mut self, first: Event, out: &mut StepOutput) { | |
| 1722 | - let mut events = VecDeque::from([first]); | |
| 1723 | - while let Some(event) = events.pop_front() { | |
| 1724 | - let durability = match &event { | |
| 1725 | - Event::DurabilityChecked { op, .. } => Some(*op), | |
| 1726 | - // A deadline resolves the same operation the proof would | |
| 1727 | - // have, so it has to release the same waiters. Without this | |
| 1728 | - // the core abandons the eviction and the caller that asked | |
| 1729 | - // for it stays blocked on a proof that is no longer coming. | |
| 1730 | - Event::TimerFired { | |
| 1731 | - timer: Timer::OperationDeadline { op }, | |
| 1732 | - .. | |
| 1733 | - } => Some(*op), | |
| 1734 | - _ => None, | |
| 1735 | - }; | |
| 1736 | - let stopped = match &event { | |
| 1737 | - Event::RuntimeStopped { op } => Some(*op), | |
| 1738 | - _ => None, | |
| 1739 | - }; | |
| 1740 | - let effects = on_event(&mut self.state, event); | |
| 1741 | - if let Some(op) = durability { | |
| 1742 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 1743 | - let stop = effects.iter().find_map(|effect| match effect { | |
| 1744 | - Effect::StopRuntime { | |
| 1745 | - op, | |
| 1746 | - cause: StopCause::Evict { .. }, | |
| 1747 | - .. | |
| 1748 | - } => Some(*op), | |
| 1749 | - _ => None, | |
| 1750 | - }); | |
| 1751 | - if let Some(stop) = stop { | |
| 1752 | - self.eviction_stops.entry(stop).or_default().extend(waiters); | |
| 1753 | - } else { | |
| 1754 | - for waiter in waiters { | |
| 1755 | - let _ = waiter.send(()); | |
| 1756 | - } | |
| 1757 | - } | |
| 1758 | - } | |
| 1759 | - } | |
| 1760 | - for effect in effects { | |
| 1761 | - self.execute(effect, &mut events, out); | |
| 1762 | - } | |
| 1763 | - if let Some(op) = stopped { | |
| 1764 | - if let Some(waiters) = self.eviction_stops.remove(&op) { | |
| 1765 | - for waiter in waiters { | |
| 1766 | - let _ = waiter.send(()); | |
| 1767 | - } | |
| 1768 | - } | |
| 1769 | - } | |
| 1770 | - if self.validate_invariants { | |
| 1771 | - self.state.validate().expect("celld core invariant"); | |
| 1772 | - } | |
| 1773 | - } | |
| 1774 | - } | |
| 1775 | - | |
| 1776 | - fn execute(&mut self, effect: Effect, immediate: &mut VecDeque<Event>, out: &mut StepOutput) { | |
| 1777 | - match effect { | |
| 1778 | - Effect::ScheduleTimer { timer, at_mono_ms } => { | |
| 1779 | - #[cfg(all(test, celld_internal_tests))] | |
| 1780 | - if matches!( | |
| 1781 | - timer, | |
| 1782 | - Timer::NodeLeaseFence { .. } | Timer::CellAlarm { .. } | |
| 1783 | - ) && crate::asyncrt::sabotage_active( | |
| 1784 | - crate::host_services::EngineSabotage::DropTimerArm, | |
| 1785 | - ) { | |
| 1786 | - return; | |
| 1787 | - } | |
| 1788 | - let (arm, _) = self.timer_slots.arm(timer, at_mono_ms, ()); | |
| 1789 | - out.timers.push(arm); | |
| 1790 | - } | |
| 1791 | - Effect::ReadSelfNodeLease { op } => { | |
| 1792 | - let ownership = self.ownership.clone(); | |
| 1793 | - let node = self.state.node().to_string(); | |
| 1794 | - out.effects.push(Box::pin(async move { | |
| 1795 | - let result = ownership.read_self_node_lease(&node).await; | |
| 1796 | - CompletedEffect::plain(Event::SelfNodeLeaseRead { | |
| 1797 | - op, | |
| 1798 | - now_ms: now_ms(), | |
| 1799 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1800 | - result, | |
| 1801 | - }) | |
| 1802 | - })); | |
| 1803 | - } | |
| 1804 | - Effect::CasNodeLease { | |
| 1805 | - op, | |
| 1806 | - guard, | |
| 1807 | - record, | |
| 1808 | - authority_expires_ms, | |
| 1809 | - } => { | |
| 1810 | - let ownership = self.ownership.clone(); | |
| 1811 | - out.effects.push(Box::pin(async move { | |
| 1812 | - let attempt_started_mono_ms = crate::asyncrt::mono_ms(); | |
| 1813 | - let node = record.node.clone(); | |
| 1814 | - let candidate_expires_ms = record.expires_ms; | |
| 1815 | - // Logged before the CAS: with only the completion line, a | |
| 1816 | - // renewal hung on a storage tail is indistinguishable from | |
| 1817 | - // a timer that never fired (the n6 fence, 2026-08-11). | |
| 1818 | - tracing::info!( | |
| 1819 | - event = "node_lease_attempt_started", | |
| 1820 | - %node, | |
| 1821 | - attempt = if authority_expires_ms.is_some() { | |
| 1822 | - "renew" | |
| 1823 | - } else { | |
| 1824 | - "acquire" | |
| 1825 | - }, | |
| 1826 | - prior_authority_headroom_ms = authority_expires_ms | |
| 1827 | - .map(|expires_ms| expires_ms.saturating_sub(now_ms())) | |
| 1828 | - .unwrap_or(0), | |
| 1829 | - "node lease attempt started" | |
| 1830 | - ); | |
| 1831 | - // A renewal must return while proven authority remains, | |
| 1832 | - // because only a returned attempt lets the ambiguity | |
| 1833 | - // read-back run before the watchdog. The 10:15Z R2 | |
| 1834 | - // brownout fenced 9 nodes whose sole hung attempt was | |
| 1835 | - // still inside the transport's 15 s timeout when the | |
| 1836 | - // 10 s TTL expired. Bound the attempt to half the | |
| 1837 | - // remaining authority (capped, floored) and map timeout | |
| 1838 | - // to Ambiguous — the same conservative outcome a lost | |
| 1839 | - // response already produces, so safety is unchanged. | |
| 1840 | - // The stamp survives a timed-out attempt: the backend | |
| 1841 | - // writes it through the out-parameter synchronously at | |
| 1842 | - // serialization, before the transport await, so even a | |
| 1843 | - // dropped future has reported what the possibly-landed | |
| 1844 | - // body carried. | |
| 1845 | - let mut stamped_log_state = None; | |
| 1846 | - let result = match authority_expires_ms { | |
| 1847 | - Some(expires_ms) => { | |
| 1848 | - let remaining = expires_ms.saturating_sub(now_ms()); | |
| 1849 | - let bound = | |
| 1850 | - std::time::Duration::from_millis((remaining / 2).clamp(250, 2_500)); | |
| 1851 | - match crate::asyncrt::timeout( | |
| 1852 | - bound, | |
| 1853 | - ownership.cas_node_lease(guard, record, &mut stamped_log_state), | |
| 1854 | - ) | |
| 1855 | - .await | |
| 1856 | - { | |
| 1857 | - Ok(result) => result, | |
| 1858 | - Err(_) => Err(Failure::Ambiguous), | |
| 1859 | - } | |
| 1860 | - } | |
| 1861 | - None => { | |
| 1862 | - ownership | |
| 1863 | - .cas_node_lease(guard, record, &mut stamped_log_state) | |
| 1864 | - .await | |
| 1865 | - } | |
| 1866 | - }; | |
| 1867 | - let completed_ms = now_ms(); | |
| 1868 | - let elapsed_ms = | |
| 1869 | - crate::asyncrt::mono_ms().saturating_sub(attempt_started_mono_ms); | |
| 1870 | - let prior_authority_headroom_ms = authority_expires_ms | |
| 1871 | - .map(|expires_ms| expires_ms.saturating_sub(completed_ms)) | |
| 1872 | - .unwrap_or(0); | |
| 1873 | - let candidate_headroom_ms = candidate_expires_ms.saturating_sub(completed_ms); | |
| 1874 | - let attempt = if authority_expires_ms.is_some() { | |
| 1875 | - "renew" | |
| 1876 | - } else { | |
| 1877 | - "acquire" | |
| 1878 | - }; | |
| 1879 | - let outcome = match &result { | |
| 1880 | - Ok(LeaseCasOutcome::Applied { .. }) => "applied", | |
| 1881 | - Ok(LeaseCasOutcome::Rejected) => "rejected", | |
| 1882 | - Err(Failure::Ambiguous) => "ambiguous", | |
| 1883 | - Err(Failure::Definite) => "definite_failure", | |
| 1884 | - }; | |
| 1885 | - if matches!(&result, Ok(LeaseCasOutcome::Applied { .. })) { | |
| 1886 | - tracing::info!( | |
| 1887 | - event = "node_lease_attempt", | |
| 1888 | - %node, | |
| 1889 | - attempt, | |
| 1890 | - outcome, | |
| 1891 | - elapsed_ms, | |
| 1892 | - prior_authority_headroom_ms, | |
| 1893 | - candidate_headroom_ms, | |
| 1894 | - "node lease attempt completed" | |
| 1895 | - ); | |
| 1896 | - } else { | |
| 1897 | - tracing::warn!( | |
| 1898 | - event = "node_lease_attempt", | |
| 1899 | - %node, | |
| 1900 | - attempt, | |
| 1901 | - outcome, | |
| 1902 | - elapsed_ms, | |
| 1903 | - prior_authority_headroom_ms, | |
| 1904 | - candidate_headroom_ms, | |
| 1905 | - "node lease attempt did not apply" | |
| 1906 | - ); | |
| 1907 | - } | |
| 1908 | - CompletedEffect::plain(Event::NodeLeaseCasCompleted { | |
| 1909 | - op, | |
| 1910 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 1911 | - result, | |
| 1912 | - stamped_log_state, | |
| 1913 | - }) | |
| 1914 | - })); | |
| 1915 | - } | |
| 1916 | - Effect::ReadLocalCells => { | |
| 1917 | - let runtime = self.host.clone(); | |
| 1918 | - out.effects.push(Box::pin(async move { | |
| 1919 | - let result = match runtime { | |
| 1920 | - // The host runtime's blocking pool, not a second | |
| 1921 | - // pool on the core's current-thread runtime. | |
| 1922 | - Some(runtime) => crate::asyncrt::blocking(move || { | |
| 1923 | - runtime.local_reload_cells().map_err(|error| { | |
| 1924 | - eprintln!("celld local reload scan failed: {error:#}"); | |
| 1925 | - Failure::Definite | |
| 1926 | - }) | |
| 1927 | - }) | |
| 1928 | - .await | |
| 1929 | - .unwrap_or(Err(Failure::Definite)), | |
| 1930 | - None => Err(Failure::Definite), | |
| 1931 | - }; | |
| 1932 | - CompletedEffect::plain(Event::LocalCellsRead { result }) | |
| 1933 | - })); | |
| 1934 | - } | |
| 1935 | - Effect::ReadOwner { op, cell } => { | |
| 1936 | - self.route_effect_started(&cell); | |
| 1937 | - let ownership = self.ownership.clone(); | |
| 1938 | - let timing_cell = cell.clone(); | |
| 1939 | - out.effects.push(Box::pin(async move { | |
| 1940 | - let started = crate::asyncrt::mono_ms(); | |
| 1941 | - let result = ownership.read_owner(&cell).await; | |
| 1942 | - CompletedEffect::timed( | |
| 1943 | - Event::OwnerRead { | |
| 1944 | - op, | |
| 1945 | - now_ms: now_ms(), | |
| 1946 | - result, | |
| 1947 | - }, | |
| 1948 | - timing_cell, | |
| 1949 | - RouteStage::OwnershipRead, | |
| 1950 | - started, | |
| 1951 | - ) | |
| 1952 | - })); | |
| 1953 | - } | |
| 1954 | - Effect::ReadNodeLease { op, cell, owner } => { | |
| 1955 | - self.route_effect_started(&cell); | |
| 1956 | - let ownership = self.ownership.clone(); | |
| 1957 | - let timing_cell = cell; | |
| 1958 | - out.effects.push(Box::pin(async move { | |
| 1959 | - let started = crate::asyncrt::mono_ms(); | |
| 1960 | - let result = ownership.read_node_lease(&owner).await; | |
| 1961 | - CompletedEffect::timed( | |
| 1962 | - Event::NodeLeaseRead { | |
| 1963 | - op, | |
| 1964 | - now_ms: now_ms(), | |
| 1965 | - result, | |
| 1966 | - }, | |
| 1967 | - timing_cell, | |
| 1968 | - RouteStage::NodeLeaseLookup, | |
| 1969 | - started, | |
| 1970 | - ) | |
| 1971 | - })); | |
| 1972 | - } | |
| 1973 | - Effect::RecoverNodeLog { op, cell, owner } => { | |
| 1974 | - self.route_effect_started(&cell); | |
| 1975 | - #[cfg(all(test, celld_internal_tests))] | |
| 1976 | - let interlock = if crate::asyncrt::sabotage_active( | |
| 1977 | - crate::host_services::EngineSabotage::SkipTakeoverInterlock, | |
| 1978 | - ) { | |
| 1979 | - None | |
| 1980 | - } else { | |
| 1981 | - self.node_log.lock().unwrap().clone() | |
| 1982 | - }; | |
| 1983 | - #[cfg(not(all(test, celld_internal_tests)))] | |
| 1984 | - let interlock = self.node_log.lock().unwrap().clone(); | |
| 1985 | - let timing_cell = cell.clone(); | |
| 1986 | - out.effects.push(Box::pin(async move { | |
| 1987 | - let started = crate::asyncrt::mono_ms(); | |
| 1988 | - let result = match interlock { | |
| 1989 | - // No log tier on this node (no bucket): nothing to | |
| 1990 | - // recover, and the claim proceeds as before. | |
| 1991 | - None => Ok(()), | |
| 1992 | - Some(interlock) => interlock | |
| 1993 | - .ensure_recovered(Some(&owner)) | |
| 1994 | - .await | |
| 1995 | - .map_err(|error| { | |
| 1996 | - eprintln!( | |
| 1997 | - "celld node-log recovery for takeover of {cell} failed: {error:#}" | |
| 1998 | - ); | |
| 1999 | - Failure::Ambiguous | |
| 2000 | - }), | |
| 2001 | - }; | |
| 2002 | - CompletedEffect::timed( | |
| 2003 | - Event::NodeLogRecovered { op, result }, | |
| 2004 | - timing_cell, | |
| 2005 | - RouteStage::NodeLeaseLookup, | |
| 2006 | - started, | |
| 2007 | - ) | |
| 2008 | - })); | |
| 2009 | - } | |
| 2010 | - Effect::ReadCapacityPeers { op, cell } => { | |
| 2011 | - self.route_effect_started(&cell); | |
| 2012 | - let ownership = self.ownership.clone(); | |
| 2013 | - let timing_cell = cell; | |
| 2014 | - out.effects.push(Box::pin(async move { | |
| 2015 | - let started = crate::asyncrt::mono_ms(); | |
| 2016 | - let result = ownership.read_capacity_peers().await; | |
| 2017 | - CompletedEffect::timed( | |
| 2018 | - Event::CapacityPeersRead { | |
| 2019 | - op, | |
| 2020 | - now_ms: now_ms(), | |
| 2021 | - result, | |
| 2022 | - }, | |
| 2023 | - timing_cell, | |
| 2024 | - RouteStage::CapacityLookup, | |
| 2025 | - started, | |
| 2026 | - ) | |
| 2027 | - })); | |
| 2028 | - } | |
| 2029 | - Effect::CasOwner { | |
| 2030 | - op, | |
| 2031 | - cell, | |
| 2032 | - guard, | |
| 2033 | - epoch, | |
| 2034 | - takeover, | |
| 2035 | - } => { | |
| 2036 | - self.route_effect_started(&cell); | |
| 2037 | - if let Some(timing) = self.route_timings.get_mut(&cell) { | |
| 2038 | - timing | |
| 2039 | - .fresh | |
| 2040 | - .get_or_insert(!takeover && matches!(guard, CasGuard::Absent)); | |
| 2041 | - } | |
| 2042 | - let ownership = self.ownership.clone(); | |
| 2043 | - let timing_cell = cell.clone(); | |
| 2044 | - out.effects.push(Box::pin(async move { | |
| 2045 | - let started = crate::asyncrt::mono_ms(); | |
| 2046 | - let result = ownership.cas_owner(&cell, guard, epoch).await; | |
| 2047 | - CompletedEffect::timed( | |
| 2048 | - Event::OwnerCasCompleted { op, result }, | |
| 2049 | - timing_cell, | |
| 2050 | - RouteStage::OwnershipAcquire, | |
| 2051 | - started, | |
| 2052 | - ) | |
| 2053 | - })); | |
| 2054 | - } | |
| 2055 | - Effect::ReconcileWakeEntry { | |
| 2056 | - cell, | |
| 2057 | - next_alarm_ms, | |
| 2058 | - } => { | |
| 2059 | - if self.host.is_some() { | |
| 2060 | - // An ARMED alarm must always be reconcilable, tracked or | |
| 2061 | - // not: belief can be lost while the alarm stands (a | |
| 2062 | - // failed arm-time PUT, an entry retired under a racing | |
| 2063 | - // arm), and skipping here would mean it is never | |
| 2064 | - // re-asserted — entryless until the alarm fires or the | |
| 2065 | - // cell moves. Gating the CONSUME side on tracking is | |
| 2066 | - // what keeps alarm-less cells op-quiescent: untracked | |
| 2067 | - // with no alarm, there is nothing to delete. | |
| 2068 | - if next_alarm_ms >= 0 || crate::js::wake_entry_tracked(&cell) { | |
| 2069 | - // On the host runtime: this arm runs on the core | |
| 2070 | - // thread, and a bare spawn would schedule the S3 | |
| 2071 | - // round trip there too. | |
| 2072 | - crate::asyncrt::spawn(async move { | |
| 2073 | - // A consume-delete only ever follows a firing, and | |
| 2074 | - // the core orders it from the far side of the | |
| 2075 | - // output gate: `alarm_finished` gates the | |
| 2076 | - // consuming commit, and only a proven | |
| 2077 | - // DurableReached — with C1's ownership read | |
| 2078 | - // behind a bucket proof — lets the alarm settle | |
| 2079 | - // into this reconcile. So by the time this delete | |
| 2080 | - // is ordered, the proof already happened, and | |
| 2081 | - // nothing here decides anything. The old | |
| 2082 | - // sync_refused probe asked the same question a | |
| 2083 | - // second way and was wrong more often: it refused | |
| 2084 | - // for any database the replicator never | |
| 2085 | - // registered, leaving the entry to outlive its | |
| 2086 | - // alarm forever. | |
| 2087 | - crate::js::reconcile_wake_entry(&cell, next_alarm_ms, true).await; | |
| 2088 | - }) | |
| 2089 | - .detach(); | |
| 2090 | - } | |
| 2091 | - } | |
| 2092 | - } | |
| 2093 | - Effect::ReleaseOwner { op, cell, epoch } => { | |
| 2094 | - let ownership = self.ownership.clone(); | |
| 2095 | - out.effects.push(Box::pin(async move { | |
| 2096 | - let result = ownership.release_owner(&cell, epoch).await; | |
| 2097 | - CompletedEffect::plain(Event::OwnerReleased { op, result }) | |
| 2098 | - })); | |
| 2099 | - } | |
| 2100 | - Effect::Restore { op, cell, spec } => { | |
| 2101 | - self.route_effect_started(&cell); | |
| 2102 | - if let Some(runtime) = self.host.clone() { | |
| 2103 | - let timing_cell = cell.clone(); | |
| 2104 | - // A restore downloads, merges, and fsyncs a whole | |
| 2105 | - // database. Poll it on the host runtime: this future | |
| 2106 | - // lives in `out`, which the core thread drives, | |
| 2107 | - // and the core owns the node lease timer. | |
| 2108 | - let task = crate::asyncrt::spawn(async move { | |
| 2109 | - let started = crate::asyncrt::mono_ms(); | |
| 2110 | - let result = runtime.restore_cell(&cell, &spec).await.map_err(|error| { | |
| 2111 | - eprintln!("celld restore failed for {cell}: {error:#}"); | |
| 2112 | - Failure::Definite | |
| 2113 | - }); | |
| 2114 | - CompletedEffect::timed( | |
| 2115 | - Event::RestoreCompleted { op, result }, | |
| 2116 | - timing_cell, | |
| 2117 | - RouteStage::Restore, | |
| 2118 | - started, | |
| 2119 | - ) | |
| 2120 | - }); | |
| 2121 | - out.effects.push(Box::pin(async move { | |
| 2122 | - task.await.expect("restore task panicked") | |
| 2123 | - })); | |
| 2124 | - } else { | |
| 2125 | - self.record_effect_timing(EffectTiming { | |
| 2126 | - cell, | |
| 2127 | - stage: RouteStage::Restore, | |
| 2128 | - elapsed_us: 0, | |
| 2129 | - }); | |
| 2130 | - immediate.push_back(Event::RestoreCompleted { | |
| 2131 | - op, | |
| 2132 | - result: Ok(celld_logic::RestoreOutcome { | |
| 2133 | - restored: false, | |
| 2134 | - alarm: None, | |
| 2135 | - }), | |
| 2136 | - }); | |
| 2137 | - } | |
| 2138 | - } | |
| 2139 | - Effect::StartRuntime { op, cell, epoch } => { | |
| 2140 | - self.route_effect_started(&cell); | |
| 2141 | - if let Some(runtime) = self.host.clone() { | |
| 2142 | - let fresh = self | |
| 2143 | - .route_timings | |
| 2144 | - .get(&cell) | |
| 2145 | - .and_then(|timing| timing.fresh) | |
| 2146 | - .unwrap_or(false); | |
| 2147 | - let timing_cell = cell.clone(); | |
| 2148 | - out.effects.push(Box::pin(async move { | |
| 2149 | - let started = crate::asyncrt::mono_ms(); | |
| 2150 | - let placed = runtime | |
| 2151 | - .start_cell(cell.clone(), epoch, fresh) | |
| 2152 | - .await | |
| 2153 | - .map_err(|error| { | |
| 2154 | - eprintln!("celld runtime start failed for {cell}: {error:#}"); | |
| 2155 | - Failure::Definite | |
| 2156 | - }); | |
| 2157 | - let isolate = placed.as_ref().ok().copied(); | |
| 2158 | - CompletedEffect::timed( | |
| 2159 | - Event::RuntimeStarted { | |
| 2160 | - op, | |
| 2161 | - isolate, | |
| 2162 | - result: placed.map(|_| ()), | |
| 2163 | - }, | |
| 2164 | - timing_cell, | |
| 2165 | - RouteStage::IsolateStartup, | |
| 2166 | - started, | |
| 2167 | - ) | |
| 2168 | - })); | |
| 2169 | - } else { | |
| 2170 | - self.record_effect_timing(EffectTiming { | |
| 2171 | - cell, | |
| 2172 | - stage: RouteStage::IsolateStartup, | |
| 2173 | - elapsed_us: 0, | |
| 2174 | - }); | |
| 2175 | - immediate.push_back(Event::RuntimeStarted { | |
| 2176 | - op, | |
| 2177 | - isolate: None, | |
| 2178 | - result: Ok(()), | |
| 2179 | - }); | |
| 2180 | - } | |
| 2181 | - } | |
| 2182 | - Effect::Publish { op, cell, epoch } => { | |
| 2183 | - self.route_effect_started(&cell); | |
| 2184 | - let publish_started = crate::asyncrt::mono_ms(); | |
| 2185 | - self.publishes += 1; | |
| 2186 | - let result = if self.fail_publish_once { | |
| 2187 | - self.fail_publish_once = false; | |
| 2188 | - Err(Failure::Ambiguous) | |
| 2189 | - } else { | |
| 2190 | - self.host | |
| 2191 | - .as_ref() | |
| 2192 | - .map_or(Ok(()), |runtime| runtime.publish_cell(&cell, epoch)) | |
| 2193 | - .map_err(|error| { | |
| 2194 | - eprintln!("celld runtime publication failed for {cell}: {error:#}"); | |
| 2195 | - Failure::Definite | |
| 2196 | - }) | |
| 2197 | - }; | |
| 2198 | - if result.is_ok() { | |
| 2199 | - self.published.insert(cell.clone()); | |
| 2200 | - } | |
| 2201 | - self.record_effect_timing(EffectTiming { | |
| 2202 | - cell: cell.clone(), | |
| 2203 | - stage: RouteStage::RegistryInsert, | |
| 2204 | - elapsed_us: mono_elapsed_us(publish_started), | |
| 2205 | - }); | |
| 2206 | - if result.is_ok() { | |
| 2207 | - let node = self.state.node().to_string(); | |
| 2208 | - self.finish_route(&cell, "activated", "", Some((&node, epoch))); | |
| 2209 | - } | |
| 2210 | - immediate.push_back(Event::Published { op, result }); | |
| 2211 | - } | |
| 2212 | - Effect::EnsureDurable { op, cell, epoch } => { | |
| 2213 | - let waiters = self.eviction_waiters.remove(&cell).unwrap_or_default(); | |
| 2214 | - self.durability_waiters.insert(op, (cell.clone(), waiters)); | |
| 2215 | - if let Some(runtime) = self.host.clone() { | |
| 2216 | - out.effects.push(Box::pin(async move { | |
| 2217 | - let result = runtime.ensure_durable(&cell, epoch).await.map_err(|error| { | |
| 2218 | - eprintln!( | |
| 2219 | - "celld durability proof failed for {cell} epoch {epoch}: {error:#}" | |
| 2220 | - ); | |
| 2221 | - Failure::Ambiguous | |
| 2222 | - }); | |
| 2223 | - CompletedEffect::plain(Event::DurabilityChecked { op, result }) | |
| 2224 | - })); | |
| 2225 | - } else { | |
| 2226 | - immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) }); | |
| 2227 | - } | |
| 2228 | - } | |
| 2229 | - // The output gate: prove the cell durable, then let the core release | |
| 2230 | - // the held write response. Reuses the same recency-proving primitive | |
| 2231 | - // as EnsureDurable — a proof issued after the write covers it. | |
| 2232 | - Effect::AwaitDurable { | |
| 2233 | - op, | |
| 2234 | - cell, | |
| 2235 | - epoch, | |
| 2236 | - position, | |
| 2237 | - } => { | |
| 2238 | - if let Some(runtime) = self.host.clone() { | |
| 2239 | - out.effects.push(Box::pin(async move { | |
| 2240 | - // The replicator reports the position it actually | |
| 2241 | - // proved durable and which mechanism proved it; the | |
| 2242 | - // core acks only if the position covers this write, | |
| 2243 | - // and decides per source whether C1's ownership | |
| 2244 | - // verification must run first (Effect::VerifyOwnership). | |
| 2245 | - let (result, source) = | |
| 2246 | - match runtime.await_durable(&cell, epoch, position).await { | |
| 2247 | - Ok((durable, source)) => { | |
| 2248 | - #[cfg(all(test, celld_internal_tests))] | |
| 2249 | - let durable = if crate::asyncrt::sabotage_active( | |
| 2250 | - crate::host_services::EngineSabotage::MisreportGatePosition, | |
| 2251 | - ) { | |
| 2252 | - durable.saturating_sub(1) | |
| 2253 | - } else { | |
| 2254 | - durable | |
| 2255 | - }; | |
| 2256 | - (Ok(durable), source) | |
| 2257 | - } | |
| 2258 | - Err(error) => { | |
| 2259 | - eprintln!( | |
| 2260 | - "celld output-gate durability proof failed for {cell} \ | |
| 2261 | - epoch {epoch}: {error:#}" | |
| 2262 | - ); | |
| 2263 | - (Err(Failure::Ambiguous), celld_logic::ProofSource::Bucket) | |
| 2264 | - } | |
| 2265 | - }; | |
| 2266 | - CompletedEffect::plain(Event::DurableReached { op, result, source }) | |
| 2267 | - })); | |
| 2268 | - } else { | |
| 2269 | - immediate.push_back(Event::DurableReached { | |
| 2270 | - op, | |
| 2271 | - result: Ok(position), | |
| 2272 | - source: celld_logic::ProofSource::Fleet, | |
| 2273 | - }); | |
| 2274 | - } | |
| 2275 | - } | |
| 2276 | - Effect::VerifyOwnership { op, cell, epoch } => { | |
| 2277 | - // C1 for bucket-proof acks. Durable in `e<epoch>/` is not | |
| 2278 | - // the same as durable: if the cell has been taken over, that | |
| 2279 | - // prefix is orphaned — the next owner restores a higher | |
| 2280 | - // epoch and this write is gone. A read is enough, and is why | |
| 2281 | - // this is one GET rather than a compare-and-swap: if the | |
| 2282 | - // record still names us, no takeover linearised before this | |
| 2283 | - // read; the LTX went up before it; so any later takeover | |
| 2284 | - // restores from a lineage that already contains the write. | |
| 2285 | - let ownership = self.ownership.clone(); | |
| 2286 | - let node = self.state.node().to_string(); | |
| 2287 | - out.effects.push(Box::pin(async move { | |
| 2288 | - #[cfg(all(test, celld_internal_tests))] | |
| 2289 | - if crate::asyncrt::sabotage_active( | |
| 2290 | - crate::host_services::EngineSabotage::SkipBucketProofOwnershipRead, | |
| 2291 | - ) { | |
| 2292 | - return CompletedEffect::plain(Event::OwnershipVerified { | |
| 2293 | - op, | |
| 2294 | - result: Ok(()), | |
| 2295 | - }); | |
| 2296 | - } | |
| 2297 | - let result = match ownership.read_owner(&cell).await { | |
| 2298 | - Ok(Some(record)) | |
| 2299 | - if record.node.as_deref() == Some(node.as_str()) | |
| 2300 | - && record.epoch == epoch => | |
| 2301 | - { | |
| 2302 | - Ok(()) | |
| 2303 | - } | |
| 2304 | - Ok(record) => { | |
| 2305 | - eprintln!( | |
| 2306 | - "celld output gate: {cell} epoch {epoch} is no longer ours \ | |
| 2307 | - (record: {record:?}); refusing to acknowledge a write in an \ | |
| 2308 | - orphaned epoch" | |
| 2309 | - ); | |
| 2310 | - Err(Failure::Definite) | |
| 2311 | - } | |
| 2312 | - Err(failure) => Err(failure), | |
| 2313 | - }; | |
| 2314 | - CompletedEffect::plain(Event::OwnershipVerified { op, result }) | |
| 2315 | - })); | |
| 2316 | - } | |
| 2317 | - Effect::ReleaseResponse { request, result } => { | |
| 2318 | - if self.ws_gated.contains_key(&request) { | |
| 2319 | - self.ws_release(request, result.is_ok()); | |
| 2320 | - } else if let Some(reply) = self.gated_responses.remove(&request) { | |
| 2321 | - let _ = reply.send(result); | |
| 2322 | - } | |
| 2323 | - } | |
| 2324 | - Effect::StopRuntime { | |
| 2325 | - op, | |
| 2326 | - cell, | |
| 2327 | - epoch, | |
| 2328 | - cause, | |
| 2329 | - } => { | |
| 2330 | - #[cfg(all(test, celld_internal_tests))] | |
| 2331 | - if matches!(cause, StopCause::Reset) | |
| 2332 | - && crate::asyncrt::sabotage_active( | |
| 2333 | - crate::host_services::EngineSabotage::SuppressResetStop, | |
| 2334 | - ) | |
| 2335 | - { | |
| 2336 | - return; | |
| 2337 | - } | |
| 2338 | - self.stops += 1; | |
| 2339 | - let evicting = matches!(cause, StopCause::Evict { .. }); | |
| 2340 | - if matches!(cause, StopCause::Fence) { | |
| 2341 | - // A fenced cell's wake entry belongs to whoever takes the | |
| 2342 | - // cell over; a retained local belief would collide with | |
| 2343 | - // the new owner's arm/consume traffic on the same key. | |
| 2344 | - crate::js::forget_wake_entry(&cell); | |
| 2345 | - } | |
| 2346 | - // Handing the cell away makes the local snapshot dead weight; | |
| 2347 | - // keeping it is the whole point of an idle eviction. A | |
| 2348 | - // reset must keep nothing: the local database is precisely | |
| 2349 | - // what could not be proved durable, so the next activation has | |
| 2350 | - // to come from the bucket. | |
| 2351 | - let preserve_local = !matches!( | |
| 2352 | - cause, | |
| 2353 | - StopCause::Evict { rebalance: true } | StopCause::Reset | |
| 2354 | - ); | |
| 2355 | - if evicting { | |
| 2356 | - if let Some(live) = &self.live_load { | |
| 2357 | - live.shed_cells.fetch_add(1, Ordering::Relaxed); | |
| 2358 | - } | |
| 2359 | - } | |
| 2360 | - self.published.remove(&cell); | |
| 2361 | - if let Some(runtime) = self.host.clone() { | |
| 2362 | - out.effects.push(Box::pin(async move { | |
| 2363 | - runtime | |
| 2364 | - .stop_cell(&cell, epoch, evicting, preserve_local) | |
| 2365 | - .await; | |
| 2366 | - CompletedEffect::plain(Event::RuntimeStopped { op }) | |
| 2367 | - })); | |
| 2368 | - } else { | |
| 2369 | - immediate.push_back(Event::RuntimeStopped { op }); | |
| 2370 | - } | |
| 2371 | - } | |
| 2372 | - Effect::FireAlarm { | |
| 2373 | - op, | |
| 2374 | - cell, | |
| 2375 | - epoch, | |
| 2376 | - scheduled_ms, | |
| 2377 | - } => { | |
| 2378 | - if let Some(runtime) = self.host.clone() { | |
| 2379 | - out.effects.push(Box::pin(async move { | |
| 2380 | - // The shell reports the firing raw: the deadline that | |
| 2381 | - // stands after the handler, whether a wake entry | |
| 2382 | - // covers it, and the position of the consuming | |
| 2383 | - // commit. Proving that commit durable — and this node | |
| 2384 | - // still the owner — is the core's job: it opens the | |
| 2385 | - // same output gate a request's write gets, so one | |
| 2386 | - // question answers for every egress on the cell, and | |
| 2387 | - // the consume-side wake-entry delete leaves only from | |
| 2388 | - // the far side of the proof. On failure the core | |
| 2389 | - // re-arms or resets; either way the entry stays | |
| 2390 | - // discoverable and at-least-once holds. | |
| 2391 | - let result = runtime | |
| 2392 | - .fire_alarm(cell.clone(), scheduled_ms) | |
| 2393 | - .await | |
| 2394 | - .map_err(|error| { | |
| 2395 | - eprintln!("celld alarm dispatch failed: {error:#}"); | |
| 2396 | - Failure::Definite | |
| 2397 | - }); | |
| 2398 | - // The tooth for the gate the core opens below. It | |
| 2399 | - // restores the shape this change replaced: prove the | |
| 2400 | - // commit here, privately, and tell the core nothing — | |
| 2401 | - // so the proof still runs, and every reader of the | |
| 2402 | - // cell is still released against it. | |
| 2403 | - #[cfg(all(test, celld_internal_tests))] | |
| 2404 | - let result = if crate::asyncrt::sabotage_active( | |
| 2405 | - crate::host_services::EngineSabotage::SkipAlarmWriteGate, | |
| 2406 | - ) { | |
| 2407 | - if let Ok((_, _, Some(position))) = result { | |
| 2408 | - let _ = runtime.await_durable(&cell, epoch, position).await; | |
| 2409 | - } | |
| 2410 | - result.map(|(at_ms, covered, _)| (at_ms, covered, None)) | |
| 2411 | - } else { | |
| 2412 | - result | |
| 2413 | - }; | |
| 2414 | - CompletedEffect::plain(Event::AlarmFinished { | |
| 2415 | - op, | |
| 2416 | - cell, | |
| 2417 | - epoch, | |
| 2418 | - now_ms: now_ms(), | |
| 2419 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2420 | - result, | |
| 2421 | - }) | |
| 2422 | - })); | |
| 2423 | - } else { | |
| 2424 | - immediate.push_back(Event::AlarmFinished { | |
| 2425 | - op, | |
| 2426 | - cell, | |
| 2427 | - epoch, | |
| 2428 | - now_ms: now_ms(), | |
| 2429 | - now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2430 | - result: Ok((None, true, None)), | |
| 2431 | - }); | |
| 2432 | - } | |
| 2433 | - } | |
| 2434 | - Effect::Complete { request, result } => { | |
| 2435 | - if let Some(cell) = self.request_cells.remove(&request) { | |
| 2436 | - match &result { | |
| 2437 | - Ok(Route::Remote { node, epoch, .. }) => { | |
| 2438 | - self.finish_route(&cell, "remote_owner", "", Some((node, *epoch))); | |
| 2439 | - // The cell lives elsewhere: its wake entry is no | |
| 2440 | - // longer this node's to track, and a stale local | |
| 2441 | - // belief would collide with the owner's own | |
| 2442 | - // arm/consume traffic on the same key. | |
| 2443 | - crate::js::forget_wake_entry(&cell); | |
| 2444 | - } | |
| 2445 | - Ok(Route::Local) => { | |
| 2446 | - self.finish_route(&cell, "resident_after_wait", "", None); | |
| 2447 | - } | |
| 2448 | - Err(error) => { | |
| 2449 | - self.finish_route( | |
| 2450 | - &cell, | |
| 2451 | - "route_error", | |
| 2452 | - request_error_phase(*error), | |
| 2453 | - None, | |
| 2454 | - ); | |
| 2455 | - } | |
| 2456 | - } | |
| 2457 | - } | |
| 2458 | - if let Some(reply) = self.pending.remove(&request) { | |
| 2459 | - let local = result == Ok(Route::Local); | |
| 2460 | - if reply | |
| 2461 | - .send(result.map(|route| Routed { request, route })) | |
| 2462 | - .is_err() | |
| 2463 | - && local | |
| 2464 | - { | |
| 2465 | - immediate.push_back(Event::ActivityFinished { request }); | |
| 2466 | - } | |
| 2467 | - } | |
| 2468 | - } | |
| 2469 | - Effect::CompleteWorker { request, route } => { | |
| 2470 | - if let Some(op) = route.as_ref().and_then(|route| route.retired_durability) { | |
| 2471 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 2472 | - for waiter in waiters { | |
| 2473 | - let _ = waiter.send(()); | |
| 2474 | - } | |
| 2475 | - } | |
| 2476 | - } | |
| 2477 | - if let Some(reply) = self.pending_workers.remove(&request) { | |
| 2478 | - let reserved = route.is_some(); | |
| 2479 | - if reply.send(WorkerRouted { request, route }).is_err() && reserved { | |
| 2480 | - immediate.push_back(Event::ActivityFinished { request }); | |
| 2481 | - } | |
| 2482 | - } | |
| 2483 | - } | |
| 2484 | - Effect::CloseWebSocket { cell, websocket } => { | |
| 2485 | - // The core declined to hold this transport. Drop it and tell | |
| 2486 | - // the core it is gone, so the cell is not left believing it | |
| 2487 | - // has a socket the node already closed. | |
| 2488 | - eprintln!( | |
| 2489 | - "celld refused an outbound WebSocket for {cell}: the node's \ | |
| 2490 | - outbound pin budget is spent" | |
| 2491 | - ); | |
| 2492 | - crate::js::ws_unregister(websocket); | |
| 2493 | - immediate.push_back(Event::WebSocketClosed { cell, websocket }); | |
| 2494 | - } | |
| 2495 | - Effect::Halt { code, reason } => { | |
| 2496 | - // Say why before going. Self-fencing is the most drastic thing | |
| 2497 | - // this process does, and an exit code on its own leaves an | |
| 2498 | - // operator to guess between a lease it could not renew, a | |
| 2499 | - // replicator that died, and a crash. | |
| 2500 | - match reason { | |
| 2501 | - celld_logic::HaltReason::NodeLeaseExpired => tracing::warn!( | |
| 2502 | - event = "node_lease_watchdog_fence", | |
| 2503 | - code, | |
| 2504 | - "SELF-FENCE: node lease not renewed within TTL — halting" | |
| 2505 | - ), | |
| 2506 | - } | |
| 2507 | - let _ = self.fence.send(code); | |
| 2508 | - } | |
| 2509 | - } | |
| 2510 | - } | |
| 2511 | - | |
| 2512 | - fn state_json(&self) -> String { | |
| 2513 | - let residents = self | |
| 2514 | - .state | |
| 2515 | - .residents() | |
| 2516 | - .into_iter() | |
| 2517 | - .map(|cell| format!("{cell:?}")) | |
| 2518 | - .collect::<Vec<_>>() | |
| 2519 | - .join(","); | |
| 2520 | - let published = self | |
| 2521 | - .published | |
| 2522 | - .iter() | |
| 2523 | - .map(|cell| format!("{cell:?}")) | |
| 2524 | - .collect::<Vec<_>>() | |
| 2525 | - .join(","); | |
| 2526 | - // Both numbers: a gap between them is memory the allocator kept, which | |
| 2527 | - // no eviction returns. One sample, so they cannot disagree. | |
| 2528 | - let memory = crate::memory::sample(); | |
| 2529 | - // `restoring` is a sum, and a node that refuses cells for a quarter of | |
| 2530 | - // an hour needs its parts. `activating` holds a permit and is doing | |
| 2531 | - // work; `activation_waiting` is queued behind the activation ceiling; | |
| 2532 | - // `capacity_waiting` is queued behind residency. The census says where | |
| 2533 | - // every cell is, which `occupied` cannot: it counts residency, so a | |
| 2534 | - // node part-way through thousands of cold starts reports almost none. | |
| 2535 | - // Issue #50 is open because none of this was recorded at the time. | |
| 2536 | - let phases = self | |
| 2537 | - .state | |
| 2538 | - .phase_census() | |
| 2539 | - .into_iter() | |
| 2540 | - .map(|(phase, count)| format!("{phase:?}:{count}")) | |
| 2541 | - .collect::<Vec<_>>() | |
| 2542 | - .join(","); | |
| 2543 | - format!( | |
| 2544 | - "{{\"ownership\":{:?},\"occupied\":{},\"evicting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}", | |
| 2545 | - self.ownership.name(), | |
| 2546 | - self.state.occupied(), | |
| 2547 | - self.state.evicting(), | |
| 2548 | - self.state.activation_backlog(), | |
| 2549 | - self.state.activating(), | |
| 2550 | - self.state.activation_waiting().len(), | |
| 2551 | - self.state.waiting().len(), | |
| 2552 | - phases, | |
| 2553 | - self.state | |
| 2554 | - .shed_reason() | |
| 2555 | - .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")), | |
| 2556 | - memory.rss_bytes, | |
| 2557 | - memory.in_use_bytes, | |
| 2558 | - residents, | |
| 2559 | - published, | |
| 2560 | - self.publishes, | |
| 2561 | - self.stops | |
| 2562 | - ) | |
| 2563 | - } | |
| 2564 | - | |
| 2565 | - fn begin_route_if_cold(&mut self, cell: &str) { | |
| 2566 | - if !matches!( | |
| 2567 | - self.state.phase(cell), | |
| 2568 | - Some(Phase::Resident { .. } | Phase::EnsuringDurability { .. } | Phase::Remote { .. }) | |
| 2569 | - ) { | |
| 2570 | - self.route_timings | |
| 2571 | - .entry(cell.to_string()) | |
| 2572 | - .or_insert_with(CellRouteTiming::new); | |
| 2573 | - } | |
| 2574 | - } | |
| 2575 | - | |
| 2576 | - fn route_effect_started(&mut self, cell: &str) { | |
| 2577 | - if let Some(timing) = self.route_timings.get_mut(cell) { | |
| 2578 | - timing.effect_started(); | |
| 2579 | - } | |
| 2580 | - } | |
| 2581 | - | |
| 2582 | - fn observe_capacity_wait(&mut self, cell: &str) { | |
| 2583 | - if matches!(self.state.phase(cell), Some(Phase::WaitingCapacity)) { | |
| 2584 | - if let Some(timing) = self.route_timings.get_mut(cell) { | |
| 2585 | - timing | |
| 2586 | - .capacity_wait_started_mono_ms | |
| 2587 | - .get_or_insert_with(crate::asyncrt::mono_ms); | |
| 2588 | - } | |
| 2589 | - } | |
| 2590 | - } | |
| 2591 | - | |
| 2592 | - fn record_effect_timing(&mut self, completed: EffectTiming) { | |
| 2593 | - if let Some(timing) = self.route_timings.get_mut(&completed.cell) { | |
| 2594 | - timing.record(completed.stage, completed.elapsed_us); | |
| 2595 | - } | |
| 2596 | - } | |
| 2597 | - | |
| 2598 | - fn finish_route( | |
| 2599 | - &mut self, | |
| 2600 | - cell: &str, | |
| 2601 | - outcome: &str, | |
| 2602 | - failure_phase: &str, | |
| 2603 | - owner: Option<(&str, u64)>, | |
| 2604 | - ) { | |
| 2605 | - let Some(mut timing) = self.route_timings.remove(cell) else { | |
| 2606 | - return; | |
| 2607 | - }; | |
| 2608 | - if let Some(started) = timing.capacity_wait_started_mono_ms.take() { | |
| 2609 | - timing.capacity_wait_us = timing | |
| 2610 | - .capacity_wait_us | |
| 2611 | - .saturating_add(mono_elapsed_us(started)); | |
| 2612 | - } | |
| 2613 | - let (owner_node, epoch) = owner.unwrap_or(("", 0)); | |
| 2614 | - tracing::debug!( | |
| 2615 | - target: "timing", | |
| 2616 | - event = "cell_route_timing", | |
| 2617 | - outcome, | |
| 2618 | - failure_phase, | |
| 2619 | - scope = %cell, | |
| 2620 | - node = %self.state.node(), | |
| 2621 | - region = %self.region, | |
| 2622 | - runtime_version = env!("CARGO_PKG_VERSION"), | |
| 2623 | - owner_node, | |
| 2624 | - epoch, | |
| 2625 | - fresh = timing.fresh.unwrap_or(false), | |
| 2626 | - total_us = mono_elapsed_us(timing.started_mono_ms), | |
| 2627 | - latch_wait_us = timing.latch_wait_us, | |
| 2628 | - ownership_read_us = timing.ownership_read_us, | |
| 2629 | - node_lease_lookup_us = timing.node_lease_lookup_us, | |
| 2630 | - capacity_lookup_us = timing.capacity_lookup_us, | |
| 2631 | - capacity_wait_us = timing.capacity_wait_us, | |
| 2632 | - activation_slot_wait_us = timing.activation_slot_wait_us, | |
| 2633 | - lease_permit_us = timing.lease_permit_us, | |
| 2634 | - ownership_acquire_us = timing.ownership_acquire_us, | |
| 2635 | - replica_discovery_us = timing.replica_discovery_us, | |
| 2636 | - restore_us = timing.restore_us, | |
| 2637 | - isolate_startup_us = timing.isolate_startup_us, | |
| 2638 | - registry_insert_us = timing.registry_insert_us, | |
| 2639 | - "cell route resolved" | |
| 2640 | - ); | |
| 2641 | - } | |
| 2642 | -} | |
| 2643 | - | |
| 2644 | -fn request_error_phase(error: RequestError) -> &'static str { | |
| 2645 | - match error { | |
| 2646 | - RequestError::NodeUnavailable | RequestError::NodeFenced => "node_authority", | |
| 2647 | - RequestError::ResolveFailed | RequestError::PeerIncompatible => "ownership_lookup", | |
| 2648 | - RequestError::CapacityExhausted => "capacity_wait", | |
| 2649 | - RequestError::AcquireFailed => "ownership_acquire", | |
| 2650 | - RequestError::RestoreFailed => "restore", | |
| 2651 | - RequestError::RuntimeFailed => "isolate_startup", | |
| 2652 | - RequestError::PublishFailed => "registry_insert", | |
| 2653 | - RequestError::DurabilityUnproven => "output_gate", | |
| 2654 | - } | |
| 5 | +use crate::js::{HttpResponse, WsOut}; | |
| 6 | +use crate::machine::{ | |
| 7 | + ownership_on_evict_from_environment, pressure_config_from_environment, | |
| 8 | + random_process_generation, DEFAULT_MAX_OUTBOUND_WEBSOCKETS, | |
| 9 | +}; | |
| 10 | +use crate::ownership_store::{now_ms, BucketOwnership}; | |
| 11 | +use crate::peer_auth::{self, PeerAuth}; | |
| 12 | +use crate::runtime::{CellHost, RuntimeManager}; | |
| 13 | +use anyhow::Context as _; | |
| 14 | +use celld_logic::{ | |
| 15 | + on_event, AdoptedCell, CapacityPeer, CasGuard, CasOutcome, Channel, Config, Effect, Event, | |
| 16 | + Failure, LeaseCasOutcome, NodeLeaseRecord, NodeLeaseSpec, OpId, OwnerRecord, OwnershipOnEvict, | |
| 17 | + Phase, RequestError, Route, State, StopCause, Timer, WebSocketKind, WorkerRoute, | |
| 18 | +}; | |
| 19 | +use futures_util::stream::FuturesUnordered; | |
| 20 | +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; | |
| 21 | +use std::future::Future; | |
| 22 | +use std::pin::Pin; | |
| 23 | +use std::sync::atomic::{AtomicUsize, Ordering}; | |
| 24 | +use std::sync::Arc; | |
| 25 | +use tokio::sync::{mpsc, oneshot, watch, Mutex}; | |
| 26 | +use tokio_util::time::{delay_queue, DelayQueue}; | |
| 27 | + | |
| 28 | +mod production; | |
| 29 | + | |
| 30 | +const DEFAULT_OPERATION_DEADLINE_MS: u64 = 15_000; | |
| 31 | + | |
| 32 | +/// The shell's deadline for one actor operation. Queue leases include this | |
| 33 | +/// exact budget for their settlement call, so the actor and broker must read | |
| 34 | +/// one accessor rather than duplicate the environment default. | |
| 35 | +pub(crate) fn operation_deadline_ms() -> anyhow::Result<u64> { | |
| 36 | + crate::env_vars::positive_or("CELLD_OPERATION_DEADLINE_MS", DEFAULT_OPERATION_DEADLINE_MS) | |
| 37 | +} | |
| 38 | + | |
| 39 | +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] | |
| 40 | +pub enum TimerSlot { | |
| 41 | + NodeLeaseRenew, | |
| 42 | + NodeLeaseFence, | |
| 43 | + CellAlarm(String), | |
| 44 | + /// Keyed by operation, deliberately. Every other timer here coalesces | |
| 45 | + /// because only its newest arming matters; a deadline is the opposite -- | |
| 46 | + /// each watches a different outstanding operation, and a shared slot | |
| 47 | + /// would let arming one silently cancel another, leaving every activation | |
| 48 | + /// but the most recent with nothing watching it. | |
| 49 | + OperationDeadline(OpId), | |
| 50 | + /// Keyed by cell and generation for the same reason as the deadline | |
| 51 | + /// above: a node parks many cells at once, and one slot per cell would | |
| 52 | + /// let a later parking disarm an earlier one. | |
| 53 | + QueuedActivation(String, u64), | |
| 54 | +} | |
| 55 | + | |
| 56 | +impl TimerSlot { | |
| 57 | + pub fn of(timer: &Timer) -> Self { | |
| 58 | + match timer { | |
| 59 | + Timer::NodeLeaseRenew { .. } => Self::NodeLeaseRenew, | |
| 60 | + Timer::NodeLeaseFence { .. } => Self::NodeLeaseFence, | |
| 61 | + Timer::CellAlarm { cell, .. } => Self::CellAlarm(cell.clone()), | |
| 62 | + Timer::OperationDeadline { op } => Self::OperationDeadline(*op), | |
| 63 | + Timer::QueuedActivation { cell, generation } => { | |
| 64 | + Self::QueuedActivation(cell.clone(), *generation) | |
| 65 | + } | |
| 66 | + } | |
| 67 | + } | |
| 68 | +} | |
| 69 | + | |
| 70 | +/// One versioned timer arm emitted by an Actor step. | |
| 71 | +#[derive(Clone, Debug, PartialEq, Eq)] | |
| 72 | +pub struct TimerArm { | |
| 73 | + pub slot: TimerSlot, | |
| 74 | + pub ordinal: u64, | |
| 75 | + pub timer: Timer, | |
| 76 | + pub at_mono_ms: u64, | |
| 77 | +} | |
| 78 | + | |
| 79 | +/// The shared displacement discipline for production and deterministic timers. | |
| 80 | +pub struct TimerSlots<V> { | |
| 81 | + armed: BTreeMap<TimerSlot, (u64, V)>, | |
| 82 | + ordinals: BTreeMap<TimerSlot, u64>, | |
| 83 | +} | |
| 84 | + | |
| 85 | +impl<V> Default for TimerSlots<V> { | |
| 86 | + fn default() -> Self { | |
| 87 | + Self { | |
| 88 | + armed: BTreeMap::new(), | |
| 89 | + ordinals: BTreeMap::new(), | |
| 90 | + } | |
| 91 | + } | |
| 92 | +} | |
| 93 | + | |
| 94 | +impl<V> TimerSlots<V> { | |
| 95 | + /// Creates one arm, assigns its stable per-slot ordinal, and applies it. | |
| 96 | + pub fn arm(&mut self, timer: Timer, at_mono_ms: u64, value: V) -> (TimerArm, Option<V>) { | |
| 97 | + let slot = TimerSlot::of(&timer); | |
| 98 | + let ordinal = self.ordinals.entry(slot.clone()).or_default(); | |
| 99 | + let arm = TimerArm { | |
| 100 | + slot: slot.clone(), | |
| 101 | + ordinal: *ordinal, | |
| 102 | + timer, | |
| 103 | + at_mono_ms, | |
| 104 | + }; | |
| 105 | + *ordinal = ordinal.saturating_add(1); | |
| 106 | + let displaced = self.replace(&slot, arm.ordinal, value); | |
| 107 | + (arm, displaced) | |
| 108 | + } | |
| 109 | + | |
| 110 | + /// Applies an arm whose ordinal the Actor has already assigned. | |
| 111 | + pub fn install(&mut self, arm: &TimerArm, value: V) -> Option<V> { | |
| 112 | + self.replace(&arm.slot, arm.ordinal, value) | |
| 113 | + } | |
| 114 | + | |
| 115 | + fn replace(&mut self, slot: &TimerSlot, ordinal: u64, value: V) -> Option<V> { | |
| 116 | + let displaced = self | |
| 117 | + .armed | |
| 118 | + .insert(slot.clone(), (ordinal, value)) | |
| 119 | + .map(|(_, value)| value); | |
| 120 | + debug_assert!( | |
| 121 | + displaced.is_none() || !matches!(slot, TimerSlot::OperationDeadline(_)), | |
| 122 | + "an operation deadline displaced another: {slot:?}" | |
| 123 | + ); | |
| 124 | + displaced | |
| 125 | + } | |
| 126 | + | |
| 127 | + /// Removes the current arm only when both parts of its identity match. | |
| 128 | + pub fn fire(&mut self, slot: &TimerSlot, ordinal: u64) -> Option<V> { | |
| 129 | + if self | |
| 130 | + .armed | |
| 131 | + .get(slot) | |
| 132 | + .is_some_and(|(armed, _)| *armed == ordinal) | |
| 133 | + { | |
| 134 | + self.armed.remove(slot).map(|(_, value)| value) | |
| 135 | + } else { | |
| 136 | + None | |
| 137 | + } | |
| 138 | + } | |
| 139 | + | |
| 140 | + fn clear_slot(&mut self, slot: &TimerSlot) { | |
| 141 | + self.armed.remove(slot); | |
| 142 | + } | |
| 143 | +} | |
| 144 | + | |
| 145 | +pub struct MemoryOwnership { | |
| 146 | + node: String, | |
| 147 | + owners: BTreeMap<String, OwnerRecord>, | |
| 148 | + leases: BTreeMap<String, NodeLeaseRecord>, | |
| 149 | + next_etag: u64, | |
| 150 | +} | |
| 151 | + | |
| 152 | +#[derive(Clone)] | |
| 153 | +pub enum Ownership { | |
| 154 | + Memory(Arc<Mutex<MemoryOwnership>>), | |
| 155 | + Bucket(Arc<BucketOwnership>), | |
| 156 | +} | |
| 157 | + | |
| 158 | +impl Ownership { | |
| 159 | + async fn read_owner(&self, cell: &str) -> Result<Option<OwnerRecord>, Failure> { | |
| 160 | + match self { | |
| 161 | + Self::Memory(memory) => Ok(memory.lock().await.owners.get(cell).cloned()), | |
| 162 | + Self::Bucket(bucket) => bucket.read_owner(cell).await.map_err(|error| { | |
| 163 | + eprintln!("celld ownership read failed: {error:#}"); | |
| 164 | + Failure::Definite | |
| 165 | + }), | |
| 166 | + } | |
| 167 | + } | |
| 168 | + | |
| 169 | + async fn read_node_lease(&self, owner: &str) -> Result<Option<NodeLeaseRecord>, Failure> { | |
| 170 | + match self { | |
| 171 | + Self::Memory(memory) => Ok(memory.lock().await.leases.get(owner).cloned()), | |
| 172 | + Self::Bucket(bucket) => bucket.read_node_lease(owner).await.map_err(|error| { | |
| 173 | + eprintln!("celld node lease read failed: {error:#}"); | |
| 174 | + Failure::Definite | |
| 175 | + }), | |
| 176 | + } | |
| 177 | + } | |
| 178 | + | |
| 179 | + async fn read_capacity_peers(&self) -> Result<Vec<celld_logic::CapacityPeer>, Failure> { | |
| 180 | + match self { | |
| 181 | + // The in-memory adapter is a single-node development mode. It has | |
| 182 | + // no external membership enumeration to offer. | |
| 183 | + Self::Memory(_) => Ok(Vec::new()), | |
| 184 | + Self::Bucket(bucket) => bucket.read_capacity_peers().await.map_err(|error| { | |
| 185 | + eprintln!("celld capacity peer read failed: {error:#}"); | |
| 186 | + Failure::Definite | |
| 187 | + }), | |
| 188 | + } | |
| 189 | + } | |
| 190 | + | |
| 191 | + async fn read_self_node_lease(&self, node: &str) -> Result<Option<NodeLeaseRecord>, Failure> { | |
| 192 | + match self { | |
| 193 | + Self::Memory(memory) => Ok(memory.lock().await.leases.get(node).cloned()), | |
| 194 | + Self::Bucket(bucket) => bucket.read_self_node_lease(node).await.map_err(|error| { | |
| 195 | + eprintln!("celld self node lease read failed: {error:#}"); | |
| 196 | + Failure::Definite | |
| 197 | + }), | |
| 198 | + } | |
| 199 | + } | |
| 200 | + | |
| 201 | + async fn cas_owner( | |
| 202 | + &self, | |
| 203 | + cell: &str, | |
| 204 | + guard: CasGuard, | |
| 205 | + epoch: u64, | |
| 206 | + ) -> Result<CasOutcome, Failure> { | |
| 207 | + match self { | |
| 208 | + Self::Memory(memory) => { | |
| 209 | + let mut memory = memory.lock().await; | |
| 210 | + let allowed = match guard { | |
| 211 | + CasGuard::Absent => !memory.owners.contains_key(cell), | |
| 212 | + CasGuard::Match(expected) => memory | |
| 213 | + .owners | |
| 214 | + .get(cell) | |
| 215 | + .is_some_and(|owner| owner.etag == expected), | |
| 216 | + }; | |
| 217 | + if allowed { | |
| 218 | + let etag = format!("e{}", memory.next_etag); | |
| 219 | + memory.next_etag += 1; | |
| 220 | + let node = memory.node.clone(); | |
| 221 | + memory.owners.insert( | |
| 222 | + cell.into(), | |
| 223 | + OwnerRecord { | |
| 224 | + node: Some(node), | |
| 225 | + epoch, | |
| 226 | + etag, | |
| 227 | + }, | |
| 228 | + ); | |
| 229 | + } | |
| 230 | + Ok(if allowed { | |
| 231 | + CasOutcome::Applied | |
| 232 | + } else { | |
| 233 | + CasOutcome::Rejected | |
| 234 | + }) | |
| 235 | + } | |
| 236 | + Self::Bucket(bucket) => bucket.cas_owner(cell, guard, epoch).await.map_err(|error| { | |
| 237 | + // Any transport or 5xx failure may have happened after the | |
| 238 | + // store committed. The core reconciles by reading the owner | |
| 239 | + // again. | |
| 240 | + eprintln!("celld ownership CAS ambiguous: {error:#}"); | |
| 241 | + Failure::Ambiguous | |
| 242 | + }), | |
| 243 | + } | |
| 244 | + } | |
| 245 | + | |
| 246 | + async fn release_owner(&self, cell: &str, epoch: u64) -> Result<CasOutcome, Failure> { | |
| 247 | + match self { | |
| 248 | + Self::Memory(memory) => { | |
| 249 | + let mut memory = memory.lock().await; | |
| 250 | + let node = memory.node.clone(); | |
| 251 | + let releasable = memory.owners.get(cell).is_some_and(|owner| { | |
| 252 | + owner.node.as_deref() == Some(node.as_str()) && owner.epoch == epoch | |
| 253 | + }); | |
| 254 | + if releasable { | |
| 255 | + let etag = format!("e{}", memory.next_etag); | |
| 256 | + memory.next_etag += 1; | |
| 257 | + memory.owners.insert( | |
| 258 | + cell.into(), | |
| 259 | + OwnerRecord { | |
| 260 | + node: None, | |
| 261 | + epoch, | |
| 262 | + etag, | |
| 263 | + }, | |
| 264 | + ); | |
| 265 | + } | |
| 266 | + Ok(if releasable { | |
| 267 | + CasOutcome::Applied | |
| 268 | + } else { | |
| 269 | + CasOutcome::Rejected | |
| 270 | + }) | |
| 271 | + } | |
| 272 | + // A release that may or may not have committed needs no | |
| 273 | + // reconciliation: the record either still names this node, and the | |
| 274 | + // next eviction releases it again, or it does not, and the cell is | |
| 275 | + // already free. Either way nothing is owed. | |
| 276 | + Self::Bucket(bucket) => bucket.release_owner(cell, epoch).await.map_err(|error| { | |
| 277 | + eprintln!("celld ownership release failed: {error:#}"); | |
| 278 | + Failure::Definite | |
| 279 | + }), | |
| 280 | + } | |
| 281 | + } | |
| 282 | + | |
| 283 | + async fn cas_node_lease( | |
| 284 | + &self, | |
| 285 | + guard: CasGuard, | |
| 286 | + mut record: NodeLeaseRecord, | |
| 287 | + stamped: &mut Option<celld_logic::log_tier::LogState>, | |
| 288 | + ) -> Result<LeaseCasOutcome, Failure> { | |
| 289 | + match self { | |
| 290 | + Self::Memory(memory) => { | |
| 291 | + let mut memory = memory.lock().await; | |
| 292 | + let current = memory.leases.get(&record.node); | |
| 293 | + let allowed = match guard { | |
| 294 | + CasGuard::Absent => current.is_none(), | |
| 295 | + CasGuard::Match(expected) => { | |
| 296 | + current.is_some_and(|lease| lease.etag == expected) | |
| 297 | + } | |
| 298 | + }; | |
| 299 | + if !allowed { | |
| 300 | + return Ok(LeaseCasOutcome::Rejected); | |
| 301 | + } | |
| 302 | + let etag = format!("e{}", memory.next_etag); | |
| 303 | + memory.next_etag += 1; | |
| 304 | + record.etag = etag.clone(); | |
| 305 | + *stamped = record.log_state; | |
| 306 | + memory.leases.insert(record.node.clone(), record); | |
| 307 | + Ok(LeaseCasOutcome::Applied { etag }) | |
| 308 | + } | |
| 309 | + Self::Bucket(bucket) => bucket | |
| 310 | + .cas_node_lease(guard, &record, stamped) | |
| 311 | + .await | |
| 312 | + .map_err(|error| { | |
| 313 | + eprintln!("celld node-lease CAS ambiguous: {error:#}"); | |
| 314 | + Failure::Ambiguous | |
| 315 | + }), | |
| 316 | + } | |
| 317 | + } | |
| 318 | + | |
| 319 | + pub fn name(&self) -> &'static str { | |
| 320 | + match self { | |
| 321 | + Self::Memory(_) => "memory", | |
| 322 | + Self::Bucket(bucket) => bucket.storage_scheme(), | |
| 323 | + } | |
| 324 | + } | |
| 325 | +} | |
| 326 | + | |
| 327 | +pub enum Message { | |
| 328 | + /// A periodic resource sample. The measuring is the shell's job; every | |
| 329 | + /// decision that follows belongs to the core. | |
| 330 | + SampleLoad, | |
| 331 | + /// The log tier changed the folded log object the next lease write | |
| 332 | + /// must carry (lease-fold): renew now so the change becomes durable. | |
| 333 | + NudgeNodeLease, | |
| 334 | + /// Stop new internal routing while a clean same-node reload drains. The | |
| 335 | + /// request shell has already stopped admission; this closes wake and | |
| 336 | + /// service paths that do not pass through the HTTP gate. | |
| 337 | + BeginPreserve, | |
| 338 | + /// The node adopted a new application generation. Resident cells on an | |
| 339 | + /// older one move to it at a safe point, or by force after `max_age_ms`; | |
| 340 | + /// cells of an eager class move at once. | |
| 341 | + GenerationChanged { | |
| 342 | + generation: crate::generation::GenerationId, | |
| 343 | + max_age_ms: u64, | |
| 344 | + eager_classes: Vec<String>, | |
| 345 | + }, | |
| 346 | + /// Graceful shutdown: release every owned cell's record so peers take | |
| 347 | + /// over immediately. The release writes run as effects inside the | |
| 348 | + /// shutdown drain window, and the drain waits for them to complete — | |
| 349 | + /// bounded by the drain deadline, so a wedged store still cannot hold | |
| 350 | + /// the exit hostage. | |
| 351 | + ReleaseAll, | |
| 352 | + /// Has the shutdown handoff finished? True once no cell occupies | |
| 353 | + /// capacity: nothing resident, restoring, or mid-eviction. The drain | |
| 354 | + /// loop polls this to exit as soon as the handoff completes instead of | |
| 355 | + /// sitting out the full drain window. | |
| 356 | + Drained { | |
| 357 | + reply: oneshot::Sender<DrainStatus>, | |
| 358 | + }, | |
| 359 | + Request { | |
| 360 | + request: u64, | |
| 361 | + cell: String, | |
| 362 | + capacity_handoff: bool, | |
| 363 | + /// Present only for the signed shutdown-handoff endpoint. The actor | |
| 364 | + /// settles this channel as soon as the ownership CAS is authoritative; | |
| 365 | + /// the ordinary route reply remains pending until it is cancelled. | |
| 366 | + handoff_accept: Option<HandoffAcceptWaiter>, | |
| 367 | + /// An event from this exact registered WebSocket can finish on a | |
| 368 | + /// quiescing resident. Ordinary requests carry no identity and wait | |
| 369 | + /// for the successor route. | |
| 370 | + websocket: Option<u64>, | |
| 371 | + reply: oneshot::Sender<Result<Routed, RequestError>>, | |
| 372 | + }, | |
| 373 | + /// A caller disappeared before routing finished. The request identity is | |
| 374 | + /// allocated by the shell, so the actor can remove it from either cold | |
| 375 | + /// admission queue immediately. | |
| 376 | + CancelRoute { | |
| 377 | + request: u64, | |
| 378 | + }, | |
| 379 | + WorkerRequest { | |
| 380 | + reply: oneshot::Sender<WorkerRouted>, | |
| 381 | + }, | |
| 382 | + ActivityFinished { | |
| 383 | + request: u64, | |
| 384 | + // The activity drop also observes the cell's alarm. Folded in here so a | |
| 385 | + // request's completion costs the serial core one message, not two — the | |
| 386 | + // hot path for every routed DO call. | |
| 387 | + cell: String, | |
| 388 | + alarm_at_ms: Option<i64>, | |
| 389 | + alarm_covered: bool, | |
| 390 | + }, | |
| 391 | + /// An outbound effect is ready to leave on `channel`. A write opens a | |
| 392 | + /// durability barrier, and a read trails the newest barrier already open on | |
| 393 | + /// its cell. The channel rides along so the release can be routed back to | |
| 394 | + /// whichever adapter is holding the effect. | |
| 395 | + Output { | |
| 396 | + request: u64, | |
| 397 | + channel: Channel, | |
| 398 | + position: Option<u64>, | |
| 399 | + reply: oneshot::Sender<Result<(), RequestError>>, | |
| 400 | + }, | |
| 401 | + /// A `webSocketMessage` finished; hand its captured outbound frames to the | |
| 402 | + /// cell's output gate. `write_position` present means the handler wrote, so | |
| 403 | + /// the frames are held behind that write until it is durable; absent means | |
| 404 | + /// flush them (behind any earlier still-pending write, else immediately). | |
| 405 | + WsOutput { | |
| 406 | + request: u64, | |
| 407 | + scope: String, | |
| 408 | + frames: Vec<(u64, WsOut)>, | |
| 409 | + write_position: Option<u64>, | |
| 410 | + reply: oneshot::Sender<()>, | |
| 411 | + }, | |
| 412 | + WebSocketOpened { | |
| 413 | + cell: String, | |
| 414 | + websocket: u64, | |
| 415 | + kind: WebSocketKind, | |
| 416 | + reply: oneshot::Sender<bool>, | |
| 417 | + }, | |
| 418 | + WebSocketClosed { | |
| 419 | + cell: String, | |
| 420 | + websocket: u64, | |
| 421 | + }, | |
| 422 | + AlarmObserved { | |
| 423 | + cell: String, | |
| 424 | + at_ms: Option<i64>, | |
| 425 | + covered: bool, | |
| 426 | + }, | |
| 427 | + WakeHint { | |
| 428 | + cell: String, | |
| 429 | + }, | |
| 430 | + Evict { | |
| 431 | + cell: String, | |
| 432 | + reply: oneshot::Sender<()>, | |
| 433 | + }, | |
| 434 | + InvalidateRemote { | |
| 435 | + cell: String, | |
| 436 | + node: String, | |
| 437 | + epoch: u64, | |
| 438 | + reply: oneshot::Sender<()>, | |
| 439 | + }, | |
| 440 | + Snapshot { | |
| 441 | + reply: oneshot::Sender<(String, Vec<celld_logic::DrainPin>, SwapCensus)>, | |
| 442 | + }, | |
| 443 | + Health { | |
| 444 | + reply: oneshot::Sender<bool>, | |
| 445 | + }, | |
| 446 | + Presence { | |
| 447 | + reply: oneshot::Sender<celld_logic::PresenceSnapshot>, | |
| 448 | + }, | |
| 449 | + ResidentEpoch { | |
| 450 | + cell: String, | |
| 451 | + reply: oneshot::Sender<Option<u64>>, | |
| 452 | + }, | |
| 453 | +} | |
| 454 | + | |
| 455 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 456 | +pub enum ShutdownMode { | |
| 457 | + /// The logical node is leaving. Release every owner record so another | |
| 458 | + /// node can take over without waiting for the node lease to expire. | |
| 459 | + Handoff, | |
| 460 | + /// The same logical node will start again at the same address. Drain the | |
| 461 | + /// request shell, but keep ownership and the local replica cache intact. | |
| 462 | + Preserve, | |
| 463 | +} | |
| 464 | + | |
| 465 | +pub struct Routed { | |
| 466 | + pub request: u64, | |
| 467 | + pub route: Route, | |
| 468 | +} | |
| 469 | + | |
| 470 | +/// A test-only receipt for three request-path outcomes. `AppHandle::request` | |
| 471 | +/// deliberately maps both channel failures to `NodeFenced`, so its public | |
| 472 | +/// result cannot identify which asynchronous seam failed. | |
| 473 | +#[cfg(all(test, celld_internal_tests))] | |
| 474 | +#[derive(Clone, Debug, PartialEq, Eq)] | |
| 475 | +pub(crate) enum RequestPathReceiptForTest { | |
| 476 | + SubmissionFailure { | |
| 477 | + request: u64, | |
| 478 | + }, | |
| 479 | + ReplyChannelClosed { | |
| 480 | + request: u64, | |
| 481 | + }, | |
| 482 | + Returned { | |
| 483 | + allocated_request: u64, | |
| 484 | + result: Result<(u64, Route), RequestError>, | |
| 485 | + }, | |
| 486 | +} | |
| 487 | + | |
| 488 | +/// A test-only receipt for three output-gate outcomes. The public gate maps | |
| 489 | +/// both channel failures to `NodeFenced`, so its result cannot identify which | |
| 490 | +/// asynchronous seam failed. | |
| 491 | +#[cfg(all(test, celld_internal_tests))] | |
| 492 | +#[derive(Clone, Debug, PartialEq, Eq)] | |
| 493 | +pub(crate) enum OutputGateReceiptForTest { | |
| 494 | + SubmissionFailure { | |
| 495 | + request: u64, | |
| 496 | + }, | |
| 497 | + ReplyChannelClosed { | |
| 498 | + request: u64, | |
| 499 | + }, | |
| 500 | + Returned { | |
| 501 | + request: u64, | |
| 502 | + result: Result<(), RequestError>, | |
| 503 | + }, | |
| 504 | +} | |
| 505 | + | |
| 506 | +enum RequestPathOutcome { | |
| 507 | + SubmissionFailure, | |
| 508 | + ReplyChannelClosed, | |
| 509 | + Returned(Result<Routed, RequestError>), | |
| 510 | +} | |
| 511 | + | |
| 512 | +enum OutputGateOutcome { | |
| 513 | + SubmissionFailure, | |
| 514 | + ReplyChannelClosed, | |
| 515 | + Returned(Result<(), RequestError>), | |
| 516 | +} | |
| 517 | + | |
| 518 | +#[derive(Clone, Copy, Default)] | |
| 519 | +pub struct DrainStatus { | |
| 520 | + pub occupied: usize, | |
| 521 | + pub activating: usize, | |
| 522 | + /// Resident cells reserved for shutdown handoff. New requests wait for | |
| 523 | + /// their successor routes while admitted work finishes. | |
| 524 | + pub quiescing: usize, | |
| 525 | + pub evicting: usize, | |
| 526 | + /// Ownership releases still in flight. A handoff drain waits for zero: | |
| 527 | + /// a released cell leaves `occupied` before its record write commits, | |
| 528 | + /// so exiting on occupancy alone can abort the write mid-flight and | |
| 529 | + /// leave a record the successor waits out the node lease for. | |
| 530 | + pub releasing: usize, | |
| 531 | + /// Released cells waiting for a successor's ownership acknowledgement. | |
| 532 | + /// These hold the shutdown pacing permits. | |
| 533 | + pub adopting: usize, | |
| 534 | + /// Monotonic ownership acknowledgements. A progressing handoff can | |
| 535 | + /// take longer than one stall interval when the node owns many cells. | |
| 536 | + pub handed_off: u64, | |
| 537 | +} | |
| 538 | + | |
| 539 | +#[derive(serde::Deserialize, serde::Serialize)] | |
| 540 | +#[serde(rename_all = "camelCase", deny_unknown_fields)] | |
| 541 | +pub struct HandoffRequest { | |
| 542 | + pub cell: String, | |
| 543 | + pub released_epoch: u64, | |
| 544 | +} | |
| 545 | + | |
| 546 | +#[derive(serde::Deserialize, serde::Serialize)] | |
| 547 | +#[serde(rename_all = "camelCase", deny_unknown_fields)] | |
| 548 | +pub struct HandoffResponse { | |
| 549 | + pub node: String, | |
| 550 | + pub addr: String, | |
| 551 | + pub epoch: u64, | |
| 552 | + pub peer_protocol: u16, | |
| 553 | + /// Whether the successor adopted the cell. It repeats what the status code | |
| 554 | + /// reports, and the donor accepts the reply only when the two agree: `200` | |
| 555 | + /// with `true` is an adoption, and `409` with `false` names the current | |
| 556 | + /// owner for the donor to contact instead. Every other pairing is refused, | |
| 557 | + /// so a disagreement between the two cannot be read as a handoff. | |
| 558 | + pub published: bool, | |
| 559 | +} | |
| 560 | + | |
| 561 | +pub struct HandoffAcceptWaiter { | |
| 562 | + released_epoch: u64, | |
| 563 | + reply: oneshot::Sender<AdoptedCell>, | |
| 564 | +} | |
| 565 | + | |
| 566 | +// Read only by the orphaned `worker_route`, and removed with the rest of the | |
| 567 | +// landing-cell machinery when that goes. | |
| 568 | +#[allow(dead_code)] | |
| 569 | +pub struct WorkerRouted { | |
| 570 | + pub request: u64, | |
| 571 | + pub route: Option<WorkerRoute>, | |
| 572 | +} | |
| 573 | + | |
| 574 | +/// Worker requests owned by one HTTP connection. Hyper can finish a failed | |
| 575 | +/// connection without dropping its service future, so the connection also | |
| 576 | +/// aborts these requests explicitly when its transport ends. | |
| 577 | +#[derive(Clone, Default)] | |
| 578 | +pub struct ConnectionWorkerRequests(Arc<std::sync::Mutex<BTreeSet<crate::js::RequestId>>>); | |
| 579 | + | |
| 580 | +impl ConnectionWorkerRequests { | |
| 581 | + pub fn register(&self, request: crate::js::RequestId) { | |
| 582 | + self.0.lock().unwrap().insert(request); | |
| 583 | + } | |
| 584 | + | |
| 585 | + pub fn complete(&self, request: crate::js::RequestId) { | |
| 586 | + self.0.lock().unwrap().remove(&request); | |
| 587 | + } | |
| 588 | + | |
| 589 | + 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); | |
| 593 | + } | |
| 594 | + } | |
| 595 | +} | |
| 596 | + | |
| 597 | +pub struct IngressAbortGuard { | |
| 598 | + request: Option<crate::js::RequestId>, | |
| 599 | + connection: ConnectionWorkerRequests, | |
| 600 | +} | |
| 601 | + | |
| 602 | +impl IngressAbortGuard { | |
| 603 | + pub fn new(request: crate::js::RequestId, connection: ConnectionWorkerRequests) -> Self { | |
| 604 | + connection.register(request); | |
| 605 | + Self { | |
| 606 | + request: Some(request), | |
| 607 | + connection, | |
| 608 | + } | |
| 609 | + } | |
| 610 | + | |
| 611 | + pub fn disarm(&mut self) { | |
| 612 | + if let Some(request) = self.request.take() { | |
| 613 | + self.connection.complete(request); | |
| 614 | + } | |
| 615 | + } | |
| 616 | +} | |
| 617 | + | |
| 618 | +/// Cancels a core route when the future awaiting it is dropped. A normal | |
| 619 | +/// route disarms the guard before returning its result. | |
| 620 | +pub struct RouteCancelGuard { | |
| 621 | + tx: mpsc::UnboundedSender<Message>, | |
| 622 | + request: Option<u64>, | |
| 623 | +} | |
| 624 | + | |
| 625 | +impl RouteCancelGuard { | |
| 626 | + pub fn new(tx: mpsc::UnboundedSender<Message>, request: u64) -> Self { | |
| 627 | + Self { | |
| 628 | + tx, | |
| 629 | + request: Some(request), | |
| 630 | + } | |
| 631 | + } | |
| 632 | + | |
| 633 | + pub fn disarm(&mut self) { | |
| 634 | + self.request = None; | |
| 635 | + } | |
| 636 | +} | |
| 637 | + | |
| 638 | +impl Drop for RouteCancelGuard { | |
| 639 | + fn drop(&mut self) { | |
| 640 | + if let Some(request) = self.request { | |
| 641 | + let _ = self.tx.send(Message::CancelRoute { request }); | |
| 642 | + } | |
| 643 | + } | |
| 644 | +} | |
| 645 | + | |
| 646 | +impl Drop for IngressAbortGuard { | |
| 647 | + fn drop(&mut self) { | |
| 648 | + if let Some(request) = self.request.take() { | |
| 649 | + self.connection.complete(request); | |
| 650 | + crate::js::abort_request(request); | |
| 651 | + } | |
| 652 | + } | |
| 653 | +} | |
| 654 | + | |
| 655 | +/// One public HTTP request admitted before shutdown closed the gate. Peer | |
| 656 | +/// requests do not hold this guard because the handoff must keep serving them. | |
| 657 | +pub struct PublicRequestGuard { | |
| 658 | + in_flight: Arc<AtomicUsize>, | |
| 659 | +} | |
| 660 | + | |
| 661 | +impl Drop for PublicRequestGuard { | |
| 662 | + fn drop(&mut self) { | |
| 663 | + self.in_flight.fetch_sub(1, Ordering::SeqCst); | |
| 664 | + } | |
| 665 | +} | |
| 666 | + | |
| 667 | +#[derive(Clone, Default)] | |
| 668 | +pub struct DrainPinRegistry(Arc<std::sync::Mutex<DrainPinState>>); | |
| 669 | + | |
| 670 | +#[derive(Default)] | |
| 671 | +struct DrainPinState { | |
| 672 | + pins: BTreeMap<u64, DrainPinTrace>, | |
| 673 | + requests: HashMap<crate::js::RequestId, u64>, | |
| 674 | +} | |
| 675 | + | |
| 676 | +struct DrainPinTrace { | |
| 677 | + request_id: Option<crate::js::RequestId>, | |
| 678 | + origin: &'static str, | |
| 679 | + started_mono_ms: u64, | |
| 680 | + phase: &'static str, | |
| 681 | + response_headers_sent: bool, | |
| 682 | + response_body_active: bool, | |
| 683 | + durable_txid: Option<u64>, | |
| 684 | + output_gate_result: &'static str, | |
| 685 | + ack_point: &'static str, | |
| 686 | + cancellation_state: &'static str, | |
| 687 | + cancel: watch::Sender<bool>, | |
| 688 | +} | |
| 689 | + | |
| 690 | +#[derive(serde::Serialize)] | |
| 691 | +#[serde(rename_all = "camelCase")] | |
| 692 | +struct DrainPinView { | |
| 693 | + cell: String, | |
| 694 | + core_request_id: Option<u64>, | |
| 695 | + request_id: Option<String>, | |
| 696 | + origin: &'static str, | |
| 697 | + age_ms: u64, | |
| 698 | + phase: &'static str, | |
| 699 | + response_headers_sent: bool, | |
| 700 | + response_body_active: bool, | |
| 701 | + durable_txid: Option<u64>, | |
| 702 | + output_gate_result: &'static str, | |
| 703 | + ack_point: &'static str, | |
| 704 | + active_request_count: usize, | |
| 705 | + output_gate_count: usize, | |
| 706 | + cancellation_state: &'static str, | |
| 707 | + regular_websocket_count: usize, | |
| 708 | + outbound_websocket_count: usize, | |
| 709 | +} | |
| 710 | + | |
| 711 | +impl DrainPinRegistry { | |
| 712 | + fn begin( | |
| 713 | + &self, | |
| 714 | + core_request: u64, | |
| 715 | + request_id: Option<crate::js::RequestId>, | |
| 716 | + origin: &'static str, | |
| 717 | + ) -> watch::Receiver<bool> { | |
| 718 | + let (cancel, receive) = watch::channel(false); | |
| 719 | + let mut state = self.0.lock().unwrap(); | |
| 720 | + state.pins.insert( | |
| 721 | + core_request, | |
| 722 | + DrainPinTrace { | |
| 723 | + request_id, | |
| 724 | + origin, | |
| 725 | + started_mono_ms: crate::asyncrt::mono_ms(), | |
| 726 | + phase: "handler", | |
| 727 | + response_headers_sent: false, | |
| 728 | + response_body_active: false, | |
| 729 | + durable_txid: None, | |
| 730 | + output_gate_result: "not_applicable", | |
| 731 | + ack_point: "not_acknowledged", | |
| 732 | + cancellation_state: "not_cancelled", | |
| 733 | + cancel, | |
| 734 | + }, | |
| 735 | + ); | |
| 736 | + if let Some(request_id) = request_id { | |
| 737 | + state.requests.insert(request_id, core_request); | |
| 738 | + } | |
| 739 | + receive | |
| 740 | + } | |
| 741 | + | |
| 742 | + fn update( | |
| 743 | + &self, | |
| 744 | + core_request: u64, | |
| 745 | + phase: &'static str, | |
| 746 | + response_headers_sent: bool, | |
| 747 | + response_body_active: bool, | |
| 748 | + ) { | |
| 749 | + if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) { | |
| 750 | + pin.phase = phase; | |
| 751 | + pin.response_headers_sent = response_headers_sent; | |
| 752 | + pin.response_body_active = response_body_active; | |
| 753 | + if response_headers_sent { | |
| 754 | + pin.ack_point = "response_headers_sent"; | |
| 755 | + } | |
| 756 | + } | |
| 757 | + } | |
| 758 | + | |
| 759 | + fn gate_started(&self, core_request: u64, durable_txid: u64) { | |
| 760 | + if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) { | |
| 761 | + pin.durable_txid = Some(durable_txid); | |
| 762 | + pin.output_gate_result = "pending"; | |
| 763 | + } | |
| 764 | + } | |
| 765 | + | |
| 766 | + fn gate_finished(&self, core_request: u64, proven: bool) { | |
| 767 | + if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) { | |
| 768 | + pin.output_gate_result = if proven { "proven" } else { "failed" }; | |
| 769 | + } | |
| 770 | + } | |
| 771 | + | |
| 772 | + pub fn cancel_request( | |
| 773 | + &self, | |
| 774 | + request_id: crate::js::RequestId, | |
| 775 | + cancellation_state: &'static str, | |
| 776 | + ) -> Option<&'static str> { | |
| 777 | + let mut state = self.0.lock().unwrap(); | |
| 778 | + let core_request = state.requests.get(&request_id).copied()?; | |
| 779 | + let pin = state.pins.get_mut(&core_request)?; | |
| 780 | + pin.cancellation_state = cancellation_state; | |
| 781 | + let _ = pin.cancel.send(true); | |
| 782 | + Some(pin.phase) | |
| 783 | + } | |
| 784 | + | |
| 785 | + fn cancel_core_request( | |
| 786 | + &self, | |
| 787 | + core_request: u64, | |
| 788 | + cancellation_state: &'static str, | |
| 789 | + ) -> Option<(Option<crate::js::RequestId>, &'static str)> { | |
| 790 | + let mut state = self.0.lock().unwrap(); | |
| 791 | + let pin = state.pins.get_mut(&core_request)?; | |
| 792 | + pin.cancellation_state = cancellation_state; | |
| 793 | + let _ = pin.cancel.send(true); | |
| 794 | + Some((pin.request_id, pin.phase)) | |
| 795 | + } | |
| 796 | + | |
| 797 | + fn finish(&self, core_request: u64) -> Option<DrainPinTrace> { | |
| 798 | + let mut state = self.0.lock().unwrap(); | |
| 799 | + let pin = state.pins.remove(&core_request)?; | |
| 800 | + if let Some(request_id) = pin.request_id { | |
| 801 | + state.requests.remove(&request_id); | |
| 802 | + } | |
| 803 | + Some(pin) | |
| 804 | + } | |
| 805 | + | |
| 806 | + fn snapshot(&self, pins: Vec<celld_logic::DrainPin>) -> Vec<DrainPinView> { | |
| 807 | + let state = self.0.lock().unwrap(); | |
| 808 | + pins.into_iter() | |
| 809 | + .map(|pin| { | |
| 810 | + let trace = pin.request.and_then(|request| state.pins.get(&request)); | |
| 811 | + DrainPinView { | |
| 812 | + cell: pin.cell, | |
| 813 | + core_request_id: pin.request, | |
| 814 | + request_id: trace | |
| 815 | + .and_then(|trace| trace.request_id) | |
| 816 | + .map(crate::js::request_id_string), | |
| 817 | + origin: trace.map_or("unknown", |trace| trace.origin), | |
| 818 | + age_ms: trace.map_or(0, |trace| { | |
| 819 | + crate::asyncrt::mono_ms().saturating_sub(trace.started_mono_ms) | |
| 820 | + }), | |
| 821 | + phase: trace.map_or("unknown", |trace| trace.phase), | |
| 822 | + response_headers_sent: trace.is_some_and(|trace| trace.response_headers_sent), | |
| 823 | + response_body_active: trace.is_some_and(|trace| trace.response_body_active), | |
| 824 | + durable_txid: trace.and_then(|trace| trace.durable_txid), | |
| 825 | + output_gate_result: trace.map_or("unknown", |trace| trace.output_gate_result), | |
| 826 | + ack_point: trace.map_or("unknown", |trace| trace.ack_point), | |
| 827 | + active_request_count: pin.active_request_count, | |
| 828 | + output_gate_count: pin.output_gate_count, | |
| 829 | + cancellation_state: trace.map_or("unknown", |trace| trace.cancellation_state), | |
| 830 | + regular_websocket_count: pin.regular_websocket_count, | |
| 831 | + outbound_websocket_count: pin.outbound_websocket_count, | |
| 832 | + } | |
| 833 | + }) | |
| 834 | + .collect() | |
| 835 | + } | |
| 836 | +} | |
| 837 | + | |
| 838 | +pub struct ActivityGuard { | |
| 839 | + tx: mpsc::UnboundedSender<Message>, | |
| 840 | + request: u64, | |
| 841 | + runtime: Option<RuntimeManager>, | |
| 842 | + cell: String, | |
| 843 | + drain_pins: DrainPinRegistry, | |
| 844 | + cancellation: watch::Receiver<bool>, | |
| 845 | +} | |
| 846 | + | |
| 847 | +impl ActivityGuard { | |
| 848 | + pub fn set_phase( | |
| 849 | + &self, | |
| 850 | + phase: &'static str, | |
| 851 | + response_headers_sent: bool, | |
| 852 | + response_body_active: bool, | |
| 853 | + ) { | |
| 854 | + self.drain_pins.update( | |
| 855 | + self.request, | |
| 856 | + phase, | |
| 857 | + response_headers_sent, | |
| 858 | + response_body_active, | |
| 859 | + ); | |
| 860 | + } | |
| 861 | + | |
| 862 | + pub fn cancellation(&self) -> watch::Receiver<bool> { | |
| 863 | + self.cancellation.clone() | |
| 864 | + } | |
| 865 | + | |
| 866 | + pub fn gate_started(&self, durable_txid: u64) { | |
| 867 | + self.drain_pins.gate_started(self.request, durable_txid); | |
| 868 | + } | |
| 869 | + | |
| 870 | + pub fn gate_finished(&self, proven: bool) { | |
| 871 | + self.drain_pins.gate_finished(self.request, proven); | |
| 872 | + } | |
| 873 | +} | |
| 874 | + | |
| 875 | +impl Drop for ActivityGuard { | |
| 876 | + fn drop(&mut self) { | |
| 877 | + if let Some(pin) = self.drain_pins.finish(self.request) { | |
| 878 | + if let Some(request_id) = pin | |
| 879 | + .request_id | |
| 880 | + .filter(|_| tracing::enabled!(target: "timing", tracing::Level::DEBUG)) | |
| 881 | + { | |
| 882 | + tracing::debug!( | |
| 883 | + target: "timing", | |
| 884 | + event = "cell_request_lifecycle", | |
| 885 | + core_request_id = self.request, | |
| 886 | + request_id = %crate::js::request_id_string(request_id), | |
| 887 | + scope = %self.cell, | |
| 888 | + origin = pin.origin, | |
| 889 | + age_ms = crate::asyncrt::mono_ms().saturating_sub(pin.started_mono_ms), | |
| 890 | + phase = pin.phase, | |
| 891 | + response_headers_sent = pin.response_headers_sent, | |
| 892 | + response_body_active = pin.response_body_active, | |
| 893 | + durable_txid = pin.durable_txid, | |
| 894 | + output_gate_result = pin.output_gate_result, | |
| 895 | + ack_point = pin.ack_point, | |
| 896 | + cancellation_state = pin.cancellation_state, | |
| 897 | + "cell request lifetime ended" | |
| 898 | + ); | |
| 899 | + } | |
| 900 | + } | |
| 901 | + // Read and send under the registry lock (`with_alarm`), so this | |
| 902 | + // report cannot carry an alarm older than one the reporter already | |
| 903 | + // sent — a stale fold arriving later would unarm the core and | |
| 904 | + // delete the wake entry (`alarm_reporter` documents the ordering). | |
| 905 | + let send = |tx: &mpsc::UnboundedSender<Message>, at_ms, covered| { | |
| 906 | + let _ = tx.send(Message::ActivityFinished { | |
| 907 | + request: self.request, | |
| 908 | + cell: self.cell.clone(), | |
| 909 | + alarm_at_ms: at_ms, | |
| 910 | + alarm_covered: covered, | |
| 911 | + }); | |
| 912 | + }; | |
| 913 | + match &self.runtime { | |
| 914 | + Some(runtime) => runtime.with_alarm(&self.cell, |at_ms| { | |
| 915 | + let covered = runtime.alarm_covered(&self.cell, at_ms); | |
| 916 | + send(&self.tx, at_ms, covered); | |
| 917 | + }), | |
| 918 | + None => send(&self.tx, None, false), | |
| 919 | + } | |
| 920 | + } | |
| 921 | +} | |
| 922 | + | |
| 923 | +#[derive(Clone, Copy)] | |
| 924 | +enum RouteStage { | |
| 925 | + OwnershipRead, | |
| 926 | + NodeLeaseLookup, | |
| 927 | + CapacityLookup, | |
| 928 | + OwnershipAcquire, | |
| 929 | + Restore, | |
| 930 | + IsolateStartup, | |
| 931 | + RegistryInsert, | |
| 932 | +} | |
| 933 | + | |
| 934 | +struct EffectTiming { | |
| 935 | + cell: String, | |
| 936 | + stage: RouteStage, | |
| 937 | + elapsed_us: u64, | |
| 938 | +} | |
| 939 | + | |
| 940 | +pub struct CompletedEffect { | |
| 941 | + event: Event, | |
| 942 | + timing: Option<EffectTiming>, | |
| 943 | +} | |
| 944 | + | |
| 945 | +impl CompletedEffect { | |
| 946 | + fn plain(event: Event) -> Self { | |
| 947 | + Self { | |
| 948 | + event, | |
| 949 | + timing: None, | |
| 950 | + } | |
| 951 | + } | |
| 952 | + | |
| 953 | + fn timed(event: Event, cell: String, stage: RouteStage, started_mono_ms: u64) -> Self { | |
| 954 | + Self { | |
| 955 | + event, | |
| 956 | + timing: Some(EffectTiming { | |
| 957 | + cell, | |
| 958 | + stage, | |
| 959 | + elapsed_us: mono_elapsed_us(started_mono_ms), | |
| 960 | + }), | |
| 961 | + } | |
| 962 | + } | |
| 963 | +} | |
| 964 | + | |
| 965 | +struct CellRouteTiming { | |
| 966 | + started_mono_ms: u64, | |
| 967 | + activation_started: bool, | |
| 968 | + capacity_wait_started_mono_ms: Option<u64>, | |
| 969 | + latch_wait_us: u64, | |
| 970 | + ownership_read_us: u64, | |
| 971 | + node_lease_lookup_us: u64, | |
| 972 | + capacity_lookup_us: u64, | |
| 973 | + capacity_wait_us: u64, | |
| 974 | + activation_slot_wait_us: u64, | |
| 975 | + lease_permit_us: u64, | |
| 976 | + ownership_acquire_us: u64, | |
| 977 | + replica_discovery_us: u64, | |
| 978 | + restore_us: u64, | |
| 979 | + isolate_startup_us: u64, | |
| 980 | + registry_insert_us: u64, | |
| 981 | + fresh: Option<bool>, | |
| 982 | +} | |
| 983 | + | |
| 984 | +impl CellRouteTiming { | |
| 985 | + fn new() -> Self { | |
| 986 | + Self { | |
| 987 | + started_mono_ms: crate::asyncrt::mono_ms(), | |
| 988 | + activation_started: false, | |
| 989 | + capacity_wait_started_mono_ms: None, | |
| 990 | + latch_wait_us: 0, | |
| 991 | + ownership_read_us: 0, | |
| 992 | + node_lease_lookup_us: 0, | |
| 993 | + capacity_lookup_us: 0, | |
| 994 | + capacity_wait_us: 0, | |
| 995 | + activation_slot_wait_us: 0, | |
| 996 | + lease_permit_us: 0, | |
| 997 | + ownership_acquire_us: 0, | |
| 998 | + replica_discovery_us: 0, | |
| 999 | + restore_us: 0, | |
| 1000 | + isolate_startup_us: 0, | |
| 1001 | + registry_insert_us: 0, | |
| 1002 | + fresh: None, | |
| 1003 | + } | |
| 1004 | + } | |
| 1005 | + | |
| 1006 | + fn effect_started(&mut self) { | |
| 1007 | + if !self.activation_started { | |
| 1008 | + self.activation_started = true; | |
| 1009 | + self.activation_slot_wait_us = mono_elapsed_us(self.started_mono_ms); | |
| 1010 | + } | |
| 1011 | + if let Some(started) = self.capacity_wait_started_mono_ms.take() { | |
| 1012 | + self.capacity_wait_us = self | |
| 1013 | + .capacity_wait_us | |
| 1014 | + .saturating_add(mono_elapsed_us(started)); | |
| 1015 | + } | |
| 1016 | + } | |
| 1017 | + | |
| 1018 | + fn record(&mut self, stage: RouteStage, elapsed_us: u64) { | |
| 1019 | + let field = match stage { | |
| 1020 | + RouteStage::OwnershipRead => &mut self.ownership_read_us, | |
| 1021 | + RouteStage::NodeLeaseLookup => &mut self.node_lease_lookup_us, | |
| 1022 | + RouteStage::CapacityLookup => &mut self.capacity_lookup_us, | |
| 1023 | + RouteStage::OwnershipAcquire => &mut self.ownership_acquire_us, | |
| 1024 | + RouteStage::Restore => &mut self.restore_us, | |
| 1025 | + RouteStage::IsolateStartup => &mut self.isolate_startup_us, | |
| 1026 | + RouteStage::RegistryInsert => &mut self.registry_insert_us, | |
| 1027 | + }; | |
| 1028 | + *field = field.saturating_add(elapsed_us); | |
| 1029 | + } | |
| 1030 | +} | |
| 1031 | + | |
| 1032 | +/// Report a cell's runtime stopped, but only once the host has actually let | |
| 1033 | +/// the cell go. | |
| 1034 | +/// | |
| 1035 | +/// A stop that failed can leave the cell's realm holding its open database, | |
| 1036 | +/// so reporting it stopped is what makes that dangerous: the core answers a | |
| 1037 | +/// stop by starting the cell again — on the current application generation | |
| 1038 | +/// for a swap, or on another node after a handoff — against storage the old | |
| 1039 | +/// realm may still have. Both stop paths therefore retry rather than report, | |
| 1040 | +/// and they share this loop so neither can drift into reporting first. | |
| 1041 | +/// | |
| 1042 | +/// The retry is unbounded on purpose. The core arms an operation deadline on | |
| 1043 | +/// the `Cleaning` phase this answers, so a host that never lets go is bounded | |
| 1044 | +/// there rather than by a count guessed here. | |
| 1045 | +async fn report_stopped_when_released<F, Fut>( | |
| 1046 | + op: OpId, | |
| 1047 | + cell: String, | |
| 1048 | + epoch: u64, | |
| 1049 | + event: &'static str, | |
| 1050 | + mut release: F, | |
| 1051 | +) -> CompletedEffect | |
| 1052 | +where | |
| 1053 | + F: FnMut() -> Fut, | |
| 1054 | + Fut: std::future::Future<Output = anyhow::Result<()>>, | |
| 1055 | +{ | |
| 1056 | + while let Err(error) = release().await { | |
| 1057 | + tracing::warn!( | |
| 1058 | + event, | |
| 1059 | + %cell, | |
| 1060 | + epoch, | |
| 1061 | + %error, | |
| 1062 | + "the host did not release the cell; retrying before reporting it stopped" | |
| 1063 | + ); | |
| 1064 | + crate::asyncrt::sleep(std::time::Duration::from_millis( | |
| 1065 | + crate::replication::CELL_RELEASE_RETRY_BASE_MS, | |
| 1066 | + )) | |
| 1067 | + .await; | |
| 1068 | + } | |
| 1069 | + CompletedEffect::plain(Event::RuntimeStopped { op }) | |
| 1070 | +} | |
| 1071 | + | |
| 1072 | +fn mono_elapsed_us(started_mono_ms: u64) -> u64 { | |
| 1073 | + crate::asyncrt::mono_ms() | |
| 1074 | + .saturating_sub(started_mono_ms) | |
| 1075 | + .saturating_mul(1_000) | |
| 1076 | +} | |
| 1077 | + | |
| 1078 | +pub type EffectFuture = Pin<Box<dyn Future<Output = CompletedEffect> + Send>>; | |
| 1079 | +pub type ConnectionFuture = Pin<Box<dyn Future<Output = ()> + Send>>; | |
| 1080 | +pub type DoCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>; | |
| 1081 | +pub type AssetCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>; | |
| 1082 | +pub type WebSocketFuture = Pin<Box<dyn Future<Output = ()> + Send>>; | |
| 1083 | +pub type CachePruneFuture = Pin< | |
| 1084 | + Box< | |
| 1085 | + dyn Future< | |
| 1086 | + Output = ( | |
| 1087 | + u64, | |
| 1088 | + Result<std::io::Result<(usize, usize, u64)>, crate::asyncrt::TaskPanic>, | |
| 1089 | + ), | |
| 1090 | + > + Send, | |
| 1091 | + >, | |
| 1092 | +>; | |
| 1093 | + | |
| 1094 | +/// One ready item selected for the serial Actor. | |
| 1095 | +pub enum ActorInput { | |
| 1096 | + Message(Message), | |
| 1097 | + Completed(CompletedEffect), | |
| 1098 | + TimerFired(Timer), | |
| 1099 | +} | |
| 1100 | + | |
| 1101 | +/// Futures and timer arms emitted by one Actor transition. | |
| 1102 | +#[derive(Default)] | |
| 1103 | +pub struct StepOutput { | |
| 1104 | + pub effects: Vec<EffectFuture>, | |
| 1105 | + pub timers: Vec<TimerArm>, | |
| 1106 | +} | |
| 1107 | + | |
| 1108 | +fn drain_step_output( | |
| 1109 | + out: &mut StepOutput, | |
| 1110 | + effects: &mut FuturesUnordered<EffectFuture>, | |
| 1111 | + delays: &mut DelayQueue<TimerArm>, | |
| 1112 | + timers: &mut TimerSlots<delay_queue::Key>, | |
| 1113 | +) { | |
| 1114 | + for effect in out.effects.drain(..) { | |
| 1115 | + effects.push(effect); | |
| 1116 | + } | |
| 1117 | + for arm in out.timers.drain(..) { | |
| 1118 | + let delay = std::time::Duration::from_millis( | |
| 1119 | + arm.at_mono_ms.saturating_sub(crate::asyncrt::mono_ms()), | |
| 1120 | + ); | |
| 1121 | + let key = delays.insert(arm.clone(), delay); | |
| 1122 | + if let Some(displaced) = timers.install(&arm, key) { | |
| 1123 | + delays.remove(&displaced); | |
| 1124 | + } | |
| 1125 | + } | |
| 1126 | +} | |
| 1127 | + | |
| 1128 | +/// The largest request body that a node accepts unless the operator lowers | |
| 1129 | +/// the limit. The value keeps the large git-pack ingress use case supported. | |
| 1130 | +pub const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1 << 30; | |
| 1131 | + | |
| 1132 | +/// The generation census `/state` reports beside the serving deployment. | |
| 1133 | +pub struct SwapCensus { | |
| 1134 | + /// Resident cells moving to the current generation right now. | |
| 1135 | + pub swapping: usize, | |
| 1136 | + /// Each resident cell and the generation its runtime started on. | |
| 1137 | + pub generations: Vec<(String, u64)>, | |
| 1138 | +} | |
| 1139 | + | |
| 1140 | +#[derive(Clone)] | |
| 1141 | +pub struct AppHandle { | |
| 1142 | + pub tx: mpsc::UnboundedSender<Message>, | |
| 1143 | + pub runtime: Option<RuntimeManager>, | |
| 1144 | + /// Asks the pointer watcher to adopt the current deployment now. Sending | |
| 1145 | + /// fails on a node with no pointer to watch, such as a local-script node. | |
| 1146 | + pub reload: crate::generation::ReloadSender, | |
| 1147 | + pub peer_http: reqwest::Client, | |
| 1148 | + pub peer_auth: Arc<PeerAuth>, | |
| 1149 | + pub advertise: String, | |
| 1150 | + pub websockets: mpsc::UnboundedSender<WebSocketFuture>, | |
| 1151 | + /// Whether the RPO=0 output gate is armed: hold a local write's response | |
| 1152 | + /// until its cell is proven durable. On by default; set `CELLD_OUTPUT_GATE=0` | |
| 1153 | + /// to acknowledge writes without proving them durable. The core and its DST | |
| 1154 | + /// are unconditional. | |
| 1155 | + pub output_gate: bool, | |
| 1156 | + /// Concurrent outbound WebSockets one cell may hold, for the refusal | |
| 1157 | + /// message; the core enforces it. | |
| 1158 | + pub max_outbound_websockets: usize, | |
| 1159 | + /// Set the instant a graceful shutdown begins, so `/.well-known/celld/health` reports | |
| 1160 | + /// unhealthy and a load balancer stops routing here before teardown. | |
| 1161 | + pub draining: Arc<std::sync::atomic::AtomicBool>, | |
| 1162 | + /// 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 | |
| 1165 | + /// fleet recovers. Fleet state never demotes readiness after the gate | |
| 1166 | + /// opens; peers reach owned cells directly regardless. | |
| 1167 | + pub fleet_ready: Arc<std::sync::atomic::AtomicBool>, | |
| 1168 | + /// Public requests which passed the shutdown gate and have not finished. | |
| 1169 | + /// This includes the complete top-level Worker call, so a cell write it | |
| 1170 | + /// goes on to make cannot outlive the pre-handoff durability boundary. | |
| 1171 | + pub public_in_flight: Arc<AtomicUsize>, | |
| 1172 | + /// Shell-side phases joined to the decision core's exact eviction pins. | |
| 1173 | + pub drain_pins: DrainPinRegistry, | |
| 1174 | + /// The log tier's follower store: this node holds peers' log fragments | |
| 1175 | + /// whatever its own durability posture. `None` without a bucket. | |
| 1176 | + pub follower: Option<Arc<crate::node_log::FollowerStore>>, | |
| 1177 | + /// Whether forwarded scheme and host headers can set `request.url`. | |
| 1178 | + /// The default is false because a direct client controls both headers. | |
| 1179 | + pub trust_forwarded_headers: bool, | |
| 1180 | + /// The maximum body size for public Worker ingress and direct Durable | |
| 1181 | + /// Object ingress. The same value must govern both entry points because a | |
| 1182 | + /// caller can choose either route for an ordinary Durable Object. | |
| 1183 | + pub max_request_body_bytes: usize, | |
| 1184 | +} | |
| 1185 | + | |
| 1186 | +impl AppHandle { | |
| 1187 | + pub async fn request(&self, cell: String) -> Result<Routed, RequestError> { | |
| 1188 | + self.request_with_mode(cell, false, None).await | |
| 1189 | + } | |
| 1190 | + | |
| 1191 | + /// Route one test request and retain which asynchronous seam produced the | |
| 1192 | + /// result. The shipping method keeps its compact public result, while this | |
| 1193 | + /// receipt prevents an inference from `NodeFenced` or an error string. | |
| 1194 | + #[cfg(all(test, celld_internal_tests))] | |
| 1195 | + pub(crate) async fn request_with_receipt_for_test( | |
| 1196 | + &self, | |
| 1197 | + cell: String, | |
| 1198 | + ) -> RequestPathReceiptForTest { | |
| 1199 | + let (request, outcome) = self.request_path(cell, false, None).await; | |
| 1200 | + match outcome { | |
| 1201 | + RequestPathOutcome::SubmissionFailure => { | |
| 1202 | + RequestPathReceiptForTest::SubmissionFailure { request } | |
| 1203 | + } | |
| 1204 | + RequestPathOutcome::ReplyChannelClosed => { | |
| 1205 | + RequestPathReceiptForTest::ReplyChannelClosed { request } | |
| 1206 | + } | |
| 1207 | + RequestPathOutcome::Returned(result) => RequestPathReceiptForTest::Returned { | |
| 1208 | + allocated_request: request, | |
| 1209 | + result: result.map(|routed| (routed.request, routed.route)), | |
| 1210 | + }, | |
| 1211 | + } | |
| 1212 | + } | |
| 1213 | + | |
| 1214 | + pub async fn capacity_request(&self, cell: String) -> Result<Routed, RequestError> { | |
| 1215 | + self.request_with_mode(cell, true, None).await | |
| 1216 | + } | |
| 1217 | + | |
| 1218 | + pub async fn websocket_request( | |
| 1219 | + &self, | |
| 1220 | + cell: String, | |
| 1221 | + websocket: u64, | |
| 1222 | + ) -> Result<Routed, RequestError> { | |
| 1223 | + self.request_with_mode(cell, false, Some(websocket)).await | |
| 1224 | + } | |
| 1225 | + | |
| 1226 | + async fn request_with_mode( | |
| 1227 | + &self, | |
| 1228 | + cell: String, | |
| 1229 | + capacity_handoff: bool, | |
| 1230 | + websocket: Option<u64>, | |
| 1231 | + ) -> Result<Routed, RequestError> { | |
| 1232 | + match self.request_path(cell, capacity_handoff, websocket).await.1 { | |
| 1233 | + RequestPathOutcome::Returned(result) => result, | |
| 1234 | + RequestPathOutcome::SubmissionFailure | RequestPathOutcome::ReplyChannelClosed => { | |
| 1235 | + Err(RequestError::NodeFenced) | |
| 1236 | + } | |
| 1237 | + } | |
| 1238 | + } | |
| 1239 | + | |
| 1240 | + async fn request_path( | |
| 1241 | + &self, | |
| 1242 | + cell: String, | |
| 1243 | + capacity_handoff: bool, | |
| 1244 | + websocket: Option<u64>, | |
| 1245 | + ) -> (u64, RequestPathOutcome) { | |
| 1246 | + let request = crate::asyncrt::next_core_request(); | |
| 1247 | + let (reply, receive) = oneshot::channel(); | |
| 1248 | + if self | |
| 1249 | + .tx | |
| 1250 | + .send(Message::Request { | |
| 1251 | + request, | |
| 1252 | + cell, | |
| 1253 | + capacity_handoff, | |
| 1254 | + handoff_accept: None, | |
| 1255 | + websocket, | |
| 1256 | + reply, | |
| 1257 | + }) | |
| 1258 | + .is_err() | |
| 1259 | + { | |
| 1260 | + return (request, RequestPathOutcome::SubmissionFailure); | |
| 1261 | + } | |
| 1262 | + let mut cancel = RouteCancelGuard::new(self.tx.clone(), request); | |
| 1263 | + let outcome = match receive.await { | |
| 1264 | + Ok(result) => RequestPathOutcome::Returned(result), | |
| 1265 | + Err(_) => RequestPathOutcome::ReplyChannelClosed, | |
| 1266 | + }; | |
| 1267 | + cancel.disarm(); | |
| 1268 | + (request, outcome) | |
| 1269 | + } | |
| 1270 | + | |
| 1271 | + /// Acquire a released cell without materializing its runtime. The donor's | |
| 1272 | + /// final snapshot makes a later demand-driven restore authoritative, and | |
| 1273 | + /// avoiding an eager restore keeps a fleet restart from becoming a cold | |
| 1274 | + /// start storm. | |
| 1275 | + pub async fn accept_handoff( | |
| 1276 | + &self, | |
| 1277 | + cell: String, | |
| 1278 | + released_epoch: u64, | |
| 1279 | + ) -> Result<HandoffAttempt, RequestError> { | |
| 1280 | + let request = crate::asyncrt::next_core_request(); | |
| 1281 | + let (route_reply, mut route_receive) = oneshot::channel(); | |
| 1282 | + let (accept_reply, mut accept_receive) = oneshot::channel(); | |
| 1283 | + if self | |
| 1284 | + .tx | |
| 1285 | + .send(Message::Request { | |
| 1286 | + request, | |
| 1287 | + cell: cell.clone(), | |
| 1288 | + capacity_handoff: true, | |
| 1289 | + handoff_accept: Some(HandoffAcceptWaiter { | |
| 1290 | + released_epoch, | |
| 1291 | + reply: accept_reply, | |
| 1292 | + }), | |
| 1293 | + websocket: None, | |
| 1294 | + reply: route_reply, | |
| 1295 | + }) | |
| 1296 | + .is_err() | |
| 1297 | + { | |
| 1298 | + return Err(RequestError::NodeFenced); | |
| 1299 | + } | |
| 1300 | + let mut cancel = RouteCancelGuard::new(self.tx.clone(), request); | |
| 1301 | + let result = crate::asyncrt::select_biased! { | |
| 1302 | + "a completed route wins a tie so current ownership precedes the accept acknowledgement"; | |
| 1303 | + routed = &mut route_receive => match routed | |
| 1304 | + .unwrap_or(Err(RequestError::NodeFenced))? | |
| 1305 | + { | |
| 1306 | + Routed { | |
| 1307 | + request, | |
| 1308 | + route: Route::Local, | |
| 1309 | + } => { | |
| 1310 | + // A repeated request can find the cell published already. | |
| 1311 | + drop(self.activity(request, cell.clone())); | |
| 1312 | + self.resident_epoch(cell) | |
| 1313 | + .await | |
| 1314 | + .filter(|epoch| *epoch > released_epoch) | |
| 1315 | + .map(|epoch| HandoffAttempt::Accepted(AdoptedCell { | |
| 1316 | + node: self.peer_auth.source().to_string(), | |
| 1317 | + addr: self.advertise.clone(), | |
| 1318 | + epoch, | |
| 1319 | + peer_protocol: peer_auth::PROTOCOL_VERSION, | |
| 1320 | + })) | |
| 1321 | + .ok_or(RequestError::AcquireFailed) | |
| 1322 | + } | |
| 1323 | + Routed { | |
| 1324 | + route: Route::Remote { | |
| 1325 | + node, | |
| 1326 | + addr, | |
| 1327 | + epoch, | |
| 1328 | + peer_protocol, | |
| 1329 | + }, | |
| 1330 | + .. | |
| 1331 | + } => Ok(HandoffAttempt::CurrentOwner(AdoptedCell { | |
| 1332 | + node, | |
| 1333 | + addr, | |
| 1334 | + epoch, | |
| 1335 | + peer_protocol, | |
| 1336 | + })), | |
| 1337 | + }, | |
| 1338 | + accepted = &mut accept_receive => accepted | |
| 1339 | + .map(HandoffAttempt::Accepted) | |
| 1340 | + .map_err(|_| RequestError::NodeFenced), | |
| 1341 | + }; | |
| 1342 | + // The ownership acknowledgement deliberately leaves no route waiter: | |
| 1343 | + // real traffic, not this synthetic request, starts materialization. | |
| 1344 | + cancel.disarm(); | |
| 1345 | + let _ = self.tx.send(Message::CancelRoute { request }); | |
| 1346 | + result | |
| 1347 | + } | |
| 1348 | + | |
| 1349 | + // Orphaned by the always-pool Worker entry below. What remains of the | |
| 1350 | + // landing-cell machinery -- this, `Message::WorkerRequest`, `WorkerRouted`, | |
| 1351 | + // `fetch_worker_on_cell`, `CellJob::WorkerFetch`, and the logic | |
| 1352 | + // `worker_request` -- is kept together so it can be removed in one piece | |
| 1353 | + // rather than unpicked here. The in-isolate dispatch it was paired with is | |
| 1354 | + // already gone, and with it the gate that path needed. | |
| 1355 | + #[allow(dead_code)] | |
| 1356 | + async fn worker_route(&self) -> anyhow::Result<WorkerRouted> { | |
| 1357 | + let (reply, receive) = oneshot::channel(); | |
| 1358 | + self.tx | |
| 1359 | + .send(Message::WorkerRequest { reply }) | |
| 1360 | + .map_err(|_| anyhow::anyhow!("core stopped before Worker routing"))?; | |
| 1361 | + receive | |
| 1362 | + .await | |
| 1363 | + .context("core stopped while routing Worker request") | |
| 1364 | + } | |
| 1365 | + | |
| 1366 | + pub async fn fetch_worker( | |
| 1367 | + &self, | |
| 1368 | + url: String, | |
| 1369 | + method: String, | |
| 1370 | + body: crate::js::RequestBody, | |
| 1371 | + headers: Vec<(String, String)>, | |
| 1372 | + connection: ConnectionWorkerRequests, | |
| 1373 | + ) -> anyhow::Result<HttpResponse> { | |
| 1374 | + let runtime = self | |
| 1375 | + .runtime | |
| 1376 | + .as_ref() | |
| 1377 | + .ok_or_else(|| anyhow::anyhow!("Worker runtime unavailable"))?; | |
| 1378 | + // Admission happens in the runtime, against the pool that actually | |
| 1379 | + // holds the requests. It used to be duplicated here against an empty | |
| 1380 | + // `PoolLoad` — a snapshot with no isolates and no affiliations, which | |
| 1381 | + // could only ever answer "yes" once pressure stopped refusing | |
| 1382 | + // outright. A decision made against a fake reading is not a fast path. | |
| 1383 | + let js_request = crate::js::next_request_id(); | |
| 1384 | + // The Worker entry is stateless — run it in the pool, always. Routing it | |
| 1385 | + // to a "landing cell" existed only to make an `env.NS.get(id)` call | |
| 1386 | + // resolve inline; but a cell runs one fetch at a time, so under any real | |
| 1387 | + // concurrency the entry can't be on the cell it calls, and the routing | |
| 1388 | + // round-trip is paid for nothing — on top of the DO call's own routing. | |
| 1389 | + // A DO call reaches its owning cell (with fencing and the output gate) on | |
| 1390 | + // 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; | |
| 1395 | + abort.disarm(); | |
| 1396 | + result | |
| 1397 | + } | |
| 1398 | + | |
| 1399 | + pub fn activity(&self, request: u64, cell: String) -> ActivityGuard { | |
| 1400 | + self.activity_for(request, cell, None, "local") | |
| 1401 | + } | |
| 1402 | + | |
| 1403 | + pub fn activity_for( | |
| 1404 | + &self, | |
| 1405 | + request: u64, | |
| 1406 | + cell: String, | |
| 1407 | + request_id: Option<crate::js::RequestId>, | |
| 1408 | + origin: &'static str, | |
| 1409 | + ) -> ActivityGuard { | |
| 1410 | + let cancellation = self.drain_pins.begin(request, request_id, origin); | |
| 1411 | + ActivityGuard { | |
| 1412 | + tx: self.tx.clone(), | |
| 1413 | + request, | |
| 1414 | + runtime: self.runtime.clone(), | |
| 1415 | + cell, | |
| 1416 | + drain_pins: self.drain_pins.clone(), | |
| 1417 | + cancellation, | |
| 1418 | + } | |
| 1419 | + } | |
| 1420 | + | |
| 1421 | + /// Hold a response until every write it can reveal is durable. A write | |
| 1422 | + /// 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 { | |
| 1431 | + OutputGateOutcome::Returned(result) => result, | |
| 1432 | + OutputGateOutcome::SubmissionFailure | OutputGateOutcome::ReplyChannelClosed => { | |
| 1433 | + Err(RequestError::NodeFenced) | |
| 1434 | + } | |
| 1435 | + } | |
| 1436 | + } | |
| 1437 | + | |
| 1438 | + async fn gate_output_path( | |
| 1439 | + &self, | |
| 1440 | + request: u64, | |
| 1441 | + channel: Channel, | |
| 1442 | + position: Option<u64>, | |
| 1443 | + ) -> OutputGateOutcome { | |
| 1444 | + let started_mono_ms = crate::asyncrt::mono_ms(); | |
| 1445 | + let (reply, receive) = oneshot::channel(); | |
| 1446 | + if self | |
| 1447 | + .tx | |
| 1448 | + .send(Message::Output { | |
| 1449 | + request, | |
| 1450 | + channel, | |
| 1451 | + position, | |
| 1452 | + reply, | |
| 1453 | + }) | |
| 1454 | + .is_err() | |
| 1455 | + { | |
| 1456 | + return OutputGateOutcome::SubmissionFailure; | |
| 1457 | + } | |
| 1458 | + let outcome = match receive.await { | |
| 1459 | + Ok(result) => OutputGateOutcome::Returned(result), | |
| 1460 | + Err(_) => OutputGateOutcome::ReplyChannelClosed, | |
| 1461 | + }; | |
| 1462 | + tracing::debug!( | |
| 1463 | + target: "timing", | |
| 1464 | + event = "gate_write_timing", | |
| 1465 | + request, | |
| 1466 | + total_us = mono_elapsed_us(started_mono_ms), | |
| 1467 | + "output gate resolved" | |
| 1468 | + ); | |
| 1469 | + outcome | |
| 1470 | + } | |
| 1471 | + | |
| 1472 | + /// Run one test output gate without collapsing its two channel failures | |
| 1473 | + /// into a returned engine rejection. The request travels in every arm, so | |
| 1474 | + /// a consumer cannot attach the receipt to another caller. | |
| 1475 | + #[cfg(all(test, celld_internal_tests))] | |
| 1476 | + pub(crate) async fn gate_output_with_receipt_for_test( | |
| 1477 | + &self, | |
| 1478 | + request: u64, | |
| 1479 | + channel: Channel, | |
| 1480 | + position: Option<u64>, | |
| 1481 | + ) -> OutputGateReceiptForTest { | |
| 1482 | + match self.gate_output_path(request, channel, position).await { | |
| 1483 | + OutputGateOutcome::SubmissionFailure => { | |
| 1484 | + OutputGateReceiptForTest::SubmissionFailure { request } | |
| 1485 | + } | |
| 1486 | + OutputGateOutcome::ReplyChannelClosed => { | |
| 1487 | + OutputGateReceiptForTest::ReplyChannelClosed { request } | |
| 1488 | + } | |
| 1489 | + OutputGateOutcome::Returned(result) => { | |
| 1490 | + OutputGateReceiptForTest::Returned { request, result } | |
| 1491 | + } | |
| 1492 | + } | |
| 1493 | + } | |
| 1494 | + | |
| 1495 | + pub async fn gate_write(&self, request: u64, position: u64) -> Result<(), RequestError> { | |
| 1496 | + self.gate_output(request, Channel::Response, Some(position)) | |
| 1497 | + .await | |
| 1498 | + } | |
| 1499 | + | |
| 1500 | + /// Hand a finished `webSocketMessage`'s frames to the cell's output gate. | |
| 1501 | + /// Awaited so the request stays pinned until the actor has registered the | |
| 1502 | + /// gate (the core reads the still-active request when it opens); frames flush | |
| 1503 | + /// or fail asynchronously as durability resolves, not here. | |
| 1504 | + pub async fn ws_output( | |
| 1505 | + &self, | |
| 1506 | + request: u64, | |
| 1507 | + scope: String, | |
| 1508 | + frames: Vec<(u64, WsOut)>, | |
| 1509 | + write_position: Option<u64>, | |
| 1510 | + ) { | |
| 1511 | + let (reply, receive) = oneshot::channel(); | |
| 1512 | + if self | |
| 1513 | + .tx | |
| 1514 | + .send(Message::WsOutput { | |
| 1515 | + request, | |
| 1516 | + scope, | |
| 1517 | + frames, | |
| 1518 | + write_position, | |
| 1519 | + reply, | |
| 1520 | + }) | |
| 1521 | + .is_ok() | |
| 1522 | + { | |
| 1523 | + let _ = receive.await; | |
| 1524 | + } | |
| 1525 | + } | |
| 1526 | + | |
| 1527 | + pub async fn websocket_opened( | |
| 1528 | + &self, | |
| 1529 | + cell: String, | |
| 1530 | + websocket: u64, | |
| 1531 | + kind: WebSocketKind, | |
| 1532 | + ) -> anyhow::Result<()> { | |
| 1533 | + let (reply, receive) = oneshot::channel(); | |
| 1534 | + self.tx | |
| 1535 | + .send(Message::WebSocketOpened { | |
| 1536 | + cell, | |
| 1537 | + websocket, | |
| 1538 | + kind, | |
| 1539 | + reply, | |
| 1540 | + }) | |
| 1541 | + .map_err(|_| anyhow::anyhow!("core stopped before WebSocket opened"))?; | |
| 1542 | + let held = receive | |
| 1543 | + .await | |
| 1544 | + .context("core stopped while opening WebSocket")?; | |
| 1545 | + anyhow::ensure!( | |
| 1546 | + held, | |
| 1547 | + "outbound WebSocket refused: a cell may hold at most {}, and a node \ | |
| 1548 | + may pin at most {}% of its residency ceiling", | |
| 1549 | + self.max_outbound_websockets, | |
| 1550 | + celld_logic::pressure::MAX_OUTBOUND_PIN_PERCENT, | |
| 1551 | + ); | |
| 1552 | + Ok(()) | |
| 1553 | + } | |
| 1554 | + | |
| 1555 | + pub fn websocket_closed(&self, cell: String, websocket: u64) { | |
| 1556 | + let _ = self.tx.send(Message::WebSocketClosed { cell, websocket }); | |
| 1557 | + } | |
| 1558 | + | |
| 1559 | + pub async fn evict(&self, cell: String) { | |
| 1560 | + let (reply, receive) = oneshot::channel(); | |
| 1561 | + if self.tx.send(Message::Evict { cell, reply }).is_ok() { | |
| 1562 | + let _ = receive.await; | |
| 1563 | + } | |
| 1564 | + } | |
| 1565 | + | |
| 1566 | + pub async fn invalidate_remote(&self, cell: String, node: String, epoch: u64) { | |
| 1567 | + let (reply, receive) = oneshot::channel(); | |
| 1568 | + if self | |
| 1569 | + .tx | |
| 1570 | + .send(Message::InvalidateRemote { | |
| 1571 | + cell, | |
| 1572 | + node, | |
| 1573 | + epoch, | |
| 1574 | + reply, | |
| 1575 | + }) | |
| 1576 | + .is_ok() | |
| 1577 | + { | |
| 1578 | + let _ = receive.await; | |
| 1579 | + } | |
| 1580 | + } | |
| 1581 | + | |
| 1582 | + pub async fn snapshot(&self) -> String { | |
| 1583 | + let (reply, receive) = oneshot::channel(); | |
| 1584 | + if self.tx.send(Message::Snapshot { reply }).is_err() { | |
| 1585 | + return "{\"error\":\"actor_stopped\"}".into(); | |
| 1586 | + } | |
| 1587 | + let Ok((state, pins, census)) = receive.await else { | |
| 1588 | + return "{\"error\":\"actor_stopped\"}".into(); | |
| 1589 | + }; | |
| 1590 | + let pins = self.drain_pins.snapshot(pins); | |
| 1591 | + let Ok(mut state) = serde_json::from_str::<serde_json::Value>(&state) else { | |
| 1592 | + return state; | |
| 1593 | + }; | |
| 1594 | + if !pins.is_empty() { | |
| 1595 | + state["drainPins"] = | |
| 1596 | + serde_json::to_value(pins).unwrap_or_else(|_| serde_json::json!([])); | |
| 1597 | + } | |
| 1598 | + // Which deployment this node serves, and which ones it is still | |
| 1599 | + // draining. Nothing else in the process records the version, so | |
| 1600 | + // this is how an operator learns whether a deploy took. | |
| 1601 | + if let Some(runtime) = &self.runtime { | |
| 1602 | + let generation = runtime.generation(); | |
| 1603 | + state["deployment"] = serde_json::json!({ | |
| 1604 | + "version": generation.version(), | |
| 1605 | + "prefix": generation.prefix(), | |
| 1606 | + "generation": generation.id(), | |
| 1607 | + "draining": runtime | |
| 1608 | + .draining_generations() | |
| 1609 | + .into_iter() | |
| 1610 | + .map(|(id, version)| serde_json::json!({"generation": id, "version": version})) | |
| 1611 | + .collect::<Vec<_>>(), | |
| 1612 | + // Resident cells moving to the current generation right now, | |
| 1613 | + // and the generation each resident cell runs: the two numbers | |
| 1614 | + // an operator watches while a deployment converges. | |
| 1615 | + "swapping": census.swapping, | |
| 1616 | + "cells": census | |
| 1617 | + .generations | |
| 1618 | + .into_iter() | |
| 1619 | + .map(|(cell, generation)| (cell, serde_json::Value::from(generation))) | |
| 1620 | + .collect::<serde_json::Map<_, _>>(), | |
| 1621 | + }); | |
| 1622 | + } | |
| 1623 | + state.to_string() | |
| 1624 | + } | |
| 1625 | + | |
| 1626 | + pub fn is_draining(&self) -> bool { | |
| 1627 | + self.draining.load(std::sync::atomic::Ordering::Relaxed) | |
| 1628 | + } | |
| 1629 | + | |
| 1630 | + pub fn fleet_ready(&self) -> bool { | |
| 1631 | + self.fleet_ready.load(std::sync::atomic::Ordering::Relaxed) | |
| 1632 | + } | |
| 1633 | + | |
| 1634 | + /// Atomically cross the public shutdown gate. The second draining read | |
| 1635 | + /// closes the race where shutdown stores the flag between the first read | |
| 1636 | + /// and the counter increment: that request backs out before user code runs. | |
| 1637 | + pub fn admit_public(&self) -> Option<PublicRequestGuard> { | |
| 1638 | + if self.draining.load(Ordering::SeqCst) { | |
| 1639 | + return None; | |
| 1640 | + } | |
| 1641 | + self.public_in_flight.fetch_add(1, Ordering::SeqCst); | |
| 1642 | + if self.draining.load(Ordering::SeqCst) { | |
| 1643 | + self.public_in_flight.fetch_sub(1, Ordering::SeqCst); | |
| 1644 | + return None; | |
| 1645 | + } | |
| 1646 | + Some(PublicRequestGuard { | |
| 1647 | + in_flight: self.public_in_flight.clone(), | |
| 1648 | + }) | |
| 1649 | + } | |
| 1650 | + | |
| 1651 | + pub fn public_in_flight(&self) -> usize { | |
| 1652 | + self.public_in_flight.load(Ordering::SeqCst) | |
| 1653 | + } | |
| 1654 | + | |
| 1655 | + /// A dead actor has nothing left to hand off, so channel failure | |
| 1656 | + /// reports drained rather than wedging shutdown. | |
| 1657 | + pub async fn drain_status(&self) -> DrainStatus { | |
| 1658 | + let (reply, receive) = oneshot::channel(); | |
| 1659 | + if self.tx.send(Message::Drained { reply }).is_err() { | |
| 1660 | + return DrainStatus::default(); | |
| 1661 | + } | |
| 1662 | + receive.await.unwrap_or_default() | |
| 1663 | + } | |
| 1664 | + | |
| 1665 | + pub async fn healthy(&self) -> bool { | |
| 1666 | + let (reply, receive) = oneshot::channel(); | |
| 1667 | + if self.tx.send(Message::Health { reply }).is_err() { | |
| 1668 | + return false; | |
| 1669 | + } | |
| 1670 | + receive.await.unwrap_or(false) | |
| 1671 | + } | |
| 1672 | + | |
| 1673 | + pub async fn presence(&self) -> Option<celld_logic::PresenceSnapshot> { | |
| 1674 | + let (reply, receive) = oneshot::channel(); | |
| 1675 | + self.tx.send(Message::Presence { reply }).ok()?; | |
| 1676 | + receive.await.ok() | |
| 1677 | + } | |
| 1678 | + | |
| 1679 | + async fn resident_epoch(&self, cell: String) -> Option<u64> { | |
| 1680 | + let (reply, receive) = oneshot::channel(); | |
| 1681 | + self.tx.send(Message::ResidentEpoch { cell, reply }).ok()?; | |
| 1682 | + receive.await.ok().flatten() | |
| 1683 | + } | |
| 1684 | +} | |
| 1685 | + | |
| 1686 | +/// One cell's WebSocket output gate: an ordered queue of write barriers. | |
| 1687 | +#[derive(Default)] | |
| 1688 | +struct WsGate { | |
| 1689 | + barriers: VecDeque<WsBarrier>, | |
| 1690 | +} | |
| 1691 | + | |
| 1692 | +/// One `webSocketMessage` batch and the outbound frames held behind it. | |
| 1693 | +/// `settled` is `None` while the verdict is outstanding, `Some(true)` once the | |
| 1694 | +/// core proved every write the frames can reveal (they may flush when this | |
| 1695 | +/// barrier reaches the front), `Some(false)` on failure (the gate breaks). | |
| 1696 | +/// | |
| 1697 | +/// Every batch gets its own barrier, including one that wrote nothing: the core | |
| 1698 | +/// decides what it trails, because only the core knows the writes other | |
| 1699 | +/// channels have outstanding on this cell. The queue keeps them in arrival | |
| 1700 | +/// order and drains only from the front, so a barrier settled early cannot | |
| 1701 | +/// overtake one still waiting. | |
| 1702 | +struct WsBarrier { | |
| 1703 | + request: u64, | |
| 1704 | + settled: Option<bool>, | |
| 1705 | + frames: Vec<(u64, WsOut)>, | |
| 1706 | +} | |
| 1707 | + | |
| 1708 | +/// The shell identity for one output held by the core. | |
| 1709 | +/// | |
| 1710 | +/// One request can hold output on multiple channels. Keeping both values in | |
| 1711 | +/// the map key prevents a later channel from replacing the first channel's | |
| 1712 | +/// waiter before the core releases it. | |
| 1713 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] | |
| 1714 | +struct HeldOutputKey { | |
| 1715 | + request: u64, | |
| 1716 | + channel: Channel, | |
| 1717 | +} | |
| 1718 | + | |
| 1719 | +impl HeldOutputKey { | |
| 1720 | + const fn websocket(request: u64) -> Self { | |
| 1721 | + Self { | |
| 1722 | + request, | |
| 1723 | + channel: Channel::WsHibernatable, | |
| 1724 | + } | |
| 1725 | + } | |
| 1726 | +} | |
| 1727 | + | |
| 1728 | +pub struct Actor { | |
| 1729 | + state: ActorState, | |
| 1730 | + pub ownership: Ownership, | |
| 1731 | + peer_http: reqwest::Client, | |
| 1732 | + peer_auth: Arc<PeerAuth>, | |
| 1733 | + paced_handoff: bool, | |
| 1734 | + handoff_directory: Arc<Mutex<HandoffDirectory>>, | |
| 1735 | + host: Option<CellHost>, | |
| 1736 | + drain_pins: DrainPinRegistry, | |
| 1737 | + /// Per-cell handoff pipeline timings, one entry per quiesce nomination. | |
| 1738 | + /// Each phase is measured from effect dispatch to its answering event, | |
| 1739 | + /// so queue time counts because that is the serial cost of the drain. | |
| 1740 | + handoff_timings: HashMap<String, HandoffCellTiming>, | |
| 1741 | + /// The in-flight pipeline step for each timed handoff operation. | |
| 1742 | + handoff_phase_ops: HashMap<OpId, (String, HandoffPhase, u64)>, | |
| 1743 | + /// The node-log manager, filled at boot once the log tier exists: | |
| 1744 | + /// the executor's RecoverNodeLog effect runs through it directly. | |
| 1745 | + pub node_log: Arc<std::sync::Mutex<Option<Arc<crate::node_log::NodeLogManager>>>>, | |
| 1746 | + region: String, | |
| 1747 | + pending: BTreeMap<u64, oneshot::Sender<Result<Routed, RequestError>>>, | |
| 1748 | + request_cells: BTreeMap<u64, String>, | |
| 1749 | + handoff_accepts: BTreeMap<u64, (String, HandoffAcceptWaiter)>, | |
| 1750 | + route_timings: BTreeMap<String, CellRouteTiming>, | |
| 1751 | + pending_workers: BTreeMap<u64, oneshot::Sender<WorkerRouted>>, | |
| 1752 | + eviction_waiters: BTreeMap<String, Vec<oneshot::Sender<()>>>, | |
| 1753 | + durability_waiters: BTreeMap<u64, (String, Vec<oneshot::Sender<()>>)>, | |
| 1754 | + eviction_stops: BTreeMap<u64, Vec<oneshot::Sender<()>>>, | |
| 1755 | + /// Outputs held by the gate, keyed by request and channel. Every output but | |
| 1756 | + /// a captured `WsHibernatable` frame waits here for the core's `Release`. | |
| 1757 | + gated_responses: BTreeMap<HeldOutputKey, oneshot::Sender<Result<(), RequestError>>>, | |
| 1758 | + /// Per-cell WebSocket output gate: a FIFO of write barriers, each holding | |
| 1759 | + /// the outbound frames produced up to it. The front drains in write order as | |
| 1760 | + /// durability proves, so no client ever sees a frame that trails an | |
| 1761 | + /// unproven write (the Cloudflare per-object output gate). | |
| 1762 | + ws_gates: BTreeMap<String, WsGate>, | |
| 1763 | + /// Gated `webSocketMessage` batches map each request-channel pair to its | |
| 1764 | + /// cell, so `Release` routes to the barrier queue rather than a oneshot. | |
| 1765 | + ws_gated: BTreeMap<HeldOutputKey, String>, | |
| 1766 | + published: BTreeSet<String>, | |
| 1767 | + fail_publish_once: bool, | |
| 1768 | + publishes: u64, | |
| 1769 | + stops: u64, | |
| 1770 | + pub lease_spec: NodeLeaseSpec, | |
| 1771 | + /// Whether to re-check every core invariant after every event. | |
| 1772 | + /// | |
| 1773 | + /// The check is a full scan of the cell table, so its cost grows with | |
| 1774 | + /// residency: roughly 800us per event at ten thousand resident cells, | |
| 1775 | + /// which would cap a busy node at about a thousand events a second in | |
| 1776 | + /// assertion code alone. It is a model-checking assertion, and the place | |
| 1777 | + /// it earns its keep is simulation, which can afford to run it after | |
| 1778 | + /// every event over far more schedules than production will ever see. | |
| 1779 | + /// Debug builds keep it. Release builds rely on the deterministic model, | |
| 1780 | + /// because this full-table scan is too expensive for production traffic. | |
| 1781 | + validate_invariants: bool, | |
| 1782 | + /// The counters peers rank this node by, when there is a bucket to | |
| 1783 | + /// publish them to. | |
| 1784 | + live_load: Option<Arc<crate::ownership_store::LiveLoad>>, | |
| 1785 | + /// The shed reason last reported to the log, so a latch that holds for | |
| 1786 | + /// minutes is reported once rather than on every sample. | |
| 1787 | + logged_shed_reason: Option<&'static str>, | |
| 1788 | + fence: mpsc::UnboundedSender<i32>, | |
| 1789 | + timer_slots: TimerSlots<()>, | |
| 1790 | + started: bool, | |
| 1791 | + preserving: bool, | |
| 1792 | +} | |
| 1793 | + | |
| 1794 | +/// One handoff pipeline step whose dispatch-to-completion time is measured. | |
| 1795 | +#[derive(Clone, Copy, PartialEq)] | |
| 1796 | +enum HandoffPhase { | |
| 1797 | + Durability, | |
| 1798 | + Stop, | |
| 1799 | + Release, | |
| 1800 | + Adopt, | |
| 1801 | +} | |
| 1802 | + | |
| 1803 | +/// The accumulating phase durations for one quiescing cell's handoff. | |
| 1804 | +struct HandoffCellTiming { | |
| 1805 | + nominated_mono_ms: u64, | |
| 1806 | + quiesce_us: Option<u64>, | |
| 1807 | + durability_us: Option<u64>, | |
| 1808 | + stop_us: Option<u64>, | |
| 1809 | + release_us: Option<u64>, | |
| 1810 | +} | |
| 1811 | + | |
| 1812 | +#[derive(Default)] | |
| 1813 | +struct HandoffDirectory { | |
| 1814 | + sampled_at_mono_ms: Option<u64>, | |
| 1815 | + peers: Vec<CapacityPeer>, | |
| 1816 | +} | |
| 1817 | + | |
| 1818 | +const HANDOFF_DIRECTORY_MAX_AGE_MS: u64 = 500; | |
| 1819 | +const HANDOFF_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(250); | |
| 1820 | + | |
| 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. | |
| 1823 | +fn handoff_tie_break(cell: &str, node: &str) -> u64 { | |
| 1824 | + let mut hash = 0xcbf2_9ce4_8422_2325_u64; | |
| 1825 | + for byte in cell | |
| 1826 | + .as_bytes() | |
| 1827 | + .iter() | |
| 1828 | + .copied() | |
| 1829 | + .chain(std::iter::once(0xff)) | |
| 1830 | + .chain(node.as_bytes().iter().copied()) | |
| 1831 | + { | |
| 1832 | + hash ^= u64::from(byte); | |
| 1833 | + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); | |
| 1834 | + } | |
| 1835 | + hash | |
| 1836 | +} | |
| 1837 | + | |
| 1838 | +async fn handoff_candidates( | |
| 1839 | + ownership: &Ownership, | |
| 1840 | + directory: &Arc<Mutex<HandoffDirectory>>, | |
| 1841 | + source: &str, | |
| 1842 | + cell: &str, | |
| 1843 | +) -> Result<Vec<CapacityPeer>, Failure> { | |
| 1844 | + let mut directory = directory.lock().await; | |
| 1845 | + let now_mono_ms = crate::asyncrt::mono_ms(); | |
| 1846 | + let stale = directory | |
| 1847 | + .sampled_at_mono_ms | |
| 1848 | + .is_none_or(|sampled| now_mono_ms.saturating_sub(sampled) >= HANDOFF_DIRECTORY_MAX_AGE_MS); | |
| 1849 | + if stale { | |
| 1850 | + directory.peers = ownership.read_capacity_peers().await?; | |
| 1851 | + directory.sampled_at_mono_ms = Some(now_mono_ms); | |
| 1852 | + } | |
| 1853 | + let current_ms = now_ms(); | |
| 1854 | + let mut peers: Vec<_> = directory | |
| 1855 | + .peers | |
| 1856 | + .iter() | |
| 1857 | + .filter(|peer| { | |
| 1858 | + peer.node != source | |
| 1859 | + && peer.expires_ms > current_ms | |
| 1860 | + && !peer.addr.is_empty() | |
| 1861 | + && peer.peer_protocol == peer_auth::PROTOCOL_VERSION | |
| 1862 | + && peer.sampled_ms != 0 | |
| 1863 | + && !peer.pressured | |
| 1864 | + && peer.paced_handoff | |
| 1865 | + }) | |
| 1866 | + .cloned() | |
| 1867 | + .collect(); | |
| 1868 | + peers.sort_by_key(|peer| { | |
| 1869 | + ( | |
| 1870 | + peer.resident_cells, | |
| 1871 | + peer.host_websockets, | |
| 1872 | + peer.rss_bytes, | |
| 1873 | + handoff_tie_break(cell, &peer.node), | |
| 1874 | + peer.node.clone(), | |
| 1875 | + ) | |
| 1876 | + }); | |
| 1877 | + Ok(peers) | |
| 1878 | +} | |
| 1879 | + | |
| 1880 | +pub enum HandoffAttempt { | |
| 1881 | + Accepted(AdoptedCell), | |
| 1882 | + CurrentOwner(AdoptedCell), | |
| 1883 | + Refused, | |
| 1884 | +} | |
| 1885 | + | |
| 1886 | +async fn request_peer_handoff( | |
| 1887 | + http: &reqwest::Client, | |
| 1888 | + auth: &PeerAuth, | |
| 1889 | + peer: &AdoptedCell, | |
| 1890 | + request: &HandoffRequest, | |
| 1891 | +) -> anyhow::Result<HandoffAttempt> { | |
| 1892 | + let path = "/peer/handoff"; | |
| 1893 | + let body = serde_json::to_vec(request)?; | |
| 1894 | + let outbound = auth.sign( | |
| 1895 | + http.post(format!("http://{}{path}", peer.addr)), | |
| 1896 | + "POST", | |
| 1897 | + path, | |
| 1898 | + &body, | |
| 1899 | + &peer.node, | |
| 1900 | + )?; | |
| 1901 | + let response = outbound.body(body).send().await?; | |
| 1902 | + peer_auth::validate_response(response.headers())?; | |
| 1903 | + let status = response.status(); | |
| 1904 | + let response: HandoffResponse = match response.json().await { | |
| 1905 | + Ok(response) => response, | |
| 1906 | + Err(_) => return Ok(HandoffAttempt::Refused), | |
| 1907 | + }; | |
| 1908 | + let owner = AdoptedCell { | |
| 1909 | + node: response.node, | |
| 1910 | + addr: response.addr, | |
| 1911 | + epoch: response.epoch, | |
| 1912 | + peer_protocol: response.peer_protocol, | |
| 1913 | + }; | |
| 1914 | + if status == reqwest::StatusCode::OK && response.published { | |
| 1915 | + Ok(HandoffAttempt::Accepted(owner)) | |
| 1916 | + } else if status == reqwest::StatusCode::CONFLICT && !response.published { | |
| 1917 | + Ok(HandoffAttempt::CurrentOwner(owner)) | |
| 1918 | + } else { | |
| 1919 | + Ok(HandoffAttempt::Refused) | |
| 1920 | + } | |
| 1921 | +} | |
| 1922 | + | |
| 1923 | +pub struct AdmissionLimits { | |
| 1924 | + pub resident: usize, | |
| 1925 | + pub activations: usize, | |
| 1926 | + pub evictions: usize, | |
| 1927 | + pub releases: usize, | |
| 1928 | +} | |
| 1929 | + | |
| 1930 | +pub struct ActorIdentity { | |
| 1931 | + pub node: String, | |
| 1932 | + pub advertise: String, | |
| 1933 | + pub region: String, | |
| 1934 | +} | |
| 1935 | + | |
| 1936 | +pub struct ActorServices { | |
| 1937 | + pub runtime: Option<RuntimeManager>, | |
| 1938 | + pub drain_pins: DrainPinRegistry, | |
| 1939 | + pub ownership: Option<Ownership>, | |
| 1940 | + pub peer_http: reqwest::Client, | |
| 1941 | + pub peer_auth: Arc<PeerAuth>, | |
| 1942 | + pub paced_handoff: bool, | |
| 1943 | +} | |
| 1944 | + | |
| 1945 | +struct ActorHostServices { | |
| 1946 | + host: Option<CellHost>, | |
| 1947 | + drain_pins: DrainPinRegistry, | |
| 1948 | + ownership: Option<Ownership>, | |
| 1949 | + peer_http: reqwest::Client, | |
| 1950 | + peer_auth: Arc<PeerAuth>, | |
| 1951 | + paced_handoff: bool, | |
| 1952 | +} | |
| 1953 | + | |
| 1954 | +impl Actor { | |
| 1955 | + pub async fn from_environment( | |
| 1956 | + limits: AdmissionLimits, | |
| 1957 | + fail_publish_once: bool, | |
| 1958 | + fence: mpsc::UnboundedSender<i32>, | |
| 1959 | + runtime: Option<RuntimeManager>, | |
| 1960 | + ownership: Option<Ownership>, | |
| 1961 | + identity: ActorIdentity, | |
| 1962 | + resume_generation: Option<String>, | |
| 1963 | + ) -> anyhow::Result<Self> { | |
| 1964 | + let peer_auth = Arc::new(PeerAuth::new([0; 32], identity.node.clone())?); | |
| 1965 | + Self::from_environment_with_cell_host( | |
| 1966 | + limits, | |
| 1967 | + fail_publish_once, | |
| 1968 | + fence, | |
| 1969 | + ActorHostServices { | |
| 1970 | + host: runtime.map(CellHost::V8), | |
| 1971 | + drain_pins: DrainPinRegistry::default(), | |
| 1972 | + ownership, | |
| 1973 | + peer_http: reqwest::Client::new(), | |
| 1974 | + peer_auth, | |
| 1975 | + paced_handoff: false, | |
| 1976 | + }, | |
| 1977 | + identity, | |
| 1978 | + resume_generation, | |
| 1979 | + ) | |
| 1980 | + .await | |
| 1981 | + } | |
| 1982 | + | |
| 1983 | + pub async fn from_environment_with_services( | |
| 1984 | + limits: AdmissionLimits, | |
| 1985 | + fail_publish_once: bool, | |
| 1986 | + fence: mpsc::UnboundedSender<i32>, | |
| 1987 | + services: ActorServices, | |
| 1988 | + identity: ActorIdentity, | |
| 1989 | + resume_generation: Option<String>, | |
| 1990 | + ) -> anyhow::Result<Self> { | |
| 1991 | + let ActorServices { | |
| 1992 | + runtime, | |
| 1993 | + drain_pins, | |
| 1994 | + ownership, | |
| 1995 | + peer_http, | |
| 1996 | + peer_auth, | |
| 1997 | + paced_handoff, | |
| 1998 | + } = services; | |
| 1999 | + Self::from_environment_with_cell_host( | |
| 2000 | + limits, | |
| 2001 | + fail_publish_once, | |
| 2002 | + fence, | |
| 2003 | + ActorHostServices { | |
| 2004 | + host: runtime.map(CellHost::V8), | |
| 2005 | + drain_pins, | |
| 2006 | + ownership, | |
| 2007 | + peer_http, | |
| 2008 | + peer_auth, | |
| 2009 | + paced_handoff, | |
| 2010 | + }, | |
| 2011 | + identity, | |
| 2012 | + resume_generation, | |
| 2013 | + ) | |
| 2014 | + .await | |
| 2015 | + } | |
| 2016 | + | |
| 2017 | + #[cfg(all(test, celld_internal_tests))] | |
| 2018 | + pub(crate) async fn from_environment_with_scripted_host( | |
| 2019 | + limits: AdmissionLimits, | |
| 2020 | + fail_publish_once: bool, | |
| 2021 | + fence: mpsc::UnboundedSender<i32>, | |
| 2022 | + host: crate::conformance_sim_cell_host::SimCellHost, | |
| 2023 | + ownership: Option<Ownership>, | |
| 2024 | + identity: ActorIdentity, | |
| 2025 | + resume_generation: Option<String>, | |
| 2026 | + ) -> anyhow::Result<Self> { | |
| 2027 | + let peer_auth = Arc::new(PeerAuth::new([0; 32], identity.node.clone())?); | |
| 2028 | + Self::from_environment_with_cell_host( | |
| 2029 | + limits, | |
| 2030 | + fail_publish_once, | |
| 2031 | + fence, | |
| 2032 | + ActorHostServices { | |
| 2033 | + host: Some(CellHost::Scripted(host)), | |
| 2034 | + drain_pins: DrainPinRegistry::default(), | |
| 2035 | + ownership, | |
| 2036 | + peer_http: reqwest::Client::new(), | |
| 2037 | + peer_auth, | |
| 2038 | + paced_handoff: false, | |
| 2039 | + }, | |
| 2040 | + identity, | |
| 2041 | + resume_generation, | |
| 2042 | + ) | |
| 2043 | + .await | |
| 2044 | + } | |
| 2045 | + | |
| 2046 | + async fn from_environment_with_cell_host( | |
| 2047 | + limits: AdmissionLimits, | |
| 2048 | + fail_publish_once: bool, | |
| 2049 | + fence: mpsc::UnboundedSender<i32>, | |
| 2050 | + services: ActorHostServices, | |
| 2051 | + identity: ActorIdentity, | |
| 2052 | + resume_generation: Option<String>, | |
| 2053 | + ) -> anyhow::Result<Self> { | |
| 2054 | + let ActorHostServices { | |
| 2055 | + host, | |
| 2056 | + drain_pins, | |
| 2057 | + ownership, | |
| 2058 | + peer_http, | |
| 2059 | + peer_auth, | |
| 2060 | + paced_handoff, | |
| 2061 | + } = services; | |
| 2062 | + let ActorIdentity { | |
| 2063 | + node, | |
| 2064 | + advertise, | |
| 2065 | + region, | |
| 2066 | + } = identity; | |
| 2067 | + let ownership = if let Some(ownership) = ownership { | |
| 2068 | + ownership | |
| 2069 | + } else { | |
| 2070 | + Ownership::Memory(Arc::new(Mutex::new(MemoryOwnership { | |
| 2071 | + node: node.clone(), | |
| 2072 | + owners: BTreeMap::new(), | |
| 2073 | + leases: BTreeMap::new(), | |
| 2074 | + next_etag: 1, | |
| 2075 | + }))) | |
| 2076 | + }; | |
| 2077 | + let live_load = match &ownership { | |
| 2078 | + Ownership::Bucket(bucket) => Some(bucket.live()), | |
| 2079 | + Ownership::Memory(_) => None, | |
| 2080 | + }; | |
| 2081 | + if let Some(live) = &live_load { | |
| 2082 | + crate::ownership_store::set_node_load(live.clone()); | |
| 2083 | + } | |
| 2084 | + let process_generation = match &ownership { | |
| 2085 | + Ownership::Bucket(bucket) => bucket | |
| 2086 | + .process_generation() | |
| 2087 | + .map(str::to_owned) | |
| 2088 | + .unwrap_or_else(random_process_generation), | |
| 2089 | + Ownership::Memory(_) => random_process_generation(), | |
| 2090 | + }; | |
| 2091 | + let ttl_ms = crate::env_vars::positive_or("CELLD_TTL_MS", 10_000)?; | |
| 2092 | + let lease_spec = NodeLeaseSpec { | |
| 2093 | + // Startup has already resolved the environment and CLI settings | |
| 2094 | + // into this validated internal address. Reading the environment | |
| 2095 | + // again would let CELLD_ADVERTISE override a later CLI option and | |
| 2096 | + // publish an address that the bound listener did not validate. | |
| 2097 | + addr: advertise, | |
| 2098 | + peer_protocol: peer_auth::PROTOCOL_VERSION, | |
| 2099 | + generation: std::env::var("CELLD_TEST_GENERATION").unwrap_or(process_generation), | |
| 2100 | + resume_generation, | |
| 2101 | + ttl_ms, | |
| 2102 | + }; | |
| 2103 | + Ok(Self { | |
| 2104 | + node_log: Arc::new(std::sync::Mutex::new(None)), | |
| 2105 | + state: ActorState::from(State::new( | |
| 2106 | + node, | |
| 2107 | + Config { | |
| 2108 | + max_resident: limits.resident, | |
| 2109 | + max_activations: limits.activations, | |
| 2110 | + max_evictions: limits.evictions, | |
| 2111 | + max_releases: limits.releases, | |
| 2112 | + alarm_resident_ms: crate::wake::resident_ms().max(0) as u64, | |
| 2113 | + require_node_lease: true, | |
| 2114 | + peer_protocol: crate::peer_auth::PROTOCOL_VERSION, | |
| 2115 | + operation_deadline_ms: Some(operation_deadline_ms()?), | |
| 2116 | + idle_evict_ms: crate::env_vars::positive::<u64>("CELLD_IDLE_EVICT_S")? | |
| 2117 | + .map(|seconds| seconds.saturating_mul(1_000)), | |
| 2118 | + pressure: pressure_config_from_environment()?, | |
| 2119 | + max_outbound_websockets: crate::env_vars::positive_or( | |
| 2120 | + "CELLD_MAX_OUTBOUND_WEBSOCKETS", | |
| 2121 | + DEFAULT_MAX_OUTBOUND_WEBSOCKETS, | |
| 2122 | + )?, | |
| 2123 | + ownership_on_evict: match &ownership { | |
| 2124 | + // Releasing a cell says "any node may take this | |
| 2125 | + // one", which is only true if some other node could | |
| 2126 | + // restore it. Without a bucket the sole copy is this | |
| 2127 | + // node's disk, keyed to an epoch a re-acquire will | |
| 2128 | + // step past, so releasing would lose the cell. | |
| 2129 | + Ownership::Memory(_) => OwnershipOnEvict::Sticky, | |
| 2130 | + Ownership::Bucket(_) => ownership_on_evict_from_environment()?, | |
| 2131 | + }, | |
| 2132 | + }, | |
| 2133 | + )), | |
| 2134 | + ownership, | |
| 2135 | + peer_http, | |
| 2136 | + peer_auth, | |
| 2137 | + paced_handoff, | |
| 2138 | + handoff_directory: Arc::new(Mutex::new(HandoffDirectory::default())), | |
| 2139 | + host, | |
| 2140 | + drain_pins, | |
| 2141 | + handoff_timings: HashMap::new(), | |
| 2142 | + handoff_phase_ops: HashMap::new(), | |
| 2143 | + region, | |
| 2144 | + pending: BTreeMap::new(), | |
| 2145 | + request_cells: BTreeMap::new(), | |
| 2146 | + handoff_accepts: BTreeMap::new(), | |
| 2147 | + route_timings: BTreeMap::new(), | |
| 2148 | + pending_workers: BTreeMap::new(), | |
| 2149 | + eviction_waiters: BTreeMap::new(), | |
| 2150 | + durability_waiters: BTreeMap::new(), | |
| 2151 | + gated_responses: BTreeMap::new(), | |
| 2152 | + ws_gates: BTreeMap::new(), | |
| 2153 | + ws_gated: BTreeMap::new(), | |
| 2154 | + eviction_stops: BTreeMap::new(), | |
| 2155 | + published: BTreeSet::new(), | |
| 2156 | + fail_publish_once, | |
| 2157 | + publishes: 0, | |
| 2158 | + stops: 0, | |
| 2159 | + lease_spec, | |
| 2160 | + live_load, | |
| 2161 | + logged_shed_reason: None, | |
| 2162 | + validate_invariants: cfg!(debug_assertions), | |
| 2163 | + fence, | |
| 2164 | + timer_slots: TimerSlots::default(), | |
| 2165 | + started: false, | |
| 2166 | + preserving: false, | |
| 2167 | + }) | |
| 2168 | + } | |
| 2169 | + | |
| 2170 | + /// Emits the exactly-once pre-loop node-lease transition. | |
| 2171 | + pub fn start(&mut self, out: &mut StepOutput) { | |
| 2172 | + assert!(!self.started, "Actor::start was called more than once"); | |
| 2173 | + self.started = true; | |
| 2174 | + self.drive( | |
| 2175 | + Event::StartNodeLease { | |
| 2176 | + now_ms: now_ms(), | |
| 2177 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2178 | + spec: self.lease_spec.clone(), | |
| 2179 | + }, | |
| 2180 | + out, | |
| 2181 | + ); | |
| 2182 | + } | |
| 2183 | + | |
| 2184 | + /// Handles exactly one ready mailbox item, completion, or timer. | |
| 2185 | + pub fn step(&mut self, input: ActorInput, out: &mut StepOutput) { | |
| 2186 | + assert!(self.started, "Actor::step was called before Actor::start"); | |
| 2187 | + match input { | |
| 2188 | + ActorInput::Message(message) => self.handle_message(message, out), | |
| 2189 | + ActorInput::Completed(completed) => { | |
| 2190 | + let route_cell = completed.timing.as_ref().map(|timing| timing.cell.clone()); | |
| 2191 | + if let Some(timing) = completed.timing { | |
| 2192 | + self.record_effect_timing(timing); | |
| 2193 | + } | |
| 2194 | + self.drive(completed.event, out); | |
| 2195 | + if let Some(cell) = route_cell { | |
| 2196 | + self.observe_capacity_wait(&cell); | |
| 2197 | + } | |
| 2198 | + } | |
| 2199 | + ActorInput::TimerFired(timer) => { | |
| 2200 | + self.timer_slots.clear_slot(&TimerSlot::of(&timer)); | |
| 2201 | + if self.preserving && matches!(timer, Timer::CellAlarm { .. }) { | |
| 2202 | + return; | |
| 2203 | + } | |
| 2204 | + self.drive( | |
| 2205 | + Event::TimerFired { | |
| 2206 | + timer, | |
| 2207 | + now_ms: now_ms(), | |
| 2208 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2209 | + }, | |
| 2210 | + out, | |
| 2211 | + ); | |
| 2212 | + } | |
| 2213 | + } | |
| 2214 | + } | |
| 2215 | + | |
| 2216 | + fn handle_message(&mut self, message: Message, out: &mut StepOutput) { | |
| 2217 | + match message { | |
| 2218 | + Message::BeginPreserve => { | |
| 2219 | + self.preserving = true; | |
| 2220 | + self.drive(Event::BeginPreserve, out); | |
| 2221 | + } | |
| 2222 | + Message::Request { reply, .. } if self.preserving => { | |
| 2223 | + let _ = reply.send(Err(RequestError::NodeFenced)); | |
| 2224 | + } | |
| 2225 | + Message::Request { | |
| 2226 | + request, | |
| 2227 | + cell, | |
| 2228 | + capacity_handoff, | |
| 2229 | + handoff_accept, | |
| 2230 | + websocket, | |
| 2231 | + reply, | |
| 2232 | + } => { | |
| 2233 | + let retired_durability = match self.state.phase(&cell) { | |
| 2234 | + Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 2235 | + _ => None, | |
| 2236 | + }; | |
| 2237 | + self.pending.insert(request, reply); | |
| 2238 | + let ownership_handoff = handoff_accept.is_some(); | |
| 2239 | + if let Some(waiter) = handoff_accept { | |
| 2240 | + self.handoff_accepts.insert(request, (cell.clone(), waiter)); | |
| 2241 | + } | |
| 2242 | + self.begin_route_if_cold(&cell); | |
| 2243 | + self.request_cells.insert(request, cell.clone()); | |
| 2244 | + self.drive( | |
| 2245 | + if let Some(websocket) = websocket { | |
| 2246 | + Event::WebSocketRequestAt { | |
| 2247 | + request, | |
| 2248 | + cell: cell.clone(), | |
| 2249 | + websocket, | |
| 2250 | + now_ms: now_ms(), | |
| 2251 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2252 | + } | |
| 2253 | + } else if ownership_handoff { | |
| 2254 | + Event::HandoffRequestAt { | |
| 2255 | + request, | |
| 2256 | + cell: cell.clone(), | |
| 2257 | + now_ms: now_ms(), | |
| 2258 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2259 | + } | |
| 2260 | + } else if capacity_handoff { | |
| 2261 | + Event::CapacityRequestAt { | |
| 2262 | + request, | |
| 2263 | + cell: cell.clone(), | |
| 2264 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2265 | + } | |
| 2266 | + } else { | |
| 2267 | + Event::RequestAt { | |
| 2268 | + request, | |
| 2269 | + cell: cell.clone(), | |
| 2270 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2271 | + } | |
| 2272 | + }, | |
| 2273 | + out, | |
| 2274 | + ); | |
| 2275 | + self.observe_capacity_wait(&cell); | |
| 2276 | + if let Some(op) = retired_durability { | |
| 2277 | + if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 2278 | + for waiter in waiters { | |
| 2279 | + let _ = waiter.send(()); | |
| 2280 | + } | |
| 2281 | + } | |
| 2282 | + } | |
| 2283 | + } | |
| 2284 | + Message::CancelRoute { request } => { | |
| 2285 | + self.pending.remove(&request); | |
| 2286 | + self.handoff_accepts.remove(&request); | |
| 2287 | + if let Some(cell) = self.request_cells.remove(&request) { | |
| 2288 | + self.finish_route(&cell, "cancelled", "caller_disconnected", None); | |
| 2289 | + } | |
| 2290 | + self.drive(Event::Cancel { request }, out); | |
| 2291 | + } | |
| 2292 | + Message::WorkerRequest { reply } if self.preserving => { | |
| 2293 | + let _ = reply.send(WorkerRouted { | |
| 2294 | + request: crate::asyncrt::next_core_request(), | |
| 2295 | + route: None, | |
| 2296 | + }); | |
| 2297 | + } | |
| 2298 | + Message::WorkerRequest { reply } => { | |
| 2299 | + let request = crate::asyncrt::next_core_request(); | |
| 2300 | + self.pending_workers.insert(request, reply); | |
| 2301 | + self.drive(Event::WorkerRequest { request }, out); | |
| 2302 | + } | |
| 2303 | + Message::ReleaseAll => self.drive(Event::ReleaseAll, out), | |
| 2304 | + Message::GenerationChanged { | |
| 2305 | + generation, | |
| 2306 | + max_age_ms, | |
| 2307 | + eager_classes, | |
| 2308 | + } => self.drive( | |
| 2309 | + Event::GenerationChanged { | |
| 2310 | + generation, | |
| 2311 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2312 | + max_age_ms, | |
| 2313 | + eager_classes, | |
| 2314 | + }, | |
| 2315 | + out, | |
| 2316 | + ), | |
| 2317 | + Message::Drained { reply } => { | |
| 2318 | + let _ = reply.send(DrainStatus { | |
| 2319 | + occupied: self.state.occupied(), | |
| 2320 | + activating: self.state.activating(), | |
| 2321 | + quiescing: self.state.quiescing(), | |
| 2322 | + evicting: self.state.evicting(), | |
| 2323 | + releasing: self.state.releasing(), | |
| 2324 | + adopting: self.state.adopting(), | |
| 2325 | + handed_off: self.state.handed_off(), | |
| 2326 | + }); | |
| 2327 | + } | |
| 2328 | + Message::ResidentEpoch { cell, reply } => { | |
| 2329 | + let epoch = match self.state.phase(&cell) { | |
| 2330 | + Some(Phase::Resident { epoch }) | |
| 2331 | + | Some(Phase::EnsuringDurability { epoch, .. }) => Some(*epoch), | |
| 2332 | + _ => None, | |
| 2333 | + }; | |
| 2334 | + let _ = reply.send(epoch); | |
| 2335 | + } | |
| 2336 | + Message::SampleLoad if self.preserving => {} | |
| 2337 | + Message::SampleLoad => { | |
| 2338 | + // Counted once: it is a walk of every cell, and the latch and | |
| 2339 | + // the number peers rank this node by must agree anyway. | |
| 2340 | + let occupied = self.state.occupied(); | |
| 2341 | + let metrics = crate::asyncrt::services().sample_metrics(); | |
| 2342 | + let cpu = metrics.cpu_percent_x100; | |
| 2343 | + let load = celld_logic::pressure::Load { | |
| 2344 | + resident_cells: occupied, | |
| 2345 | + rss_bytes: metrics.rss_bytes, | |
| 2346 | + in_use_bytes: metrics.in_use_bytes, | |
| 2347 | + cgroup_working_set_bytes: metrics.cgroup_working_set_bytes, | |
| 2348 | + cgroup_current_bytes: metrics.cgroup_current_bytes, | |
| 2349 | + }; | |
| 2350 | + let now_mono_ms = crate::asyncrt::mono_ms(); | |
| 2351 | + self.drive(Event::LoadSampled { load, now_mono_ms }, out); | |
| 2352 | + // Report a change of shed reason once. `rss-hard` retains its | |
| 2353 | + // established name, but in a Linux cgroup it says | |
| 2354 | + // `memory.current` crossed the absolute cap. | |
| 2355 | + let reason = self.state.shed_reason(); | |
| 2356 | + if reason != self.logged_shed_reason { | |
| 2357 | + self.logged_shed_reason = reason; | |
| 2358 | + // How many V8 heaps the resident cells hold open. Most of | |
| 2359 | + // what a cell costs is its heap, and a heap comes back | |
| 2360 | + // only when its last cell goes, so cells alone do not say | |
| 2361 | + // how much a walk down can still return. | |
| 2362 | + let heaps = self | |
| 2363 | + .state | |
| 2364 | + .resident_isolates() | |
| 2365 | + .into_iter() | |
| 2366 | + .collect::<BTreeSet<_>>() | |
| 2367 | + .len(); | |
| 2368 | + match reason { | |
| 2369 | + Some(celld_logic::pressure::SHED_RSS_HARD) => tracing::warn!( | |
| 2370 | + rss_bytes = load.rss_bytes, | |
| 2371 | + in_use_bytes = load.in_use_bytes, | |
| 2372 | + cgroup_working_set_bytes = load.cgroup_working_set_bytes, | |
| 2373 | + cgroup_current_bytes = load.cgroup_current_bytes, | |
| 2374 | + heaps, | |
| 2375 | + "shedding on the absolute memory cap" | |
| 2376 | + ), | |
| 2377 | + Some(reason) => tracing::info!( | |
| 2378 | + reason, | |
| 2379 | + rss_bytes = load.rss_bytes, | |
| 2380 | + in_use_bytes = load.in_use_bytes, | |
| 2381 | + cgroup_working_set_bytes = load.cgroup_working_set_bytes, | |
| 2382 | + cgroup_current_bytes = load.cgroup_current_bytes, | |
| 2383 | + heaps, | |
| 2384 | + "shedding" | |
| 2385 | + ), | |
| 2386 | + None => tracing::info!("no longer shedding"), | |
| 2387 | + } | |
| 2388 | + } | |
| 2389 | + // Republish what peers rank this node by. The same numbers the | |
| 2390 | + // latch just saw: a node that reports last tick's residency | |
| 2391 | + // attracts work it has already refused. | |
| 2392 | + if let Some(live) = &self.live_load { | |
| 2393 | + live.resident_cells.store(occupied, Ordering::Relaxed); | |
| 2394 | + live.host_websockets | |
| 2395 | + .store(self.state.host_websockets(), Ordering::Relaxed); | |
| 2396 | + live.pressured | |
| 2397 | + .store(self.state.shedding(), Ordering::Relaxed); | |
| 2398 | + live.memory_headroom | |
| 2399 | + .store(self.state.memory_headroom(), Ordering::Relaxed); | |
| 2400 | + live.cpu_percent_x100.store(cpu, Ordering::Relaxed); | |
| 2401 | + live.restoring | |
| 2402 | + .store(self.state.activation_backlog() as u64, Ordering::Relaxed); | |
| 2403 | + } | |
| 2404 | + } | |
| 2405 | + Message::Output { | |
| 2406 | + request, | |
| 2407 | + channel, | |
| 2408 | + position, | |
| 2409 | + reply, | |
| 2410 | + } => { | |
| 2411 | + self.gated_responses | |
| 2412 | + .insert(HeldOutputKey { request, channel }, reply); | |
| 2413 | + self.drive( | |
| 2414 | + Event::Output { | |
| 2415 | + request, | |
| 2416 | + channel, | |
| 2417 | + position, | |
| 2418 | + }, | |
| 2419 | + out, | |
| 2420 | + ); | |
| 2421 | + } | |
| 2422 | + Message::WsOutput { | |
| 2423 | + request, | |
| 2424 | + scope, | |
| 2425 | + frames, | |
| 2426 | + write_position, | |
| 2427 | + reply, | |
| 2428 | + } => { | |
| 2429 | + // Open a barrier for every batch, then let the core decide | |
| 2430 | + // what it trails: its own write when the handler wrote, and | |
| 2431 | + // otherwise the newest write still outstanding on this cell, | |
| 2432 | + // whichever channel made it. The queue consulted here before | |
| 2433 | + // was filled in one place -- the arm below that writes -- so it | |
| 2434 | + // held only writes a `webSocketMessage` handler made itself, | |
| 2435 | + // and an HTTP, RPC, or peer write on the same cell was | |
| 2436 | + // invisible to a batch that only read. | |
| 2437 | + // | |
| 2438 | + // Both registrations happen before the drive, and must: `drive` | |
| 2439 | + // runs the effects it produces synchronously, so a read with no | |
| 2440 | + // barrier open on its cell is released inside the call below. | |
| 2441 | + // Moved after it, that `Effect::Release` would find no | |
| 2442 | + // `ws_gated` entry, fall through to the `gated_responses` map, | |
| 2443 | + // match nothing, and strand these frames behind a barrier that | |
| 2444 | + // nothing will ever settle. | |
| 2445 | + self.ws_gates | |
| 2446 | + .entry(scope.clone()) | |
| 2447 | + .or_default() | |
| 2448 | + .barriers | |
| 2449 | + .push_back(WsBarrier { | |
| 2450 | + request, | |
| 2451 | + settled: None, | |
| 2452 | + frames, | |
| 2453 | + }); | |
| 2454 | + self.ws_gated | |
| 2455 | + .insert(HeldOutputKey::websocket(request), scope); | |
| 2456 | + // The core answers for every writer on the cell, including an | |
| 2457 | + // alarm: its consuming commit opens a barrier of its own, so a | |
| 2458 | + // read-only batch trails that too. | |
| 2459 | + self.drive( | |
| 2460 | + Event::Output { | |
| 2461 | + request, | |
| 2462 | + channel: Channel::WsHibernatable, | |
| 2463 | + position: write_position, | |
| 2464 | + }, | |
| 2465 | + out, | |
| 2466 | + ); | |
| 2467 | + let _ = reply.send(()); | |
| 2468 | + } | |
| 2469 | + Message::ActivityFinished { | |
| 2470 | + request, | |
| 2471 | + cell, | |
| 2472 | + alarm_at_ms, | |
| 2473 | + alarm_covered, | |
| 2474 | + } => { | |
| 2475 | + // Folded from the old AlarmObserved-then-ActivityFinished pair the | |
| 2476 | + // activity drop sent: observe the alarm and release any retired | |
| 2477 | + // durability waiters, then finish the activity — same events, same | |
| 2478 | + // order, one message instead of two. | |
| 2479 | + let retired_durability = match self.state.phase(&cell) { | |
| 2480 | + Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 2481 | + _ => None, | |
| 2482 | + }; | |
| 2483 | + self.drive( | |
| 2484 | + Event::AlarmObserved { | |
| 2485 | + cell, | |
| 2486 | + at_ms: alarm_at_ms, | |
| 2487 | + covered: alarm_covered, | |
| 2488 | + now_ms: now_ms(), | |
| 2489 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2490 | + }, | |
| 2491 | + out, | |
| 2492 | + ); | |
| 2493 | + if let Some(op) = retired_durability { | |
| 2494 | + if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 2495 | + for waiter in waiters { | |
| 2496 | + let _ = waiter.send(()); | |
| 2497 | + } | |
| 2498 | + } | |
| 2499 | + } | |
| 2500 | + self.drive(Event::ActivityFinished { request }, out); | |
| 2501 | + } | |
| 2502 | + Message::WebSocketOpened { | |
| 2503 | + cell, | |
| 2504 | + websocket, | |
| 2505 | + kind, | |
| 2506 | + reply, | |
| 2507 | + } => { | |
| 2508 | + self.drive( | |
| 2509 | + Event::WebSocketOpened { | |
| 2510 | + cell: cell.clone(), | |
| 2511 | + websocket, | |
| 2512 | + kind, | |
| 2513 | + }, | |
| 2514 | + out, | |
| 2515 | + ); | |
| 2516 | + // The core may decline to hold the transport. Say so, rather | |
| 2517 | + // than acknowledging an open and closing the socket a moment | |
| 2518 | + // later: an application that hit a ceiling deserves to be | |
| 2519 | + // told which one, not left watching a socket disappear. | |
| 2520 | + // Only an outbound socket can be declined, and only for a | |
| 2521 | + // cell the core knows: an inbound transport is never refused, | |
| 2522 | + // and reporting one as refused fails opens that succeeded. | |
| 2523 | + let refused = kind == WebSocketKind::Outbound | |
| 2524 | + && !self.state.holds_websocket(&cell, websocket); | |
| 2525 | + let _ = reply.send(!refused); | |
| 2526 | + } | |
| 2527 | + Message::WebSocketClosed { cell, websocket } => { | |
| 2528 | + self.drive(Event::WebSocketClosed { cell, websocket }, out); | |
| 2529 | + } | |
| 2530 | + Message::AlarmObserved { | |
| 2531 | + cell, | |
| 2532 | + at_ms, | |
| 2533 | + covered, | |
| 2534 | + } => { | |
| 2535 | + let retired_durability = match self.state.phase(&cell) { | |
| 2536 | + Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 2537 | + _ => None, | |
| 2538 | + }; | |
| 2539 | + self.drive( | |
| 2540 | + Event::AlarmObserved { | |
| 2541 | + cell, | |
| 2542 | + at_ms, | |
| 2543 | + covered, | |
| 2544 | + now_ms: now_ms(), | |
| 2545 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2546 | + }, | |
| 2547 | + out, | |
| 2548 | + ); | |
| 2549 | + if let Some(op) = retired_durability { | |
| 2550 | + if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 2551 | + for waiter in waiters { | |
| 2552 | + let _ = waiter.send(()); | |
| 2553 | + } | |
| 2554 | + } | |
| 2555 | + } | |
| 2556 | + } | |
| 2557 | + Message::NudgeNodeLease => { | |
| 2558 | + self.drive( | |
| 2559 | + Event::NudgeNodeLease { | |
| 2560 | + now_ms: now_ms(), | |
| 2561 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2562 | + }, | |
| 2563 | + out, | |
| 2564 | + ); | |
| 2565 | + } | |
| 2566 | + Message::WakeHint { .. } if self.preserving => {} | |
| 2567 | + Message::WakeHint { cell } => { | |
| 2568 | + self.drive( | |
| 2569 | + Event::WakeHintAt { | |
| 2570 | + cell, | |
| 2571 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2572 | + }, | |
| 2573 | + out, | |
| 2574 | + ); | |
| 2575 | + } | |
| 2576 | + Message::Evict { reply, .. } if self.preserving => { | |
| 2577 | + let _ = reply.send(()); | |
| 2578 | + } | |
| 2579 | + Message::Evict { cell, reply } if self.state.is_active(&cell) => { | |
| 2580 | + let _ = reply.send(()); | |
| 2581 | + } | |
| 2582 | + Message::Evict { cell, reply } => match self.state.phase(&cell) { | |
| 2583 | + Some(Phase::Resident { .. }) => { | |
| 2584 | + self.eviction_waiters | |
| 2585 | + .entry(cell.clone()) | |
| 2586 | + .or_default() | |
| 2587 | + .push(reply); | |
| 2588 | + self.drive(Event::Evict { cell }, out); | |
| 2589 | + } | |
| 2590 | + Some(Phase::EnsuringDurability { op, .. }) => { | |
| 2591 | + self.durability_waiters | |
| 2592 | + .entry(*op) | |
| 2593 | + .or_insert_with(|| (cell, Vec::new())) | |
| 2594 | + .1 | |
| 2595 | + .push(reply); | |
| 2596 | + } | |
| 2597 | + Some(Phase::Cleaning { | |
| 2598 | + op, | |
| 2599 | + cause: StopCause::Evict { .. }, | |
| 2600 | + .. | |
| 2601 | + }) => { | |
| 2602 | + self.eviction_stops.entry(*op).or_default().push(reply); | |
| 2603 | + } | |
| 2604 | + _ => { | |
| 2605 | + let _ = reply.send(()); | |
| 2606 | + } | |
| 2607 | + }, | |
| 2608 | + Message::InvalidateRemote { | |
| 2609 | + cell, | |
| 2610 | + node, | |
| 2611 | + epoch, | |
| 2612 | + reply, | |
| 2613 | + } => { | |
| 2614 | + self.drive(Event::InvalidateRemote { cell, node, epoch }, out); | |
| 2615 | + let _ = reply.send(()); | |
| 2616 | + } | |
| 2617 | + Message::Snapshot { reply } => { | |
| 2618 | + let generations = self | |
| 2619 | + .state | |
| 2620 | + .residents() | |
| 2621 | + .into_iter() | |
| 2622 | + .map(|cell| { | |
| 2623 | + let generation = self.state.cell_generation(&cell).unwrap_or(0); | |
| 2624 | + (cell, generation) | |
| 2625 | + }) | |
| 2626 | + .collect(); | |
| 2627 | + let census = SwapCensus { | |
| 2628 | + swapping: self.state.swapping(), | |
| 2629 | + generations, | |
| 2630 | + }; | |
| 2631 | + let _ = reply.send((self.state_json(), self.state.drain_pins(), census)); | |
| 2632 | + } | |
| 2633 | + Message::Health { reply } => { | |
| 2634 | + let _ = reply.send(self.state.ready_to_serve()); | |
| 2635 | + } | |
| 2636 | + Message::Presence { reply } => { | |
| 2637 | + let _ = reply.send(self.state.presence_snapshot()); | |
| 2638 | + } | |
| 2639 | + } | |
| 2640 | + } | |
| 2641 | + | |
| 2642 | + /// Settle a gated `webSocketMessage`'s durability. On success mark its | |
| 2643 | + /// barrier durable and flush the durable prefix in write order; on failure | |
| 2644 | + /// break the whole cell gate — drop every held frame and reset its sockets, | |
| 2645 | + /// since an unproven write must never leave an acknowledged trace. | |
| 2646 | + fn ws_release(&mut self, held: HeldOutputKey, ok: bool) { | |
| 2647 | + let Some(scope) = self.ws_gated.remove(&held) else { | |
| 2648 | + return; | |
| 2649 | + }; | |
| 2650 | + let mut flush = Vec::new(); | |
| 2651 | + let broke = { | |
| 2652 | + let Some(gate) = self.ws_gates.get_mut(&scope) else { | |
| 2653 | + return; | |
| 2654 | + }; | |
| 2655 | + if let Some(barrier) = gate.barriers.iter_mut().find(|b| b.request == held.request) { | |
| 2656 | + barrier.settled = Some(ok); | |
| 2657 | + } | |
| 2658 | + if gate.barriers.iter().any(|b| b.settled == Some(false)) { | |
| 2659 | + true | |
| 2660 | + } else { | |
| 2661 | + while gate | |
| 2662 | + .barriers | |
| 2663 | + .front() | |
| 2664 | + .is_some_and(|b| b.settled == Some(true)) | |
| 2665 | + { | |
| 2666 | + flush.push(gate.barriers.pop_front().unwrap().frames); | |
| 2667 | + } | |
| 2668 | + false | |
| 2669 | + } | |
| 2670 | + }; | |
| 2671 | + if broke { | |
| 2672 | + self.ws_gates.remove(&scope); | |
| 2673 | + self.ws_gated.retain(|_, s| *s != scope); | |
| 2674 | + crate::js::ws_close_scope(&scope, 1011, "durability unproven"); | |
| 2675 | + return; | |
| 2676 | + } | |
| 2677 | + for frames in flush { | |
| 2678 | + crate::js::ws_emit_batch(frames); | |
| 2679 | + } | |
| 2680 | + if self | |
| 2681 | + .ws_gates | |
| 2682 | + .get(&scope) | |
| 2683 | + .is_some_and(|g| g.barriers.is_empty()) | |
| 2684 | + { | |
| 2685 | + self.ws_gates.remove(&scope); | |
| 2686 | + } | |
| 2687 | + } | |
| 2688 | + | |
| 2689 | + /// Close a timed handoff pipeline step when its answering event arrives, | |
| 2690 | + /// and emit the cell's aggregate timing once adoption succeeds. A failed | |
| 2691 | + /// adoption keeps the cell entry so its retry accumulates on the same | |
| 2692 | + /// record; an expired operation abandons its pipeline entirely. | |
| 2693 | + fn close_handoff_phase(&mut self, event: &Event) { | |
| 2694 | + let (op, adopted) = match event { | |
| 2695 | + Event::DurabilityChecked { op, .. } | |
| 2696 | + | Event::RuntimeStopped { op } | |
| 2697 | + | Event::OwnerReleased { op, .. } => (*op, None), | |
| 2698 | + Event::SuccessorAdopted { op, result } => (*op, Some(result.is_ok())), | |
| 2699 | + Event::TimerFired { | |
| 2700 | + timer: Timer::OperationDeadline { op }, | |
| 2701 | + .. | |
| 2702 | + } => { | |
| 2703 | + if let Some((cell, _, _)) = self.handoff_phase_ops.remove(op) { | |
| 2704 | + self.handoff_timings.remove(&cell); | |
| 2705 | + } | |
| 2706 | + return; | |
| 2707 | + } | |
| 2708 | + _ => return, | |
| 2709 | + }; | |
| 2710 | + let Some((cell, phase, started_mono_ms)) = self.handoff_phase_ops.remove(&op) else { | |
| 2711 | + return; | |
| 2712 | + }; | |
| 2713 | + let elapsed = mono_elapsed_us(started_mono_ms); | |
| 2714 | + if phase == HandoffPhase::Adopt { | |
| 2715 | + if adopted == Some(true) { | |
| 2716 | + if let Some(timing) = self.handoff_timings.remove(&cell) { | |
| 2717 | + tracing::info!( | |
| 2718 | + event = "cell_handoff_timing", | |
| 2719 | + %cell, | |
| 2720 | + quiesce_us = timing.quiesce_us.unwrap_or(0), | |
| 2721 | + durability_us = timing.durability_us.unwrap_or(0), | |
| 2722 | + stop_us = timing.stop_us.unwrap_or(0), | |
| 2723 | + release_us = timing.release_us.unwrap_or(0), | |
| 2724 | + adopt_us = elapsed, | |
| 2725 | + total_us = mono_elapsed_us(timing.nominated_mono_ms), | |
| 2726 | + "handoff pipeline completed" | |
| 2727 | + ); | |
| 2728 | + } | |
| 2729 | + } | |
| 2730 | + return; | |
| 2731 | + } | |
| 2732 | + let Some(timing) = self.handoff_timings.get_mut(&cell) else { | |
| 2733 | + return; | |
| 2734 | + }; | |
| 2735 | + match phase { | |
| 2736 | + HandoffPhase::Durability => timing.durability_us = Some(elapsed), | |
| 2737 | + HandoffPhase::Stop => timing.stop_us = Some(elapsed), | |
| 2738 | + HandoffPhase::Release => timing.release_us = Some(elapsed), | |
| 2739 | + HandoffPhase::Adopt => {} | |
| 2740 | + } | |
| 2741 | + } | |
| 2742 | + | |
| 2743 | + fn drive(&mut self, first: Event, out: &mut StepOutput) { | |
| 2744 | + let mut events = VecDeque::from([first]); | |
| 2745 | + while let Some(event) = events.pop_front() { | |
| 2746 | + self.close_handoff_phase(&event); | |
| 2747 | + let durability = match &event { | |
| 2748 | + Event::DurabilityChecked { op, .. } => Some(*op), | |
| 2749 | + // A deadline resolves the same operation the proof would | |
| 2750 | + // have, so it has to release the same waiters. Without this | |
| 2751 | + // the core abandons the eviction and the caller that asked | |
| 2752 | + // for it stays blocked on a proof that is no longer coming. | |
| 2753 | + Event::TimerFired { | |
| 2754 | + timer: Timer::OperationDeadline { op }, | |
| 2755 | + .. | |
| 2756 | + } => Some(*op), | |
| 2757 | + _ => None, | |
| 2758 | + }; | |
| 2759 | + let stopped = match &event { | |
| 2760 | + Event::RuntimeStopped { op } => Some(*op), | |
| 2761 | + _ => None, | |
| 2762 | + }; | |
| 2763 | + let effects = apply_core_event(&mut self.state, event); | |
| 2764 | + if let Some(op) = durability { | |
| 2765 | + if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 2766 | + let stop = effects.iter().find_map(|effect| match effect { | |
| 2767 | + Effect::StopRuntime { | |
| 2768 | + op, | |
| 2769 | + cause: StopCause::Evict { .. }, | |
| 2770 | + .. | |
| 2771 | + } => Some(*op), | |
| 2772 | + _ => None, | |
| 2773 | + }); | |
| 2774 | + if let Some(stop) = stop { | |
| 2775 | + self.eviction_stops.entry(stop).or_default().extend(waiters); | |
| 2776 | + } else { | |
| 2777 | + for waiter in waiters { | |
| 2778 | + let _ = waiter.send(()); | |
| 2779 | + } | |
| 2780 | + } | |
| 2781 | + } | |
| 2782 | + } | |
| 2783 | + for effect in effects { | |
| 2784 | + self.execute(effect, &mut events, out); | |
| 2785 | + } | |
| 2786 | + self.settle_handoff_accepts(); | |
| 2787 | + if let Some(op) = stopped { | |
| 2788 | + if let Some(waiters) = self.eviction_stops.remove(&op) { | |
| 2789 | + for waiter in waiters { | |
| 2790 | + let _ = waiter.send(()); | |
| 2791 | + } | |
| 2792 | + } | |
| 2793 | + } | |
| 2794 | + if self.validate_invariants { | |
| 2795 | + self.state.validate().expect("celld core invariant"); | |
| 2796 | + } | |
| 2797 | + } | |
| 2798 | + } | |
| 2799 | + | |
| 2800 | + fn settle_handoff_accepts(&mut self) { | |
| 2801 | + let accepted: Vec<_> = self | |
| 2802 | + .handoff_accepts | |
| 2803 | + .iter() | |
| 2804 | + .filter_map(|(request, (cell, waiter))| { | |
| 2805 | + self.state | |
| 2806 | + .accepted_epoch(cell) | |
| 2807 | + .filter(|epoch| *epoch > waiter.released_epoch) | |
| 2808 | + .map(|epoch| (*request, epoch)) | |
| 2809 | + }) | |
| 2810 | + .collect(); | |
| 2811 | + for (request, epoch) in accepted { | |
| 2812 | + let Some((_, waiter)) = self.handoff_accepts.remove(&request) else { | |
| 2813 | + continue; | |
| 2814 | + }; | |
| 2815 | + let _ = waiter.reply.send(AdoptedCell { | |
| 2816 | + node: self.state.node().to_string(), | |
| 2817 | + addr: self.lease_spec.addr.clone(), | |
| 2818 | + epoch, | |
| 2819 | + peer_protocol: peer_auth::PROTOCOL_VERSION, | |
| 2820 | + }); | |
| 2821 | + } | |
| 2822 | + } | |
| 2823 | + | |
| 2824 | + fn execute(&mut self, effect: Effect, immediate: &mut VecDeque<Event>, out: &mut StepOutput) { | |
| 2825 | + match effect { | |
| 2826 | + Effect::ScheduleTimer { timer, at_mono_ms } => { | |
| 2827 | + let (arm, _) = self.timer_slots.arm(timer, at_mono_ms, ()); | |
| 2828 | + out.timers.push(arm); | |
| 2829 | + } | |
| 2830 | + Effect::ReadSelfNodeLease { op } => { | |
| 2831 | + let ownership = self.ownership.clone(); | |
| 2832 | + let node = self.state.node().to_string(); | |
| 2833 | + out.effects.push(Box::pin(async move { | |
| 2834 | + let result = ownership.read_self_node_lease(&node).await; | |
| 2835 | + CompletedEffect::plain(Event::SelfNodeLeaseRead { | |
| 2836 | + op, | |
| 2837 | + now_ms: now_ms(), | |
| 2838 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2839 | + result, | |
| 2840 | + }) | |
| 2841 | + })); | |
| 2842 | + } | |
| 2843 | + Effect::CasNodeLease { | |
| 2844 | + op, | |
| 2845 | + guard, | |
| 2846 | + record, | |
| 2847 | + authority_expires_ms, | |
| 2848 | + } => { | |
| 2849 | + let ownership = self.ownership.clone(); | |
| 2850 | + out.effects.push(Box::pin(async move { | |
| 2851 | + let attempt_started_mono_ms = crate::asyncrt::mono_ms(); | |
| 2852 | + let node = record.node.clone(); | |
| 2853 | + let candidate_expires_ms = record.expires_ms; | |
| 2854 | + // Logged before the CAS: with only the completion line, a | |
| 2855 | + // renewal hung on a storage tail is indistinguishable from | |
| 2856 | + // a timer that never fired (the n6 fence, 2026-08-11). | |
| 2857 | + tracing::info!( | |
| 2858 | + event = "node_lease_attempt_started", | |
| 2859 | + %node, | |
| 2860 | + attempt = if authority_expires_ms.is_some() { | |
| 2861 | + "renew" | |
| 2862 | + } else { | |
| 2863 | + "acquire" | |
| 2864 | + }, | |
| 2865 | + prior_authority_headroom_ms = authority_expires_ms | |
| 2866 | + .map(|expires_ms| expires_ms.saturating_sub(now_ms())) | |
| 2867 | + .unwrap_or(0), | |
| 2868 | + "node lease attempt started" | |
| 2869 | + ); | |
| 2870 | + // A renewal must return while proven authority remains, | |
| 2871 | + // because only a returned attempt lets the ambiguity | |
| 2872 | + // read-back run before the watchdog. The 10:15Z R2 | |
| 2873 | + // brownout fenced 9 nodes whose sole hung attempt was | |
| 2874 | + // still inside the transport's 15 s timeout when the | |
| 2875 | + // 10 s TTL expired. Bound the attempt to half the | |
| 2876 | + // remaining authority (capped, floored) and map timeout | |
| 2877 | + // to Ambiguous — the same conservative outcome a lost | |
| 2878 | + // response already produces, so safety is unchanged. | |
| 2879 | + // The stamp survives a timed-out attempt: the backend | |
| 2880 | + // writes it through the out-parameter synchronously at | |
| 2881 | + // serialization, before the transport await, so even a | |
| 2882 | + // dropped future has reported what the possibly-landed | |
| 2883 | + // body carried. | |
| 2884 | + let mut stamped_log_state = None; | |
| 2885 | + let result = match authority_expires_ms { | |
| 2886 | + Some(expires_ms) => { | |
| 2887 | + let remaining = expires_ms.saturating_sub(now_ms()); | |
| 2888 | + let bound = | |
| 2889 | + std::time::Duration::from_millis((remaining / 2).clamp(250, 2_500)); | |
| 2890 | + match crate::asyncrt::timeout( | |
| 2891 | + bound, | |
| 2892 | + ownership.cas_node_lease(guard, record, &mut stamped_log_state), | |
| 2893 | + ) | |
| 2894 | + .await | |
| 2895 | + { | |
| 2896 | + Ok(result) => result, | |
| 2897 | + Err(_) => Err(Failure::Ambiguous), | |
| 2898 | + } | |
| 2899 | + } | |
| 2900 | + None => { | |
| 2901 | + ownership | |
| 2902 | + .cas_node_lease(guard, record, &mut stamped_log_state) | |
| 2903 | + .await | |
| 2904 | + } | |
| 2905 | + }; | |
| 2906 | + let completed_ms = now_ms(); | |
| 2907 | + let elapsed_ms = | |
| 2908 | + crate::asyncrt::mono_ms().saturating_sub(attempt_started_mono_ms); | |
| 2909 | + let prior_authority_headroom_ms = authority_expires_ms | |
| 2910 | + .map(|expires_ms| expires_ms.saturating_sub(completed_ms)) | |
| 2911 | + .unwrap_or(0); | |
| 2912 | + let candidate_headroom_ms = candidate_expires_ms.saturating_sub(completed_ms); | |
| 2913 | + let attempt = if authority_expires_ms.is_some() { | |
| 2914 | + "renew" | |
| 2915 | + } else { | |
| 2916 | + "acquire" | |
| 2917 | + }; | |
| 2918 | + let outcome = match &result { | |
| 2919 | + Ok(LeaseCasOutcome::Applied { .. }) => "applied", | |
| 2920 | + Ok(LeaseCasOutcome::Rejected) => "rejected", | |
| 2921 | + Err(Failure::Ambiguous) => "ambiguous", | |
| 2922 | + Err(Failure::Definite) => "definite_failure", | |
| 2923 | + }; | |
| 2924 | + if matches!(&result, Ok(LeaseCasOutcome::Applied { .. })) { | |
| 2925 | + tracing::info!( | |
| 2926 | + event = "node_lease_attempt", | |
| 2927 | + %node, | |
| 2928 | + attempt, | |
| 2929 | + outcome, | |
| 2930 | + elapsed_ms, | |
| 2931 | + prior_authority_headroom_ms, | |
| 2932 | + candidate_headroom_ms, | |
| 2933 | + "node lease attempt completed" | |
| 2934 | + ); | |
| 2935 | + } else { | |
| 2936 | + tracing::warn!( | |
| 2937 | + event = "node_lease_attempt", | |
| 2938 | + %node, | |
| 2939 | + attempt, | |
| 2940 | + outcome, | |
| 2941 | + elapsed_ms, | |
| 2942 | + prior_authority_headroom_ms, | |
| 2943 | + candidate_headroom_ms, | |
| 2944 | + "node lease attempt did not apply" | |
| 2945 | + ); | |
| 2946 | + } | |
| 2947 | + CompletedEffect::plain(Event::NodeLeaseCasCompleted { | |
| 2948 | + op, | |
| 2949 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2950 | + result, | |
| 2951 | + stamped_log_state, | |
| 2952 | + }) | |
| 2953 | + })); | |
| 2954 | + } | |
| 2955 | + Effect::ReadLocalCells => { | |
| 2956 | + let runtime = self.host.clone(); | |
| 2957 | + out.effects.push(Box::pin(async move { | |
| 2958 | + let result = match runtime { | |
| 2959 | + // The host runtime's blocking pool, not a second | |
| 2960 | + // pool on the core's current-thread runtime. | |
| 2961 | + Some(runtime) => crate::asyncrt::blocking(move || { | |
| 2962 | + runtime.local_reload_cells().map_err(|error| { | |
| 2963 | + eprintln!("celld local reload scan failed: {error:#}"); | |
| 2964 | + Failure::Definite | |
| 2965 | + }) | |
| 2966 | + }) | |
| 2967 | + .await | |
| 2968 | + .unwrap_or(Err(Failure::Definite)), | |
| 2969 | + None => Err(Failure::Definite), | |
| 2970 | + }; | |
| 2971 | + CompletedEffect::plain(Event::LocalCellsRead { result }) | |
| 2972 | + })); | |
| 2973 | + } | |
| 2974 | + Effect::ReadOwner { op, cell } => { | |
| 2975 | + self.route_effect_started(&cell); | |
| 2976 | + let ownership = self.ownership.clone(); | |
| 2977 | + let timing_cell = cell.clone(); | |
| 2978 | + out.effects.push(Box::pin(async move { | |
| 2979 | + let started = crate::asyncrt::mono_ms(); | |
| 2980 | + let result = ownership.read_owner(&cell).await; | |
| 2981 | + CompletedEffect::timed( | |
| 2982 | + Event::OwnerRead { | |
| 2983 | + op, | |
| 2984 | + now_ms: now_ms(), | |
| 2985 | + result, | |
| 2986 | + }, | |
| 2987 | + timing_cell, | |
| 2988 | + RouteStage::OwnershipRead, | |
| 2989 | + started, | |
| 2990 | + ) | |
| 2991 | + })); | |
| 2992 | + } | |
| 2993 | + Effect::ReadNodeLease { op, cell, owner } => { | |
| 2994 | + self.route_effect_started(&cell); | |
| 2995 | + let ownership = self.ownership.clone(); | |
| 2996 | + let timing_cell = cell; | |
| 2997 | + out.effects.push(Box::pin(async move { | |
| 2998 | + let started = crate::asyncrt::mono_ms(); | |
| 2999 | + let result = ownership.read_node_lease(&owner).await; | |
| 3000 | + CompletedEffect::timed( | |
| 3001 | + Event::NodeLeaseRead { | |
| 3002 | + op, | |
| 3003 | + now_ms: now_ms(), | |
| 3004 | + result, | |
| 3005 | + }, | |
| 3006 | + timing_cell, | |
| 3007 | + RouteStage::NodeLeaseLookup, | |
| 3008 | + started, | |
| 3009 | + ) | |
| 3010 | + })); | |
| 3011 | + } | |
| 3012 | + Effect::RecoverNodeLog { op, cell, owner } => { | |
| 3013 | + self.route_effect_started(&cell); | |
| 3014 | + let interlock = self.node_log.lock().unwrap().clone(); | |
| 3015 | + let timing_cell = cell.clone(); | |
| 3016 | + out.effects.push(Box::pin(async move { | |
| 3017 | + let started = crate::asyncrt::mono_ms(); | |
| 3018 | + let result = match interlock { | |
| 3019 | + // No log tier on this node (no bucket): nothing to | |
| 3020 | + // recover, and the claim proceeds as before. | |
| 3021 | + None => Ok(()), | |
| 3022 | + Some(interlock) => interlock | |
| 3023 | + .ensure_recovered(Some(&owner)) | |
| 3024 | + .await | |
| 3025 | + .map_err(|error| { | |
| 3026 | + eprintln!( | |
| 3027 | + "celld node-log recovery for takeover of {cell} failed: {error:#}" | |
| 3028 | + ); | |
| 3029 | + Failure::Ambiguous | |
| 3030 | + }), | |
| 3031 | + }; | |
| 3032 | + CompletedEffect::timed( | |
| 3033 | + Event::NodeLogRecovered { op, result }, | |
| 3034 | + timing_cell, | |
| 3035 | + RouteStage::NodeLeaseLookup, | |
| 3036 | + started, | |
| 3037 | + ) | |
| 3038 | + })); | |
| 3039 | + } | |
| 3040 | + Effect::ReadCapacityPeers { op, cell } => { | |
| 3041 | + self.route_effect_started(&cell); | |
| 3042 | + let ownership = self.ownership.clone(); | |
| 3043 | + let timing_cell = cell; | |
| 3044 | + out.effects.push(Box::pin(async move { | |
| 3045 | + let started = crate::asyncrt::mono_ms(); | |
| 3046 | + let result = ownership.read_capacity_peers().await; | |
| 3047 | + CompletedEffect::timed( | |
| 3048 | + Event::CapacityPeersRead { | |
| 3049 | + op, | |
| 3050 | + now_ms: now_ms(), | |
| 3051 | + result, | |
| 3052 | + }, | |
| 3053 | + timing_cell, | |
| 3054 | + RouteStage::CapacityLookup, | |
| 3055 | + started, | |
| 3056 | + ) | |
| 3057 | + })); | |
| 3058 | + } | |
| 3059 | + Effect::CasOwner { | |
| 3060 | + op, | |
| 3061 | + cell, | |
| 3062 | + guard, | |
| 3063 | + epoch, | |
| 3064 | + takeover, | |
| 3065 | + } => { | |
| 3066 | + self.route_effect_started(&cell); | |
| 3067 | + if let Some(timing) = self.route_timings.get_mut(&cell) { | |
| 3068 | + timing | |
| 3069 | + .fresh | |
| 3070 | + .get_or_insert(!takeover && matches!(guard, CasGuard::Absent)); | |
| 3071 | + } | |
| 3072 | + let ownership = self.ownership.clone(); | |
| 3073 | + let timing_cell = cell.clone(); | |
| 3074 | + out.effects.push(Box::pin(async move { | |
| 3075 | + let started = crate::asyncrt::mono_ms(); | |
| 3076 | + let result = ownership.cas_owner(&cell, guard, epoch).await; | |
| 3077 | + CompletedEffect::timed( | |
| 3078 | + Event::OwnerCasCompleted { op, result }, | |
| 3079 | + timing_cell, | |
| 3080 | + RouteStage::OwnershipAcquire, | |
| 3081 | + started, | |
| 3082 | + ) | |
| 3083 | + })); | |
| 3084 | + } | |
| 3085 | + Effect::ReconcileWakeEntry { | |
| 3086 | + cell, | |
| 3087 | + next_alarm_ms, | |
| 3088 | + } => { | |
| 3089 | + if self.host.is_some() { | |
| 3090 | + // An ARMED alarm must always be reconcilable, tracked or | |
| 3091 | + // not: belief can be lost while the alarm stands (a | |
| 3092 | + // failed arm-time PUT, an entry retired under a racing | |
| 3093 | + // arm), and skipping here would mean it is never | |
| 3094 | + // re-asserted — entryless until the alarm fires or the | |
| 3095 | + // cell moves. Gating the CONSUME side on tracking is | |
| 3096 | + // what keeps alarm-less cells op-quiescent: untracked | |
| 3097 | + // with no alarm, there is nothing to delete. | |
| 3098 | + if next_alarm_ms >= 0 || crate::js::wake_entry_tracked(&cell) { | |
| 3099 | + // On the host runtime: this arm runs on the core | |
| 3100 | + // thread, and a bare spawn would schedule the S3 | |
| 3101 | + // round trip there too. | |
| 3102 | + crate::asyncrt::spawn(async move { | |
| 3103 | + // A consume-delete only ever follows a firing, and | |
| 3104 | + // the core orders it from the far side of the | |
| 3105 | + // output gate: `alarm_finished` gates the | |
| 3106 | + // consuming commit, and only a proven | |
| 3107 | + // DurableReached — with an ownership read behind a | |
| 3108 | + // bucket proof — lets the alarm settle | |
| 3109 | + // into this reconcile. So by the time this delete | |
| 3110 | + // is ordered, the proof already happened, and | |
| 3111 | + // nothing here decides anything. The old | |
| 3112 | + // sync_refused probe asked the same question a | |
| 3113 | + // second way and was wrong more often: it refused | |
| 3114 | + // for any database the replicator never | |
| 3115 | + // registered, leaving the entry to outlive its | |
| 3116 | + // alarm forever. | |
| 3117 | + crate::js::reconcile_wake_entry(&cell, next_alarm_ms, true).await; | |
| 3118 | + }) | |
| 3119 | + .detach(); | |
| 3120 | + } | |
| 3121 | + } | |
| 3122 | + } | |
| 3123 | + Effect::ReleaseOwner { op, cell, epoch } => { | |
| 3124 | + if self.handoff_timings.contains_key(&cell) { | |
| 3125 | + self.handoff_phase_ops.insert( | |
| 3126 | + op, | |
| 3127 | + ( | |
| 3128 | + cell.clone(), | |
| 3129 | + HandoffPhase::Release, | |
| 3130 | + crate::asyncrt::mono_ms(), | |
| 3131 | + ), | |
| 3132 | + ); | |
| 3133 | + } | |
| 3134 | + let ownership = self.ownership.clone(); | |
| 3135 | + out.effects.push(Box::pin(async move { | |
| 3136 | + let result = ownership.release_owner(&cell, epoch).await; | |
| 3137 | + CompletedEffect::plain(Event::OwnerReleased { op, result }) | |
| 3138 | + })); | |
| 3139 | + } | |
| 3140 | + Effect::AdoptReleased { | |
| 3141 | + op, | |
| 3142 | + cell, | |
| 3143 | + released_epoch, | |
| 3144 | + } => { | |
| 3145 | + // The in-memory adapter is one process, so it has no successor | |
| 3146 | + // to acknowledge a handoff. The feature switch is an escape | |
| 3147 | + // hatch for mixed operational use, not the production default. | |
| 3148 | + if !self.paced_handoff || matches!(&self.ownership, Ownership::Memory(_)) { | |
| 3149 | + immediate.push_back(Event::SuccessorAdopted { | |
| 3150 | + op, | |
| 3151 | + result: Err(Failure::Definite), | |
| 3152 | + }); | |
| 3153 | + return; | |
| 3154 | + } | |
| 3155 | + if self.handoff_timings.contains_key(&cell) { | |
| 3156 | + self.handoff_phase_ops.insert( | |
| 3157 | + op, | |
| 3158 | + (cell.clone(), HandoffPhase::Adopt, crate::asyncrt::mono_ms()), | |
| 3159 | + ); | |
| 3160 | + } | |
| 3161 | + let ownership = self.ownership.clone(); | |
| 3162 | + let directory = self.handoff_directory.clone(); | |
| 3163 | + let http = self.peer_http.clone(); | |
| 3164 | + let auth = self.peer_auth.clone(); | |
| 3165 | + let source = self.state.node().to_string(); | |
| 3166 | + out.effects.push(Box::pin(async move { | |
| 3167 | + let started_mono_ms = crate::asyncrt::mono_ms(); | |
| 3168 | + let request = HandoffRequest { | |
| 3169 | + cell: cell.clone(), | |
| 3170 | + released_epoch, | |
| 3171 | + }; | |
| 3172 | + let mut attempts = 0_u64; | |
| 3173 | + loop { | |
| 3174 | + let peers = handoff_candidates(&ownership, &directory, &source, &cell) | |
| 3175 | + .await | |
| 3176 | + .unwrap_or_default(); | |
| 3177 | + for peer in peers { | |
| 3178 | + let mut target = AdoptedCell { | |
| 3179 | + node: peer.node, | |
| 3180 | + addr: peer.addr, | |
| 3181 | + epoch: 0, | |
| 3182 | + peer_protocol: peer.peer_protocol, | |
| 3183 | + }; | |
| 3184 | + let mut visited = BTreeSet::new(); | |
| 3185 | + for _ in 0..4 { | |
| 3186 | + if target.node == source | |
| 3187 | + || target.addr.is_empty() | |
| 3188 | + || target.peer_protocol != peer_auth::PROTOCOL_VERSION | |
| 3189 | + || !visited.insert(target.node.clone()) | |
| 3190 | + { | |
| 3191 | + break; | |
| 3192 | + } | |
| 3193 | + attempts = attempts.saturating_add(1); | |
| 3194 | + match request_peer_handoff(&http, &auth, &target, &request).await { | |
| 3195 | + Ok(HandoffAttempt::Accepted(adopted)) | |
| 3196 | + if adopted.epoch > released_epoch => | |
| 3197 | + { | |
| 3198 | + tracing::info!( | |
| 3199 | + event = "cell_handoff_accepted", | |
| 3200 | + %cell, | |
| 3201 | + released_epoch, | |
| 3202 | + successor = %adopted.node, | |
| 3203 | + successor_epoch = adopted.epoch, | |
| 3204 | + attempts, | |
| 3205 | + elapsed_ms = crate::asyncrt::mono_ms() | |
| 3206 | + .saturating_sub(started_mono_ms), | |
| 3207 | + "successor acquired a released cell for demand-driven restore" | |
| 3208 | + ); | |
| 3209 | + return CompletedEffect::plain(Event::SuccessorAdopted { | |
| 3210 | + op, | |
| 3211 | + result: Ok(adopted), | |
| 3212 | + }); | |
| 3213 | + } | |
| 3214 | + Ok(HandoffAttempt::CurrentOwner(owner)) => { | |
| 3215 | + target = owner; | |
| 3216 | + } | |
| 3217 | + Ok(HandoffAttempt::Accepted(_)) | |
| 3218 | + | Ok(HandoffAttempt::Refused) | |
| 3219 | + | Err(_) => break, | |
| 3220 | + } | |
| 3221 | + } | |
| 3222 | + } | |
| 3223 | + // No peer can accept yet. Retain the core permit and | |
| 3224 | + // retry until the process-wide shutdown deadline. | |
| 3225 | + crate::asyncrt::sleep(HANDOFF_RETRY_DELAY).await; | |
| 3226 | + } | |
| 3227 | + })); | |
| 3228 | + } | |
| 3229 | + Effect::CancelCellActivity { | |
| 3230 | + cell, | |
| 3231 | + requests, | |
| 3232 | + websockets, | |
| 3233 | + keep_hibernatable, | |
| 3234 | + } => { | |
| 3235 | + self.handoff_timings | |
| 3236 | + .entry(cell.clone()) | |
| 3237 | + .or_insert(HandoffCellTiming { | |
| 3238 | + nominated_mono_ms: crate::asyncrt::mono_ms(), | |
| 3239 | + quiesce_us: None, | |
| 3240 | + durability_us: None, | |
| 3241 | + stop_us: None, | |
| 3242 | + release_us: None, | |
| 3243 | + }); | |
| 3244 | + for request in requests { | |
| 3245 | + if let Some((request_id, phase)) = self | |
| 3246 | + .drain_pins | |
| 3247 | + .cancel_core_request(request, "shutdown_quiesce") | |
| 3248 | + { | |
| 3249 | + if phase == "handler" { | |
| 3250 | + if let (Some(runtime), Some(request_id)) = (&self.host, request_id) { | |
| 3251 | + runtime.abort_fetch(&cell, request_id); | |
| 3252 | + } | |
| 3253 | + } | |
| 3254 | + } | |
| 3255 | + } | |
| 3256 | + if !websockets.is_empty() { | |
| 3257 | + if keep_hibernatable { | |
| 3258 | + for websocket in &websockets { | |
| 3259 | + crate::js::ws_close(*websocket, 1012, "service restart"); | |
| 3260 | + } | |
| 3261 | + } else { | |
| 3262 | + crate::js::ws_close_scope(&cell, 1012, "service restart"); | |
| 3263 | + } | |
| 3264 | + for websocket in websockets { | |
| 3265 | + crate::js::ws_unregister(websocket); | |
| 3266 | + immediate.push_back(Event::WebSocketClosed { | |
| 3267 | + cell: cell.clone(), | |
| 3268 | + websocket, | |
| 3269 | + }); | |
| 3270 | + } | |
| 3271 | + } | |
| 3272 | + } | |
| 3273 | + Effect::Restore { op, cell, spec } => { | |
| 3274 | + self.route_effect_started(&cell); | |
| 3275 | + if let Some(runtime) = self.host.clone() { | |
| 3276 | + let timing_cell = cell.clone(); | |
| 3277 | + // A restore downloads, merges, and fsyncs a whole | |
| 3278 | + // database. Poll it on the host runtime: this future | |
| 3279 | + // lives in `out`, which the core thread drives, | |
| 3280 | + // and the core owns the node lease timer. | |
| 3281 | + let task = crate::asyncrt::spawn(async move { | |
| 3282 | + let started = crate::asyncrt::mono_ms(); | |
| 3283 | + let result = runtime.restore_cell(&cell, &spec).await.map_err(|error| { | |
| 3284 | + eprintln!("celld restore failed for {cell}: {error:#}"); | |
| 3285 | + Failure::Definite | |
| 3286 | + }); | |
| 3287 | + CompletedEffect::timed( | |
| 3288 | + Event::RestoreCompleted { op, result }, | |
| 3289 | + timing_cell, | |
| 3290 | + RouteStage::Restore, | |
| 3291 | + started, | |
| 3292 | + ) | |
| 3293 | + }); | |
| 3294 | + out.effects.push(Box::pin(async move { | |
| 3295 | + task.await.expect("restore task panicked") | |
| 3296 | + })); | |
| 3297 | + } else { | |
| 3298 | + self.record_effect_timing(EffectTiming { | |
| 3299 | + cell, | |
| 3300 | + stage: RouteStage::Restore, | |
| 3301 | + elapsed_us: 0, | |
| 3302 | + }); | |
| 3303 | + immediate.push_back(Event::RestoreCompleted { | |
| 3304 | + op, | |
| 3305 | + result: Ok(celld_logic::RestoreOutcome { | |
| 3306 | + restored: false, | |
| 3307 | + alarm: None, | |
| 3308 | + }), | |
| 3309 | + }); | |
| 3310 | + } | |
| 3311 | + } | |
| 3312 | + Effect::StartRuntime { op, cell, epoch } => { | |
| 3313 | + self.route_effect_started(&cell); | |
| 3314 | + if let Some(runtime) = self.host.clone() { | |
| 3315 | + let fresh = self | |
| 3316 | + .route_timings | |
| 3317 | + .get(&cell) | |
| 3318 | + .and_then(|timing| timing.fresh) | |
| 3319 | + .unwrap_or(false); | |
| 3320 | + let timing_cell = cell.clone(); | |
| 3321 | + out.effects.push(Box::pin(async move { | |
| 3322 | + let started = crate::asyncrt::mono_ms(); | |
| 3323 | + let placed = runtime | |
| 3324 | + .start_cell(cell.clone(), epoch, fresh) | |
| 3325 | + .await | |
| 3326 | + .map_err(|error| { | |
| 3327 | + eprintln!("celld runtime start failed for {cell}: {error:#}"); | |
| 3328 | + Failure::Definite | |
| 3329 | + }); | |
| 3330 | + let isolate = placed.as_ref().ok().map(|(isolate, _)| *isolate); | |
| 3331 | + let generation = placed | |
| 3332 | + .as_ref() | |
| 3333 | + .ok() | |
| 3334 | + .map_or(0, |(_, generation)| *generation); | |
| 3335 | + CompletedEffect::timed( | |
| 3336 | + Event::RuntimeStarted { | |
| 3337 | + op, | |
| 3338 | + isolate, | |
| 3339 | + generation, | |
| 3340 | + result: placed.map(|_| ()), | |
| 3341 | + }, | |
| 3342 | + timing_cell, | |
| 3343 | + RouteStage::IsolateStartup, | |
| 3344 | + started, | |
| 3345 | + ) | |
| 3346 | + })); | |
| 3347 | + } else { | |
| 3348 | + self.record_effect_timing(EffectTiming { | |
| 3349 | + cell, | |
| 3350 | + stage: RouteStage::IsolateStartup, | |
| 3351 | + elapsed_us: 0, | |
| 3352 | + }); | |
| 3353 | + immediate.push_back(Event::RuntimeStarted { | |
| 3354 | + op, | |
| 3355 | + isolate: None, | |
| 3356 | + generation: 0, | |
| 3357 | + result: Ok(()), | |
| 3358 | + }); | |
| 3359 | + } | |
| 3360 | + } | |
| 3361 | + Effect::Publish { op, cell, epoch } => { | |
| 3362 | + self.route_effect_started(&cell); | |
| 3363 | + let publish_started = crate::asyncrt::mono_ms(); | |
| 3364 | + self.publishes += 1; | |
| 3365 | + let result = if self.fail_publish_once { | |
| 3366 | + self.fail_publish_once = false; | |
| 3367 | + Err(Failure::Ambiguous) | |
| 3368 | + } else { | |
| 3369 | + self.host | |
| 3370 | + .as_ref() | |
| 3371 | + .map_or(Ok(()), |runtime| runtime.publish_cell(&cell, epoch)) | |
| 3372 | + .map_err(|error| { | |
| 3373 | + eprintln!("celld runtime publication failed for {cell}: {error:#}"); | |
| 3374 | + Failure::Definite | |
| 3375 | + }) | |
| 3376 | + }; | |
| 3377 | + if result.is_ok() { | |
| 3378 | + self.published.insert(cell.clone()); | |
| 3379 | + } | |
| 3380 | + self.record_effect_timing(EffectTiming { | |
| 3381 | + cell: cell.clone(), | |
| 3382 | + stage: RouteStage::RegistryInsert, | |
| 3383 | + elapsed_us: mono_elapsed_us(publish_started), | |
| 3384 | + }); | |
| 3385 | + if result.is_ok() { | |
| 3386 | + let node = self.state.node().to_string(); | |
| 3387 | + self.finish_route(&cell, "activated", "", Some((&node, epoch))); | |
| 3388 | + } | |
| 3389 | + immediate.push_back(Event::Published { op, result }); | |
| 3390 | + } | |
| 3391 | + Effect::EnsureDurable { op, cell, epoch } => { | |
| 3392 | + if let Some(timing) = self.handoff_timings.get_mut(&cell) { | |
| 3393 | + if timing.quiesce_us.is_none() { | |
| 3394 | + timing.quiesce_us = Some(mono_elapsed_us(timing.nominated_mono_ms)); | |
| 3395 | + } | |
| 3396 | + self.handoff_phase_ops.insert( | |
| 3397 | + op, | |
| 3398 | + ( | |
| 3399 | + cell.clone(), | |
| 3400 | + HandoffPhase::Durability, | |
| 3401 | + crate::asyncrt::mono_ms(), | |
| 3402 | + ), | |
| 3403 | + ); | |
| 3404 | + } | |
| 3405 | + let waiters = self.eviction_waiters.remove(&cell).unwrap_or_default(); | |
| 3406 | + self.durability_waiters.insert(op, (cell.clone(), waiters)); | |
| 3407 | + if let Some(runtime) = self.host.clone() { | |
| 3408 | + out.effects.push(Box::pin(async move { | |
| 3409 | + let result = runtime.ensure_durable(&cell, epoch).await.map_err(|error| { | |
| 3410 | + eprintln!( | |
| 3411 | + "celld durability proof failed for {cell} epoch {epoch}: {error:#}" | |
| 3412 | + ); | |
| 3413 | + Failure::Ambiguous | |
| 3414 | + }); | |
| 3415 | + CompletedEffect::plain(Event::DurabilityChecked { op, result }) | |
| 3416 | + })); | |
| 3417 | + } else { | |
| 3418 | + immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) }); | |
| 3419 | + } | |
| 3420 | + } | |
| 3421 | + // The output gate: prove the cell durable, then let the core release | |
| 3422 | + // the held write response. Reuses the same recency-proving primitive | |
| 3423 | + // as EnsureDurable — a proof issued after the write covers it. | |
| 3424 | + Effect::AwaitDurable { | |
| 3425 | + op, | |
| 3426 | + cell, | |
| 3427 | + epoch, | |
| 3428 | + position, | |
| 3429 | + } => { | |
| 3430 | + if let Some(runtime) = self.host.clone() { | |
| 3431 | + out.effects.push(Box::pin(async move { | |
| 3432 | + // The replicator reports the position it actually | |
| 3433 | + // proved durable and which mechanism proved it; the | |
| 3434 | + // core acks only if the position covers this write, | |
| 3435 | + // and decides per source whether ownership | |
| 3436 | + // verification must run first (Effect::VerifyOwnership). | |
| 3437 | + let (result, source) = | |
| 3438 | + match runtime.await_durable(&cell, epoch, position).await { | |
| 3439 | + Ok((durable, source)) => (Ok(durable), source), | |
| 3440 | + Err(error) => { | |
| 3441 | + eprintln!( | |
| 3442 | + "celld output-gate durability proof failed for {cell} \ | |
| 3443 | + epoch {epoch}: {error:#}" | |
| 3444 | + ); | |
| 3445 | + (Err(Failure::Ambiguous), celld_logic::ProofSource::Bucket) | |
| 3446 | + } | |
| 3447 | + }; | |
| 3448 | + CompletedEffect::plain(Event::DurableReached { op, result, source }) | |
| 3449 | + })); | |
| 3450 | + } else { | |
| 3451 | + immediate.push_back(Event::DurableReached { | |
| 3452 | + op, | |
| 3453 | + result: Ok(position), | |
| 3454 | + source: celld_logic::ProofSource::Fleet, | |
| 3455 | + }); | |
| 3456 | + } | |
| 3457 | + } | |
| 3458 | + Effect::VerifyOwnership { op, cell, epoch } => { | |
| 3459 | + // Verify ownership for bucket-proof acks. Durable in | |
| 3460 | + // `e<epoch>/` is not the same as durable: if the cell has been taken over, that | |
| 3461 | + // prefix is orphaned — the next owner restores a higher | |
| 3462 | + // epoch and this write is gone. A read is enough, and is why | |
| 3463 | + // this is one GET rather than a compare-and-swap: if the | |
| 3464 | + // record still names us, no takeover linearised before this | |
| 3465 | + // read; the LTX went up before it; so any later takeover | |
| 3466 | + // restores from a lineage that already contains the write. | |
| 3467 | + let ownership = self.ownership.clone(); | |
| 3468 | + let node = self.state.node().to_string(); | |
| 3469 | + out.effects.push(Box::pin(async move { | |
| 3470 | + let result = match ownership.read_owner(&cell).await { | |
| 3471 | + Ok(Some(record)) | |
| 3472 | + if record.node.as_deref() == Some(node.as_str()) | |
| 3473 | + && record.epoch == epoch => | |
| 3474 | + { | |
| 3475 | + Ok(()) | |
| 3476 | + } | |
| 3477 | + Ok(record) => { | |
| 3478 | + eprintln!( | |
| 3479 | + "celld output gate: {cell} epoch {epoch} is no longer ours \ | |
| 3480 | + (record: {record:?}); refusing to acknowledge a write in an \ | |
| 3481 | + orphaned epoch" | |
| 3482 | + ); | |
| 3483 | + Err(Failure::Definite) | |
| 3484 | + } | |
| 3485 | + Err(failure) => Err(failure), | |
| 3486 | + }; | |
| 3487 | + CompletedEffect::plain(Event::OwnershipVerified { op, result }) | |
| 3488 | + })); | |
| 3489 | + } | |
| 3490 | + // 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. | |
| 3495 | + // | |
| 3496 | + // The channel says which way the effect leaves; `ws_gated` says how | |
| 3497 | + // this one is being held. They agree except in one case, and there | |
| 3498 | + // the holding mechanism decides: a frame for a hibernatable socket | |
| 3499 | + // raised OUTSIDE a `webSocketMessage` handler -- from `fetch`, an | |
| 3500 | + // alarm, or `webSocketClose` -- is never captured, so it waits on a | |
| 3501 | + // ticket like every other channel rather than in the cell's barrier | |
| 3502 | + // queue. Routing it to the barrier queue would find no entry and | |
| 3503 | + // strand the task waiting on the ticket. | |
| 3504 | + Effect::Release { | |
| 3505 | + request, | |
| 3506 | + channel, | |
| 3507 | + result, | |
| 3508 | + } => { | |
| 3509 | + let held = HeldOutputKey { request, channel }; | |
| 3510 | + match channel { | |
| 3511 | + Channel::WsHibernatable if self.ws_gated.contains_key(&held) => { | |
| 3512 | + self.ws_release(held, result.is_ok()) | |
| 3513 | + } | |
| 3514 | + Channel::Response | |
| 3515 | + | Channel::Fetch | |
| 3516 | + | Channel::WsHibernatable | |
| 3517 | + | Channel::WsSelf | |
| 3518 | + | Channel::Service | |
| 3519 | + | Channel::CellRpc | |
| 3520 | + | Channel::Queue => { | |
| 3521 | + if let Some(reply) = self.gated_responses.remove(&held) { | |
| 3522 | + let _ = reply.send(result); | |
| 3523 | + } | |
| 3524 | + } | |
| 3525 | + } | |
| 3526 | + } | |
| 3527 | + Effect::StopRuntime { | |
| 3528 | + op, | |
| 3529 | + cell, | |
| 3530 | + epoch, | |
| 3531 | + cause, | |
| 3532 | + } => { | |
| 3533 | + if self.handoff_timings.contains_key(&cell) { | |
| 3534 | + self.handoff_phase_ops.insert( | |
| 3535 | + op, | |
| 3536 | + (cell.clone(), HandoffPhase::Stop, crate::asyncrt::mono_ms()), | |
| 3537 | + ); | |
| 3538 | + } | |
| 3539 | + self.stops += 1; | |
| 3540 | + if matches!(cause, StopCause::Swap) { | |
| 3541 | + // A generation swap: the cell leaves its isolate and | |
| 3542 | + // nothing else changes. No durability barrier, no | |
| 3543 | + // replica release, no local unlink -- the same epoch | |
| 3544 | + // starts again on the current generation as soon as the | |
| 3545 | + // core hears the stop. | |
| 3546 | + self.published.remove(&cell); | |
| 3547 | + if let Some(runtime) = self.host.clone() { | |
| 3548 | + let released = cell.clone(); | |
| 3549 | + let task = crate::asyncrt::spawn(report_stopped_when_released( | |
| 3550 | + op, | |
| 3551 | + cell, | |
| 3552 | + epoch, | |
| 3553 | + "generation_swap_out_retry", | |
| 3554 | + move || { | |
| 3555 | + let runtime = runtime.clone(); | |
| 3556 | + let cell = released.clone(); | |
| 3557 | + async move { runtime.swap_out_cell(&cell, epoch).await } | |
| 3558 | + }, | |
| 3559 | + )); | |
| 3560 | + out.effects.push(Box::pin(async move { | |
| 3561 | + task.await.expect("swap out task panicked") | |
| 3562 | + })); | |
| 3563 | + } else { | |
| 3564 | + immediate.push_back(Event::RuntimeStopped { op }); | |
| 3565 | + } | |
| 3566 | + } else { | |
| 3567 | + let evicting = matches!(cause, StopCause::Evict { .. }); | |
| 3568 | + if matches!(cause, StopCause::Fence) { | |
| 3569 | + // A fenced cell's wake entry belongs to whoever takes the | |
| 3570 | + // cell over; a retained local belief would collide with | |
| 3571 | + // the new owner's arm/consume traffic on the same key. | |
| 3572 | + crate::js::forget_wake_entry(&cell); | |
| 3573 | + } | |
| 3574 | + // Keep the persistence decision whole. A cleanup still has | |
| 3575 | + // authority, so it makes the closed image a proved local | |
| 3576 | + // base. A fence can only close in place, and a reset must | |
| 3577 | + // discard the database that failed its durability proof. | |
| 3578 | + let stop_mode = match cause { | |
| 3579 | + StopCause::Evict { rebalance } => crate::runtime::StopMode::Evict { | |
| 3580 | + preserve_local: !rebalance, | |
| 3581 | + }, | |
| 3582 | + StopCause::Cleanup => crate::runtime::StopMode::Rebase, | |
| 3583 | + StopCause::Fence => crate::runtime::StopMode::CloseInPlace, | |
| 3584 | + StopCause::Reset => crate::runtime::StopMode::Discard, | |
| 3585 | + StopCause::Swap => unreachable!("generation swaps return above"), | |
| 3586 | + }; | |
| 3587 | + if evicting { | |
| 3588 | + if let Some(live) = &self.live_load { | |
| 3589 | + live.shed_cells.fetch_add(1, Ordering::Relaxed); | |
| 3590 | + } | |
| 3591 | + } | |
| 3592 | + self.published.remove(&cell); | |
| 3593 | + if let Some(runtime) = self.host.clone() { | |
| 3594 | + // A stop closes a whole database. It fsyncs the directory | |
| 3595 | + // and the file, then unlinks the local copy, and it does | |
| 3596 | + // all of that inside one synchronous call. Poll it on the | |
| 3597 | + // host runtime: this future lives in `out`, which the core | |
| 3598 | + // thread drives in the same select as the timer queue, and | |
| 3599 | + // the core owns the node lease timer. A slow fsync on the | |
| 3600 | + // core thread starves the lease renew and the lease fence, | |
| 3601 | + // and the node then fences itself. | |
| 3602 | + let released = cell.clone(); | |
| 3603 | + let task = crate::asyncrt::spawn(report_stopped_when_released( | |
| 3604 | + op, | |
| 3605 | + cell, | |
| 3606 | + epoch, | |
| 3607 | + "stop_runtime_retry", | |
| 3608 | + move || { | |
| 3609 | + let runtime = runtime.clone(); | |
| 3610 | + let cell = released.clone(); | |
| 3611 | + async move { runtime.stop_cell(&cell, epoch, stop_mode).await } | |
| 3612 | + }, | |
| 3613 | + )); | |
| 3614 | + out.effects.push(Box::pin(async move { | |
| 3615 | + task.await.expect("stop runtime task panicked") | |
| 3616 | + })); | |
| 3617 | + } else { | |
| 3618 | + immediate.push_back(Event::RuntimeStopped { op }); | |
| 3619 | + } | |
| 3620 | + } | |
| 3621 | + } | |
| 3622 | + Effect::FireAlarm { | |
| 3623 | + op, | |
| 3624 | + cell, | |
| 3625 | + epoch, | |
| 3626 | + scheduled_ms, | |
| 3627 | + } => { | |
| 3628 | + if let Some(runtime) = self.host.clone() { | |
| 3629 | + out.effects.push(Box::pin(async move { | |
| 3630 | + // The shell reports the firing raw: the deadline that | |
| 3631 | + // stands after the handler, whether a wake entry | |
| 3632 | + // covers it, and the position of the consuming | |
| 3633 | + // commit. Proving that commit durable — and this node | |
| 3634 | + // still the owner — is the core's job: it opens the | |
| 3635 | + // same output gate a request's write gets, so one | |
| 3636 | + // question answers for every egress on the cell, and | |
| 3637 | + // the consume-side wake-entry delete leaves only from | |
| 3638 | + // the far side of the proof. On failure the core | |
| 3639 | + // re-arms or resets; either way the entry stays | |
| 3640 | + // discoverable and at-least-once holds. | |
| 3641 | + let result = runtime | |
| 3642 | + .fire_alarm(cell.clone(), scheduled_ms) | |
| 3643 | + .await | |
| 3644 | + .map_err(|error| { | |
| 3645 | + eprintln!("celld alarm dispatch failed: {error:#}"); | |
| 3646 | + Failure::Definite | |
| 3647 | + }); | |
| 3648 | + CompletedEffect::plain(Event::AlarmFinished { | |
| 3649 | + op, | |
| 3650 | + cell, | |
| 3651 | + epoch, | |
| 3652 | + now_ms: now_ms(), | |
| 3653 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 3654 | + result, | |
| 3655 | + }) | |
| 3656 | + })); | |
| 3657 | + } else { | |
| 3658 | + immediate.push_back(Event::AlarmFinished { | |
| 3659 | + op, | |
| 3660 | + cell, | |
| 3661 | + epoch, | |
| 3662 | + now_ms: now_ms(), | |
| 3663 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 3664 | + result: Ok((None, true, None)), | |
| 3665 | + }); | |
| 3666 | + } | |
| 3667 | + } | |
| 3668 | + Effect::Complete { request, result } => { | |
| 3669 | + if let Some(cell) = self.request_cells.remove(&request) { | |
| 3670 | + match &result { | |
| 3671 | + Ok(Route::Remote { node, epoch, .. }) => { | |
| 3672 | + self.finish_route(&cell, "remote_owner", "", Some((node, *epoch))); | |
| 3673 | + // The cell lives elsewhere: its wake entry is no | |
| 3674 | + // longer this node's to track, and a stale local | |
| 3675 | + // belief would collide with the owner's own | |
| 3676 | + // arm/consume traffic on the same key. | |
| 3677 | + crate::js::forget_wake_entry(&cell); | |
| 3678 | + } | |
| 3679 | + Ok(Route::Local) => { | |
| 3680 | + self.finish_route(&cell, "resident_after_wait", "", None); | |
| 3681 | + } | |
| 3682 | + Err(error) => { | |
| 3683 | + self.finish_route( | |
| 3684 | + &cell, | |
| 3685 | + "route_error", | |
| 3686 | + request_error_phase(*error), | |
| 3687 | + None, | |
| 3688 | + ); | |
| 3689 | + } | |
| 3690 | + } | |
| 3691 | + } | |
| 3692 | + if let Some(reply) = self.pending.remove(&request) { | |
| 3693 | + let local = result == Ok(Route::Local); | |
| 3694 | + if reply | |
| 3695 | + .send(result.map(|route| Routed { request, route })) | |
| 3696 | + .is_err() | |
| 3697 | + && local | |
| 3698 | + { | |
| 3699 | + immediate.push_back(Event::ActivityFinished { request }); | |
| 3700 | + } | |
| 3701 | + } | |
| 3702 | + } | |
| 3703 | + Effect::CompleteWorker { request, route } => { | |
| 3704 | + if let Some(op) = route.as_ref().and_then(|route| route.retired_durability) { | |
| 3705 | + if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 3706 | + for waiter in waiters { | |
| 3707 | + let _ = waiter.send(()); | |
| 3708 | + } | |
| 3709 | + } | |
| 3710 | + } | |
| 3711 | + if let Some(reply) = self.pending_workers.remove(&request) { | |
| 3712 | + let reserved = route.is_some(); | |
| 3713 | + if reply.send(WorkerRouted { request, route }).is_err() && reserved { | |
| 3714 | + immediate.push_back(Event::ActivityFinished { request }); | |
| 3715 | + } | |
| 3716 | + } | |
| 3717 | + } | |
| 3718 | + Effect::CloseWebSocket { cell, websocket } => { | |
| 3719 | + // The core declined to hold this transport. Drop it and tell | |
| 3720 | + // the core it is gone, so the cell is not left believing it | |
| 3721 | + // has a socket the node already closed. | |
| 3722 | + eprintln!( | |
| 3723 | + "celld refused an outbound WebSocket for {cell}: the node's \ | |
| 3724 | + outbound pin budget is spent" | |
| 3725 | + ); | |
| 3726 | + crate::js::ws_unregister(websocket); | |
| 3727 | + immediate.push_back(Event::WebSocketClosed { cell, websocket }); | |
| 3728 | + } | |
| 3729 | + Effect::Halt { code, reason } => { | |
| 3730 | + // Say why before going. Self-fencing is the most drastic thing | |
| 3731 | + // this process does, and an exit code on its own leaves an | |
| 3732 | + // operator to guess between a lease it could not renew, a | |
| 3733 | + // replicator that died, and a crash. | |
| 3734 | + match reason { | |
| 3735 | + celld_logic::HaltReason::NodeLeaseExpired => tracing::warn!( | |
| 3736 | + event = "node_lease_watchdog_fence", | |
| 3737 | + code, | |
| 3738 | + "SELF-FENCE: node lease not renewed within TTL — halting" | |
| 3739 | + ), | |
| 3740 | + } | |
| 3741 | + let _ = self.fence.send(code); | |
| 3742 | + } | |
| 3743 | + } | |
| 3744 | + } | |
| 3745 | + | |
| 3746 | + fn state_json(&self) -> String { | |
| 3747 | + let activity = self.state.presence_snapshot().activity; | |
| 3748 | + let residents = self | |
| 3749 | + .state | |
| 3750 | + .residents() | |
| 3751 | + .into_iter() | |
| 3752 | + .map(|cell| format!("{cell:?}")) | |
| 3753 | + .collect::<Vec<_>>() | |
| 3754 | + .join(","); | |
| 3755 | + let published = self | |
| 3756 | + .published | |
| 3757 | + .iter() | |
| 3758 | + .map(|cell| format!("{cell:?}")) | |
| 3759 | + .collect::<Vec<_>>() | |
| 3760 | + .join(","); | |
| 3761 | + // Both numbers: a gap between them is memory the allocator kept, which | |
| 3762 | + // no eviction returns. One sample, so they cannot disagree. | |
| 3763 | + let memory = crate::memory::sample(); | |
| 3764 | + // `restoring` is a sum, and a node that refuses cells for a quarter of | |
| 3765 | + // an hour needs its parts. `activating` holds a permit and is doing | |
| 3766 | + // work; `activation_waiting` is queued behind the activation ceiling; | |
| 3767 | + // `capacity_waiting` is queued behind residency. The census says where | |
| 3768 | + // every cell is, which `occupied` cannot: it counts residency, so a | |
| 3769 | + // node part-way through thousands of cold starts reports almost none. | |
| 3770 | + // Issue #50 is open because none of this was recorded at the time. | |
| 3771 | + let phases = self | |
| 3772 | + .state | |
| 3773 | + .phase_census() | |
| 3774 | + .into_iter() | |
| 3775 | + .map(|(phase, count)| format!("{phase:?}:{count}")) | |
| 3776 | + .collect::<Vec<_>>() | |
| 3777 | + .join(","); | |
| 3778 | + 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\":{}}}", | |
| 3780 | + self.ownership.name(), | |
| 3781 | + self.state.occupied(), | |
| 3782 | + self.state.quiescing(), | |
| 3783 | + self.state.evicting(), | |
| 3784 | + self.state.releasing(), | |
| 3785 | + self.state.adopting(), | |
| 3786 | + self.state.activation_backlog(), | |
| 3787 | + self.state.activating(), | |
| 3788 | + self.state.activation_waiting().len(), | |
| 3789 | + self.state.waiting().len(), | |
| 3790 | + phases, | |
| 3791 | + activity.handed_off, | |
| 3792 | + activity.handoff_failed, | |
| 3793 | + self.state | |
| 3794 | + .shed_reason() | |
| 3795 | + .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")), | |
| 3796 | + memory.rss_bytes, | |
| 3797 | + memory.in_use_bytes, | |
| 3798 | + memory | |
| 3799 | + .cgroup_working_set_bytes | |
| 3800 | + .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()), | |
| 3801 | + memory | |
| 3802 | + .cgroup_current_bytes | |
| 3803 | + .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()), | |
| 3804 | + residents, | |
| 3805 | + published, | |
| 3806 | + self.publishes, | |
| 3807 | + self.stops | |
| 3808 | + ) | |
| 3809 | + } | |
| 3810 | + | |
| 3811 | + fn begin_route_if_cold(&mut self, cell: &str) { | |
| 3812 | + if !matches!( | |
| 3813 | + self.state.phase(cell), | |
| 3814 | + Some(Phase::Resident { .. } | Phase::EnsuringDurability { .. } | Phase::Remote { .. }) | |
| 3815 | + ) { | |
| 3816 | + self.route_timings | |
| 3817 | + .entry(cell.to_string()) | |
| 3818 | + .or_insert_with(CellRouteTiming::new); | |
| 3819 | + } | |
| 3820 | + } | |
| 3821 | + | |
| 3822 | + fn route_effect_started(&mut self, cell: &str) { | |
| 3823 | + if let Some(timing) = self.route_timings.get_mut(cell) { | |
| 3824 | + timing.effect_started(); | |
| 3825 | + } | |
| 3826 | + } | |
| 3827 | + | |
| 3828 | + fn observe_capacity_wait(&mut self, cell: &str) { | |
| 3829 | + if matches!(self.state.phase(cell), Some(Phase::WaitingCapacity)) { | |
| 3830 | + if let Some(timing) = self.route_timings.get_mut(cell) { | |
| 3831 | + timing | |
| 3832 | + .capacity_wait_started_mono_ms | |
| 3833 | + .get_or_insert_with(crate::asyncrt::mono_ms); | |
| 3834 | + } | |
| 3835 | + } | |
| 3836 | + } | |
| 3837 | + | |
| 3838 | + fn record_effect_timing(&mut self, completed: EffectTiming) { | |
| 3839 | + if let Some(timing) = self.route_timings.get_mut(&completed.cell) { | |
| 3840 | + timing.record(completed.stage, completed.elapsed_us); | |
| 3841 | + } | |
| 3842 | + } | |
| 3843 | + | |
| 3844 | + fn finish_route( | |
| 3845 | + &mut self, | |
| 3846 | + cell: &str, | |
| 3847 | + outcome: &str, | |
| 3848 | + failure_phase: &str, | |
| 3849 | + owner: Option<(&str, u64)>, | |
| 3850 | + ) { | |
| 3851 | + let Some(mut timing) = self.route_timings.remove(cell) else { | |
| 3852 | + return; | |
| 3853 | + }; | |
| 3854 | + if let Some(started) = timing.capacity_wait_started_mono_ms.take() { | |
| 3855 | + timing.capacity_wait_us = timing | |
| 3856 | + .capacity_wait_us | |
| 3857 | + .saturating_add(mono_elapsed_us(started)); | |
| 3858 | + } | |
| 3859 | + let (owner_node, epoch) = owner.unwrap_or(("", 0)); | |
| 3860 | + tracing::debug!( | |
| 3861 | + target: "timing", | |
| 3862 | + event = "cell_route_timing", | |
| 3863 | + outcome, | |
| 3864 | + failure_phase, | |
| 3865 | + scope = %cell, | |
| 3866 | + node = %self.state.node(), | |
| 3867 | + region = %self.region, | |
| 3868 | + runtime_version = env!("CARGO_PKG_VERSION"), | |
| 3869 | + owner_node, | |
| 3870 | + epoch, | |
| 3871 | + fresh = timing.fresh.unwrap_or(false), | |
| 3872 | + total_us = mono_elapsed_us(timing.started_mono_ms), | |
| 3873 | + latch_wait_us = timing.latch_wait_us, | |
| 3874 | + ownership_read_us = timing.ownership_read_us, | |
| 3875 | + node_lease_lookup_us = timing.node_lease_lookup_us, | |
| 3876 | + capacity_lookup_us = timing.capacity_lookup_us, | |
| 3877 | + capacity_wait_us = timing.capacity_wait_us, | |
| 3878 | + activation_slot_wait_us = timing.activation_slot_wait_us, | |
| 3879 | + lease_permit_us = timing.lease_permit_us, | |
| 3880 | + ownership_acquire_us = timing.ownership_acquire_us, | |
| 3881 | + replica_discovery_us = timing.replica_discovery_us, | |
| 3882 | + restore_us = timing.restore_us, | |
| 3883 | + isolate_startup_us = timing.isolate_startup_us, | |
| 3884 | + registry_insert_us = timing.registry_insert_us, | |
| 3885 | + "cell route resolved" | |
| 3886 | + ); | |
| 3887 | + } | |
| 3888 | +} | |
| 3889 | + | |
| 3890 | +fn request_error_phase(error: RequestError) -> &'static str { | |
| 3891 | + match error { | |
| 3892 | + RequestError::NodeUnavailable | RequestError::NodeFenced => "node_authority", | |
| 3893 | + RequestError::ResolveFailed | RequestError::PeerIncompatible => "ownership_lookup", | |
| 3894 | + RequestError::CapacityExhausted => "capacity_wait", | |
| 3895 | + RequestError::AcquireFailed => "ownership_acquire", | |
| 3896 | + RequestError::RestoreFailed => "restore", | |
| 3897 | + RequestError::RuntimeFailed => "isolate_startup", | |
| 3898 | + RequestError::PublishFailed => "registry_insert", | |
| 3899 | + RequestError::DurabilityUnproven => "output_gate", | |
| 3900 | + } | |
| 3901 | +} | |
| 3902 | + | |
| 3903 | +#[cfg(not(all(test, celld_internal_tests)))] | |
| 3904 | +type ActorState = State; | |
| 3905 | + | |
| 3906 | +#[cfg(not(all(test, celld_internal_tests)))] | |
| 3907 | +fn apply_core_event(state: &mut ActorState, event: Event) -> Vec<Effect> { | |
| 3908 | + on_event(state, event) | |
| 2655 | 3909 | } |
| 2656 | 3910 | |
| 2657 | 3911 | #[cfg(all(test, celld_internal_tests))] |
modifiedcrates/celld/actor/production.rs+5−7View file
| @@ -1,18 +1,16 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -//! The production selector which the deterministic World replaces. | |
| 3 | +//! The production selector for the Actor execution domain. | |
| 4 | 4 | |
| 5 | -#![allow(clippy::disallowed_macros)] | |
| 6 | - | |
| 7 | 5 | use super::*; |
| 8 | 6 | use futures_util::StreamExt as _; |
| 9 | 7 | |
| 10 | 8 | impl Actor { |
| 11 | 9 | /// Runs the production start-select-step loop. |
| 12 | 10 | /// |
| 13 | - /// This selector stays unbiased because production has always permitted | |
| 14 | - /// every ready-input order. The World calls [`Actor::start`] and | |
| 15 | - /// [`Actor::step`] directly, so it never executes this raw Tokio select. | |
| 11 | + /// This selector stays unbiased because production permits every | |
| 12 | + /// ready-input order. Direct callers can use [`Actor::start`] and | |
| 13 | + /// [`Actor::step`] without this raw Tokio select. | |
| 16 | 14 | pub async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Message>) { |
| 17 | 15 | let mut effects = FuturesUnordered::new(); |
| 18 | 16 | let mut delays = DelayQueue::new(); |
| @@ -21,7 +19,7 @@ | ||
| 21 | 19 | self.start(&mut out); |
| 22 | 20 | drain_step_output(&mut out, &mut effects, &mut delays, &mut timer_slots); |
| 23 | 21 | loop { |
| 24 | - tokio::select! { | |
| 22 | + crate::asyncrt::select! { | |
| 25 | 23 | message = rx.recv() => { |
| 26 | 24 | let Some(message) = message else { |
| 27 | 25 | break; |
modifiedcrates/celld/assets.rs+204−6View file
| @@ -1,12 +1,15 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -// Asset download and cache maintenance execute in the V8/process arm, which | |
| 4 | -// the World replaces with scripted client and cell-host boundaries. | |
| 3 | +// Asset download and cache maintenance execute outside the Actor execution | |
| 4 | +// domain. | |
| 5 | 5 | #![allow(clippy::disallowed_methods, clippy::disallowed_types)] |
| 6 | 6 | |
| 7 | 7 | use crate::bucket::Bucket; |
| 8 | 8 | use crate::js; |
| 9 | -use crate::protocol::{asset_blob_key, AssetEntry, AssetIndex, AssetManifestRef, RunWorkerFirst}; | |
| 9 | +use crate::protocol::{ | |
| 10 | + asset_blob_key, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest, | |
| 11 | + RunWorkerFirst, | |
| 12 | +}; | |
| 10 | 13 | use anyhow::{anyhow, Context}; |
| 11 | 14 | use axum::body::Body; |
| 12 | 15 | use axum::http::{HeaderMap, HeaderValue, StatusCode}; |
| @@ -29,10 +32,59 @@ | ||
| 29 | 32 | inner: Arc<AssetResolverInner>, |
| 30 | 33 | } |
| 31 | 34 | |
| 35 | +/// Where a resolver can look for a NEWER deployment's asset index than the | |
| 36 | +/// one this process booted with. During a rolling restart an upgraded node | |
| 37 | +/// serves HTML whose content-hashed asset paths an un-restarted node has | |
| 38 | +/// never heard of; the blobs are content-addressed and fleet-visible, so | |
| 39 | +/// only the index is stale. denoland/celld#161. | |
| 40 | +pub struct FallbackSource { | |
| 41 | + /// The pointer this deployment was loaded from (`deploy/current.json`, | |
| 42 | + /// or the script-scoped pointer for a service). | |
| 43 | + pub pointer_key: String, | |
| 44 | + /// The deployment prefix loaded at boot; a pointer naming another | |
| 45 | + /// prefix names a newer deployment. | |
| 46 | + pub boot_prefix: String, | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// The newest foreign index this resolver has adopted, plus the throttle | |
| 50 | +/// that keeps a miss storm from becoming a pointer-GET storm. Guarded by a | |
| 51 | +/// std mutex that is NEVER held across I/O: the refresh runs in a spawned | |
| 52 | +/// task, so a degraded bucket cannot stall the miss path — before this | |
| 53 | +/// rule, one slow pointer GET head-of-line-blocked every Worker-bound | |
| 54 | +/// request whose path missed the index. | |
| 55 | +/// What one refresh pass concluded about the pointer. | |
| 56 | +enum Adoption { | |
| 57 | + /// The pointer names the booted deployment: any adoption is withdrawn. | |
| 58 | + Booted, | |
| 59 | + /// The pointer names the deployment already adopted. | |
| 60 | + Unchanged, | |
| 61 | + /// The pointer names a deployment this resolver now adopts. Boxed: | |
| 62 | + /// an index can be large, and the other variants carry nothing. | |
| 63 | + Newer { | |
| 64 | + prefix: String, | |
| 65 | + index: Box<AssetIndex>, | |
| 66 | + }, | |
| 67 | +} | |
| 68 | + | |
| 69 | +#[derive(Default)] | |
| 70 | +struct FallbackState { | |
| 71 | + checked: Option<std::time::Instant>, | |
| 72 | + refreshing: bool, | |
| 73 | + prefix: Option<String>, | |
| 74 | + index: Option<Arc<AssetIndex>>, | |
| 75 | +} | |
| 76 | + | |
| 77 | +/// How long a pointer observation stays fresh. A newer deployment's assets | |
| 78 | +/// become servable within this bound after its pointer lands, which is far | |
| 79 | +/// inside the window a rolling restart leaves a node un-upgraded. | |
| 80 | +const FALLBACK_CHECK_MS: u64 = 5_000; | |
| 81 | + | |
| 32 | 82 | struct AssetResolverInner { |
| 33 | 83 | bucket: Bucket, |
| 34 | 84 | index: AssetIndex, |
| 35 | 85 | asset_only: bool, |
| 86 | + fallback: Option<FallbackSource>, | |
| 87 | + fallback_state: std::sync::Mutex<FallbackState>, | |
| 36 | 88 | cache_root: PathBuf, |
| 37 | 89 | cache_max_bytes: u64, |
| 38 | 90 | download_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>, |
| @@ -88,6 +140,7 @@ | ||
| 88 | 140 | prefix: &str, |
| 89 | 141 | reference: &AssetManifestRef, |
| 90 | 142 | asset_only: bool, |
| 143 | + fallback: Option<FallbackSource>, | |
| 91 | 144 | ) -> anyhow::Result<Self> { |
| 92 | 145 | if reference.index != "assets.json" { |
| 93 | 146 | return Err(anyhow!("unsupported asset index name: {}", reference.index)); |
| @@ -120,6 +173,8 @@ | ||
| 120 | 173 | bucket: bucket.clone(), |
| 121 | 174 | index, |
| 122 | 175 | asset_only, |
| 176 | + fallback, | |
| 177 | + fallback_state: std::sync::Mutex::new(FallbackState::default()), | |
| 123 | 178 | cache_root, |
| 124 | 179 | cache_max_bytes, |
| 125 | 180 | download_locks: Mutex::new(HashMap::new()), |
| @@ -219,7 +274,22 @@ | ||
| 219 | 274 | } |
| 220 | 275 | break; |
| 221 | 276 | } |
| 222 | - match selected.unwrap_or_else(|| route(&self.inner.index, &path, include_not_found)) { | |
| 277 | + let routed = match selected { | |
| 278 | + Some(routed) => routed, | |
| 279 | + None => { | |
| 280 | + let mut routed = route(&self.inner.index, &path, false); | |
| 281 | + if matches!(routed, Route::Missing) { | |
| 282 | + if let Some(fresh) = self.newer_deployment_route(&path) { | |
| 283 | + routed = fresh; | |
| 284 | + } | |
| 285 | + } | |
| 286 | + if matches!(routed, Route::Missing) && include_not_found { | |
| 287 | + routed = not_found_route(&self.inner.index, &path); | |
| 288 | + } | |
| 289 | + routed | |
| 290 | + } | |
| 291 | + }; | |
| 292 | + match routed { | |
| 223 | 293 | Route::Missing => Ok(None), |
| 224 | 294 | Route::Redirect { |
| 225 | 295 | mut location, |
| @@ -332,7 +402,7 @@ | ||
| 332 | 402 | body: b"Method not allowed".to_vec(), |
| 333 | 403 | stream: None, |
| 334 | 404 | headers: vec![("content-type".into(), "text/plain; charset=utf-8".into())], |
| 335 | - ws: None, | |
| 405 | + websocket: None, | |
| 336 | 406 | write_position: None, |
| 337 | 407 | }); |
| 338 | 408 | } |
| @@ -383,7 +453,7 @@ | ||
| 383 | 453 | ) |
| 384 | 454 | }) |
| 385 | 455 | .collect(), |
| 386 | - ws: None, | |
| 456 | + websocket: None, | |
| 387 | 457 | write_position: None, |
| 388 | 458 | }) |
| 389 | 459 | } |
| @@ -428,6 +498,125 @@ | ||
| 428 | 498 | Ok(()) |
| 429 | 499 | } |
| 430 | 500 | |
| 501 | + /// A route from a NEWER deployment's index, when the fleet pointer has | |
| 502 | + /// moved past the one this process booted with. Best-effort: every | |
| 503 | + /// failure keeps the booted behavior, so the fallback can make an asset | |
| 504 | + /// appear but never disappear. The lock never crosses I/O — the refresh | |
| 505 | + /// runs in a spawned task on the host runtime and the triggering miss | |
| 506 | + /// routes against the last adopted snapshot, so a degraded bucket | |
| 507 | + /// degrades only the fallback, never the miss path. One refresh per | |
| 508 | + /// `FALLBACK_CHECK_MS`, and the `refreshing` latch keeps a refresh that | |
| 509 | + /// outlives the interval from stacking a second one behind it | |
| 510 | + /// (denoland/celld#161). | |
| 511 | + fn newer_deployment_route(&self, path: &str) -> Option<Route> { | |
| 512 | + self.inner.fallback.as_ref()?; | |
| 513 | + let (snapshot, refresh_due) = { | |
| 514 | + let mut state = self.inner.fallback_state.lock().unwrap(); | |
| 515 | + let due = !state.refreshing | |
| 516 | + && state.checked.is_none_or(|at| { | |
| 517 | + at.elapsed() >= std::time::Duration::from_millis(FALLBACK_CHECK_MS) | |
| 518 | + }); | |
| 519 | + if due { | |
| 520 | + state.refreshing = true; | |
| 521 | + state.checked = Some(std::time::Instant::now()); | |
| 522 | + } | |
| 523 | + (state.index.clone(), due) | |
| 524 | + }; | |
| 525 | + if refresh_due { | |
| 526 | + let resolver = self.clone(); | |
| 527 | + crate::asyncrt::op_handle().spawn(async move { | |
| 528 | + resolver.refresh_fallback().await; | |
| 529 | + }); | |
| 530 | + } | |
| 531 | + let index = snapshot?; | |
| 532 | + match route(&index, path, false) { | |
| 533 | + Route::Missing => None, | |
| 534 | + found => Some(found), | |
| 535 | + } | |
| 536 | + } | |
| 537 | + | |
| 538 | + /// One refresh pass: read the pointer, adopt a newer deployment's | |
| 539 | + /// checksum-validated index, clear the adoption when the pointer moved | |
| 540 | + /// BACK to the booted deployment — a rollback must withdraw the rolled- | |
| 541 | + /// back assets, not pin them until restart. | |
| 542 | + async fn refresh_fallback(&self) { | |
| 543 | + let Some(source) = self.inner.fallback.as_ref() else { | |
| 544 | + return; | |
| 545 | + }; | |
| 546 | + let adopted = self.inner.fallback_state.lock().unwrap().prefix.clone(); | |
| 547 | + let outcome = self.adopt_newer_index(source, adopted.as_deref()).await; | |
| 548 | + let mut state = self.inner.fallback_state.lock().unwrap(); | |
| 549 | + state.refreshing = false; | |
| 550 | + match outcome { | |
| 551 | + Ok(Adoption::Newer { prefix, index }) => { | |
| 552 | + state.prefix = Some(prefix); | |
| 553 | + state.index = Some(Arc::new(*index)); | |
| 554 | + } | |
| 555 | + Ok(Adoption::Booted) => { | |
| 556 | + state.prefix = None; | |
| 557 | + state.index = None; | |
| 558 | + } | |
| 559 | + Ok(Adoption::Unchanged) => {} | |
| 560 | + Err(error) => { | |
| 561 | + tracing::warn!(%error, "asset version-skew fallback refresh failed"); | |
| 562 | + } | |
| 563 | + } | |
| 564 | + } | |
| 565 | + | |
| 566 | + /// Read the pointer and, when it names a deployment this resolver has | |
| 567 | + /// not adopted, load and validate that deployment's asset index with | |
| 568 | + /// the same gates the boot path applies. | |
| 569 | + async fn adopt_newer_index( | |
| 570 | + &self, | |
| 571 | + source: &FallbackSource, | |
| 572 | + adopted: Option<&str>, | |
| 573 | + ) -> anyhow::Result<Adoption> { | |
| 574 | + let bucket = &self.inner.bucket; | |
| 575 | + let (bytes, _) = bucket | |
| 576 | + .get(&source.pointer_key) | |
| 577 | + .await? | |
| 578 | + .with_context(|| format!("read {}", source.pointer_key))?; | |
| 579 | + let pointer: DeployPointer = | |
| 580 | + serde_json::from_slice(&bytes).context("decode deploy pointer")?; | |
| 581 | + if pointer.prefix == source.boot_prefix { | |
| 582 | + return Ok(Adoption::Booted); | |
| 583 | + } | |
| 584 | + if Some(pointer.prefix.as_str()) == adopted { | |
| 585 | + return Ok(Adoption::Unchanged); | |
| 586 | + } | |
| 587 | + let manifest_key = format!("{}/manifest.json", pointer.prefix); | |
| 588 | + let (bytes, _) = bucket | |
| 589 | + .get(&manifest_key) | |
| 590 | + .await? | |
| 591 | + .with_context(|| format!("read {manifest_key}"))?; | |
| 592 | + let manifest: Manifest = | |
| 593 | + serde_json::from_slice(&bytes).context("decode deployment manifest")?; | |
| 594 | + crate::protocol::validate_required_features(&manifest.required_features)?; | |
| 595 | + let Some(reference) = manifest.assets else { | |
| 596 | + // The newer deployment has no assets: adopt an empty index so | |
| 597 | + // the pointer is not re-fetched for every miss until it moves. | |
| 598 | + return Ok(Adoption::Newer { | |
| 599 | + prefix: pointer.prefix, | |
| 600 | + index: Box::default(), | |
| 601 | + }); | |
| 602 | + }; | |
| 603 | + let index_key = format!("{}/{}", pointer.prefix, reference.index); | |
| 604 | + let (bytes, _) = bucket | |
| 605 | + .get(&index_key) | |
| 606 | + .await? | |
| 607 | + .with_context(|| format!("read {index_key}"))?; | |
| 608 | + let sha256 = format!("{:x}", Sha256::digest(&bytes)); | |
| 609 | + if sha256 != reference.sha256 { | |
| 610 | + return Err(anyhow!("fallback asset index checksum mismatch")); | |
| 611 | + } | |
| 612 | + let index: AssetIndex = serde_json::from_slice(&bytes).context("decode asset index")?; | |
| 613 | + validate_index(&index, &reference)?; | |
| 614 | + Ok(Adoption::Newer { | |
| 615 | + prefix: pointer.prefix, | |
| 616 | + index: Box::new(index), | |
| 617 | + }) | |
| 618 | + } | |
| 619 | + | |
| 431 | 620 | fn navigation_prefers_asset_serving(&self, headers: &HeaderMap) -> bool { |
| 432 | 621 | if headers |
| 433 | 622 | .get("sec-fetch-mode") |
| @@ -857,6 +1046,15 @@ | ||
| 857 | 1046 | if !include_not_found { |
| 858 | 1047 | return Route::Missing; |
| 859 | 1048 | } |
| 1049 | + not_found_route(index, path) | |
| 1050 | +} | |
| 1051 | + | |
| 1052 | +/// The `not_found_handling` tail of `route`, separated so the version-skew | |
| 1053 | +/// fallback can run between an exact miss and the not-found fabrication: a | |
| 1054 | +/// single-page application must serve a NEW deployment's hashed asset, not | |
| 1055 | +/// its own stale `/index.html`, when both are possible. | |
| 1056 | +fn not_found_route(index: &AssetIndex, path: &str) -> Route { | |
| 1057 | + let entries = &index.entries; | |
| 860 | 1058 | match index.config.not_found_handling.as_deref() { |
| 861 | 1059 | Some("single-page-application") => entries |
| 862 | 1060 | .get("/index.html") |
modifiedcrates/celld/asyncrt.rs+28−3View file
| @@ -3,13 +3,12 @@ | ||
| 3 | 3 | // This module owns the ambient production primitives which the boundary lint |
| 4 | 4 | // prohibits elsewhere. |
| 5 | 5 | #![allow(clippy::disallowed_methods, clippy::disallowed_types)] |
| 6 | -#![warn(clippy::disallowed_macros)] | |
| 7 | 6 | |
| 8 | 7 | //! The production execution facade for celld. |
| 9 | 8 | //! |
| 10 | 9 | //! This module delegates tasks and timers to Tokio and obtains nondeterministic |
| 11 | -//! process values from the host. The private conformance build replaces this | |
| 12 | -//! module with its deterministic execution backend. | |
| 10 | +//! process values from the host. A cfg-gated build can replace this module | |
| 11 | +//! with another execution backend. | |
| 13 | 12 | |
| 14 | 13 | use crate::host_services::HostServices; |
| 15 | 14 | use rand::{CryptoRng, RngCore}; |
| @@ -24,6 +23,7 @@ | ||
| 24 | 23 | |
| 25 | 24 | static PROCESS_DOMAIN: OnceLock<ProductionDomain> = OnceLock::new(); |
| 26 | 25 | static FALLBACK_SERVICES: OnceLock<Arc<HostServices>> = OnceLock::new(); |
| 26 | +static SELECT_STATE: OnceLock<AtomicU64> = OnceLock::new(); | |
| 27 | 27 | |
| 28 | 28 | thread_local! { |
| 29 | 29 | static SPAWNS: RefCell<Vec<(u64, OpFuture)>> = const { RefCell::new(Vec::new()) }; |
| @@ -157,11 +157,35 @@ | ||
| 157 | 157 | current_domain().started_at.elapsed().as_millis() as u64 |
| 158 | 158 | } |
| 159 | 159 | |
| 160 | +/// Return monotonic process time in microseconds for timing instrumentation. | |
| 161 | +pub fn mono_us() -> u64 { | |
| 162 | + current_domain().started_at.elapsed().as_micros() as u64 | |
| 163 | +} | |
| 164 | + | |
| 160 | 165 | pub fn rng(consumer: &'static str) -> rng::Stream { |
| 161 | 166 | let _ = consumer; |
| 162 | 167 | rng::Stream::production() |
| 163 | 168 | } |
| 164 | 169 | |
| 170 | +fn mix_select(mut value: u64) -> u64 { | |
| 171 | + value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); | |
| 172 | + value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); | |
| 173 | + value ^ (value >> 31) | |
| 174 | +} | |
| 175 | + | |
| 176 | +/// Return the first branch index for one unbiased select poll. | |
| 177 | +pub fn select_start(branches: u32) -> u32 { | |
| 178 | + debug_assert!(branches > 0); | |
| 179 | + // A select can run before the process installs its Tokio handle. Keep its | |
| 180 | + // process-wide state separate, so branch ordering cannot capture a | |
| 181 | + // short-lived runtime that another operation later tries to use. | |
| 182 | + let state = SELECT_STATE | |
| 183 | + .get_or_init(|| AtomicU64::new(rand::rngs::OsRng.next_u64())) | |
| 184 | + .fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed) | |
| 185 | + .wrapping_add(0x9e37_79b9_7f4a_7c15); | |
| 186 | + (mix_select(state) % u64::from(branches)) as u32 | |
| 187 | +} | |
| 188 | + | |
| 165 | 189 | pub fn process_tag() -> u64 { |
| 166 | 190 | current_domain().process_tag |
| 167 | 191 | } |
| @@ -323,6 +347,7 @@ | ||
| 323 | 347 | } |
| 324 | 348 | |
| 325 | 349 | pub use crate::__celld_domain_select as select; |
| 350 | +pub use crate::__celld_domain_select_biased as select_biased; | |
| 326 | 351 | |
| 327 | 352 | pub mod rng { |
| 328 | 353 | use super::*; |
modifiedcrates/celld/bucket.rs+738−52View file
| @@ -1,7 +1,5 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -#![warn(clippy::disallowed_macros)] | |
| 4 | - | |
| 5 | 3 | //! The engine's single object-store client: the `object_store` crate |
| 6 | 4 | //! `celld-ltx` already links, bound to one bucket. Replaces aws-sdk-s3. |
| 7 | 5 | //! No call site streamed a body, so everything is in-memory `Bytes`. |
| @@ -28,6 +26,7 @@ | ||
| 28 | 26 | use anyhow::anyhow; |
| 29 | 27 | use anyhow::Context; |
| 30 | 28 | use bytes::Bytes; |
| 29 | +use futures_util::stream::BoxStream; | |
| 31 | 30 | use futures_util::StreamExt; |
| 32 | 31 | use object_store::aws::AmazonS3Builder; |
| 33 | 32 | use object_store::aws::S3ConditionalPut; |
| @@ -35,15 +34,20 @@ | ||
| 35 | 34 | use object_store::azure::AzureConfigKey; |
| 36 | 35 | use object_store::azure::MicrosoftAzureBuilder; |
| 37 | 36 | use object_store::gcp::GoogleCloudStorageBuilder; |
| 37 | +use object_store::list::PaginatedListOptions; | |
| 38 | +use object_store::list::PaginatedListStore; | |
| 38 | 39 | use object_store::path::Path; |
| 39 | 40 | use object_store::Attribute; |
| 40 | 41 | use object_store::Attributes; |
| 41 | 42 | use object_store::ClientOptions; |
| 42 | 43 | use object_store::Error; |
| 43 | 44 | use object_store::GetOptions; |
| 45 | +use object_store::GetRange; | |
| 46 | +use object_store::MultipartUpload; | |
| 44 | 47 | use object_store::ObjectMeta; |
| 45 | 48 | use object_store::ObjectStore; |
| 46 | 49 | use object_store::PutMode; |
| 50 | +use object_store::PutMultipartOptions; | |
| 47 | 51 | use object_store::PutOptions; |
| 48 | 52 | use object_store::PutPayload; |
| 49 | 53 | use object_store::RetryConfig; |
| @@ -68,10 +72,12 @@ | ||
| 68 | 72 | /// applies If-None-Match and If-Match to the etag, exactly as S3 does, |
| 69 | 73 | /// so the two share [`Self::token`] and [`Self::update`]. |
| 70 | 74 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 71 | -pub(crate) enum StorageBackend { | |
| 75 | +#[doc(hidden)] | |
| 76 | +pub enum StorageBackend { | |
| 72 | 77 | S3, |
| 73 | 78 | Gcs, |
| 74 | 79 | Azure, |
| 80 | + Local, | |
| 75 | 81 | } |
| 76 | 82 | |
| 77 | 83 | impl StorageBackend { |
| @@ -80,6 +86,7 @@ | ||
| 80 | 86 | StorageBackend::S3 => "s3", |
| 81 | 87 | StorageBackend::Gcs => "gs", |
| 82 | 88 | StorageBackend::Azure => "az", |
| 89 | + StorageBackend::Local => "dev", | |
| 83 | 90 | } |
| 84 | 91 | } |
| 85 | 92 | |
| @@ -87,9 +94,10 @@ | ||
| 87 | 94 | /// per dialect. A response without one cannot be fenced against, so a |
| 88 | 95 | /// missing or empty token is an error — never an empty string a later |
| 89 | 96 | /// conditional write would send as a real precondition. |
| 90 | - fn token(self, e_tag: Option<String>, version: Option<String>) -> anyhow::Result<String> { | |
| 97 | + #[doc(hidden)] | |
| 98 | + pub fn token(self, e_tag: Option<String>, version: Option<String>) -> anyhow::Result<String> { | |
| 91 | 99 | let (token, header) = match self { |
| 92 | - StorageBackend::S3 | StorageBackend::Azure => (e_tag, "ETag"), | |
| 100 | + StorageBackend::S3 | StorageBackend::Azure | StorageBackend::Local => (e_tag, "ETag"), | |
| 93 | 101 | StorageBackend::Gcs => (version, "x-goog-generation"), |
| 94 | 102 | }; |
| 95 | 103 | match token { |
| @@ -101,9 +109,10 @@ | ||
| 101 | 109 | } |
| 102 | 110 | |
| 103 | 111 | /// The precondition a conditional update sends for a held token. |
| 104 | - fn update(self, token: &str) -> UpdateVersion { | |
| 112 | + #[doc(hidden)] | |
| 113 | + pub fn update(self, token: &str) -> UpdateVersion { | |
| 105 | 114 | match self { |
| 106 | - StorageBackend::S3 | StorageBackend::Azure => UpdateVersion { | |
| 115 | + StorageBackend::S3 | StorageBackend::Azure | StorageBackend::Local => UpdateVersion { | |
| 107 | 116 | e_tag: Some(token.to_string()), |
| 108 | 117 | version: None, |
| 109 | 118 | }, |
| @@ -120,7 +129,9 @@ | ||
| 120 | 129 | /// wrong place. |
| 121 | 130 | fn precondition(self) -> &'static str { |
| 122 | 131 | match self { |
| 123 | - StorageBackend::S3 | StorageBackend::Azure => "If-Match / If-None-Match", | |
| 132 | + StorageBackend::S3 | StorageBackend::Azure | StorageBackend::Local => { | |
| 133 | + "If-Match / If-None-Match" | |
| 134 | + } | |
| 124 | 135 | StorageBackend::Gcs => "x-goog-if-generation-match", |
| 125 | 136 | } |
| 126 | 137 | } |
| @@ -131,13 +142,22 @@ | ||
| 131 | 142 | /// instance also isolates its traffic. |
| 132 | 143 | #[derive(Clone)] |
| 133 | 144 | pub struct Bucket { |
| 134 | - store: Arc<dyn ObjectStore>, | |
| 145 | + pub store: Arc<dyn ObjectStore>, | |
| 146 | + /// The same client as `store`, reached through the paginated listing | |
| 147 | + /// trait. `ObjectStore::list_with_delimiter` drains every continuation | |
| 148 | + /// page into one buffer before it returns, so it cannot answer "the | |
| 149 | + /// first N" without paying for all of them. `PaginatedListStore` takes | |
| 150 | + /// a page size and returns a resumption token, which is what bounds a | |
| 151 | + /// listing's cost rather than only its output. It is a separate trait, | |
| 152 | + /// so the concrete client has to be kept here as it is built — | |
| 153 | + /// `Arc<dyn ObjectStore>` cannot be widened to it later. | |
| 154 | + paginated: Arc<dyn PaginatedListStore>, | |
| 135 | 155 | /// Conditional writes only, built with retries OFF: a retried CAS put |
| 136 | 156 | /// can land on the first attempt's own token change and report a clean |
| 137 | 157 | /// 412 — converting "may have committed" into a false rejection. The |
| 138 | 158 | /// ambiguity must surface as `Err` so the caller reconciles. |
| 139 | - cas_store: Arc<dyn ObjectStore>, | |
| 140 | - backend: StorageBackend, | |
| 159 | + pub cas_store: Arc<dyn ObjectStore>, | |
| 160 | + pub backend: StorageBackend, | |
| 141 | 161 | /// Bucket name, for messages — the store is already bound to it. |
| 142 | 162 | pub name: String, |
| 143 | 163 | /// Empty, or a slash-terminated key prefix every operation is scoped |
| @@ -146,11 +166,21 @@ | ||
| 146 | 166 | pub prefix: String, |
| 147 | 167 | } |
| 148 | 168 | |
| 169 | +/// One page of [`Bucket::common_prefixes_page`]. | |
| 170 | +pub struct CommonPrefixPage { | |
| 171 | + /// The children this page listed, in the store's key order. | |
| 172 | + pub prefixes: Vec<String>, | |
| 173 | + /// Present exactly when the store truncated the page, so a caller | |
| 174 | + /// learns that more children exist without a second request. | |
| 175 | + pub page_token: Option<String>, | |
| 176 | +} | |
| 177 | + | |
| 149 | 178 | /// Whether a conditional write reached a provider-enforced conflict. |
| 150 | 179 | /// Azure reports a failed `If-None-Match` as `Precondition`, while some |
| 151 | 180 | /// stores report the same create conflict as `AlreadyExists`. Both are a |
| 152 | 181 | /// clean lost race. Every other error remains ambiguous. |
| 153 | -fn is_clean_cas_rejection(error: &Error) -> bool { | |
| 182 | +#[doc(hidden)] | |
| 183 | +pub fn is_clean_cas_rejection(error: &Error) -> bool { | |
| 154 | 184 | matches!( |
| 155 | 185 | error, |
| 156 | 186 | Error::Precondition { .. } | Error::AlreadyExists { .. } |
| @@ -167,7 +197,8 @@ | ||
| 167 | 197 | /// from `AZURE_STORAGE_ACCOUNT_NAME`. The second path segment is the key |
| 168 | 198 | /// prefix on all three schemes, so the account cannot live there without |
| 169 | 199 | /// making `az://` parse differently from the other two. |
| 170 | -fn split_spec(spec: &str) -> (StorageBackend, &str, String) { | |
| 200 | +#[doc(hidden)] | |
| 201 | +pub fn split_spec(spec: &str) -> (StorageBackend, &str, String) { | |
| 171 | 202 | let (backend, spec) = match (spec.strip_prefix("gs://"), spec.strip_prefix("az://")) { |
| 172 | 203 | (Some(rest), _) => (StorageBackend::Gcs, rest), |
| 173 | 204 | (_, Some(rest)) => (StorageBackend::Azure, rest), |
| @@ -182,10 +213,252 @@ | ||
| 182 | 213 | ) |
| 183 | 214 | } |
| 184 | 215 | |
| 216 | +/// The S3 endpoint the environment supplies when no explicit one was | |
| 217 | +/// given: the AWS SDK's standard `AWS_ENDPOINT_URL`, then the older | |
| 218 | +/// `AWS_ENDPOINT` — the same variables `AmazonS3Builder::from_env` | |
| 219 | +/// injects into the client. Resolved here so the path-style decision and | |
| 220 | +/// the client always agree about whether an endpoint is in play. | |
| 221 | +#[doc(hidden)] | |
| 222 | +pub fn resolve_env_endpoint() -> Option<String> { | |
| 223 | + ["AWS_ENDPOINT_URL", "AWS_ENDPOINT"] | |
| 224 | + .iter() | |
| 225 | + .find_map(|var| std::env::var(var).ok().filter(|value| !value.is_empty())) | |
| 226 | +} | |
| 227 | + | |
| 228 | +/// The byte range a `get` asked for. R2 spells a range four ways and so | |
| 229 | +/// does `object_store`, so the request reaches the backend as the caller | |
| 230 | +/// wrote it rather than widened to a whole-object read. | |
| 231 | +#[derive(Clone, Copy)] | |
| 232 | +pub enum BlobRange { | |
| 233 | + /// The whole object. | |
| 234 | + Whole, | |
| 235 | + /// `offset` onwards, to the end of the object. | |
| 236 | + From(u64), | |
| 237 | + /// `length` bytes starting at `offset`. | |
| 238 | + Bounded { offset: u64, length: u64 }, | |
| 239 | + /// The last `length` bytes. | |
| 240 | + Suffix(u64), | |
| 241 | +} | |
| 242 | + | |
| 243 | +/// R2's `onlyIf`, split by who can answer it. The etag halves ride down | |
| 244 | +/// to the store as If-Match / If-None-Match, so no concurrent write slips | |
| 245 | +/// between the check and the read. The upload-time halves are checked | |
| 246 | +/// here: R2 compares milliseconds and an HTTP date carries only seconds, | |
| 247 | +/// so If-Modified-Since would answer a different question for every | |
| 248 | +/// object written in the same second as the bound. | |
| 249 | +#[derive(Default, Clone)] | |
| 250 | +pub struct BlobConditions { | |
| 251 | + pub if_match: Option<String>, | |
| 252 | + pub if_none_match: Option<String>, | |
| 253 | + pub uploaded_before_ms: Option<i64>, | |
| 254 | + pub uploaded_after_ms: Option<i64>, | |
| 255 | +} | |
| 256 | + | |
| 257 | +impl BlobConditions { | |
| 258 | + /// Whether an etag satisfies the halves the store checks. Used on the | |
| 259 | + /// write path, which evaluates the whole condition itself against a | |
| 260 | + /// head rather than sending it, because a write's precondition has to | |
| 261 | + /// be paired with the CAS token of the very version it inspected. | |
| 262 | + fn etag_met(&self, etag: Option<&str>) -> bool { | |
| 263 | + let matches = |list: &str| match list.trim() { | |
| 264 | + "*" => etag.is_some(), | |
| 265 | + list => list | |
| 266 | + .split(',') | |
| 267 | + .any(|candidate| etag_eq(candidate, etag.unwrap_or_default())), | |
| 268 | + }; | |
| 269 | + self.if_match.as_deref().is_none_or(&matches) | |
| 270 | + && !self.if_none_match.as_deref().is_some_and(&matches) | |
| 271 | + } | |
| 272 | + | |
| 273 | + /// Whether an upload time satisfies the halves this module checks. | |
| 274 | + fn time_met(&self, uploaded_ms: i64) -> bool { | |
| 275 | + self.uploaded_before_ms | |
| 276 | + .is_none_or(|before| uploaded_ms < before) | |
| 277 | + && self | |
| 278 | + .uploaded_after_ms | |
| 279 | + .is_none_or(|after| uploaded_ms > after) | |
| 280 | + } | |
| 281 | + | |
| 282 | + fn is_empty(&self) -> bool { | |
| 283 | + self.if_match.is_none() | |
| 284 | + && self.if_none_match.is_none() | |
| 285 | + && self.uploaded_before_ms.is_none() | |
| 286 | + && self.uploaded_after_ms.is_none() | |
| 287 | + } | |
| 288 | +} | |
| 289 | + | |
| 290 | +/// Etag comparison, weak-marker and quote insensitive. R2 hands a Worker | |
| 291 | +/// the unquoted etag and takes either spelling back. | |
| 292 | +fn etag_eq(left: &str, right: &str) -> bool { | |
| 293 | + let bare = |value: &str| { | |
| 294 | + value | |
| 295 | + .trim() | |
| 296 | + .trim_start_matches("W/") | |
| 297 | + .trim_matches('"') | |
| 298 | + .to_string() | |
| 299 | + }; | |
| 300 | + bare(left) == bare(right) | |
| 301 | +} | |
| 302 | + | |
| 303 | +/// The HTTP headers and the user metadata an object carries. The five | |
| 304 | +/// headers are the ones every backend stores as headers, and are R2's | |
| 305 | +/// `httpMetadata` minus `cacheExpiry`, which no backend has a header for. | |
| 306 | +/// `metadata` is the backend's user metadata, kept under its own | |
| 307 | +/// `x-amz-meta-` / `x-goog-meta-` / `x-ms-meta-` prefix; what an R2 | |
| 308 | +/// binding puts in there is the binding's business, not this module's. | |
| 309 | +#[derive(Default, Clone)] | |
| 310 | +pub struct BlobAttributes { | |
| 311 | + pub content_type: Option<String>, | |
| 312 | + pub content_language: Option<String>, | |
| 313 | + pub content_disposition: Option<String>, | |
| 314 | + pub content_encoding: Option<String>, | |
| 315 | + pub cache_control: Option<String>, | |
| 316 | + pub metadata: Vec<(String, String)>, | |
| 317 | +} | |
| 318 | + | |
| 319 | +impl BlobAttributes { | |
| 320 | + /// The headers and user metadata on a response. Every other attribute | |
| 321 | + /// `object_store` parses is a transport detail, not the object's. | |
| 322 | + fn read(attributes: &Attributes) -> Self { | |
| 323 | + let value = |attribute: &Attribute| { | |
| 324 | + attributes | |
| 325 | + .get(attribute) | |
| 326 | + .map(|value| value.as_ref().to_string()) | |
| 327 | + }; | |
| 328 | + Self { | |
| 329 | + content_type: value(&Attribute::ContentType), | |
| 330 | + content_language: value(&Attribute::ContentLanguage), | |
| 331 | + content_disposition: value(&Attribute::ContentDisposition), | |
| 332 | + content_encoding: value(&Attribute::ContentEncoding), | |
| 333 | + cache_control: value(&Attribute::CacheControl), | |
| 334 | + metadata: user_metadata(attributes), | |
| 335 | + } | |
| 336 | + } | |
| 337 | + | |
| 338 | + /// The same, as the store's write-side attribute set. | |
| 339 | + fn write(&self) -> Attributes { | |
| 340 | + let mut attributes = Attributes::new(); | |
| 341 | + let mut set = |attribute: Attribute, value: &Option<String>| { | |
| 342 | + if let Some(value) = value { | |
| 343 | + attributes.insert(attribute, value.clone().into()); | |
| 344 | + } | |
| 345 | + }; | |
| 346 | + set(Attribute::ContentType, &self.content_type); | |
| 347 | + set(Attribute::ContentLanguage, &self.content_language); | |
| 348 | + set(Attribute::ContentDisposition, &self.content_disposition); | |
| 349 | + set(Attribute::ContentEncoding, &self.content_encoding); | |
| 350 | + set(Attribute::CacheControl, &self.cache_control); | |
| 351 | + for (name, value) in &self.metadata { | |
| 352 | + attributes.insert( | |
| 353 | + Attribute::Metadata(Cow::Owned(name.clone())), | |
| 354 | + value.clone().into(), | |
| 355 | + ); | |
| 356 | + } | |
| 357 | + attributes | |
| 358 | + } | |
| 359 | +} | |
| 360 | + | |
| 361 | +/// What every answer about an object knows, whatever asked for it. | |
| 362 | +pub struct BlobMeta { | |
| 363 | + pub size: u64, | |
| 364 | + pub etag: Option<String>, | |
| 365 | + /// The backend's version id, where the bucket has versioning on. | |
| 366 | + pub version: Option<String>, | |
| 367 | + /// The conditional-write token for exactly this version, in the | |
| 368 | + /// backend's dialect — the etag on S3 and Azure, the generation on | |
| 369 | + /// GCS. A conditional write pairs the check it made on this metadata | |
| 370 | + /// with the token, so a racing write cannot land in between. | |
| 371 | + pub cas: Option<String>, | |
| 372 | + pub uploaded_ms: i64, | |
| 373 | + pub attributes: BlobAttributes, | |
| 374 | +} | |
| 375 | + | |
| 376 | +/// A blob a `get` answered, with its body still on the wire. | |
| 377 | +pub struct Blob { | |
| 378 | + pub meta: BlobMeta, | |
| 379 | + /// The slice of the object this response carries, `(offset, length)`. | |
| 380 | + /// A bounded read that runs past the end is clamped by the store, so | |
| 381 | + /// this is what was served rather than what was asked for. | |
| 382 | + pub range: (u64, u64), | |
| 383 | + pub body: BoxStream<'static, Result<Vec<u8>, String>>, | |
| 384 | +} | |
| 385 | + | |
| 386 | +/// What a conditional read found. | |
| 387 | +pub enum BlobRead { | |
| 388 | + /// No such key. | |
| 389 | + Missing, | |
| 390 | + /// The key is there and the condition refused it. R2 answers the | |
| 391 | + /// object's metadata with no body, so the caller sees what it has. | |
| 392 | + Unmet(BlobMeta), | |
| 393 | + Hit(Blob), | |
| 394 | +} | |
| 395 | + | |
| 396 | +/// One object in a listing page. | |
| 397 | +pub struct BlobEntry { | |
| 398 | + pub key: String, | |
| 399 | + pub size: u64, | |
| 400 | + pub etag: Option<String>, | |
| 401 | + pub version: Option<String>, | |
| 402 | + pub uploaded_ms: i64, | |
| 403 | +} | |
| 404 | + | |
| 405 | +/// One page of a listing. | |
| 406 | +pub struct BlobPage { | |
| 407 | + pub objects: Vec<BlobEntry>, | |
| 408 | + /// The keys a delimiter rolled up, in key order and deduplicated. | |
| 409 | + pub prefixes: Vec<String>, | |
| 410 | + pub truncated: bool, | |
| 411 | + /// The last key this page consumed, whether it was listed or rolled | |
| 412 | + /// up. The next page resumes strictly after it, which is what R2's | |
| 413 | + /// opaque cursor does. | |
| 414 | + pub cursor: Option<String>, | |
| 415 | +} | |
| 416 | + | |
| 417 | +/// The user metadata on a response, as name/value pairs. `object_store` | |
| 418 | +/// parses the backend's `x-amz-meta-` / `x-goog-meta-` / `x-ms-meta-` | |
| 419 | +/// headers into `Attribute::Metadata`; every other attribute is a standard | |
| 420 | +/// HTTP header and not part of R2's `customMetadata`. | |
| 421 | +fn user_metadata(attributes: &Attributes) -> Vec<(String, String)> { | |
| 422 | + attributes | |
| 423 | + .iter() | |
| 424 | + .filter_map(|(attribute, value)| match attribute { | |
| 425 | + Attribute::Metadata(name) => { | |
| 426 | + Some((name.as_ref().to_string(), value.as_ref().to_string())) | |
| 427 | + } | |
| 428 | + _ => None, | |
| 429 | + }) | |
| 430 | + .collect() | |
| 431 | +} | |
| 432 | + | |
| 433 | +/// The paginated listing an injected store cannot serve. | |
| 434 | +/// | |
| 435 | +/// A test build constructs a bucket over plain injected stores, and a | |
| 436 | +/// paginated listing serves an operator command rather than a node | |
| 437 | +/// decision, so no injected store reaches one. Refusing is louder than an | |
| 438 | +/// empty page, which a caller would read as a fleet that holds no cells. | |
| 439 | +#[cfg(celld_internal_tests)] | |
| 440 | +#[derive(Debug)] | |
| 441 | +struct UnpaginatedStore; | |
| 442 | + | |
| 443 | +#[cfg(celld_internal_tests)] | |
| 444 | +#[async_trait::async_trait] | |
| 445 | +impl PaginatedListStore for UnpaginatedStore { | |
| 446 | + async fn list_paginated( | |
| 447 | + &self, | |
| 448 | + _prefix: Option<&str>, | |
| 449 | + _options: PaginatedListOptions, | |
| 450 | + ) -> object_store::Result<object_store::list::PaginatedListResult> { | |
| 451 | + Err(object_store::Error::NotSupported { | |
| 452 | + source: "an injected store serves no paginated listing".into(), | |
| 453 | + }) | |
| 454 | + } | |
| 455 | +} | |
| 456 | + | |
| 185 | 457 | impl Bucket { |
| 186 | 458 | /// Builds a bucket over injected ordinary and conditional-write stores. |
| 187 | - #[cfg(all(test, celld_internal_tests))] | |
| 188 | - pub(crate) fn with_stores( | |
| 459 | + #[cfg(celld_internal_tests)] | |
| 460 | + #[doc(hidden)] | |
| 461 | + pub fn with_stores( | |
| 189 | 462 | store: Arc<dyn ObjectStore>, |
| 190 | 463 | cas_store: Arc<dyn ObjectStore>, |
| 191 | 464 | backend: StorageBackend, |
| @@ -194,6 +467,7 @@ | ||
| 194 | 467 | ) -> Self { |
| 195 | 468 | Self { |
| 196 | 469 | store, |
| 470 | + paginated: Arc::new(UnpaginatedStore), | |
| 197 | 471 | cas_store, |
| 198 | 472 | backend, |
| 199 | 473 | name, |
| @@ -225,6 +499,10 @@ | ||
| 225 | 499 | credentials: Option<StaticCredentials>, |
| 226 | 500 | app: Option<&str>, |
| 227 | 501 | ) -> anyhow::Result<Bucket> { |
| 502 | + anyhow::ensure!( | |
| 503 | + !bucket.starts_with("dev://"), | |
| 504 | + "dev:// storage is internal to `celld dev` and is not a fleet bucket" | |
| 505 | + ); | |
| 228 | 506 | Self::open_with_sources( |
| 229 | 507 | bucket, |
| 230 | 508 | endpoint, |
| @@ -235,11 +513,27 @@ | ||
| 235 | 513 | ) |
| 236 | 514 | } |
| 237 | 515 | |
| 516 | + /// Open the machine-local development store. Only the `celld dev` | |
| 517 | + /// supervisor and its child node receive this constructor; fleet flags | |
| 518 | + /// continue to resolve exclusively through the cloud backend parser. | |
| 519 | + pub(crate) fn open_dev(database: &std::path::Path) -> anyhow::Result<Bucket> { | |
| 520 | + let store = Arc::new(crate::local_store::LocalStore::open(database)?); | |
| 521 | + Ok(Bucket { | |
| 522 | + store: store.clone(), | |
| 523 | + paginated: store.clone(), | |
| 524 | + cas_store: store, | |
| 525 | + backend: StorageBackend::Local, | |
| 526 | + name: database.display().to_string(), | |
| 527 | + prefix: String::new(), | |
| 528 | + }) | |
| 529 | + } | |
| 530 | + | |
| 238 | 531 | /// The body of [`Self::open`], taking the cloud configuration instead |
| 239 | 532 | /// of deriving it from the `GOOGLE_*` and `AZURE_*` environments. A |
| 240 | 533 | /// caller that passes explicit sources is independent of that |
| 241 | 534 | /// environment. |
| 242 | - fn open_with_sources( | |
| 535 | + #[doc(hidden)] | |
| 536 | + pub fn open_with_sources( | |
| 243 | 537 | bucket: &str, |
| 244 | 538 | endpoint: Option<&str>, |
| 245 | 539 | region: &str, |
| @@ -284,15 +578,30 @@ | ||
| 284 | 578 | retry_timeout: Duration::from_secs(30), |
| 285 | 579 | ..RetryConfig::default() |
| 286 | 580 | }; |
| 287 | - let (store, cas_store): (Arc<dyn ObjectStore>, Arc<dyn ObjectStore>) = match backend { | |
| 581 | + let (store, paginated, cas_store): ( | |
| 582 | + Arc<dyn ObjectStore>, | |
| 583 | + Arc<dyn PaginatedListStore>, | |
| 584 | + Arc<dyn ObjectStore>, | |
| 585 | + ) = match backend { | |
| 288 | 586 | StorageBackend::S3 => { |
| 587 | + // An endpoint can also arrive through the environment: | |
| 588 | + // `AmazonS3Builder::from_env` reads the AWS SDK's standard | |
| 589 | + // AWS_ENDPOINT_URL / AWS_ENDPOINT into the client. The | |
| 590 | + // path-style decision below must see that endpoint too — | |
| 591 | + // an env-supplied endpoint with virtual-hosted-style | |
| 592 | + // requests half-configures the client, and against an | |
| 593 | + // S3-compatible store every operation then fails with a | |
| 594 | + // NoSuchBucket that names the key prefix, pointing well | |
| 595 | + // away from the cause. An explicit argument (--endpoint / | |
| 596 | + // S3_ENDPOINT, resolved by the caller) still wins. | |
| 597 | + let endpoint = endpoint.map(str::to_string).or_else(resolve_env_endpoint); | |
| 289 | 598 | let mut builder = AmazonS3Builder::from_env() |
| 290 | 599 | .with_bucket_name(bucket) |
| 291 | 600 | .with_region(region) |
| 292 | 601 | .with_conditional_put(S3ConditionalPut::ETagMatch) |
| 293 | 602 | .with_retry(retry) |
| 294 | 603 | .with_client_options(options); |
| 295 | - if let Some(endpoint) = endpoint { | |
| 604 | + if let Some(endpoint) = endpoint.as_deref() { | |
| 296 | 605 | // Path-style against explicit S3-compatible endpoints, exactly |
| 297 | 606 | // as the aws client's force_path_style(endpoint.is_some()). |
| 298 | 607 | builder = builder |
| @@ -310,8 +619,10 @@ | ||
| 310 | 619 | } |
| 311 | 620 | } |
| 312 | 621 | let cas_builder = builder.clone().with_retry(cas_retry); |
| 622 | + let client = Arc::new(builder.build().context("build s3 client")?); | |
| 313 | 623 | ( |
| 314 | - Arc::new(builder.build().context("build s3 client")?), | |
| 624 | + client.clone(), | |
| 625 | + client, | |
| 315 | 626 | Arc::new(cas_builder.build().context("build s3 cas client")?), |
| 316 | 627 | ) |
| 317 | 628 | } |
| @@ -338,8 +649,10 @@ | ||
| 338 | 649 | .with_retry(retry) |
| 339 | 650 | .with_client_options(options); |
| 340 | 651 | let cas_builder = builder.clone().with_retry(cas_retry); |
| 652 | + let client = Arc::new(builder.build().context("build gcs client")?); | |
| 341 | 653 | ( |
| 342 | - Arc::new(builder.build().context("build gcs client")?), | |
| 654 | + client.clone(), | |
| 655 | + client, | |
| 343 | 656 | Arc::new(cas_builder.build().context("build gcs cas client")?), |
| 344 | 657 | ) |
| 345 | 658 | } |
| @@ -365,14 +678,20 @@ | ||
| 365 | 678 | .with_retry(retry) |
| 366 | 679 | .with_client_options(options); |
| 367 | 680 | let cas_builder = builder.clone().with_retry(cas_retry); |
| 681 | + let client = Arc::new(builder.build().context("build azure client")?); | |
| 368 | 682 | ( |
| 369 | - Arc::new(builder.build().context("build azure client")?), | |
| 683 | + client.clone(), | |
| 684 | + client, | |
| 370 | 685 | Arc::new(cas_builder.build().context("build azure cas client")?), |
| 371 | 686 | ) |
| 372 | 687 | } |
| 688 | + StorageBackend::Local => { | |
| 689 | + unreachable!("the local development store has its own constructor") | |
| 690 | + } | |
| 373 | 691 | }; |
| 374 | 692 | Ok(Bucket { |
| 375 | 693 | store, |
| 694 | + paginated, | |
| 376 | 695 | cas_store, |
| 377 | 696 | backend, |
| 378 | 697 | name: bucket.to_string(), |
| @@ -388,7 +707,8 @@ | ||
| 388 | 707 | |
| 389 | 708 | /// The dialect this bucket speaks, for choosing the matching |
| 390 | 709 | /// replication store. |
| 391 | - pub(crate) fn backend(&self) -> StorageBackend { | |
| 710 | + #[doc(hidden)] | |
| 711 | + pub fn backend(&self) -> StorageBackend { | |
| 392 | 712 | self.backend |
| 393 | 713 | } |
| 394 | 714 | |
| @@ -433,7 +753,7 @@ | ||
| 433 | 753 | .backend |
| 434 | 754 | .token(meta.e_tag, meta.version) |
| 435 | 755 | .with_context(|| format!("head {}://{}/{key}", self.scheme(), self.name))?; |
| 436 | - Ok(Some((meta.size as u64, token))) | |
| 756 | + Ok(Some((meta.size, token))) | |
| 437 | 757 | } |
| 438 | 758 | Err(Error::NotFound { .. }) => Ok(None), |
| 439 | 759 | Err(error) => { |
| @@ -474,7 +794,7 @@ | ||
| 474 | 794 | .attributes |
| 475 | 795 | .get(&Attribute::Metadata(name.to_string().into())) |
| 476 | 796 | .map(|value| value.as_ref().to_string()); |
| 477 | - Ok(Some((result.meta.size as u64, value))) | |
| 797 | + Ok(Some((result.meta.size, value))) | |
| 478 | 798 | } |
| 479 | 799 | Err(Error::NotFound { .. }) => Ok(None), |
| 480 | 800 | Err(error) => { |
| @@ -526,15 +846,6 @@ | ||
| 526 | 846 | None => PutMode::Create, |
| 527 | 847 | Some(token) => PutMode::Update(self.backend.update(token)), |
| 528 | 848 | }; |
| 529 | - #[cfg(all(test, celld_internal_tests))] | |
| 530 | - let mode = if token.is_none() | |
| 531 | - && crate::asyncrt::sabotage_active( | |
| 532 | - crate::host_services::EngineSabotage::FreshCreateOverwrites, | |
| 533 | - ) { | |
| 534 | - PutMode::Overwrite | |
| 535 | - } else { | |
| 536 | - mode | |
| 537 | - }; | |
| 538 | 849 | match self |
| 539 | 850 | .cas_store |
| 540 | 851 | .put_opts( |
| @@ -644,8 +955,66 @@ | ||
| 644 | 955 | } |
| 645 | 956 | } |
| 646 | 957 | |
| 958 | + /// One page of the immediate child "directories" under `prefix/`. | |
| 959 | + /// | |
| 960 | + /// `start_after` resumes from a child a previous page returned, and | |
| 961 | + /// `page_token` continues the same walk. Pass one or the other: a | |
| 962 | + /// token is exact and works on every backend, while `start_after` | |
| 963 | + /// survives between separate processes, so an operator can resume a | |
| 964 | + /// listing by name. | |
| 965 | + /// | |
| 966 | + /// The store compares `start_after` against object keys, not against | |
| 967 | + /// children, and every key below `prefix/child/` sorts after that | |
| 968 | + /// prefix itself. So the page that resumes a walk repeats the child it | |
| 969 | + /// resumed from, and the caller drops it. The reverse error would skip | |
| 970 | + /// a cell, so the boundary is deliberately inclusive. | |
| 971 | + pub async fn common_prefixes_page( | |
| 972 | + &self, | |
| 973 | + prefix: &str, | |
| 974 | + start_after: Option<&str>, | |
| 975 | + page_token: Option<String>, | |
| 976 | + max_keys: usize, | |
| 977 | + ) -> 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('/'))); | |
| 981 | + if start_after.is_some() && self.backend == StorageBackend::Azure { | |
| 982 | + anyhow::bail!( | |
| 983 | + "az:// cannot resume a listing by name, because Azure listing has no \ | |
| 984 | + start-after; drop --after and list the whole container" | |
| 985 | + ); | |
| 986 | + } | |
| 987 | + let result = self | |
| 988 | + .paginated | |
| 989 | + .list_paginated( | |
| 990 | + Some(path.as_str()), | |
| 991 | + PaginatedListOptions { | |
| 992 | + offset: start_after.map(|child| self.key(&format!("{child}/"))), | |
| 993 | + delimiter: Some(std::borrow::Cow::Borrowed("/")), | |
| 994 | + max_keys: Some(max_keys), | |
| 995 | + page_token, | |
| 996 | + ..PaginatedListOptions::default() | |
| 997 | + }, | |
| 998 | + ) | |
| 999 | + .await | |
| 1000 | + .with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; | |
| 1001 | + Ok(CommonPrefixPage { | |
| 1002 | + prefixes: result | |
| 1003 | + .result | |
| 1004 | + .common_prefixes | |
| 1005 | + .into_iter() | |
| 1006 | + .map(|child| self.unkey(child.as_ref()).to_string()) | |
| 1007 | + .collect(), | |
| 1008 | + page_token: result.page_token, | |
| 1009 | + }) | |
| 1010 | + } | |
| 1011 | + | |
| 647 | 1012 | /// Immediate child "directories" under `prefix/` (delimiter listing), |
| 648 | 1013 | /// as full prefixes with the trailing slash stripped. |
| 1014 | + /// | |
| 1015 | + /// Every page is drained into one buffer, so the cost is the whole | |
| 1016 | + /// listing. A caller that only needs a bounded answer must use | |
| 1017 | + /// [`Self::common_prefixes_page`] instead. | |
| 649 | 1018 | pub async fn common_prefixes(&self, prefix: &str) -> anyhow::Result<Vec<String>> { |
| 650 | 1019 | let path = Path::from(self.key(prefix.trim_end_matches('/'))); |
| 651 | 1020 | let result = self |
| @@ -660,6 +1029,316 @@ | ||
| 660 | 1029 | .collect()) |
| 661 | 1030 | } |
| 662 | 1031 | |
| 1032 | + // ---- R2 binding primitives ------------------------------------------ | |
| 1033 | + // | |
| 1034 | + // An `r2_buckets` binding is served out of the fleet bucket under the | |
| 1035 | + // reserved `r2/<bucket_name>/` prefix, so a Worker's blobs share the | |
| 1036 | + // durability and the credentials of everything else celld stores and | |
| 1037 | + // need no second bucket. These are the only operations that reach past | |
| 1038 | + // the in-memory `Bytes` contract the rest of this module keeps: a blob | |
| 1039 | + // is a Worker's payload and can be far larger than a fleet object, so | |
| 1040 | + // it is read as a stream and a large write goes through multipart. | |
| 1041 | + | |
| 1042 | + /// Everything about an object except its bytes, or `None` when the key | |
| 1043 | + /// does not exist. This is R2's `head`, and the read half of every | |
| 1044 | + /// conditional write. | |
| 1045 | + pub async fn head_blob(&self, key: &str) -> anyhow::Result<Option<BlobMeta>> { | |
| 1046 | + let key = self.key(key); | |
| 1047 | + let options = GetOptions { | |
| 1048 | + head: true, | |
| 1049 | + ..GetOptions::default() | |
| 1050 | + }; | |
| 1051 | + match self | |
| 1052 | + .store | |
| 1053 | + .get_opts(&Path::from(key.as_str()), options) | |
| 1054 | + .await | |
| 1055 | + { | |
| 1056 | + Ok(result) => Ok(Some(self.blob_meta(&result.meta, &result.attributes))), | |
| 1057 | + Err(Error::NotFound { .. }) => Ok(None), | |
| 1058 | + Err(error) => { | |
| 1059 | + Err(anyhow!(error).context(format!("head {}://{}/{key}", self.scheme(), self.name))) | |
| 1060 | + } | |
| 1061 | + } | |
| 1062 | + } | |
| 1063 | + | |
| 1064 | + /// One blob a `get` answered, with its body still on the wire. | |
| 1065 | + pub async fn get_blob( | |
| 1066 | + &self, | |
| 1067 | + key: &str, | |
| 1068 | + range: BlobRange, | |
| 1069 | + conditions: &BlobConditions, | |
| 1070 | + ) -> anyhow::Result<BlobRead> { | |
| 1071 | + let scoped = self.key(key); | |
| 1072 | + let options = GetOptions { | |
| 1073 | + range: match range { | |
| 1074 | + BlobRange::Whole => None, | |
| 1075 | + BlobRange::From(offset) => Some(GetRange::Offset(offset)), | |
| 1076 | + BlobRange::Bounded { offset, length } => { | |
| 1077 | + Some(GetRange::Bounded(offset..offset.saturating_add(length))) | |
| 1078 | + } | |
| 1079 | + BlobRange::Suffix(length) => Some(GetRange::Suffix(length)), | |
| 1080 | + }, | |
| 1081 | + if_match: conditions.if_match.clone(), | |
| 1082 | + if_none_match: conditions.if_none_match.clone(), | |
| 1083 | + ..GetOptions::default() | |
| 1084 | + }; | |
| 1085 | + let result = match self | |
| 1086 | + .store | |
| 1087 | + .get_opts(&Path::from(scoped.as_str()), options) | |
| 1088 | + .await | |
| 1089 | + { | |
| 1090 | + Ok(result) => result, | |
| 1091 | + // Only an absent key is a miss. A range that overshoots the end | |
| 1092 | + // of the object is served short, as R2 serves it; a range that | |
| 1093 | + // *starts* past the end is a 416, and it stays an error rather | |
| 1094 | + // than being turned into a miss, because that is what R2 does | |
| 1095 | + // with one too. | |
| 1096 | + Err(Error::NotFound { .. }) => return Ok(BlobRead::Missing), | |
| 1097 | + // The store says only that the condition failed. R2 answers a | |
| 1098 | + // refused `onlyIf` with the object itself, minus the body, so | |
| 1099 | + // one more head fills in what the caller is entitled to see. | |
| 1100 | + Err(Error::Precondition { .. } | Error::NotModified { .. }) => { | |
| 1101 | + return Ok(match self.head_blob(key).await? { | |
| 1102 | + Some(meta) => BlobRead::Unmet(meta), | |
| 1103 | + None => BlobRead::Missing, | |
| 1104 | + }) | |
| 1105 | + } | |
| 1106 | + Err(error) => { | |
| 1107 | + return Err(anyhow!(error).context(format!( | |
| 1108 | + "read {}://{}/{scoped}", | |
| 1109 | + self.scheme(), | |
| 1110 | + self.name | |
| 1111 | + ))) | |
| 1112 | + } | |
| 1113 | + }; | |
| 1114 | + let meta = self.blob_meta(&result.meta, &result.attributes); | |
| 1115 | + // The upload-time half of `onlyIf` is answered here, against the | |
| 1116 | + // millisecond the object carries. The body is dropped unread. | |
| 1117 | + if !conditions.time_met(meta.uploaded_ms) { | |
| 1118 | + return Ok(BlobRead::Unmet(meta)); | |
| 1119 | + } | |
| 1120 | + // `range` is the slice this response actually carries, which is | |
| 1121 | + // what the caller reads; a bounded request past the end is clamped | |
| 1122 | + // here rather than by the store. | |
| 1123 | + let served = result.range.clone(); | |
| 1124 | + let label = format!("read body {}://{}/{scoped}", self.scheme(), self.name); | |
| 1125 | + let body = result | |
| 1126 | + .into_stream() | |
| 1127 | + .map(move |chunk| match chunk { | |
| 1128 | + Ok(bytes) => Ok(bytes.to_vec()), | |
| 1129 | + Err(error) => Err(format!("{label}: {error}")), | |
| 1130 | + }) | |
| 1131 | + .boxed(); | |
| 1132 | + Ok(BlobRead::Hit(Blob { | |
| 1133 | + meta, | |
| 1134 | + range: (served.start, served.end.saturating_sub(served.start)), | |
| 1135 | + body, | |
| 1136 | + })) | |
| 1137 | + } | |
| 1138 | + | |
| 1139 | + /// A plain (non-multipart) write, carrying R2's `httpMetadata` and | |
| 1140 | + /// `customMetadata`. | |
| 1141 | + /// | |
| 1142 | + /// `conditions` is R2's `onlyIf`, and is answered by reading the | |
| 1143 | + /// object first and pairing the verdict with that version's CAS token: | |
| 1144 | + /// the check and the write then apply to the same version, and a racing | |
| 1145 | + /// write between them is refused rather than overwritten. `Ok(None)` is | |
| 1146 | + /// a refused precondition — R2 reports one as a `null` return, not a | |
| 1147 | + /// throw — and every other failure stays an error. | |
| 1148 | + pub async fn put_blob( | |
| 1149 | + &self, | |
| 1150 | + key: &str, | |
| 1151 | + body: PutPayload, | |
| 1152 | + attributes: &BlobAttributes, | |
| 1153 | + conditions: &BlobConditions, | |
| 1154 | + ) -> anyhow::Result<Option<BlobMeta>> { | |
| 1155 | + let size = body.content_length() as u64; | |
| 1156 | + let mode = match conditions.is_empty() { | |
| 1157 | + true => PutMode::Overwrite, | |
| 1158 | + false => match self.head_blob(key).await? { | |
| 1159 | + Some(current) => { | |
| 1160 | + if !conditions.etag_met(current.etag.as_deref()) | |
| 1161 | + || !conditions.time_met(current.uploaded_ms) | |
| 1162 | + { | |
| 1163 | + return Ok(None); | |
| 1164 | + } | |
| 1165 | + let Some(cas) = current.cas else { | |
| 1166 | + return Err(anyhow!( | |
| 1167 | + "conditional R2 write of {}://{}/{key} cannot be fenced: \ | |
| 1168 | + the store answered no version token", | |
| 1169 | + self.scheme(), | |
| 1170 | + self.name | |
| 1171 | + )); | |
| 1172 | + }; | |
| 1173 | + PutMode::Update(self.backend.update(&cas)) | |
| 1174 | + } | |
| 1175 | + // Nothing there: only a condition that an absent object can | |
| 1176 | + // satisfy may write, and it writes as a create so that a | |
| 1177 | + // racing create loses. | |
| 1178 | + None => match conditions.etag_met(None) { | |
| 1179 | + true => PutMode::Create, | |
| 1180 | + false => return Ok(None), | |
| 1181 | + }, | |
| 1182 | + }, | |
| 1183 | + }; | |
| 1184 | + let conditional = !matches!(mode, PutMode::Overwrite); | |
| 1185 | + let store = match conditional { | |
| 1186 | + true => &self.cas_store, | |
| 1187 | + false => &self.store, | |
| 1188 | + }; | |
| 1189 | + let scoped = self.key(key); | |
| 1190 | + let options = PutOptions { | |
| 1191 | + mode, | |
| 1192 | + attributes: attributes.write(), | |
| 1193 | + ..PutOptions::default() | |
| 1194 | + }; | |
| 1195 | + match store | |
| 1196 | + .put_opts(&Path::from(scoped.as_str()), body, options) | |
| 1197 | + .await | |
| 1198 | + { | |
| 1199 | + Ok(result) => Ok(Some(BlobMeta { | |
| 1200 | + size, | |
| 1201 | + cas: self | |
| 1202 | + .backend | |
| 1203 | + .token(result.e_tag.clone(), result.version.clone()) | |
| 1204 | + .ok(), | |
| 1205 | + etag: result.e_tag, | |
| 1206 | + version: result.version, | |
| 1207 | + uploaded_ms: crate::asyncrt::wall_ms(), | |
| 1208 | + attributes: attributes.clone(), | |
| 1209 | + })), | |
| 1210 | + // A racing write took the version this one checked. The | |
| 1211 | + // caller's precondition is no longer true, which is the answer | |
| 1212 | + // R2 would have given had the race gone the other way. | |
| 1213 | + Err(error) if conditional && is_clean_cas_rejection(&error) => Ok(None), | |
| 1214 | + Err(error) => Err(anyhow!(error).context(format!( | |
| 1215 | + "write {}://{}/{scoped}", | |
| 1216 | + self.scheme(), | |
| 1217 | + self.name | |
| 1218 | + ))), | |
| 1219 | + } | |
| 1220 | + } | |
| 1221 | + | |
| 1222 | + /// One listing page: every object whose full key starts with `prefix`, | |
| 1223 | + /// in key order, resuming strictly after `after`. `limit` bounds the | |
| 1224 | + /// page, counting a rolled-up prefix as R2 counts one — against the | |
| 1225 | + /// same limit as an object. | |
| 1226 | + /// | |
| 1227 | + /// `prefix` is a raw string prefix, as R2's is, not the directory | |
| 1228 | + /// prefix the rest of this module lists by: the store is asked for the | |
| 1229 | + /// enclosing directory and the tail is matched here. | |
| 1230 | + /// | |
| 1231 | + /// `delimiter` is R2's: the run of a key between the end of `prefix` | |
| 1232 | + /// and the delimiter's first occurrence after it stands in for every | |
| 1233 | + /// key sharing it, and those keys are not listed individually. | |
| 1234 | + pub async fn list_page( | |
| 1235 | + &self, | |
| 1236 | + prefix: &str, | |
| 1237 | + after: Option<&str>, | |
| 1238 | + limit: usize, | |
| 1239 | + delimiter: Option<&str>, | |
| 1240 | + ) -> anyhow::Result<BlobPage> { | |
| 1241 | + let directory = prefix.rsplit_once('/').map_or("", |(head, _)| head); | |
| 1242 | + let path = Path::from(self.key(directory).as_str()); | |
| 1243 | + let mut stream = match after { | |
| 1244 | + Some(after) => self | |
| 1245 | + .store | |
| 1246 | + .list_with_offset(Some(&path), &Path::from(self.key(after).as_str())), | |
| 1247 | + None => self.store.list(Some(&path)), | |
| 1248 | + }; | |
| 1249 | + let delimiter = delimiter.filter(|delimiter| !delimiter.is_empty()); | |
| 1250 | + let mut page = BlobPage { | |
| 1251 | + objects: Vec::with_capacity(limit.min(1024)), | |
| 1252 | + prefixes: Vec::new(), | |
| 1253 | + truncated: false, | |
| 1254 | + cursor: None, | |
| 1255 | + }; | |
| 1256 | + // The rolled-up prefixes seen so far. A listing is in key order, so | |
| 1257 | + // a run of keys under one prefix is contiguous and only the newest | |
| 1258 | + // prefix can repeat — but a delimiter is any string, not only `/`, | |
| 1259 | + // so `prefix` can be re-entered later and the set is kept whole. | |
| 1260 | + // Ordered, because nothing in the engine may hold state a replay | |
| 1261 | + // would walk in a different order. | |
| 1262 | + let mut rolled = std::collections::BTreeSet::new(); | |
| 1263 | + while let Some(meta) = stream.next().await { | |
| 1264 | + let meta = | |
| 1265 | + meta.with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; | |
| 1266 | + let key = self.unkey(meta.location.as_ref()); | |
| 1267 | + if !key.starts_with(prefix) { | |
| 1268 | + continue; | |
| 1269 | + } | |
| 1270 | + let group = delimiter.and_then(|delimiter| { | |
| 1271 | + key[prefix.len()..] | |
| 1272 | + .find(delimiter) | |
| 1273 | + .map(|at| key[..prefix.len() + at + delimiter.len()].to_string()) | |
| 1274 | + }); | |
| 1275 | + // A prefix already rolled up costs nothing and does not end the | |
| 1276 | + // page: it is the same entry the caller has already been given. | |
| 1277 | + if let Some(group) = &group { | |
| 1278 | + if rolled.contains(group) { | |
| 1279 | + page.cursor = Some(key.to_string()); | |
| 1280 | + continue; | |
| 1281 | + } | |
| 1282 | + } | |
| 1283 | + if page.objects.len() + page.prefixes.len() == limit { | |
| 1284 | + page.truncated = true; | |
| 1285 | + break; | |
| 1286 | + } | |
| 1287 | + match group { | |
| 1288 | + Some(group) => { | |
| 1289 | + rolled.insert(group.clone()); | |
| 1290 | + page.prefixes.push(group); | |
| 1291 | + } | |
| 1292 | + None => page.objects.push(BlobEntry { | |
| 1293 | + key: key.to_string(), | |
| 1294 | + size: meta.size, | |
| 1295 | + etag: meta.e_tag, | |
| 1296 | + version: meta.version, | |
| 1297 | + uploaded_ms: meta.last_modified.timestamp_millis(), | |
| 1298 | + }), | |
| 1299 | + } | |
| 1300 | + page.cursor = Some(key.to_string()); | |
| 1301 | + } | |
| 1302 | + if !page.truncated { | |
| 1303 | + page.cursor = None; | |
| 1304 | + } | |
| 1305 | + Ok(page) | |
| 1306 | + } | |
| 1307 | + | |
| 1308 | + /// Open a multipart upload carrying R2's `httpMetadata` and | |
| 1309 | + /// `customMetadata`. The parts and the completion ride on the returned | |
| 1310 | + /// handle. | |
| 1311 | + pub async fn begin_multipart( | |
| 1312 | + &self, | |
| 1313 | + key: &str, | |
| 1314 | + attributes: &BlobAttributes, | |
| 1315 | + ) -> anyhow::Result<Box<dyn MultipartUpload>> { | |
| 1316 | + let key = self.key(key); | |
| 1317 | + let options = PutMultipartOptions { | |
| 1318 | + attributes: attributes.write(), | |
| 1319 | + ..PutMultipartOptions::default() | |
| 1320 | + }; | |
| 1321 | + self.store | |
| 1322 | + .put_multipart_opts(&Path::from(key.as_str()), options) | |
| 1323 | + .await | |
| 1324 | + .with_context(|| format!("begin multipart {}://{}/{key}", self.scheme(), self.name)) | |
| 1325 | + } | |
| 1326 | + | |
| 1327 | + /// One object's metadata, in the shape every R2 answer carries. | |
| 1328 | + fn blob_meta(&self, meta: &ObjectMeta, attributes: &Attributes) -> BlobMeta { | |
| 1329 | + BlobMeta { | |
| 1330 | + size: meta.size, | |
| 1331 | + etag: meta.e_tag.clone(), | |
| 1332 | + version: meta.version.clone(), | |
| 1333 | + cas: self | |
| 1334 | + .backend | |
| 1335 | + .token(meta.e_tag.clone(), meta.version.clone()) | |
| 1336 | + .ok(), | |
| 1337 | + uploaded_ms: meta.last_modified.timestamp_millis(), | |
| 1338 | + attributes: BlobAttributes::read(attributes), | |
| 1339 | + } | |
| 1340 | + } | |
| 1341 | + | |
| 663 | 1342 | /// The head_bucket replacement: prove the bucket is reachable and the |
| 664 | 1343 | /// credential is accepted with one list page. Scoped to the prefix, so |
| 665 | 1344 | /// a credential scoped to it validates too. |
| @@ -805,13 +1484,15 @@ | ||
| 805 | 1484 | /// (OAuth via Application Default Credentials or the `GOOGLE_*` env), |
| 806 | 1485 | /// with the same bounded retry policy the S3 replica lane uses. Replica |
| 807 | 1486 | /// writes are plain puts, so retries stay on. |
| 808 | -pub(crate) fn gcs_replica_store(bucket: &str) -> anyhow::Result<Arc<dyn ObjectStore>> { | |
| 1487 | +#[doc(hidden)] | |
| 1488 | +pub fn gcs_replica_store(bucket: &str) -> anyhow::Result<Arc<dyn ObjectStore>> { | |
| 809 | 1489 | gcs_replica_store_with_builder(GoogleCloudStorageBuilder::from_env(), bucket) |
| 810 | 1490 | } |
| 811 | 1491 | |
| 812 | 1492 | /// The body of [`gcs_replica_store`], taking the base builder for the same |
| 813 | 1493 | /// reason [`Bucket::open_with_sources`] does. |
| 814 | -fn gcs_replica_store_with_builder( | |
| 1494 | +#[doc(hidden)] | |
| 1495 | +pub fn gcs_replica_store_with_builder( | |
| 815 | 1496 | builder: GoogleCloudStorageBuilder, |
| 816 | 1497 | bucket: &str, |
| 817 | 1498 | ) -> anyhow::Result<Arc<dyn ObjectStore>> { |
| @@ -828,13 +1509,15 @@ | ||
| 828 | 1509 | /// and connection pool, authenticated like [`Bucket::open`]'s az:// path, |
| 829 | 1510 | /// with the same bounded retry policy the S3 replica lane uses. Replica |
| 830 | 1511 | /// writes are plain puts, so retries stay on. |
| 831 | -pub(crate) fn azure_replica_store(container: &str) -> anyhow::Result<Arc<dyn ObjectStore>> { | |
| 1512 | +#[doc(hidden)] | |
| 1513 | +pub fn azure_replica_store(container: &str) -> anyhow::Result<Arc<dyn ObjectStore>> { | |
| 832 | 1514 | azure_replica_store_with_env(&AzureEnv::from_process(), container) |
| 833 | 1515 | } |
| 834 | 1516 | |
| 835 | 1517 | /// The body of [`azure_replica_store`], taking the environment for the |
| 836 | 1518 | /// same reason [`Bucket::open_with_sources`] does. |
| 837 | -fn azure_replica_store_with_env( | |
| 1519 | +#[doc(hidden)] | |
| 1520 | +pub fn azure_replica_store_with_env( | |
| 838 | 1521 | env: &AzureEnv, |
| 839 | 1522 | container: &str, |
| 840 | 1523 | ) -> anyhow::Result<Arc<dyn ObjectStore>> { |
| @@ -849,11 +1532,12 @@ | ||
| 849 | 1532 | /// The `AZURE_*` variables an `az://` bucket can inspect. celld captures |
| 850 | 1533 | /// them instead of letting `MicrosoftAzureBuilder::from_env` read the |
| 851 | 1534 | /// process environment, because the fleet client must decide which |
| 852 | -/// recognized settings it honors, and a test must be able to supply a | |
| 853 | -/// set of its own. Names that `AzureConfigKey` does not parse are inert | |
| 1535 | +/// recognized settings it honors, and a caller can supply an explicit set. | |
| 1536 | +/// Names that `AzureConfigKey` does not parse are inert | |
| 854 | 1537 | /// and stay ignored, as they are in `from_env`. |
| 855 | 1538 | #[derive(Clone, Default)] |
| 856 | -pub(crate) struct AzureEnv { | |
| 1539 | +#[doc(hidden)] | |
| 1540 | +pub struct AzureEnv { | |
| 857 | 1541 | variables: Vec<(String, String)>, |
| 858 | 1542 | } |
| 859 | 1543 | |
| @@ -863,7 +1547,8 @@ | ||
| 863 | 1547 | AzureEnv::from_pairs(std::env::vars().filter(|(name, _)| name.starts_with("AZURE_"))) |
| 864 | 1548 | } |
| 865 | 1549 | |
| 866 | - fn from_pairs<K, V>(pairs: impl IntoIterator<Item = (K, V)>) -> AzureEnv | |
| 1550 | + #[doc(hidden)] | |
| 1551 | + pub fn from_pairs<K, V>(pairs: impl IntoIterator<Item = (K, V)>) -> AzureEnv | |
| 867 | 1552 | where |
| 868 | 1553 | K: Into<String>, |
| 869 | 1554 | V: Into<String>, |
| @@ -882,9 +1567,10 @@ | ||
| 882 | 1567 | /// environment: the GCS builder, and the `AZURE_*` variables. Bundled so |
| 883 | 1568 | /// the seam that makes construction environment-independent stays one |
| 884 | 1569 | /// parameter as backends are added. |
| 885 | -pub(crate) struct CloudSources { | |
| 886 | - gcs: GoogleCloudStorageBuilder, | |
| 887 | - azure: AzureEnv, | |
| 1570 | +#[doc(hidden)] | |
| 1571 | +pub struct CloudSources { | |
| 1572 | + pub gcs: GoogleCloudStorageBuilder, | |
| 1573 | + pub azure: AzureEnv, | |
| 888 | 1574 | } |
| 889 | 1575 | |
| 890 | 1576 | impl CloudSources { |
| @@ -1090,14 +1776,14 @@ | ||
| 1090 | 1776 | ) { |
| 1091 | 1777 | return true; |
| 1092 | 1778 | } |
| 1093 | - // The list path wraps HTTP errors as Generic; the status only | |
| 1094 | - // survives in the retry error's message. | |
| 1779 | + // The S3 list path wraps its private retry error as Generic, so the | |
| 1780 | + // status survives only in Display. object_store 0.11 used `status | |
| 1781 | + // 403`, and 0.12 uses the canonical HTTP phrase below. A revoked | |
| 1782 | + // managed credential must keep the same operator-visible state. | |
| 1095 | 1783 | let text = cause.to_string(); |
| 1096 | - text.contains("status 403") || text.contains("status 401") | |
| 1784 | + text.contains("status 403") | |
| 1785 | + || text.contains("status 401") | |
| 1786 | + || text.contains("status code: 403 Forbidden") | |
| 1787 | + || text.contains("status code: 401 Unauthorized") | |
| 1097 | 1788 | }) |
| 1098 | 1789 | } |
| 1099 | - | |
| 1100 | -#[cfg(all(test, celld_internal_tests))] | |
| 1101 | -mod conformance_bucket_tests { | |
| 1102 | - include!(env!("CELLD_CONFORMANCE_BUCKET_TESTS")); | |
| 1103 | -} |
addedcrates/celld/cell_cli.rs+250−0View file
| @@ -1,0 +1,250 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +// The cell CLI times an operator's listing outside the execution boundary. | |
| 4 | +#![allow(clippy::disallowed_methods)] | |
| 5 | +// The package macro policy keeps listing data behind `Output`, which is the | |
| 6 | +// boundary that this module exists to preserve. | |
| 7 | + | |
| 8 | +//! `celld cell` — the operator's view of the Durable Object instances a | |
| 9 | +//! fleet holds. | |
| 10 | +//! | |
| 11 | +//! A fleet bucket can hold millions of cells, and one `LIST` request | |
| 12 | +//! returns at most a thousand children. So a listing's cost is set by how | |
| 13 | +//! many cells exist, not by how many the operator asked to see. The default | |
| 14 | +//! answer therefore costs one request, `--after` resumes, and `--all` is the | |
| 15 | +//! explicit request for the whole walk. [`crate::cli_output`] owns those | |
| 16 | +//! rules; this module supplies the rows. | |
| 17 | + | |
| 18 | +use anyhow::bail; | |
| 19 | +use anyhow::Context; | |
| 20 | +use std::borrow::Cow; | |
| 21 | + | |
| 22 | +use crate::cli_options::FleetFlags; | |
| 23 | +use crate::cli_options::FLEET_HELP; | |
| 24 | +use crate::cli_options::LISTING_HELP; | |
| 25 | +use crate::cli_output::list; | |
| 26 | +use crate::cli_output::Bounds; | |
| 27 | +use crate::cli_output::Format; | |
| 28 | +use crate::cli_output::Output; | |
| 29 | +use crate::cli_output::Page; | |
| 30 | +use crate::cli_output::Record; | |
| 31 | +use crate::cli_output::Resumable; | |
| 32 | +use crate::cli_output::Resume; | |
| 33 | +use crate::note; | |
| 34 | + | |
| 35 | +/// One Durable Object instance. | |
| 36 | +struct Cell { | |
| 37 | + scope: String, | |
| 38 | +} | |
| 39 | + | |
| 40 | +impl Record for Cell { | |
| 41 | + fn json(&self) -> serde_json::Value { | |
| 42 | + // A scope carries no class when an application named a bare | |
| 43 | + // instance. A null reads back as absent rather than as a class | |
| 44 | + // named "", and the keys stay present either way so a reader that | |
| 45 | + // infers a schema from the first line sees every column. | |
| 46 | + let (class, id) = match self.scope.split_once(':') { | |
| 47 | + Some((class, id)) => (serde_json::Value::from(class), serde_json::Value::from(id)), | |
| 48 | + None => ( | |
| 49 | + serde_json::Value::Null, | |
| 50 | + serde_json::Value::from(self.scope.as_str()), | |
| 51 | + ), | |
| 52 | + }; | |
| 53 | + // A fleet holds celld's own cells beside the application's: D1 | |
| 54 | + // databases, KV namespaces and Workflows are each a reserved class. | |
| 55 | + // They are real cells that hold real bytes, so hiding them would | |
| 56 | + // understate the bucket -- but an operator asking which Durable | |
| 57 | + // Objects their application has does not mean these, so the row | |
| 58 | + // says which it is and a reader can filter on it. | |
| 59 | + let reserved = class.as_str().is_some_and(crate::deploy::is_reserved_class); | |
| 60 | + serde_json::json!({ | |
| 61 | + "scope": self.scope, | |
| 62 | + "class": class, | |
| 63 | + "id": id, | |
| 64 | + "reserved": reserved, | |
| 65 | + }) | |
| 66 | + } | |
| 67 | + | |
| 68 | + fn text(&self) -> Cow<'_, str> { | |
| 69 | + Cow::Borrowed(&self.scope) | |
| 70 | + } | |
| 71 | +} | |
| 72 | + | |
| 73 | +impl Resumable for Cell { | |
| 74 | + fn cursor(&self) -> &str { | |
| 75 | + &self.scope | |
| 76 | + } | |
| 77 | +} | |
| 78 | + | |
| 79 | +#[derive(Debug, Default, PartialEq, Eq)] | |
| 80 | +pub(crate) struct ListOptions { | |
| 81 | + pub(crate) fleet: FleetFlags, | |
| 82 | + pub(crate) bounds: Bounds, | |
| 83 | + pub(crate) class: Option<String>, | |
| 84 | + pub(crate) json: bool, | |
| 85 | +} | |
| 86 | + | |
| 87 | +pub(crate) fn list_options_from_arguments( | |
| 88 | + arguments: Vec<String>, | |
| 89 | +) -> anyhow::Result<Option<ListOptions>> { | |
| 90 | + let mut options = ListOptions::default(); | |
| 91 | + let mut arguments = arguments.into_iter(); | |
| 92 | + while let Some(argument) = arguments.next() { | |
| 93 | + // Rebuilt per iteration so the loop and the flag helpers can share | |
| 94 | + // the iterator without holding two borrows at once. | |
| 95 | + let mut value = |option: &str| { | |
| 96 | + arguments | |
| 97 | + .next() | |
| 98 | + .ok_or_else(|| anyhow::anyhow!("{option} requires a value")) | |
| 99 | + }; | |
| 100 | + match argument.as_str() { | |
| 101 | + "-h" | "--help" => return Ok(None), | |
| 102 | + "--json" => options.json = true, | |
| 103 | + other => { | |
| 104 | + if options.fleet.consume(other, &mut value)? { | |
| 105 | + continue; | |
| 106 | + } | |
| 107 | + if options.bounds.consume(other, &mut value)? { | |
| 108 | + continue; | |
| 109 | + } | |
| 110 | + // A class is the only positional, so a leading dash is a | |
| 111 | + // mistyped option rather than a class named "--clas". | |
| 112 | + if other.starts_with('-') { | |
| 113 | + bail!( | |
| 114 | + "unknown cell list option: {other}; run `celld cell list --help` for usage" | |
| 115 | + ); | |
| 116 | + } | |
| 117 | + if let Some(existing) = options.class.as_deref() { | |
| 118 | + bail!("celld cell list takes one class, and already has {existing:?}"); | |
| 119 | + } | |
| 120 | + options.class = Some(other.to_string()); | |
| 121 | + } | |
| 122 | + } | |
| 123 | + } | |
| 124 | + options.bounds.validate()?; | |
| 125 | + if let Some(after) = options.bounds.after.as_deref() { | |
| 126 | + if !celld_logic::cell::valid_cell_scope(after) { | |
| 127 | + bail!("--after takes a cell scope this command printed, not {after:?}"); | |
| 128 | + } | |
| 129 | + } | |
| 130 | + Ok(Some(options)) | |
| 131 | +} | |
| 132 | + | |
| 133 | +pub(crate) fn help_text() -> String { | |
| 134 | + format!( | |
| 135 | + r#"List the Durable Object instances in the fleet bucket. | |
| 136 | + | |
| 137 | +USAGE: | |
| 138 | + celld cell list [CLASS] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS] | |
| 139 | + | |
| 140 | +The listing is bounded by default, because a fleet can hold far more cells | |
| 141 | +than an operator wants to read and each request returns at most {page} | |
| 142 | +children. A bounded answer reports on stderr that more cells exist. | |
| 143 | + | |
| 144 | +OPTIONS: | |
| 145 | +{FLEET_HELP} | |
| 146 | +{LISTING_HELP} | |
| 147 | + -h, --help Show this help | |
| 148 | + | |
| 149 | +Output is in the store's key order, which is what makes --after resume | |
| 150 | +exactly where the previous answer stopped."#, | |
| 151 | + page = Bounds::MAX_PAGE, | |
| 152 | + ) | |
| 153 | +} | |
| 154 | + | |
| 155 | +/// The cell scopes in one page of children, in the order the store listed | |
| 156 | +/// them. `after` is dropped when it repeats: the store resumes from a key, | |
| 157 | +/// and every key below `cells/<after>/` sorts after that prefix, so the | |
| 158 | +/// resumed page lists the boundary child again. | |
| 159 | +pub(crate) fn cell_scopes_from_prefixes<'a>( | |
| 160 | + prefixes: impl IntoIterator<Item = String> + 'a, | |
| 161 | + class: Option<&'a str>, | |
| 162 | + after: Option<&'a str>, | |
| 163 | +) -> impl Iterator<Item = String> + 'a { | |
| 164 | + prefixes | |
| 165 | + .into_iter() | |
| 166 | + .filter_map(|prefix| prefix.strip_prefix("cells/").map(str::to_string)) | |
| 167 | + // The scope charset is the engine's storage fence. A prefix that | |
| 168 | + // fails it was not written by a celld node, so listing it would | |
| 169 | + // present foreign bucket content as a Durable Object instance. | |
| 170 | + .filter(|cell| celld_logic::cell::valid_cell_scope(cell)) | |
| 171 | + .filter(move |cell| after != Some(cell.as_str())) | |
| 172 | + .filter(move |cell| { | |
| 173 | + class.is_none_or(|class| { | |
| 174 | + cell.split_once(':') | |
| 175 | + .is_some_and(|(cell_class, _)| cell_class == class) | |
| 176 | + }) | |
| 177 | + }) | |
| 178 | +} | |
| 179 | + | |
| 180 | +pub async fn run(arguments: Vec<String>) -> anyhow::Result<()> { | |
| 181 | + let mut arguments = arguments.into_iter(); | |
| 182 | + match arguments.next().as_deref() { | |
| 183 | + Some("list") => run_list(arguments.collect()).await, | |
| 184 | + None | Some("-h") | Some("--help") | Some("help") => { | |
| 185 | + Output::new(Format::Text).help(&help_text()) | |
| 186 | + } | |
| 187 | + Some(other) => bail!("unknown cell command: {other}; celld cell list is the only one"), | |
| 188 | + } | |
| 189 | +} | |
| 190 | + | |
| 191 | +async fn run_list(arguments: Vec<String>) -> anyhow::Result<()> { | |
| 192 | + let Some(options) = list_options_from_arguments(arguments)? else { | |
| 193 | + return Output::new(Format::Text).help(&help_text()); | |
| 194 | + }; | |
| 195 | + let storage = options.fleet.resolve("celld cell list")?; | |
| 196 | + let store = storage.open().await?; | |
| 197 | + | |
| 198 | + let mut out = Output::new(if options.json { | |
| 199 | + Format::Json | |
| 200 | + } else { | |
| 201 | + Format::Text | |
| 202 | + }); | |
| 203 | + let started = std::time::Instant::now(); | |
| 204 | + let class = options.class.clone(); | |
| 205 | + | |
| 206 | + let listed = list(&mut out, &options.bounds, |resume, want| { | |
| 207 | + let store = &store; | |
| 208 | + let class = class.clone(); | |
| 209 | + // The store resumes from a child of `cells/`, while the cursor an | |
| 210 | + // operator sees is the scope. The two differ by the prefix, and | |
| 211 | + // passing the scope raw silently matches nothing, which reads as a | |
| 212 | + // cursor that works. | |
| 213 | + let boundary = resume.boundary().map(str::to_string); | |
| 214 | + let start_after = boundary.as_deref().map(|scope| format!("cells/{scope}")); | |
| 215 | + let token = match resume { | |
| 216 | + Resume::Token(token) => Some(token), | |
| 217 | + Resume::From(_) => None, | |
| 218 | + }; | |
| 219 | + async move { | |
| 220 | + let page = store | |
| 221 | + .common_prefixes_page("cells/", start_after.as_deref(), token, want) | |
| 222 | + .await | |
| 223 | + .context("enumerate Durable Object instances")?; | |
| 224 | + Ok(Page { | |
| 225 | + rows: cell_scopes_from_prefixes( | |
| 226 | + page.prefixes, | |
| 227 | + class.as_deref(), | |
| 228 | + boundary.as_deref(), | |
| 229 | + ) | |
| 230 | + .map(|scope| Cell { scope }) | |
| 231 | + .collect(), | |
| 232 | + next: page.page_token, | |
| 233 | + }) | |
| 234 | + } | |
| 235 | + }) | |
| 236 | + .await?; | |
| 237 | + | |
| 238 | + out.finish()?; | |
| 239 | + if listed.printed == 0 && !listed.abandoned { | |
| 240 | + match options.class.as_deref() { | |
| 241 | + Some(class) => note!("no cells of class {class}"), | |
| 242 | + None => note!("no cells"), | |
| 243 | + } | |
| 244 | + } else if options.bounds.all { | |
| 245 | + listed.report_all("cell", started.elapsed()); | |
| 246 | + } else { | |
| 247 | + listed.report("cell", "--after"); | |
| 248 | + } | |
| 249 | + Ok(()) | |
| 250 | +} |
addedcrates/celld/cli_options.rs+142−0View file
| @@ -1,0 +1,142 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +// Operator commands read the process environment for their fleet settings. | |
| 4 | +#![allow(clippy::disallowed_methods)] | |
| 5 | + | |
| 6 | +//! The flags every operator command shares. | |
| 7 | +//! | |
| 8 | +//! `--bucket`, `--endpoint` and `--region` name the same fleet whichever | |
| 9 | +//! command reads them, and four commands parsed them separately before this | |
| 10 | +//! module existed. That is how `--bucket gs://name` came to be handled in | |
| 11 | +//! one place and not another: a rule spread across four loops is a rule | |
| 12 | +//! four authors have to remember. | |
| 13 | +//! | |
| 14 | +//! The environment fallbacks live here too, so `CELLD_BUCKET`, | |
| 15 | +//! `S3_ENDPOINT`, `AWS_REGION` and `AWS_DEFAULT_REGION` mean one thing | |
| 16 | +//! across the CLI. | |
| 17 | + | |
| 18 | +use anyhow::Context; | |
| 19 | + | |
| 20 | +/// A non-empty environment variable, or nothing. | |
| 21 | +/// | |
| 22 | +/// An empty variable is how a shell spells "unset" in a script that always | |
| 23 | +/// exports, so it must not beat a flag or a default. | |
| 24 | +fn env(name: &str) -> Option<String> { | |
| 25 | + std::env::var(name) | |
| 26 | + .ok() | |
| 27 | + .filter(|value| !value.trim().is_empty()) | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// Which fleet a command acts on. | |
| 31 | +#[derive(Clone, Debug, Default, PartialEq, Eq)] | |
| 32 | +pub struct FleetFlags { | |
| 33 | + pub bucket: Option<String>, | |
| 34 | + pub endpoint: Option<String>, | |
| 35 | + pub region: Option<String>, | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// A fleet's resolved storage location: everything [`crate::fleet`] needs to | |
| 39 | +/// open a bucket. | |
| 40 | +/// | |
| 41 | +/// Returned as one value because a bucket without its region opens against | |
| 42 | +/// the wrong endpoint, and separate accessors let a caller take one and | |
| 43 | +/// forget the other. | |
| 44 | +pub struct Storage { | |
| 45 | + pub bucket: String, | |
| 46 | + pub endpoint: Option<String>, | |
| 47 | + pub region: String, | |
| 48 | +} | |
| 49 | + | |
| 50 | +impl FleetFlags { | |
| 51 | + /// Consume one fleet flag, or report that it is not one. | |
| 52 | + pub fn consume( | |
| 53 | + &mut self, | |
| 54 | + argument: &str, | |
| 55 | + value: &mut impl FnMut(&str) -> anyhow::Result<String>, | |
| 56 | + ) -> anyhow::Result<bool> { | |
| 57 | + 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 | + } | |
| 64 | + "--endpoint" => self.endpoint = Some(value("--endpoint")?), | |
| 65 | + "--region" => self.region = Some(value("--region")?), | |
| 66 | + _ => return Ok(false), | |
| 67 | + } | |
| 68 | + Ok(true) | |
| 69 | + } | |
| 70 | + | |
| 71 | + /// Fill anything the flags left unset from the environment. | |
| 72 | + pub fn with_environment(mut self) -> Self { | |
| 73 | + 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 | + }); | |
| 81 | + } | |
| 82 | + if self.endpoint.is_none() { | |
| 83 | + self.endpoint = env("S3_ENDPOINT"); | |
| 84 | + } | |
| 85 | + if self.region.is_none() { | |
| 86 | + self.region = env("AWS_REGION").or_else(|| env("AWS_DEFAULT_REGION")); | |
| 87 | + } | |
| 88 | + self | |
| 89 | + } | |
| 90 | + | |
| 91 | + /// The region a bucket opens against, whether or not one was named. | |
| 92 | + fn region(&self) -> String { | |
| 93 | + self.region | |
| 94 | + .clone() | |
| 95 | + .unwrap_or_else(|| "us-east-1".to_string()) | |
| 96 | + } | |
| 97 | + | |
| 98 | + /// Resolve to a complete storage location, or explain what is missing. | |
| 99 | + /// | |
| 100 | + /// `command` names the caller so the message says which invocation to | |
| 101 | + /// fix, rather than making an operator guess which of several commands | |
| 102 | + /// in a script wanted a bucket. | |
| 103 | + pub fn resolve(self, command: &str) -> anyhow::Result<Storage> { | |
| 104 | + let resolved = self.with_environment(); | |
| 105 | + let region = resolved.region(); | |
| 106 | + let bucket = resolved | |
| 107 | + .bucket | |
| 108 | + .filter(|bucket| !bucket.is_empty()) | |
| 109 | + .with_context(|| { | |
| 110 | + format!( | |
| 111 | + "{command} requires --bucket s3://NAME, gs://NAME or az://CONTAINER \ | |
| 112 | + (or CELLD_BUCKET)" | |
| 113 | + ) | |
| 114 | + })?; | |
| 115 | + Ok(Storage { | |
| 116 | + bucket, | |
| 117 | + endpoint: resolved.endpoint, | |
| 118 | + region, | |
| 119 | + }) | |
| 120 | + } | |
| 121 | +} | |
| 122 | + | |
| 123 | +impl Storage { | |
| 124 | + /// Open the fleet bucket and prove it is reachable. | |
| 125 | + pub async fn open(&self) -> anyhow::Result<crate::bucket::Bucket> { | |
| 126 | + let store = | |
| 127 | + crate::fleet::bucket_client(&self.bucket, self.endpoint.as_deref(), &self.region)?; | |
| 128 | + crate::fleet::validate_bucket(&store).await?; | |
| 129 | + Ok(store) | |
| 130 | + } | |
| 131 | +} | |
| 132 | + | |
| 133 | +/// The shared fleet-flag help, so every command documents them identically. | |
| 134 | +pub const FLEET_HELP: &str = " --bucket NAME Fleet bucket (or CELLD_BUCKET) | |
| 135 | + --endpoint URL Optional S3-compatible endpoint (or S3_ENDPOINT) | |
| 136 | + --region REGION Storage region (default: AWS_REGION or us-east-1)"; | |
| 137 | + | |
| 138 | +/// The shared listing help, for a command that bounds its output. | |
| 139 | +pub const LISTING_HELP: &str = " --limit N Maximum rows to print (default: 1000) | |
| 140 | + --after CURSOR Resume after this row | |
| 141 | + --all Print every row; this reads the whole listing | |
| 142 | + --json Print one JSON object per line instead of text"; |
addedcrates/celld/cli_output.rs+494−0View file
| @@ -1,0 +1,494 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +// An operator command writes to the terminal and times its own work, | |
| 4 | +// outside the execution boundary. | |
| 5 | +#![allow(clippy::disallowed_methods)] | |
| 6 | + | |
| 7 | +//! What an operator command prints, and how. | |
| 8 | +//! | |
| 9 | +//! Three rules hold across every subcommand, and this module exists so that | |
| 10 | +//! no command can implement them differently: | |
| 11 | +//! | |
| 12 | +//! 1. stdout carries data, stderr carries everything a person reads. A | |
| 13 | +//! command that mixes them corrupts the first pipe it meets. | |
| 14 | +//! 2. A listing is bounded by default, and says on stderr what it withheld | |
| 15 | +//! and how to continue. Cost follows the fleet's size, not the | |
| 16 | +//! operator's question. | |
| 17 | +//! 3. A closed pipe ends the output; it is not a failure. | |
| 18 | +//! | |
| 19 | +//! The enforcement is [`Record`]: a row cannot be printed as text without | |
| 20 | +//! also declaring its JSON shape, so `--json` cannot be half-implemented. | |
| 21 | + | |
| 22 | +use std::borrow::Cow; | |
| 23 | +use std::io::ErrorKind; | |
| 24 | +use std::io::IsTerminal; | |
| 25 | +use std::io::Write; | |
| 26 | + | |
| 27 | +/// One row of a command's output. | |
| 28 | +/// | |
| 29 | +/// Both methods are required on purpose. A command that could print text | |
| 30 | +/// without declaring JSON would leave `--json` to each author's discretion, | |
| 31 | +/// which is the divergence this module exists to prevent. | |
| 32 | +pub trait Record { | |
| 33 | + /// The machine shape. `--json` prints this as one line. | |
| 34 | + fn json(&self) -> serde_json::Value; | |
| 35 | + /// The line a person reads. | |
| 36 | + fn text(&self) -> Cow<'_, str>; | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// A record a bounded listing can resume after. | |
| 40 | +/// | |
| 41 | +/// Separate from [`Record`] so that [`list`] can demand it. A listing that | |
| 42 | +/// forgets its cursor then fails to compile instead of printing a resume | |
| 43 | +/// line that does not work. | |
| 44 | +pub trait Resumable: Record { | |
| 45 | + /// The value an operator passes back to continue after this row. | |
| 46 | + fn cursor(&self) -> &str; | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// How a command renders its rows. | |
| 50 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 51 | +pub enum Format { | |
| 52 | + Text, | |
| 53 | + Json, | |
| 54 | +} | |
| 55 | + | |
| 56 | +/// A message for a person: progress, a warning, a summary, a resume line. | |
| 57 | +/// | |
| 58 | +/// Always stderr, whatever the verdict, so that stdout survives a pipe and | |
| 59 | +/// a redirect keeps failures rather than dropping them. Never panics: a | |
| 60 | +/// caller with a closed stderr must still finish its work. | |
| 61 | +#[macro_export] | |
| 62 | +macro_rules! note { | |
| 63 | + ($($arg:tt)*) => {{ | |
| 64 | + use std::io::Write as _; | |
| 65 | + let _ = writeln!(std::io::stderr(), $($arg)*); | |
| 66 | + }}; | |
| 67 | +} | |
| 68 | + | |
| 69 | +struct Sink<W> { | |
| 70 | + data: W, | |
| 71 | + closed: bool, | |
| 72 | +} | |
| 73 | + | |
| 74 | +impl<W: Write> Sink<W> { | |
| 75 | + fn new(data: W) -> Self { | |
| 76 | + Self { | |
| 77 | + data, | |
| 78 | + closed: false, | |
| 79 | + } | |
| 80 | + } | |
| 81 | + | |
| 82 | + fn line_and_flush(&mut self, arguments: std::fmt::Arguments<'_>) -> anyhow::Result<()> { | |
| 83 | + self.write(|data| writeln!(data, "{arguments}"))?; | |
| 84 | + self.write(|data| data.flush()) | |
| 85 | + } | |
| 86 | + | |
| 87 | + /// Run one write, converting a closed reader into a quiet stop. | |
| 88 | + /// | |
| 89 | + /// `BrokenPipe` is the only write error that means success: the reader | |
| 90 | + /// asked for less than we had, which is what `| head` does. Every other | |
| 91 | + /// error stays an error, because a blanket "ignore stdout failures" | |
| 92 | + /// would turn a truncated redirect — a full disk, a dying device — into | |
| 93 | + /// a silent success, which is worse than the defect it fixes. | |
| 94 | + fn write( | |
| 95 | + &mut self, | |
| 96 | + operation: impl FnOnce(&mut W) -> std::io::Result<()>, | |
| 97 | + ) -> anyhow::Result<()> { | |
| 98 | + if self.closed { | |
| 99 | + return Ok(()); | |
| 100 | + } | |
| 101 | + match operation(&mut self.data) { | |
| 102 | + Ok(()) => Ok(()), | |
| 103 | + Err(error) if error.kind() == ErrorKind::BrokenPipe => { | |
| 104 | + self.closed = true; | |
| 105 | + Ok(()) | |
| 106 | + } | |
| 107 | + Err(error) => Err(anyhow::Error::new(error).context("write to stdout")), | |
| 108 | + } | |
| 109 | + } | |
| 110 | +} | |
| 111 | + | |
| 112 | +/// The write side of a command's answer. | |
| 113 | +/// | |
| 114 | +/// A command never holds a stdout handle, so it cannot address the two | |
| 115 | +/// streams separately even by accident. | |
| 116 | +pub struct Output { | |
| 117 | + // `Stdout` is a `LineWriter`, so an unbuffered loop flushes once per row | |
| 118 | + // and a million-row walk becomes a million write syscalls. One lock and | |
| 119 | + // one buffer serve the whole command. | |
| 120 | + sink: Sink<std::io::BufWriter<std::io::Stdout>>, | |
| 121 | + format: Format, | |
| 122 | +} | |
| 123 | + | |
| 124 | +impl Output { | |
| 125 | + pub fn new(format: Format) -> Self { | |
| 126 | + Self { | |
| 127 | + sink: Sink::new(std::io::BufWriter::new(std::io::stdout())), | |
| 128 | + format, | |
| 129 | + } | |
| 130 | + } | |
| 131 | + | |
| 132 | + /// Whether the reader has gone away. A caller that drives an expensive | |
| 133 | + /// walk must check this and stop: continuing costs storage requests for | |
| 134 | + /// output nobody will read. | |
| 135 | + pub fn closed(&self) -> bool { | |
| 136 | + self.sink.closed | |
| 137 | + } | |
| 138 | + | |
| 139 | + /// Print one row, in whichever format the operator asked for. | |
| 140 | + pub fn row(&mut self, record: &dyn Record) -> anyhow::Result<()> { | |
| 141 | + if self.sink.closed { | |
| 142 | + return Ok(()); | |
| 143 | + } | |
| 144 | + let line = match self.format { | |
| 145 | + Format::Text => record.text().into_owned(), | |
| 146 | + Format::Json => serde_json::to_string(&record.json())?, | |
| 147 | + }; | |
| 148 | + self.sink.write(|data| writeln!(data, "{line}")) | |
| 149 | + } | |
| 150 | + | |
| 151 | + /// One opaque payload, byte for byte. | |
| 152 | + /// | |
| 153 | + /// Takes `self`, so nothing can be appended afterwards. That is what | |
| 154 | + /// makes the `d1 execute` defect — rows, then a prose summary, on one | |
| 155 | + /// stream — unrepresentable rather than merely discouraged. | |
| 156 | + pub fn bytes(mut self, payload: &[u8]) -> anyhow::Result<()> { | |
| 157 | + self.sink.write(|data| data.write_all(payload))?; | |
| 158 | + self.finish() | |
| 159 | + } | |
| 160 | + | |
| 161 | + /// Write one formatted line and flush it before returning. | |
| 162 | + /// | |
| 163 | + /// The method takes `fmt::Arguments`, so a protocol caller can format the | |
| 164 | + /// line directly into stdout without an intermediate `String`. | |
| 165 | + pub fn line(mut self, arguments: std::fmt::Arguments<'_>) -> anyhow::Result<()> { | |
| 166 | + self.sink.line_and_flush(arguments) | |
| 167 | + } | |
| 168 | + | |
| 169 | + /// Help text: the one place a command legitimately writes prose to | |
| 170 | + /// stdout, because an operator redirects `--help` on purpose. | |
| 171 | + pub fn help(mut self, text: &str) -> anyhow::Result<()> { | |
| 172 | + self.sink.write(|data| writeln!(data, "{text}"))?; | |
| 173 | + self.finish() | |
| 174 | + } | |
| 175 | + | |
| 176 | + /// A table's header, in text mode only. | |
| 177 | + /// | |
| 178 | + /// JSON rows carry their own keys, so this is a no-op there. Narrow on | |
| 179 | + /// purpose: it cannot put prose in front of a machine-readable stream, | |
| 180 | + /// which is the failure it would otherwise reintroduce. | |
| 181 | + pub fn header(&mut self, line: &str) -> anyhow::Result<()> { | |
| 182 | + if self.format == Format::Json { | |
| 183 | + return Ok(()); | |
| 184 | + } | |
| 185 | + self.sink.write(|data| writeln!(data, "{line}")) | |
| 186 | + } | |
| 187 | + | |
| 188 | + /// Flush what is buffered and report anything that is a real failure. | |
| 189 | + pub fn finish(mut self) -> anyhow::Result<()> { | |
| 190 | + self.sink.write(|data| data.flush()) | |
| 191 | + } | |
| 192 | +} | |
| 193 | + | |
| 194 | +/// Lay out a table: the header line, its rule, and one padded line per row. | |
| 195 | +/// | |
| 196 | +/// A column's width has to be known before any of its rows print, so a | |
| 197 | +/// caller renders the whole result set and then streams it. That is | |
| 198 | +/// affordable because a result set already arrived as one response; it is | |
| 199 | +/// not a pattern for a listing, which is why [`list`] does not use it. | |
| 200 | +pub fn align(columns: &[String], rows: &[Vec<String>]) -> (String, String, Vec<String>) { | |
| 201 | + let widths: Vec<usize> = columns | |
| 202 | + .iter() | |
| 203 | + .enumerate() | |
| 204 | + .map(|(index, column)| { | |
| 205 | + rows.iter() | |
| 206 | + .filter_map(|row| row.get(index)) | |
| 207 | + .map(|cell| cell.chars().count()) | |
| 208 | + .chain(std::iter::once(column.chars().count())) | |
| 209 | + .max() | |
| 210 | + .unwrap_or_default() | |
| 211 | + }) | |
| 212 | + .collect(); | |
| 213 | + let pad = |cell: &str, width: usize| { | |
| 214 | + let mut padded = cell.to_string(); | |
| 215 | + // Pad by character count, not by byte length, so a non-ASCII value | |
| 216 | + // does not shift every column to its right. | |
| 217 | + for _ in cell.chars().count()..width { | |
| 218 | + padded.push(' '); | |
| 219 | + } | |
| 220 | + padded | |
| 221 | + }; | |
| 222 | + let line = |cells: &[String]| { | |
| 223 | + cells | |
| 224 | + .iter() | |
| 225 | + .zip(&widths) | |
| 226 | + .map(|(cell, width)| pad(cell, *width)) | |
| 227 | + .collect::<Vec<_>>() | |
| 228 | + .join(" ") | |
| 229 | + .trim_end() | |
| 230 | + .to_string() | |
| 231 | + }; | |
| 232 | + let rule = widths | |
| 233 | + .iter() | |
| 234 | + .map(|width| "-".repeat(*width)) | |
| 235 | + .collect::<Vec<_>>() | |
| 236 | + .join(" "); | |
| 237 | + ( | |
| 238 | + line(columns), | |
| 239 | + rule.trim_end().to_string(), | |
| 240 | + rows.iter().map(|row| line(row)).collect(), | |
| 241 | + ) | |
| 242 | +} | |
| 243 | + | |
| 244 | +/// Where a listing picks up. | |
| 245 | +/// | |
| 246 | +/// The distinction is not cosmetic. A row cursor is meaningful to an | |
| 247 | +/// operator and survives between processes, but not every store can resume | |
| 248 | +/// from a key — Azure rejects listing offsets outright. A store token can | |
| 249 | +/// always continue the walk it came from, and never outlives it. So an | |
| 250 | +/// operator's `--after` starts the walk and the store's token carries it, | |
| 251 | +/// and a listing that used the cursor for every page would work on S3 and | |
| 252 | +/// GCS and stop after one page on Azure. | |
| 253 | +pub enum Resume { | |
| 254 | + /// Begin, optionally after a cursor the operator supplied. | |
| 255 | + From(Option<String>), | |
| 256 | + /// Continue this walk with the store's own token. | |
| 257 | + Token(String), | |
| 258 | +} | |
| 259 | + | |
| 260 | +impl Resume { | |
| 261 | + /// The operator cursor this page resumes from, if any. | |
| 262 | + /// | |
| 263 | + /// A store resumes from a key and every key below a listed child sorts | |
| 264 | + /// after that child's own prefix, so the page that resumes a walk | |
| 265 | + /// repeats the row it resumed from. A caller drops that row by name. | |
| 266 | + /// Continuing with a token repeats nothing, so there is nothing to drop. | |
| 267 | + pub fn boundary(&self) -> Option<&str> { | |
| 268 | + match self { | |
| 269 | + Self::From(after) => after.as_deref(), | |
| 270 | + Self::Token(_) => None, | |
| 271 | + } | |
| 272 | + } | |
| 273 | +} | |
| 274 | + | |
| 275 | +/// One page of a bounded listing. | |
| 276 | +pub struct Page<R> { | |
| 277 | + pub rows: Vec<R>, | |
| 278 | + /// The store's continuation for this walk, or `None` when the listing | |
| 279 | + /// is exhausted. It must come from the store's own truncation signal, | |
| 280 | + /// never from a row count: a page filled exactly to its bound is not | |
| 281 | + /// evidence that another row exists. | |
| 282 | + pub next: Option<String>, | |
| 283 | +} | |
| 284 | + | |
| 285 | +/// How much of a listing the operator asked for. | |
| 286 | +#[derive(Clone, Debug, PartialEq, Eq)] | |
| 287 | +pub struct Bounds { | |
| 288 | + pub limit: usize, | |
| 289 | + pub after: Option<String>, | |
| 290 | + pub all: bool, | |
| 291 | + /// Set when `--limit` was given, so `--all` can refuse the combination | |
| 292 | + /// rather than silently pick one. | |
| 293 | + limit_set: bool, | |
| 294 | +} | |
| 295 | + | |
| 296 | +impl Default for Bounds { | |
| 297 | + fn default() -> Self { | |
| 298 | + Self { | |
| 299 | + limit: Self::DEFAULT_LIMIT, | |
| 300 | + after: None, | |
| 301 | + all: false, | |
| 302 | + limit_set: false, | |
| 303 | + } | |
| 304 | + } | |
| 305 | +} | |
| 306 | + | |
| 307 | +impl Bounds { | |
| 308 | + /// The default bound, and the largest page every supported store | |
| 309 | + /// serves, so an unqualified listing costs exactly one request. | |
| 310 | + pub const DEFAULT_LIMIT: usize = 1_000; | |
| 311 | + | |
| 312 | + /// The largest page a store will serve. A larger `--limit` costs more | |
| 313 | + /// requests, so the page size stays pinned and the driver loops. | |
| 314 | + pub const MAX_PAGE: usize = 1_000; | |
| 315 | + | |
| 316 | + /// Consume one listing flag, or report that it is not one. | |
| 317 | + /// | |
| 318 | + /// Commands share this so that `--limit`, `--after` and `--all` cannot | |
| 319 | + /// drift in spelling or in meaning between listings. | |
| 320 | + pub fn consume( | |
| 321 | + &mut self, | |
| 322 | + argument: &str, | |
| 323 | + value: &mut impl FnMut(&str) -> anyhow::Result<String>, | |
| 324 | + ) -> anyhow::Result<bool> { | |
| 325 | + match argument { | |
| 326 | + "--limit" => { | |
| 327 | + let raw = value("--limit")?; | |
| 328 | + self.limit = raw | |
| 329 | + .parse::<usize>() | |
| 330 | + .ok() | |
| 331 | + .filter(|limit| *limit > 0) | |
| 332 | + .ok_or_else(|| { | |
| 333 | + anyhow::anyhow!("--limit takes a positive whole number, not {raw:?}") | |
| 334 | + })?; | |
| 335 | + self.limit_set = true; | |
| 336 | + } | |
| 337 | + "--after" => self.after = Some(value("--after")?), | |
| 338 | + "--all" => self.all = true, | |
| 339 | + _ => return Ok(false), | |
| 340 | + } | |
| 341 | + Ok(true) | |
| 342 | + } | |
| 343 | + | |
| 344 | + /// Reject a bound and a full walk together. Guessing which one an | |
| 345 | + /// operator meant either truncates the walk or makes a bounded request | |
| 346 | + /// cost the whole store. | |
| 347 | + pub fn validate(&self) -> anyhow::Result<()> { | |
| 348 | + if self.all && self.limit_set { | |
| 349 | + anyhow::bail!("--all and --limit contradict each other; pass one of them"); | |
| 350 | + } | |
| 351 | + Ok(()) | |
| 352 | + } | |
| 353 | + | |
| 354 | + /// How many rows to request next, given how many are already printed. | |
| 355 | + fn want(&self, printed: usize) -> usize { | |
| 356 | + if self.all { | |
| 357 | + return Self::MAX_PAGE; | |
| 358 | + } | |
| 359 | + match self.limit.checked_sub(printed) { | |
| 360 | + // The bound is met, so this page only has to find one more row | |
| 361 | + // to prove the answer was partial. A full page keeps that proof | |
| 362 | + // to one request even when a long run of filtered rows follows. | |
| 363 | + None | Some(0) => Self::MAX_PAGE, | |
| 364 | + // One past the bound, so the proof usually arrives with the rows | |
| 365 | + // themselves rather than costing a second request. | |
| 366 | + Some(remaining) => remaining.saturating_add(1).min(Self::MAX_PAGE), | |
| 367 | + } | |
| 368 | + } | |
| 369 | +} | |
| 370 | + | |
| 371 | +/// How often a full walk reports that it is still going. | |
| 372 | +const PROGRESS_EVERY: usize = 100_000; | |
| 373 | + | |
| 374 | +/// What a finished listing did, for the caller's own summary line. | |
| 375 | +pub struct Listed { | |
| 376 | + pub printed: usize, | |
| 377 | + pub requests: usize, | |
| 378 | + /// A row exists past the bound. Not the same as the store truncating a | |
| 379 | + /// page: a filter can drop every row after the last one printed. | |
| 380 | + pub more: bool, | |
| 381 | + /// The cursor that continues the listing, when one was withheld. | |
| 382 | + pub resume: Option<String>, | |
| 383 | + /// The reader closed the pipe, so nothing was withheld from anyone. | |
| 384 | + pub abandoned: bool, | |
| 385 | +} | |
| 386 | + | |
| 387 | +/// Drive a bounded listing to the operator's bound. | |
| 388 | +/// | |
| 389 | +/// `fetch` takes the resume cursor and the number of rows to ask for, and | |
| 390 | +/// returns one page. The driver owns everything else — the probe past the | |
| 391 | +/// bound, the progress line, the stop when a reader leaves — so that every | |
| 392 | +/// listing in the CLI answers those the same way. | |
| 393 | +pub async fn list<R, F, Fut>( | |
| 394 | + out: &mut Output, | |
| 395 | + bounds: &Bounds, | |
| 396 | + mut fetch: F, | |
| 397 | +) -> anyhow::Result<Listed> | |
| 398 | +where | |
| 399 | + R: Resumable, | |
| 400 | + F: FnMut(Resume, usize) -> Fut, | |
| 401 | + Fut: std::future::Future<Output = anyhow::Result<Page<R>>>, | |
| 402 | +{ | |
| 403 | + let mut after = bounds.after.clone(); | |
| 404 | + let mut resume = Resume::From(after.clone()); | |
| 405 | + let mut printed = 0usize; | |
| 406 | + let mut requests = 0usize; | |
| 407 | + let mut reported = 0usize; | |
| 408 | + let mut more = false; | |
| 409 | + | |
| 410 | + 'walk: loop { | |
| 411 | + let page = fetch(resume, bounds.want(printed)).await?; | |
| 412 | + requests += 1; | |
| 413 | + for row in &page.rows { | |
| 414 | + if !bounds.all && printed >= bounds.limit { | |
| 415 | + more = true; | |
| 416 | + break 'walk; | |
| 417 | + } | |
| 418 | + out.row(row)?; | |
| 419 | + // A reader that closed the pipe wants nothing further, and the | |
| 420 | + // next page would cost a storage request to satisfy nobody. | |
| 421 | + if out.closed() { | |
| 422 | + break 'walk; | |
| 423 | + } | |
| 424 | + after = Some(row.cursor().to_string()); | |
| 425 | + printed += 1; | |
| 426 | + } | |
| 427 | + if bounds.all && printed >= reported + PROGRESS_EVERY { | |
| 428 | + reported = printed - printed % PROGRESS_EVERY; | |
| 429 | + note!("listed {reported}…"); | |
| 430 | + } | |
| 431 | + match page.next { | |
| 432 | + Some(token) => resume = Resume::Token(token), | |
| 433 | + None => break, | |
| 434 | + } | |
| 435 | + } | |
| 436 | + | |
| 437 | + Ok(Listed { | |
| 438 | + printed, | |
| 439 | + requests, | |
| 440 | + more, | |
| 441 | + resume: more.then(|| after.clone()).flatten(), | |
| 442 | + abandoned: out.closed(), | |
| 443 | + }) | |
| 444 | +} | |
| 445 | + | |
| 446 | +impl Listed { | |
| 447 | + /// Say on stderr what the listing withheld, and how to continue it. | |
| 448 | + /// | |
| 449 | + /// Nothing is reported to a reader who left: a closed pipe means the | |
| 450 | + /// operator asked for less than existed on purpose. | |
| 451 | + pub fn report(&self, noun: &str, resume_flag: &str) { | |
| 452 | + if self.abandoned { | |
| 453 | + return; | |
| 454 | + } | |
| 455 | + let plural = if self.printed == 1 { "" } else { "s" }; | |
| 456 | + if let (true, Some(resume)) = (self.more, self.resume.as_deref()) { | |
| 457 | + note!( | |
| 458 | + "{} {noun}{plural} shown; more exist. Continue with {resume_flag} {resume}", | |
| 459 | + self.printed | |
| 460 | + ); | |
| 461 | + if std::io::stderr().is_terminal() { | |
| 462 | + note!("Pass --all to list every {noun}."); | |
| 463 | + } | |
| 464 | + } | |
| 465 | + } | |
| 466 | + | |
| 467 | + /// The closing line of a full walk: how much, how long, how many | |
| 468 | + /// requests it cost. | |
| 469 | + pub fn report_all(&self, noun: &str, elapsed: std::time::Duration) { | |
| 470 | + if self.abandoned { | |
| 471 | + return; | |
| 472 | + } | |
| 473 | + let plural = |count: usize| if count == 1 { "" } else { "s" }; | |
| 474 | + // Seconds to one decimal reads as "0.0s" for anything under 50ms, | |
| 475 | + // which looks like a missing measurement rather than a fast walk. | |
| 476 | + let took = if elapsed.as_secs_f64() < 1.0 { | |
| 477 | + format!("{}ms", elapsed.as_millis()) | |
| 478 | + } else { | |
| 479 | + format!("{:.1}s", elapsed.as_secs_f64()) | |
| 480 | + }; | |
| 481 | + note!( | |
| 482 | + "{} {noun}{} in {took} ({} list request{})", | |
| 483 | + self.printed, | |
| 484 | + plural(self.printed), | |
| 485 | + self.requests, | |
| 486 | + plural(self.requests), | |
| 487 | + ); | |
| 488 | + } | |
| 489 | +} | |
| 490 | + | |
| 491 | +#[cfg(all(test, celld_internal_tests))] | |
| 492 | +mod cli_output_contract { | |
| 493 | + include!(env!("CELLD_INTERNAL_CLI_OUTPUT_TESTS")); | |
| 494 | +} |
modifiedcrates/celld/control_plane.rs+121−116View file
| @@ -1,13 +1,10 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -// Managed control-plane sessions do not execute in the engine World. | |
| 4 | -#![allow( | |
| 5 | - clippy::disallowed_macros, | |
| 6 | - clippy::disallowed_methods, | |
| 7 | - clippy::disallowed_types | |
| 8 | -)] | |
| 3 | +// Managed control-plane sessions execute outside the Actor execution domain. | |
| 4 | +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] | |
| 9 | 5 | |
| 10 | 6 | use crate::bucket::Bucket; |
| 7 | +use crate::note; | |
| 11 | 8 | use crate::protocol::{asset_blob_key, AssetIndex, DeployPointer, Manifest}; |
| 12 | 9 | use anyhow::{anyhow, Context}; |
| 13 | 10 | use celld_logic::PresenceSnapshot; |
| @@ -21,7 +18,6 @@ | ||
| 21 | 18 | use std::future::Future; |
| 22 | 19 | use std::path::{Path, PathBuf}; |
| 23 | 20 | use std::pin::Pin; |
| 24 | -use std::sync::atomic::{AtomicBool, Ordering}; | |
| 25 | 21 | use std::sync::{Arc, Mutex, OnceLock}; |
| 26 | 22 | use std::time::{Duration, Instant}; |
| 27 | 23 | use tracing::{info, warn}; |
| @@ -39,11 +35,24 @@ | ||
| 39 | 35 | const MAX_MANAGED_MODULES: usize = 64; |
| 40 | 36 | const MAX_MANAGED_MODULE_BYTES: usize = 25 * 1024 * 1024; |
| 41 | 37 | |
| 38 | +/// Whether a managed deployment still replaces the process image, as it did | |
| 39 | +/// before nodes adopted deployments in place. Off by default: the exec cut | |
| 40 | +/// in-flight requests and cold-restored every resident cell. Kept for one | |
| 41 | +/// release as an escape hatch, then removed. | |
| 42 | 42 | fn restart_on_deployment_enabled() -> bool { |
| 43 | - crate::env_vars::flag("CELLD_CLOUD_RESTART_ON_DEPLOY", true) | |
| 43 | + crate::env_vars::flag("CELLD_CLOUD_RESTART_ON_DEPLOY", false) | |
| 44 | 44 | .expect("validated CELLD_CLOUD_RESTART_ON_DEPLOY") |
| 45 | 45 | } |
| 46 | 46 | |
| 47 | +/// React to a deployment the control plane says is current: nudge the | |
| 48 | +/// pointer watcher, or under the escape hatch replace the process image. | |
| 49 | +fn adopt_or_restart(reload: &crate::generation::ReloadSender) { | |
| 50 | + if restart_on_deployment_enabled() { | |
| 51 | + restart_for_deployment(); | |
| 52 | + } | |
| 53 | + crate::generation::nudge(reload); | |
| 54 | +} | |
| 55 | + | |
| 47 | 56 | #[cfg(unix)] |
| 48 | 57 | fn restart_process(trigger: &'static str) -> ! { |
| 49 | 58 | use std::os::unix::process::CommandExt; |
| @@ -341,30 +350,32 @@ | ||
| 341 | 350 | } |
| 342 | 351 | |
| 343 | 352 | #[derive(Deserialize)] |
| 344 | -struct AgentDeployment { | |
| 345 | - script_name: String, | |
| 346 | - version: String, | |
| 347 | - manifest: Manifest, | |
| 348 | - pointer: DeployPointer, | |
| 349 | - modules: Vec<AgentModule>, | |
| 353 | +#[doc(hidden)] | |
| 354 | +pub struct AgentDeployment { | |
| 355 | + pub script_name: String, | |
| 356 | + pub version: String, | |
| 357 | + pub manifest: Manifest, | |
| 358 | + pub pointer: DeployPointer, | |
| 359 | + pub modules: Vec<AgentModule>, | |
| 350 | 360 | #[serde(default)] |
| 351 | - assets: Option<AgentAssets>, | |
| 361 | + pub assets: Option<AgentAssets>, | |
| 352 | 362 | } |
| 353 | 363 | |
| 354 | 364 | #[derive(Deserialize)] |
| 355 | -struct AgentModule { | |
| 356 | - name: String, | |
| 357 | - sha256: String, | |
| 358 | - download_url: String, | |
| 365 | +#[doc(hidden)] | |
| 366 | +pub struct AgentModule { | |
| 367 | + pub name: String, | |
| 368 | + pub sha256: String, | |
| 369 | + pub download_url: String, | |
| 359 | 370 | } |
| 360 | 371 | |
| 361 | 372 | #[derive(Deserialize)] |
| 362 | -struct AgentAssets { | |
| 363 | - index_download_url: String, | |
| 364 | - blob_download_base_url: String, | |
| 365 | - sha256: String, | |
| 366 | - file_count: u32, | |
| 367 | - total_bytes: u64, | |
| 373 | +pub struct AgentAssets { | |
| 374 | + pub index_download_url: String, | |
| 375 | + pub blob_download_base_url: String, | |
| 376 | + pub sha256: String, | |
| 377 | + pub file_count: u32, | |
| 378 | + pub total_bytes: u64, | |
| 368 | 379 | } |
| 369 | 380 | |
| 370 | 381 | #[derive(Serialize)] |
| @@ -419,12 +430,12 @@ | ||
| 419 | 430 | ) -> anyhow::Result<()> { |
| 420 | 431 | let arguments = arguments.into_iter().collect::<Vec<_>>(); |
| 421 | 432 | if matches!(arguments.as_slice(), [a] if a == "--help" || a == "-h") { |
| 422 | - println!( | |
| 433 | + // Help is prose an operator redirects on purpose, so it is stdout. | |
| 434 | + return crate::cli_output::Output::new(crate::cli_output::Format::Text).help( | |
| 423 | 435 | "Print this fleet's deploy token, and how to deploy with it.\n\n\ |
| 424 | 436 | USAGE:\n celld token [--format shell]\n\n\ |
| 425 | - OPTIONS:\n --format shell Print only shell exports, suitable for `eval`.\n" | |
| 437 | + OPTIONS:\n --format shell Print only shell exports, suitable for `eval`.\n", | |
| 426 | 438 | ); |
| 427 | - return Ok(()); | |
| 428 | 439 | } |
| 429 | 440 | let shell_only = match arguments.as_slice() { |
| 430 | 441 | [] => false, |
| @@ -472,39 +483,24 @@ | ||
| 472 | 483 | api_base_url: String, |
| 473 | 484 | } |
| 474 | 485 | let issued: DeployTokenResponse = response.json().await.context("decode deploy token")?; |
| 475 | - print!( | |
| 476 | - "{}", | |
| 477 | - render_deploy_token( | |
| 478 | - &issued.token, | |
| 479 | - &issued.account_id, | |
| 480 | - &issued.api_base_url, | |
| 481 | - shell_only, | |
| 482 | - ) | |
| 483 | - ); | |
| 484 | - Ok(()) | |
| 486 | + let exports = render_deploy_token(&issued.token, &issued.account_id, &issued.api_base_url); | |
| 487 | + if !shell_only { | |
| 488 | + // Say what to do next, not merely what happened -- on stderr, so | |
| 489 | + // that `eval "$(celld token)"` sees only the exports. | |
| 490 | + note!("Deploy token for this fleet:\n\n {}\n", issued.token); | |
| 491 | + note!("Deploy your app with these exports, then `npx wrangler@4 deploy`:\n"); | |
| 492 | + } | |
| 493 | + crate::cli_output::Output::new(crate::cli_output::Format::Text).bytes(exports.as_bytes()) | |
| 485 | 494 | } |
| 486 | 495 | |
| 487 | -fn render_deploy_token( | |
| 488 | - token: &str, | |
| 489 | - account_id: &str, | |
| 490 | - api_base_url: &str, | |
| 491 | - shell_only: bool, | |
| 492 | -) -> String { | |
| 493 | - let exports = format!( | |
| 496 | +fn render_deploy_token(token: &str, account_id: &str, api_base_url: &str) -> String { | |
| 497 | + format!( | |
| 494 | 498 | "export CLOUDFLARE_API_TOKEN={}\n\ |
| 495 | 499 | export CLOUDFLARE_ACCOUNT_ID={}\n\ |
| 496 | 500 | export CLOUDFLARE_API_BASE_URL={}\n", |
| 497 | 501 | shell_quote(token), |
| 498 | 502 | shell_quote(account_id), |
| 499 | 503 | shell_quote(api_base_url), |
| 500 | - ); | |
| 501 | - if shell_only { | |
| 502 | - return exports; | |
| 503 | - } | |
| 504 | - // Say what to do next, not merely what happened. | |
| 505 | - format!( | |
| 506 | - "Deploy token for this fleet:\n\n {token}\n\n\ | |
| 507 | - Deploy your app with:\n\n{exports}npx wrangler@4 deploy\n" | |
| 508 | 504 | ) |
| 509 | 505 | } |
| 510 | 506 | |
| @@ -546,7 +542,7 @@ | ||
| 546 | 542 | .timeout(Duration::from_secs(15)) |
| 547 | 543 | .build()?; |
| 548 | 544 | let archive = disconnect_at_path(path, &client).await?; |
| 549 | - println!( | |
| 545 | + note!( | |
| 550 | 546 | "Disconnected this installation from the Managed Control Plane.\nArchived its revoked local record at {}.", |
| 551 | 547 | archive.display() |
| 552 | 548 | ); |
| @@ -630,7 +626,7 @@ | ||
| 630 | 626 | config.credential_handoff_id = None; |
| 631 | 627 | config.previous_credential = None; |
| 632 | 628 | save_config(&path, &config)?; |
| 633 | - println!( | |
| 629 | + note!( | |
| 634 | 630 | "Managed credential refresh completed (version {}).", |
| 635 | 631 | config.credential_version |
| 636 | 632 | ); |
| @@ -645,7 +641,7 @@ | ||
| 645 | 641 | .await |
| 646 | 642 | .context("request staged managed credential")?; |
| 647 | 643 | if response.status() == reqwest::StatusCode::NO_CONTENT { |
| 648 | - println!("No managed credential rotation is pending."); | |
| 644 | + note!("No managed credential rotation is pending."); | |
| 649 | 645 | return Ok(()); |
| 650 | 646 | } |
| 651 | 647 | if response.status() == reqwest::StatusCode::UNAUTHORIZED { |
| @@ -695,7 +691,7 @@ | ||
| 695 | 691 | config.credential_handoff_id = None; |
| 696 | 692 | config.previous_credential = None; |
| 697 | 693 | save_config(&path, &config)?; |
| 698 | - println!( | |
| 694 | + note!( | |
| 699 | 695 | "Managed credential refresh completed (version {}).", |
| 700 | 696 | config.credential_version |
| 701 | 697 | ); |
| @@ -790,6 +786,8 @@ | ||
| 790 | 786 | /// snapshot as those credentials, not from a later presence-agent read. |
| 791 | 787 | pub credential_version: u64, |
| 792 | 788 | pub snapshot: PresenceSnapshotSource, |
| 789 | + /// The pointer watcher a deployment notification nudges. | |
| 790 | + pub reload: crate::generation::ReloadSender, | |
| 793 | 791 | } |
| 794 | 792 | |
| 795 | 793 | pub fn start_presence_agent(runtime: PresenceRuntime) -> bool { |
| @@ -806,7 +804,7 @@ | ||
| 806 | 804 | let mut consecutive_failures = 0_u32; |
| 807 | 805 | loop { |
| 808 | 806 | let started = Instant::now(); |
| 809 | - let result = tokio::select! { | |
| 807 | + let result = crate::asyncrt::select! { | |
| 810 | 808 | result = presence_session(&config, &runtime, &hostname) => result, |
| 811 | 809 | credential_version = wait_for_credential_rotation(runtime.credential_version) => { |
| 812 | 810 | restart_for_credential_rotation(runtime.credential_version, credential_version); |
| @@ -837,7 +835,7 @@ | ||
| 837 | 835 | let exponent = consecutive_failures.saturating_sub(1).min(5); |
| 838 | 836 | let seconds = 2_u64.saturating_mul(1_u64 << exponent).min(60); |
| 839 | 837 | let jitter_ms = (rand::random::<u16>() as u64) % 1000; |
| 840 | - tokio::select! { | |
| 838 | + crate::asyncrt::select! { | |
| 841 | 839 | _ = tokio::time::sleep(Duration::from_millis(seconds * 1000 + jitter_ms)) => {} |
| 842 | 840 | credential_version = wait_for_credential_rotation(runtime.credential_version) => { |
| 843 | 841 | restart_for_credential_rotation(runtime.credential_version, credential_version); |
| @@ -985,6 +983,8 @@ | ||
| 985 | 983 | "expired_owner_leases": snapshot.activity.expired_owner_leases, |
| 986 | 984 | "restored": snapshot.activity.restored, |
| 987 | 985 | "advanced_epochs": snapshot.activity.advanced_epochs, |
| 986 | + "handed_off": snapshot.activity.handed_off, | |
| 987 | + "handoff_failed": snapshot.activity.handoff_failed, | |
| 988 | 988 | }, |
| 989 | 989 | }); |
| 990 | 990 | if let Some(observation) = lease_shadow { |
| @@ -1012,14 +1012,11 @@ | ||
| 1012 | 1012 | if poll_and_apply(&client, config, &runtime.s3) |
| 1013 | 1013 | .await? |
| 1014 | 1014 | .is_some() |
| 1015 | - && restart_on_deployment_enabled() | |
| 1016 | 1015 | { |
| 1017 | - restart_for_deployment(); | |
| 1016 | + adopt_or_restart(&runtime.reload); | |
| 1018 | 1017 | } |
| 1019 | 1018 | } |
| 1020 | - Some("deployment_current") if restart_on_deployment_enabled() => { | |
| 1021 | - restart_for_deployment(); | |
| 1022 | - } | |
| 1019 | + Some("deployment_current") => adopt_or_restart(&runtime.reload), | |
| 1023 | 1020 | _ => {} |
| 1024 | 1021 | } |
| 1025 | 1022 | Ok(None) |
| @@ -1035,9 +1032,8 @@ | ||
| 1035 | 1032 | /// in local variables, so dropping that future keeps the buffer advanced and |
| 1036 | 1033 | /// loses the header. The next read then treats a payload byte as a frame header |
| 1037 | 1034 | /// and the stream never realigns. An earlier version of this session read the |
| 1038 | -/// socket in the same `tokio::select!` as the heartbeat timer, so every tick | |
| 1039 | -/// dropped a read in progress; a test that cancels a read mid-payload fails | |
| 1040 | -/// against that shape. | |
| 1035 | +/// socket in the same select as the heartbeat timer, so every tick dropped a read | |
| 1036 | +/// in progress. Cancelling a read mid-payload fails against that shape. | |
| 1041 | 1037 | /// |
| 1042 | 1038 | /// One async block therefore owns each direction, and the socket is split so |
| 1043 | 1039 | /// that the heartbeat can write while the reader reads. The select at the end |
| @@ -1054,7 +1050,8 @@ | ||
| 1054 | 1050 | /// `heartbeat` returns the message for one tick. `text` handles one text message |
| 1055 | 1051 | /// and returns an optional reply. Ping and Close keep the automatic reply of the |
| 1056 | 1052 | /// reader, so only Text reaches `text`. |
| 1057 | -async fn pump_presence<S, H, HFut, T, TFut>( | |
| 1053 | +#[doc(hidden)] | |
| 1054 | +pub async fn pump_presence<S, H, HFut, T, TFut>( | |
| 1058 | 1055 | socket: fastwebsockets::WebSocket<S>, |
| 1059 | 1056 | heartbeat_period: Duration, |
| 1060 | 1057 | mut heartbeat: H, |
| @@ -1129,7 +1126,7 @@ | ||
| 1129 | 1126 | |
| 1130 | 1127 | let mut beat = std::pin::pin!(beat); |
| 1131 | 1128 | let mut read = std::pin::pin!(read); |
| 1132 | - tokio::select! { | |
| 1129 | + crate::asyncrt::select! { | |
| 1133 | 1130 | result = &mut beat => result, |
| 1134 | 1131 | result = &mut read => result, |
| 1135 | 1132 | } |
| @@ -1222,7 +1219,11 @@ | ||
| 1222 | 1219 | let Some(cell) = message |
| 1223 | 1220 | .get("cell_id") |
| 1224 | 1221 | .and_then(|value| value.as_str()) |
| 1225 | - .filter(|cell| valid_explorer_cell_id(cell)) | |
| 1222 | + // The engine's storage fence, the same one the listing | |
| 1223 | + // applies. An inbound id is spliced into a bucket key, so | |
| 1224 | + // the charset that decides what a node could have written | |
| 1225 | + // also decides what this can ask for. | |
| 1226 | + .filter(|cell| celld_logic::cell::valid_cell_scope(cell)) | |
| 1226 | 1227 | else { |
| 1227 | 1228 | return explorer_error(request_id, "invalid_request"); |
| 1228 | 1229 | }; |
| @@ -1342,29 +1343,24 @@ | ||
| 1342 | 1343 | }) |
| 1343 | 1344 | } |
| 1344 | 1345 | |
| 1345 | -fn valid_explorer_cell_id(cell: &str) -> bool { | |
| 1346 | - !cell.is_empty() | |
| 1347 | - && cell.len() <= MAX_PRESENCE_CELL_ID_BYTES | |
| 1348 | - && !cell.contains('/') | |
| 1349 | - && !cell.contains('\\') | |
| 1350 | - && !cell.contains('?') | |
| 1351 | - && !cell.contains('#') | |
| 1352 | - && !cell.contains("..") | |
| 1353 | - && cell.bytes().all(|byte| byte.is_ascii_graphic()) | |
| 1354 | -} | |
| 1355 | - | |
| 1356 | 1346 | async fn list_durable_cells( |
| 1357 | 1347 | bucket: &Bucket, |
| 1358 | 1348 | cursor: Option<&str>, |
| 1359 | 1349 | ) -> anyhow::Result<serde_json::Value> { |
| 1360 | - // object_store exposes no server-side cursor, so paging is client-side | |
| 1361 | - // over the full delimiter listing (bounded by the fleet's cell count). | |
| 1350 | + // Paging is client-side over the full delimiter listing, bounded by the | |
| 1351 | + // fleet's cell count. `Bucket::common_prefixes_page` would bound the | |
| 1352 | + // request too, but the explorer's cursor is a sorted position and the | |
| 1353 | + // store lists in key order, which are not the same sequence. | |
| 1362 | 1354 | let mut cells = bucket |
| 1363 | 1355 | .common_prefixes("cells/") |
| 1364 | 1356 | .await? |
| 1365 | 1357 | .into_iter() |
| 1366 | 1358 | .filter_map(|prefix| prefix.strip_prefix("cells/").map(str::to_string)) |
| 1367 | - .filter(|cell| valid_explorer_cell_id(cell)) | |
| 1359 | + // The same fence `celld cell list` applies: the engine's storage | |
| 1360 | + // charset decides what a celld node could have written. A second | |
| 1361 | + // opinion here would show foreign bucket content as a cell in one | |
| 1362 | + // surface and hide it in the other. | |
| 1363 | + .filter(|cell| celld_logic::cell::valid_cell_scope(cell)) | |
| 1368 | 1364 | .collect::<Vec<_>>(); |
| 1369 | 1365 | cells.sort(); |
| 1370 | 1366 | if let Some(cursor) = cursor { |
| @@ -1603,7 +1599,7 @@ | ||
| 1603 | 1599 | Ok((url.into(), headers)) |
| 1604 | 1600 | } |
| 1605 | 1601 | |
| 1606 | -pub fn start_deploy_agent(bucket: Bucket, runtime_ready: Arc<AtomicBool>) -> bool { | |
| 1602 | +pub fn start_deploy_agent(bucket: Bucket, reload: crate::generation::ReloadSender) -> bool { | |
| 1607 | 1603 | let config = match connected_config() { |
| 1608 | 1604 | Ok(Some(config)) => config, |
| 1609 | 1605 | Ok(None) => return false, |
| @@ -1636,15 +1632,13 @@ | ||
| 1636 | 1632 | ); |
| 1637 | 1633 | } |
| 1638 | 1634 | consecutive_failures = 0; |
| 1639 | - if runtime_ready.load(Ordering::SeqCst) && restart_on_deployment_enabled() { | |
| 1640 | - info!( | |
| 1641 | - event = "control_plane_restart_for_deploy", | |
| 1642 | - deployment_id = %applied.id, | |
| 1643 | - script_name = %applied.script_name, | |
| 1644 | - "deployment applied; restarting celld to load it" | |
| 1645 | - ); | |
| 1646 | - restart_for_deployment(); | |
| 1647 | - } | |
| 1635 | + info!( | |
| 1636 | + event = "control_plane_deployment_applied", | |
| 1637 | + deployment_id = %applied.id, | |
| 1638 | + script_name = %applied.script_name, | |
| 1639 | + "deployment applied to the fleet bucket; adopting it" | |
| 1640 | + ); | |
| 1641 | + adopt_or_restart(&reload); | |
| 1648 | 1642 | } |
| 1649 | 1643 | Ok(None) => { |
| 1650 | 1644 | if consecutive_failures > 0 { |
| @@ -1685,8 +1679,8 @@ | ||
| 1685 | 1679 | let client = reqwest::Client::builder() |
| 1686 | 1680 | .timeout(Duration::from_secs(30)) |
| 1687 | 1681 | .build()?; |
| 1688 | - println!("Waiting for the first Managed Control Plane deployment..."); | |
| 1689 | - println!( | |
| 1682 | + note!("Waiting for the first Managed Control Plane deployment..."); | |
| 1683 | + note!( | |
| 1690 | 1684 | "Deploy from {}/control; this process will start automatically.", |
| 1691 | 1685 | config.control_url.trim_end_matches('/') |
| 1692 | 1686 | ); |
| @@ -1805,7 +1799,8 @@ | ||
| 1805 | 1799 | })) |
| 1806 | 1800 | } |
| 1807 | 1801 | |
| 1808 | -async fn apply_deployment( | |
| 1802 | +#[doc(hidden)] | |
| 1803 | +pub async fn apply_deployment( | |
| 1809 | 1804 | client: &reqwest::Client, |
| 1810 | 1805 | token: &str, |
| 1811 | 1806 | bucket: &Bucket, |
| @@ -1820,6 +1815,12 @@ | ||
| 1820 | 1815 | validate_managed_module_envelope(deployment)?; |
| 1821 | 1816 | validate_managed_class_migrations(&deployment.manifest)?; |
| 1822 | 1817 | crate::protocol::validate_required_features(&deployment.manifest.required_features)?; |
| 1818 | + crate::protocol::validate_queue_manifest(&deployment.manifest)?; | |
| 1819 | + // Read the current owner before writing this deployment's immutable | |
| 1820 | + // objects. A competing Queue consumer must refuse the deployment without | |
| 1821 | + // leaving a prefix that looks publishable. | |
| 1822 | + let queue_attachments = | |
| 1823 | + crate::deploy::prepare_queue_attachments(bucket, &deployment.manifest).await?; | |
| 1823 | 1824 | |
| 1824 | 1825 | let mut asset_files = 0_u32; |
| 1825 | 1826 | let mut asset_bytes = 0_u64; |
| @@ -1973,6 +1974,16 @@ | ||
| 1973 | 1974 | serde_json::to_vec_pretty(&deployment.manifest)?, |
| 1974 | 1975 | ) |
| 1975 | 1976 | .await?; |
| 1977 | + // A producer can run in a different script, so the manifest is not a | |
| 1978 | + // discoverable consumer index. Publish the same fleet-wide attachment as | |
| 1979 | + // `celld deploy`, after its exact deployment prefix is complete. | |
| 1980 | + crate::deploy::publish_queue_attachments( | |
| 1981 | + bucket, | |
| 1982 | + &deployment.manifest, | |
| 1983 | + &deployment.pointer.prefix, | |
| 1984 | + queue_attachments, | |
| 1985 | + ) | |
| 1986 | + .await?; | |
| 1976 | 1987 | bucket |
| 1977 | 1988 | .put( |
| 1978 | 1989 | &format!("deploy/{}/current.json", deployment.script_name), |
| @@ -2370,9 +2381,10 @@ | ||
| 2370 | 2381 | expires_in_seconds = claim.expires_in, |
| 2371 | 2382 | "authenticate to connect this celld instance" |
| 2372 | 2383 | ); |
| 2373 | - println!( | |
| 2384 | + note!( | |
| 2374 | 2385 | "\nConnect this celld instance to the Managed Control Plane:\n\n {}\n\nEnvironment: {}\n", |
| 2375 | - claim.verification_uri_complete, config.environment | |
| 2386 | + claim.verification_uri_complete, | |
| 2387 | + config.environment | |
| 2376 | 2388 | ); |
| 2377 | 2389 | |
| 2378 | 2390 | if wait { |
| @@ -2528,7 +2540,7 @@ | ||
| 2528 | 2540 | environment = %config.environment, |
| 2529 | 2541 | "celld connected to the Managed Control Plane" |
| 2530 | 2542 | ); |
| 2531 | - println!( | |
| 2543 | + note!( | |
| 2532 | 2544 | "Connected to the Managed Control Plane ({}).\n\ |
| 2533 | 2545 | Keep celld running. In your app directory, run `celld token`, apply the \ |
| 2534 | 2546 | exports it prints, then run `npx wrangler@4 deploy`.", |
| @@ -2538,7 +2550,7 @@ | ||
| 2538 | 2550 | } |
| 2539 | 2551 | // Make expiry visible so an unattended process cannot keep displaying a |
| 2540 | 2552 | // dead approval URL. |
| 2541 | - println!( | |
| 2553 | + note!( | |
| 2542 | 2554 | "\nThe activation link expired before it was approved.\n\ |
| 2543 | 2555 | Restart celld to get a new one.\n" |
| 2544 | 2556 | ); |
| @@ -2789,7 +2801,7 @@ | ||
| 2789 | 2801 | } |
| 2790 | 2802 | if let Some(pending) = config.pending_claim { |
| 2791 | 2803 | if pending.expires_at_ms > current_time_ms() { |
| 2792 | - println!( | |
| 2804 | + note!( | |
| 2793 | 2805 | "\nConnect this celld installation to the Managed Control Plane:\n\n {}\n\nEnvironment: {}\n", |
| 2794 | 2806 | pending.verification_uri_complete, config.environment |
| 2795 | 2807 | ); |
| @@ -2875,26 +2887,19 @@ | ||
| 2875 | 2887 | // The presence session read the socket in the same select! as the heartbeat |
| 2876 | 2888 | // timer, so every tick dropped a read in progress. The fault is invisible from |
| 2877 | 2889 | // outside: the session reconnects and only the messages in the window are gone, |
| 2878 | -// so it takes a test that watches the frames themselves. | |
| 2879 | -#[cfg(all(test, celld_internal_tests))] | |
| 2880 | -mod presence_cancel_private { | |
| 2881 | - include!(env!("CELLD_CONFORMANCE_PRESENCE_CANCEL_TESTS")); | |
| 2882 | -} | |
| 2890 | +// so frame-level observation is required. | |
| 2883 | 2891 | |
| 2884 | 2892 | fn print_connect_help() { |
| 2885 | - println!( | |
| 2886 | - "Connect this celld installation to the Managed Control Plane.\n\nUSAGE:\n celld connect [--env prod] [--control-url https://celld.dev] [--force]" | |
| 2887 | - ); | |
| 2893 | + let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text) | |
| 2894 | + .help("Connect this celld installation to the Managed Control Plane.\n\nUSAGE:\n celld connect [--env prod] [--control-url https://celld.dev] [--force]"); | |
| 2888 | 2895 | } |
| 2889 | 2896 | |
| 2890 | 2897 | fn print_credentials_help() { |
| 2891 | - println!( | |
| 2892 | - "Refresh a staged Managed Control Plane credential.\n\nUSAGE:\n celld credentials refresh\n\nRunning celld processes sharing this installation automatically reload after the replacement is saved. Unix processes re-exec; other platforms exit 75 for their supervisor." | |
| 2893 | - ); | |
| 2898 | + let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text) | |
| 2899 | + .help("Refresh a staged Managed Control Plane credential.\n\nUSAGE:\n celld credentials refresh\n\nRunning celld processes sharing this installation automatically reload after the replacement is saved. Unix processes re-exec; other platforms exit 75 for their supervisor."); | |
| 2894 | 2900 | } |
| 2895 | 2901 | |
| 2896 | 2902 | fn print_disconnect_help() { |
| 2897 | - println!( | |
| 2898 | - "Revoke and disconnect this Managed Control Plane installation.\n\nUSAGE:\n celld disconnect --yes\n\nStop every celld process sharing this installation first. Other installations in the fleet are unaffected." | |
| 2899 | - ); | |
| 2903 | + let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text) | |
| 2904 | + .help("Revoke and disconnect this Managed Control Plane installation.\n\nUSAGE:\n celld disconnect --yes\n\nStop every celld process sharing this installation first. Other installations in the fleet are unaffected."); | |
| 2900 | 2905 | } |
modifiedcrates/celld/d1_cli.rs+161−261View file
| @@ -2,13 +2,15 @@ | ||
| 2 | 2 | |
| 3 | 3 | // The D1 CLI reads operator input and migration files outside node storage. |
| 4 | 4 | #![allow(clippy::disallowed_methods)] |
| 5 | +// Reaching stdout past `Output` is what mixed the result rows and the | |
| 6 | +// summary onto one stream here in the first place. | |
| 5 | 7 | |
| 6 | 8 | //! `celld d1` — run SQL and migrations against a deployed D1 database. |
| 7 | 9 | //! |
| 8 | 10 | //! A D1 database is a cell, so it is only reachable through the node that owns |
| 9 | 11 | //! it. This command finds the fleet the way `celld diagnose` does — it walks |
| 10 | 12 | //! the node leases in the bucket, and it reads the same shared secret — and |
| 11 | -//! then sends the SQL to a live node's `/__d1/` route, which forwards to the | |
| 13 | +//! then sends the SQL to a live node's `/runtime/` route, which forwards to the | |
| 12 | 14 | //! owner. The CLI therefore holds no ownership logic and no SQLite: it reaches |
| 13 | 15 | //! the database over the dispatch a Worker's `env.DB` reaches it over. |
| 14 | 16 | //! |
| @@ -18,13 +20,62 @@ | ||
| 18 | 20 | //! refuses a D1 scope and sends the caller here. |
| 19 | 21 | |
| 20 | 22 | use std::path::PathBuf; |
| 21 | -use std::time::Duration; | |
| 22 | 23 | |
| 23 | 24 | use anyhow::{anyhow, bail, Context}; |
| 24 | 25 | use serde_json::Value; |
| 25 | 26 | |
| 26 | -use crate::bucket::Bucket; | |
| 27 | +use crate::cli_options::FleetFlags; | |
| 28 | +use crate::cli_options::FLEET_HELP; | |
| 29 | +use crate::cli_output::{align, Format, Output, Record}; | |
| 30 | +use crate::note; | |
| 31 | +use crate::operator_cell::{Fleet, Reachable, Subject}; | |
| 32 | +use std::borrow::Cow; | |
| 27 | 33 | |
| 34 | +/// One row of a `d1 execute` result set. | |
| 35 | +/// | |
| 36 | +/// The text is rendered when the set is laid out, because a column's width | |
| 37 | +/// depends on every row in it. The JSON keeps the column names as keys, so | |
| 38 | +/// `--json` output is self-describing without the header line. | |
| 39 | +struct Row { | |
| 40 | + object: Value, | |
| 41 | + text: String, | |
| 42 | +} | |
| 43 | + | |
| 44 | +impl Record for Row { | |
| 45 | + fn json(&self) -> Value { | |
| 46 | + self.object.clone() | |
| 47 | + } | |
| 48 | + | |
| 49 | + fn text(&self) -> Cow<'_, str> { | |
| 50 | + Cow::Borrowed(&self.text) | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +/// One migration, listed rather than applied. | |
| 55 | +struct Pending { | |
| 56 | + name: String, | |
| 57 | +} | |
| 58 | + | |
| 59 | +impl Record for Pending { | |
| 60 | + fn json(&self) -> Value { | |
| 61 | + serde_json::json!({ "migration": self.name }) | |
| 62 | + } | |
| 63 | + | |
| 64 | + fn text(&self) -> Cow<'_, str> { | |
| 65 | + Cow::Borrowed(&self.name) | |
| 66 | + } | |
| 67 | +} | |
| 68 | + | |
| 69 | +/// A SQL value as a table cell. JSON keeps the real type; this is only the | |
| 70 | +/// human rendering, so a string prints bare and a null prints as nothing. | |
| 71 | +fn cell(value: &Value) -> String { | |
| 72 | + match value { | |
| 73 | + Value::Null => String::new(), | |
| 74 | + Value::String(text) => text.clone(), | |
| 75 | + other => other.to_string(), | |
| 76 | + } | |
| 77 | +} | |
| 78 | + | |
| 28 | 79 | pub async fn run(arguments: Vec<String>) -> anyhow::Result<()> { |
| 29 | 80 | let Some(command) = Command::parse(arguments)? else { |
| 30 | 81 | print_help(); |
| @@ -55,8 +106,30 @@ | ||
| 55 | 106 | ) |
| 56 | 107 | })?; |
| 57 | 108 | let scope = crate::js::d1_cell_scope(&declaration.database_identity); |
| 58 | - let database = Reachable::open(&command, scope).await?; | |
| 109 | + let storage = command.fleet.clone().resolve("celld d1")?; | |
| 110 | + let database = Reachable::open( | |
| 111 | + Fleet { | |
| 112 | + bucket: &storage.bucket, | |
| 113 | + endpoint: storage.endpoint.as_deref(), | |
| 114 | + region: &storage.region, | |
| 115 | + unsafe_public_advertise: command.unsafe_public_advertise, | |
| 116 | + }, | |
| 117 | + Subject { | |
| 118 | + noun: "database", | |
| 119 | + source: "d1", | |
| 120 | + // A migration on a large table is not a diagnostic ping. | |
| 121 | + timeout: std::time::Duration::from_secs(120), | |
| 122 | + }, | |
| 123 | + scope, | |
| 124 | + None, | |
| 125 | + ) | |
| 126 | + .await?; | |
| 59 | 127 | |
| 128 | + let mut out = Output::new(if command.json { | |
| 129 | + Format::Json | |
| 130 | + } else { | |
| 131 | + Format::Text | |
| 132 | + }); | |
| 60 | 133 | match command.action { |
| 61 | 134 | Action::Execute { command: sql, file } => { |
| 62 | 135 | let source = match (sql, file) { |
| @@ -68,80 +141,96 @@ | ||
| 68 | 141 | let result = database.exec(&source).await?; |
| 69 | 142 | // The rows, not only the count: an operator running a SELECT is |
| 70 | 143 | // asking for its result, and `wrangler d1 execute` prints it. |
| 71 | - for set in result | |
| 144 | + for (index, set) in result | |
| 72 | 145 | .get("results") |
| 73 | 146 | .and_then(Value::as_array) |
| 74 | 147 | .into_iter() |
| 75 | 148 | .flatten() |
| 149 | + .enumerate() | |
| 76 | 150 | { |
| 77 | - let columns: Vec<&str> = set | |
| 151 | + let columns: Vec<String> = set | |
| 78 | 152 | .get("columns") |
| 79 | 153 | .and_then(Value::as_array) |
| 80 | 154 | .into_iter() |
| 81 | 155 | .flatten() |
| 82 | 156 | .filter_map(Value::as_str) |
| 157 | + .map(str::to_string) | |
| 83 | 158 | .collect(); |
| 84 | - let shaped: Vec<Value> = set | |
| 159 | + let values: Vec<Vec<Value>> = set | |
| 85 | 160 | .get("rows") |
| 86 | 161 | .and_then(Value::as_array) |
| 87 | 162 | .into_iter() |
| 88 | 163 | .flatten() |
| 89 | 164 | .filter_map(Value::as_array) |
| 90 | - .map(|row| { | |
| 91 | - Value::Object( | |
| 92 | - columns | |
| 93 | - .iter() | |
| 94 | - .zip(row) | |
| 95 | - .map(|(column, value)| (column.to_string(), value.clone())) | |
| 96 | - .collect(), | |
| 97 | - ) | |
| 98 | - }) | |
| 165 | + .map(|row| row.to_vec()) | |
| 99 | 166 | .collect(); |
| 100 | - println!( | |
| 101 | - "{}", | |
| 102 | - serde_json::to_string_pretty(&Value::Array(shaped)) | |
| 103 | - .context("encode the result rows")? | |
| 104 | - ); | |
| 167 | + let cells: Vec<Vec<String>> = values | |
| 168 | + .iter() | |
| 169 | + .map(|row| row.iter().map(cell).collect()) | |
| 170 | + .collect(); | |
| 171 | + let (header, rule, lines) = align(&columns, &cells); | |
| 172 | + // A blank line between result sets, so several statements | |
| 173 | + // read as several tables rather than one ragged one. | |
| 174 | + if index > 0 { | |
| 175 | + out.header("")?; | |
| 176 | + } | |
| 177 | + out.header(&header)?; | |
| 178 | + out.header(&rule)?; | |
| 179 | + for (row, text) in values.iter().zip(lines) { | |
| 180 | + let object = | |
| 181 | + Value::Object(columns.iter().cloned().zip(row.iter().cloned()).collect()); | |
| 182 | + out.row(&Row { object, text })?; | |
| 183 | + } | |
| 105 | 184 | } |
| 106 | - println!( | |
| 107 | - "Executed {} statement(s) in {:.2} sec", | |
| 108 | - result | |
| 109 | - .get("count") | |
| 110 | - .and_then(Value::as_u64) | |
| 111 | - .unwrap_or_default(), | |
| 112 | - result | |
| 113 | - .get("duration") | |
| 114 | - .and_then(Value::as_f64) | |
| 115 | - .unwrap_or_default() | |
| 116 | - / 1000.0 | |
| 117 | - ); | |
| 185 | + // stderr, not stdout. This line used to follow the rows on the | |
| 186 | + // same stream, so `celld d1 execute | jq` parsed prose. | |
| 187 | + let count = result | |
| 188 | + .get("count") | |
| 189 | + .and_then(Value::as_u64) | |
| 190 | + .unwrap_or_default(); | |
| 191 | + let milliseconds = result | |
| 192 | + .get("duration") | |
| 193 | + .and_then(Value::as_f64) | |
| 194 | + .unwrap_or_default(); | |
| 195 | + // "0.00 sec" reads as a missing measurement rather than a fast | |
| 196 | + // statement, the same way "0.0s" did on a listing summary. | |
| 197 | + let took = if milliseconds < 1000.0 { | |
| 198 | + format!("{}ms", milliseconds.round() as u64) | |
| 199 | + } else { | |
| 200 | + format!("{:.2} sec", milliseconds / 1000.0) | |
| 201 | + }; | |
| 202 | + note!("Executed {count} statement(s) in {took}"); | |
| 118 | 203 | } |
| 119 | 204 | Action::MigrationsList => { |
| 120 | 205 | let pending = database.pending(declaration).await?; |
| 121 | 206 | if pending.is_empty() { |
| 122 | - println!("No migrations to apply."); | |
| 123 | - return Ok(()); | |
| 207 | + note!("No migrations to apply."); | |
| 208 | + return out.finish(); | |
| 124 | 209 | } |
| 125 | - println!("Migrations to be applied:"); | |
| 210 | + note!("Migrations to be applied:"); | |
| 126 | 211 | for migration in &pending { |
| 127 | - println!(" {}", migration.name); | |
| 212 | + out.row(&Pending { | |
| 213 | + name: migration.name.clone(), | |
| 214 | + })?; | |
| 128 | 215 | } |
| 129 | 216 | } |
| 130 | 217 | Action::MigrationsApply => { |
| 131 | 218 | let pending = database.pending(declaration).await?; |
| 132 | 219 | if pending.is_empty() { |
| 133 | - println!("No migrations to apply."); | |
| 134 | - return Ok(()); | |
| 220 | + note!("No migrations to apply."); | |
| 221 | + return out.finish(); | |
| 135 | 222 | } |
| 136 | 223 | for migration in pending { |
| 137 | 224 | database |
| 138 | 225 | .apply(&migration, &declaration.migrations_table) |
| 139 | 226 | .await?; |
| 140 | - println!("Applied {}", migration.name); | |
| 227 | + // Applying is an action, not data: its progress belongs on | |
| 228 | + // stderr so a redirect of the listing stays parseable. | |
| 229 | + note!("Applied {}", migration.name); | |
| 141 | 230 | } |
| 142 | 231 | } |
| 143 | 232 | } |
| 144 | - Ok(()) | |
| 233 | + out.finish() | |
| 145 | 234 | } |
| 146 | 235 | |
| 147 | 236 | struct Migration { |
| @@ -151,135 +240,7 @@ | ||
| 151 | 240 | |
| 152 | 241 | /// One entrance into the fleet: a node's address and the identity a request |
| 153 | 242 | /// to it must be signed for. |
| 154 | -struct Entrance { | |
| 155 | - node: String, | |
| 156 | - url: String, | |
| 157 | - path: String, | |
| 158 | -} | |
| 159 | - | |
| 160 | -/// A database resolved to the nodes that can carry SQL to it. | |
| 161 | -struct Reachable { | |
| 162 | - http: reqwest::Client, | |
| 163 | - /// The fleet's shared peer secret, read from the bucket. `/__d1/` refuses | |
| 164 | - /// an unsigned request, because a D1 database holds application data and | |
| 165 | - /// answers arbitrary SQL. | |
| 166 | - auth: crate::peer_auth::PeerAuth, | |
| 167 | - /// Every node with a live lease. Any one of them forwards to the owner, so | |
| 168 | - /// the list is a set of equal entrances and not a route: it stays correct | |
| 169 | - /// even when the cell moves between calls. | |
| 170 | - entrances: Vec<Entrance>, | |
| 171 | -} | |
| 172 | - | |
| 173 | 243 | impl Reachable { |
| 174 | - async fn open(command: &Command, scope: String) -> anyhow::Result<Self> { | |
| 175 | - let bucket = crate::fleet::bucket_client( | |
| 176 | - &command.bucket, | |
| 177 | - command.endpoint.as_deref(), | |
| 178 | - &command.region, | |
| 179 | - )?; | |
| 180 | - let nodes = live_nodes(&bucket, command.unsafe_public_advertise).await?; | |
| 181 | - // The same secret and the same source shape `celld diagnose` uses. | |
| 182 | - let auth = | |
| 183 | - crate::peer_auth::PeerAuth::new(crate::peer_auth::load_existing(&bucket).await?, "d1")?; | |
| 184 | - let http = reqwest::Client::builder() | |
| 185 | - .connect_timeout(Duration::from_secs(5)) | |
| 186 | - // A migration on a large table is not a diagnostic ping, so this | |
| 187 | - // budget is the handler budget's order rather than the probe's. | |
| 188 | - .timeout(Duration::from_secs(120)) | |
| 189 | - .build() | |
| 190 | - .context("build the D1 client")?; | |
| 191 | - let path = format!("/__d1/{scope}"); | |
| 192 | - Ok(Self { | |
| 193 | - http, | |
| 194 | - auth, | |
| 195 | - entrances: nodes | |
| 196 | - .into_iter() | |
| 197 | - .map(|(node, addr)| Entrance { | |
| 198 | - node, | |
| 199 | - url: format!("http://{addr}{path}"), | |
| 200 | - path: path.clone(), | |
| 201 | - }) | |
| 202 | - .collect(), | |
| 203 | - }) | |
| 204 | - } | |
| 205 | - | |
| 206 | - /// A lease outlives the node that wrote it, and a node that drains keeps | |
| 207 | - /// its lease while it refuses work, so the first entrance in the list is | |
| 208 | - /// not always usable. Move to the next one when a node cannot be reached | |
| 209 | - /// or is draining, because in both cases the request provably did not run. | |
| 210 | - /// Nothing else is retried: a timeout is not evidence that the work was | |
| 211 | - /// refused, and re-sending a migration that in fact ran would apply it | |
| 212 | - /// twice. | |
| 213 | - async fn call(&self, body: Value) -> anyhow::Result<Value> { | |
| 214 | - // Signed per entrance, because the signature binds the node it is | |
| 215 | - // addressed to: a signature for one node is not replayable at another. | |
| 216 | - let payload = serde_json::to_vec(&body).context("encode the request")?; | |
| 217 | - let mut refused = Vec::new(); | |
| 218 | - for (index, entrance) in self.entrances.iter().enumerate() { | |
| 219 | - let last = index + 1 == self.entrances.len(); | |
| 220 | - let url = &entrance.url; | |
| 221 | - let request = self | |
| 222 | - .auth | |
| 223 | - .sign( | |
| 224 | - self.http.post(url).body(payload.clone()), | |
| 225 | - "POST", | |
| 226 | - &entrance.path, | |
| 227 | - &payload, | |
| 228 | - &entrance.node, | |
| 229 | - ) | |
| 230 | - .with_context(|| format!("sign the request to {}", entrance.node))?; | |
| 231 | - let response = match request.send().await { | |
| 232 | - Ok(response) => response, | |
| 233 | - Err(error) if error.is_connect() && !last => { | |
| 234 | - refused.push(format!("{url}: {error}")); | |
| 235 | - continue; | |
| 236 | - } | |
| 237 | - Err(error) => { | |
| 238 | - return Err(anyhow::Error::new(error)).with_context(|| { | |
| 239 | - format!("reach the database at {url}{}", report(&refused)) | |
| 240 | - }); | |
| 241 | - } | |
| 242 | - }; | |
| 243 | - let status = response.status(); | |
| 244 | - let text = response.text().await.context("read the database reply")?; | |
| 245 | - if status == reqwest::StatusCode::SERVICE_UNAVAILABLE | |
| 246 | - && text.contains("\"draining\"") | |
| 247 | - && !last | |
| 248 | - { | |
| 249 | - refused.push(format!("{url}: the node is draining")); | |
| 250 | - continue; | |
| 251 | - } | |
| 252 | - // The dispatcher refusing at the door is the doc comment's | |
| 253 | - // criterion exactly: the request provably did not run, so the | |
| 254 | - // next entrance is safe to try where a timeout would not be. | |
| 255 | - if status == reqwest::StatusCode::SERVICE_UNAVAILABLE | |
| 256 | - && text.contains("dispatcher unavailable") | |
| 257 | - && !last | |
| 258 | - { | |
| 259 | - refused.push(format!("{url}: the node's dispatcher is unavailable")); | |
| 260 | - continue; | |
| 261 | - } | |
| 262 | - let value: Value = serde_json::from_str(&text) | |
| 263 | - .with_context(|| format!("decode the database reply ({status}): {text}"))?; | |
| 264 | - if let Some(error) = value.get("error").and_then(Value::as_str) { | |
| 265 | - bail!("{error}{}", report(&refused)); | |
| 266 | - } | |
| 267 | - if !status.is_success() { | |
| 268 | - bail!( | |
| 269 | - "the database refused the request ({status}): {text}{}", | |
| 270 | - report(&refused) | |
| 271 | - ); | |
| 272 | - } | |
| 273 | - return value.get("result").cloned().ok_or_else(|| { | |
| 274 | - anyhow!( | |
| 275 | - "the database reply carried no result: {text}{}", | |
| 276 | - report(&refused) | |
| 277 | - ) | |
| 278 | - }); | |
| 279 | - } | |
| 280 | - bail!("no node in the fleet answered{}", report(&refused)) | |
| 281 | - } | |
| 282 | - | |
| 283 | 244 | async fn exec(&self, source: &str) -> anyhow::Result<Value> { |
| 284 | 245 | // `rows: true` is the CLI's difference from the Worker binding's |
| 285 | 246 | // exec(): the operator asked to see the result, not only the count. |
| @@ -347,7 +308,6 @@ | ||
| 347 | 308 | Ok(()) |
| 348 | 309 | } |
| 349 | 310 | } |
| 350 | - | |
| 351 | 311 | fn read_migrations(directory: &std::path::Path) -> anyhow::Result<Vec<Migration>> { |
| 352 | 312 | if !directory.exists() { |
| 353 | 313 | bail!( |
| @@ -443,63 +403,6 @@ | ||
| 443 | 403 | /// works. They are all returned rather than only the first, because a lease |
| 444 | 404 | /// outlives the node that wrote it and a draining node keeps its lease while |
| 445 | 405 | /// it refuses work. |
| 446 | -async fn live_nodes( | |
| 447 | - bucket: &Bucket, | |
| 448 | - unsafe_public_advertise: bool, | |
| 449 | -) -> anyhow::Result<Vec<(String, String)>> { | |
| 450 | - let nodes = crate::fleet::node_lease_ids(bucket).await?; | |
| 451 | - if nodes.is_empty() { | |
| 452 | - bail!("no node leases in the bucket; celld d1 needs a running fleet"); | |
| 453 | - } | |
| 454 | - let mut reachable = Vec::new(); | |
| 455 | - let mut refused = Vec::new(); | |
| 456 | - for node in &nodes { | |
| 457 | - let lease = match crate::fleet::live_node_lease(bucket, node).await { | |
| 458 | - Ok(Some(lease)) => lease, | |
| 459 | - Ok(None) => continue, | |
| 460 | - Err(error) => { | |
| 461 | - refused.push(format!("{node}: {error}")); | |
| 462 | - continue; | |
| 463 | - } | |
| 464 | - }; | |
| 465 | - let advertise = match crate::startup::parse_advertise(&lease.addr) { | |
| 466 | - Ok(advertise) => advertise, | |
| 467 | - Err(error) => { | |
| 468 | - refused.push(format!( | |
| 469 | - "{node}: malformed address {:?}: {error}", | |
| 470 | - lease.addr | |
| 471 | - )); | |
| 472 | - continue; | |
| 473 | - } | |
| 474 | - }; | |
| 475 | - if advertise.is_public_ip() && !unsafe_public_advertise { | |
| 476 | - refused.push(format!( | |
| 477 | - "{node}: public advertise address {}; use a private overlay or \ | |
| 478 | - --unsafe-public-advertise", | |
| 479 | - lease.addr | |
| 480 | - )); | |
| 481 | - continue; | |
| 482 | - } | |
| 483 | - reachable.push((node.clone(), lease.addr.clone())); | |
| 484 | - } | |
| 485 | - if reachable.is_empty() { | |
| 486 | - bail!( | |
| 487 | - "no node in the fleet is reachable; every lease is expired or refused{}", | |
| 488 | - report(&refused) | |
| 489 | - ); | |
| 490 | - } | |
| 491 | - Ok(reachable) | |
| 492 | -} | |
| 493 | - | |
| 494 | -/// Indented detail under a refusal, or nothing when there is none to give. | |
| 495 | -fn report(refused: &[String]) -> String { | |
| 496 | - if refused.is_empty() { | |
| 497 | - String::new() | |
| 498 | - } else { | |
| 499 | - format!("\n {}", refused.join("\n ")) | |
| 500 | - } | |
| 501 | -} | |
| 502 | - | |
| 503 | 406 | enum Action { |
| 504 | 407 | /// Exactly one of the two, enforced at parse. |
| 505 | 408 | Execute { |
| @@ -514,9 +417,8 @@ | ||
| 514 | 417 | action: Action, |
| 515 | 418 | database: String, |
| 516 | 419 | project: Option<PathBuf>, |
| 517 | - bucket: String, | |
| 518 | - endpoint: Option<String>, | |
| 519 | - region: String, | |
| 420 | + fleet: FleetFlags, | |
| 421 | + json: bool, | |
| 520 | 422 | unsafe_public_advertise: bool, |
| 521 | 423 | } |
| 522 | 424 | |
| @@ -548,17 +450,11 @@ | ||
| 548 | 450 | .filter(|value| !value.starts_with('-')) |
| 549 | 451 | .ok_or_else(|| anyhow!("celld d1 needs a database name"))?; |
| 550 | 452 | |
| 551 | - let env = |name: &str| { | |
| 552 | - std::env::var(name) | |
| 553 | - .ok() | |
| 554 | - .filter(|value| !value.trim().is_empty()) | |
| 555 | - }; | |
| 556 | 453 | let mut sql = None; |
| 557 | 454 | let mut file = None; |
| 558 | 455 | let mut project = None; |
| 559 | - let mut bucket = env("CELLD_BUCKET"); | |
| 560 | - let mut endpoint = env("S3_ENDPOINT"); | |
| 561 | - let mut region = env("AWS_REGION").or_else(|| env("AWS_DEFAULT_REGION")); | |
| 456 | + let mut fleet = FleetFlags::default(); | |
| 457 | + let mut json = false; | |
| 562 | 458 | let mut unsafe_public_advertise = false; |
| 563 | 459 | while let Some(argument) = arguments.next() { |
| 564 | 460 | let mut value = |flag: &str| { |
| @@ -569,17 +465,21 @@ | ||
| 569 | 465 | match argument.as_str() { |
| 570 | 466 | "--command" => sql = Some(value("--command")?), |
| 571 | 467 | "--file" => file = Some(PathBuf::from(value("--file")?)), |
| 572 | - "--bucket" => { | |
| 573 | - bucket = Some(value("--bucket")?.trim_start_matches("s3://").to_string()); | |
| 574 | - } | |
| 575 | - "--endpoint" => endpoint = Some(value("--endpoint")?), | |
| 576 | - "--region" => region = Some(value("--region")?), | |
| 468 | + "--json" => json = true, | |
| 577 | 469 | "--unsafe-public-advertise" => unsafe_public_advertise = true, |
| 578 | 470 | "--help" | "-h" => return Ok(None), |
| 579 | - other if other.starts_with('-') => { | |
| 580 | - bail!("unknown option: {other}; run `celld d1 --help` for usage") | |
| 471 | + other => { | |
| 472 | + // The fleet flags are shared, so `--bucket gs://name` | |
| 473 | + // resolves here exactly as it does for every other | |
| 474 | + // command rather than through a second copy of the rule. | |
| 475 | + if fleet.consume(other, &mut value)? { | |
| 476 | + continue; | |
| 477 | + } | |
| 478 | + if other.starts_with('-') { | |
| 479 | + bail!("unknown option: {other}; run `celld d1 --help` for usage") | |
| 480 | + } | |
| 481 | + project = Some(PathBuf::from(other)); | |
| 581 | 482 | } |
| 582 | - other => project = Some(PathBuf::from(other)), | |
| 583 | 483 | } |
| 584 | 484 | } |
| 585 | 485 | let action = match action { |
| @@ -601,23 +501,21 @@ | ||
| 601 | 501 | Action::Execute { command: sql, file } |
| 602 | 502 | } |
| 603 | 503 | }; |
| 604 | - let bucket = bucket.ok_or_else(|| { | |
| 605 | - anyhow!("celld d1 requires --bucket [s3://|gs://|az://]NAME (or CELLD_BUCKET)") | |
| 606 | - })?; | |
| 607 | 504 | Ok(Some(Self { |
| 608 | 505 | action, |
| 609 | 506 | database, |
| 610 | 507 | project, |
| 611 | - bucket, | |
| 612 | - endpoint, | |
| 613 | - region: region.unwrap_or_else(|| "us-east-1".to_string()), | |
| 508 | + // Resolution is deferred to `run`, so the missing-bucket message | |
| 509 | + // is the one every command shares. | |
| 510 | + fleet: fleet.with_environment(), | |
| 511 | + json, | |
| 614 | 512 | unsafe_public_advertise, |
| 615 | 513 | })) |
| 616 | 514 | } |
| 617 | 515 | } |
| 618 | 516 | |
| 619 | 517 | pub fn print_help() { |
| 620 | - println!( | |
| 518 | + let text = format!( | |
| 621 | 519 | r#"celld d1 — run SQL and migrations against a deployed D1 database |
| 622 | 520 | |
| 623 | 521 | USAGE: |
| @@ -643,15 +541,17 @@ | ||
| 643 | 541 | (`d1_migrations` by default), the same table and columns |
| 644 | 542 | `wrangler d1 migrations` uses. |
| 645 | 543 | |
| 544 | +`execute` prints a table, and every message goes to stderr, so its stdout | |
| 545 | +carries only result rows. Pass --json for one JSON object per row. | |
| 546 | + | |
| 646 | 547 | OPTIONS: |
| 647 | - --command SQL SQL to run; several statements are permitted | |
| 648 | - --file PATH Read the SQL from a file instead | |
| 649 | - --bucket [s3://|gs://|az://]NAME[/PREFIX] | |
| 650 | - Fleet bucket; same as CELLD_BUCKET | |
| 651 | - --endpoint URL S3-compatible endpoint; same as S3_ENDPOINT | |
| 652 | - --region REGION Storage region (default: AWS_REGION or us-east-1) | |
| 548 | + --command SQL SQL to run; several statements are permitted | |
| 549 | + --file PATH Read the SQL from a file instead | |
| 550 | + --json Print one JSON object per row instead of a table | |
| 551 | +{FLEET_HELP} | |
| 653 | 552 | --unsafe-public-advertise |
| 654 | - Permit a node whose advertised address is a public IP | |
| 655 | - -h, --help Show this help"# | |
| 553 | + Permit a node whose advertised address is a public IP | |
| 554 | + -h, --help Show this help"# | |
| 656 | 555 | ); |
| 556 | + let _ = Output::new(Format::Text).help(&text); | |
| 657 | 557 | } |
modifiedcrates/celld/dead_node_gc.rs+4−6View file
| @@ -1,7 +1,5 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -#![warn(clippy::disallowed_macros)] | |
| 4 | - | |
| 5 | 3 | //! Compatibility garbage collection for dead celld process generations. |
| 6 | 4 | //! |
| 7 | 5 | //! Wake entries and lazy ownership takeover provide serving correctness. |
| @@ -90,7 +88,8 @@ | ||
| 90 | 88 | let pass = self.run_pass(bucket, tick_ms); |
| 91 | 89 | tokio::pin!(pass); |
| 92 | 90 | loop { |
| 93 | - crate::asyncrt::select! { | |
| 91 | + crate::asyncrt::select_biased! { | |
| 92 | + "a due waker-lease renewal wins a tie with completion of the GC pass"; | |
| 94 | 93 | _ = renewal.tick() => { |
| 95 | 94 | if !crate::wake::try_hold_waker( |
| 96 | 95 | bucket, |
| @@ -317,9 +316,8 @@ | ||
| 317 | 316 | ) { |
| 318 | 317 | return Ok(false); |
| 319 | 318 | } |
| 320 | - // A folded record is never deleted (lease-fold, second cold review, | |
| 321 | - // finding 1). Two reasons compose. An unsealed log is the fleet's | |
| 322 | - // only pointer to an unrecovered tail, so the record must outlive | |
| 319 | + // A folded record is never deleted. Two reasons compose. An unsealed log | |
| 320 | + // is the fleet's only pointer to an unrecovered tail, so the record must outlive | |
| 323 | 321 | // recovery — the dead-leader sweep seals it, and a later pass |
| 324 | 322 | // retires it here. And object_store has no conditional delete, so |
| 325 | 323 | // an unconditional delete can land arbitrarily late — after the |
modifiedcrates/celld/deploy.rs+754−43View file
| @@ -1,7 +1,9 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -// Deployment is an operator control-plane path outside the engine World. | |
| 3 | +// Deployment is an operator control-plane path outside the Actor execution | |
| 4 | +// domain. | |
| 4 | 5 | #![allow(clippy::disallowed_methods)] |
| 6 | +// Deploy narrates progress; every line of it is for a person. | |
| 5 | 7 | |
| 6 | 8 | //! `celld deploy` — build a Wrangler project and write it to the fleet bucket. |
| 7 | 9 | //! |
| @@ -10,10 +12,13 @@ | ||
| 10 | 12 | //! Cloudflare-shaped API. Config keys are an allowlist: anything we do not |
| 11 | 13 | //! model is refused, never silently dropped. |
| 12 | 14 | use crate::bucket::Bucket; |
| 15 | +use crate::note; | |
| 13 | 16 | use crate::protocol::{ |
| 14 | 17 | asset_blob_key, AssetConfig, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest, |
| 15 | - ModuleKind, ModuleRef, Rollout, RunWorkerFirst, FEATURE_ASSETS_V1, FEATURE_CRON_V1, | |
| 16 | - FEATURE_D1_V1, FEATURE_SQLITE_VEC_V1, FEATURE_WASM_V1, | |
| 18 | + ModuleKind, ModuleRef, QueueConsumerAttachment, QueueConsumerConfig, QueueConsumerDeployment, | |
| 19 | + Rollout, RunWorkerFirst, FEATURE_ASSETS_V1, FEATURE_CRON_V1, FEATURE_D1_V1, FEATURE_KV_V1, | |
| 20 | + FEATURE_QUEUES_V1, FEATURE_R2_V1, FEATURE_SQLITE_VEC_V1, FEATURE_WASM_V1, FEATURE_WORKFLOWS_V1, | |
| 21 | + QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION, | |
| 17 | 22 | }; |
| 18 | 23 | use anyhow::{anyhow, bail, Context}; |
| 19 | 24 | use flate2::write::GzEncoder; |
| @@ -43,6 +48,10 @@ | ||
| 43 | 48 | "triggers", |
| 44 | 49 | "vars", |
| 45 | 50 | "d1_databases", |
| 51 | + "kv_namespaces", | |
| 52 | + "queues", | |
| 53 | + "workflows", | |
| 54 | + "r2_buckets", | |
| 46 | 55 | "no_bundle", |
| 47 | 56 | ]; |
| 48 | 57 | |
| @@ -54,15 +63,117 @@ | ||
| 54 | 63 | /// the loader skips it rather than let it shadow the built-in. |
| 55 | 64 | pub const D1_CLASS: &str = "__D1Database"; |
| 56 | 65 | |
| 57 | -/// Whether a cell scope names a D1 database. The unauthenticated operator | |
| 58 | -/// route uses this to refuse one: a D1 cell answers arbitrary SQL, and its | |
| 59 | -/// scope is derivable from the project's config rather than secret. | |
| 60 | -pub fn is_d1_scope(scope: &str) -> bool { | |
| 61 | - scope | |
| 62 | - .strip_prefix(D1_CLASS) | |
| 63 | - .is_some_and(|rest| rest.starts_with(':')) | |
| 66 | +/// The Durable Object class every workflow instance runs as. Like `D1_CLASS`, | |
| 67 | +/// it is supplied by the runtime and refused as a user class name. | |
| 68 | +pub const WORKFLOW_CLASS: &str = "__Workflow"; | |
| 69 | + | |
| 70 | +/// The Durable Object class every KV namespace runs as. | |
| 71 | +/// | |
| 72 | +/// Fleet-wide, like `D1_CLASS` and unlike `workflow_class`: a namespace is a | |
| 73 | +/// resource several Workers bind, so two scripts naming one namespace mean to | |
| 74 | +/// reach one set of cells. | |
| 75 | +pub const KV_CLASS: &str = celld_logic::kv::RESERVED_CLASS; | |
| 76 | + | |
| 77 | +/// The Durable Object class every Queue broker runs as. | |
| 78 | +pub const QUEUE_CLASS: &str = celld_logic::queue::RESERVED_CLASS; | |
| 79 | + | |
| 80 | +/// Every runtime-supplied Durable Object class. | |
| 81 | +pub const RESERVED_CLASSES: &[&str] = &[D1_CLASS, WORKFLOW_CLASS, KV_CLASS, QUEUE_CLASS]; | |
| 82 | + | |
| 83 | +/// The Durable Object class a script's workflow instances run as. | |
| 84 | +/// | |
| 85 | +/// Script-scoped, because a workflow instance already is. Its namespace key is | |
| 86 | +/// `cells:v1:<len>:<script>:__Workflow`, so two co-hosted scripts address | |
| 87 | +/// different cells — but both used to register the *same* class name, and a | |
| 88 | +/// deployment's class registry is one flat map, so the second script collided | |
| 89 | +/// with the first and the node refused to start at all. The name now says what | |
| 90 | +/// the namespace key always said. | |
| 91 | +/// | |
| 92 | +/// D1 deliberately does not get this treatment. Its namespace is fleet-wide so | |
| 93 | +/// that several Workers can bind one database and a Worker rename cannot rename | |
| 94 | +/// it, which means a D1 cell genuinely is shared and one entry is correct. | |
| 95 | +/// | |
| 96 | +/// `.` is the separator for three reasons, and all three are constraints | |
| 97 | +/// rather than taste. A JavaScript class name cannot contain one, so no user | |
| 98 | +/// export can collide. It is not `:`, which is what the cell-scope parser | |
| 99 | +/// splits a class from an id on. And it is inside | |
| 100 | +/// `celld_logic::cell::valid_cell_scope`'s charset, which is a security fence | |
| 101 | +/// on a name that becomes a path component and an object-store key — `@` is | |
| 102 | +/// not, and a scope carrying one is refused before it reaches storage. Cron | |
| 103 | +/// picked `.` for the first of those reasons already. | |
| 104 | +pub fn workflow_class(script_name: &str) -> String { | |
| 105 | + format!("{WORKFLOW_CLASS}.{script_name}") | |
| 64 | 106 | } |
| 65 | 107 | |
| 108 | +/// Whether a reserved class names cells that several scripts share on purpose. | |
| 109 | +/// | |
| 110 | +/// Only D1. Its namespace key is fleet-wide precisely so that a database | |
| 111 | +/// outlives the name of any one Worker that binds it, so two scripts declaring | |
| 112 | +/// `d1_databases` mean to reach the same cells, and one registry entry serving | |
| 113 | +/// both is correct rather than merely tolerated. A workflow class carries its | |
| 114 | +/// script, so it is never shared and a collision there is a real one. | |
| 115 | +pub fn is_shared_reserved_class(class: &str) -> bool { | |
| 116 | + class == D1_CLASS || class == KV_CLASS || class == QUEUE_CLASS | |
| 117 | +} | |
| 118 | + | |
| 119 | +/// Whether a class name is a script-scoped workflow class. | |
| 120 | +/// | |
| 121 | +/// One reading of the shape, because three call sites wanted it and three | |
| 122 | +/// copies of `strip_prefix(WORKFLOW_CLASS)` is how the separator comes to mean | |
| 123 | +/// two things. | |
| 124 | +pub fn is_workflow_class(class: &str) -> bool { | |
| 125 | + class | |
| 126 | + .strip_prefix(WORKFLOW_CLASS) | |
| 127 | + .is_some_and(|rest| rest.starts_with('.')) | |
| 128 | +} | |
| 129 | + | |
| 130 | +pub fn is_reserved_class(class: &str) -> bool { | |
| 131 | + RESERVED_CLASSES.contains(&class) || is_workflow_class(class) | |
| 132 | +} | |
| 133 | + | |
| 134 | +/// The reserved class a cell scope names, or `None` for an ordinary Durable | |
| 135 | +/// Object. | |
| 136 | +/// | |
| 137 | +/// A scope is `<class>:<instance>` and the instance may itself contain a `:`, | |
| 138 | +/// so the class is everything before the first one — the same split | |
| 139 | +/// `Runtime::start_cell` makes when it resolves a cell to its Worker config. | |
| 140 | +pub fn reserved_class_of(scope: &str) -> Option<&str> { | |
| 141 | + let (class, _) = scope.split_once(':')?; | |
| 142 | + is_reserved_class(class).then_some(class) | |
| 143 | +} | |
| 144 | + | |
| 145 | +/// Whether a cell scope names any runtime-supplied class. | |
| 146 | +/// | |
| 147 | +/// This is what the unauthenticated `/do/` route refuses, and it is deliberately | |
| 148 | +/// one question rather than one question per class. `/do/` used to ask | |
| 149 | +/// one predicate per class, so every reserved class added a | |
| 150 | +/// third, a fourth, and a place to forget one — and a forgotten refusal is not | |
| 151 | +/// a missing feature, it is an unauthenticated route onto a cell whose whole | |
| 152 | +/// surface is an operator protocol. Adding a class to `RESERVED_CLASSES` now | |
| 153 | +/// closes that door with no new code. | |
| 154 | +pub fn is_reserved_scope(scope: &str) -> bool { | |
| 155 | + reserved_class_of(scope).is_some() | |
| 156 | +} | |
| 157 | + | |
| 158 | +/// What to tell an operator who reached a reserved class on the wrong route. | |
| 159 | +/// | |
| 160 | +/// A hint, never a gate. The refusal is `is_reserved_scope`, which cannot be | |
| 161 | +/// forgotten; this only decides how helpful the message is, so a class with no | |
| 162 | +/// entry here is still refused and simply gets the general answer. | |
| 163 | +pub fn operator_hint(class: &str) -> &'static str { | |
| 164 | + if class == D1_CLASS { | |
| 165 | + "use `celld d1`" | |
| 166 | + } else if class == KV_CLASS { | |
| 167 | + "use `celld kv`" | |
| 168 | + } else if class == QUEUE_CLASS { | |
| 169 | + "use `celld queue`" | |
| 170 | + } else if is_workflow_class(class) { | |
| 171 | + "use the workflow binding" | |
| 172 | + } else { | |
| 173 | + "reach it through its binding" | |
| 174 | + } | |
| 175 | +} | |
| 176 | + | |
| 66 | 177 | const MAX_ASSET_FILES: usize = 20_000; |
| 67 | 178 | const MAX_ASSET_BYTES: u64 = 1024 * 1024 * 1024; |
| 68 | 179 | const MAX_ASSET_FILE_BYTES: u64 = 25 * 1024 * 1024; |
| @@ -75,24 +186,25 @@ | ||
| 75 | 186 | pub endpoint: Option<String>, |
| 76 | 187 | pub region: Option<String>, |
| 77 | 188 | pub dry_run: bool, |
| 189 | + pub json: bool, | |
| 78 | 190 | } |
| 79 | 191 | |
| 80 | 192 | pub fn print_help() { |
| 81 | - println!( | |
| 82 | - "celld deploy — build a Worker with esbuild and write it to the fleet bucket\n\n\ | |
| 193 | + let text = "celld deploy — build a Worker with esbuild and write it to the fleet bucket\n\n\ | |
| 83 | 194 | USAGE:\n celld deploy [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]\n\n\ |
| 84 | 195 | PROJECT is a directory or a Wrangler config; it defaults to the working\n\ |
| 85 | 196 | directory, where celld looks for wrangler.jsonc or wrangler.json.\n\n\ |
| 86 | -OPTIONS:\n --config PATH Same as passing PROJECT positionally\n --bucket [s3://|gs://|az://]NAME[/PREFIX]\n Fleet bucket and prefix; defaults to CELLD_BUCKET.\n gs:// selects a Google Cloud Storage bucket, az://\n an Azure Blob Storage container with its account in\n AZURE_STORAGE_ACCOUNT_NAME; celld then rejects\n --endpoint and ignores --region\n --endpoint URL S3-compatible endpoint; defaults to S3_ENDPOINT\n --region REGION Storage region; defaults to AWS_REGION\n --dry-run Bundle and print the version without writing\n -h, --help Show this help\n\n\ | |
| 197 | +OPTIONS:\n --config PATH Same as passing PROJECT positionally\n --bucket [s3://|gs://|az://]NAME[/PREFIX]\n Fleet bucket and prefix; defaults to CELLD_BUCKET.\n gs:// selects a Google Cloud Storage bucket, az://\n an Azure Blob Storage container with its account in\n AZURE_STORAGE_ACCOUNT_NAME; celld then rejects\n --endpoint and ignores --region\n --endpoint URL S3-compatible endpoint; defaults to S3_ENDPOINT\n --region REGION Storage region; defaults to AWS_REGION\n --dry-run Bundle and print the version without writing\n --json Print the deployment as one JSON object\n -h, --help Show this help\n\n\ | |
| 87 | 198 | Credentials come from the standard AWS credential chain, from Google\n\ |
| 88 | 199 | Application Default Credentials for a gs:// bucket, or from an Azure storage\n\ |
| 89 | 200 | account key, managed identity, or workload identity for an az:// bucket.\n\n\ |
| 90 | 201 | Worker projects require `esbuild` on PATH; asset-only projects do not. Static\n\ |
| 91 | 202 | assets, service bindings, and string vars are supported. Routes are not; use\n\ |
| 92 | 203 | Wrangler for route configuration.\n\ |
| 93 | -Nodes load a deployment at startup, so an existing node keeps serving the old\n\ | |
| 94 | -version until it restarts." | |
| 95 | - ); | |
| 204 | +A running node polls the deployment pointer and adopts the new version in\n\ | |
| 205 | +place; nothing restarts." | |
| 206 | + ; | |
| 207 | + let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text).help(text); | |
| 96 | 208 | } |
| 97 | 209 | |
| 98 | 210 | pub fn options_from_arguments( |
| @@ -104,12 +216,14 @@ | ||
| 104 | 216 | endpoint: None, |
| 105 | 217 | region: None, |
| 106 | 218 | dry_run: false, |
| 219 | + json: false, | |
| 107 | 220 | }; |
| 108 | 221 | let mut arguments = arguments.into_iter(); |
| 109 | 222 | while let Some(argument) = arguments.next() { |
| 110 | 223 | match argument.as_str() { |
| 111 | 224 | "--help" | "-h" => return Ok(None), |
| 112 | 225 | "--dry-run" => options.dry_run = true, |
| 226 | + "--json" => options.json = true, | |
| 113 | 227 | "--config" => { |
| 114 | 228 | options.config = Some(PathBuf::from( |
| 115 | 229 | arguments.next().context("--config requires a value")?, |
| @@ -151,6 +265,11 @@ | ||
| 151 | 265 | do_classes: Vec<String>, |
| 152 | 266 | sqlite_classes: Vec<String>, |
| 153 | 267 | crons: Vec<String>, |
| 268 | + has_workflows: bool, | |
| 269 | + has_kv: bool, | |
| 270 | + queue_consumers: Vec<QueueConsumerConfig>, | |
| 271 | + has_queues: bool, | |
| 272 | + has_r2: bool, | |
| 154 | 273 | } |
| 155 | 274 | |
| 156 | 275 | struct ProjectAssets { |
| @@ -186,15 +305,15 @@ | ||
| 186 | 305 | /// cannot stand behind: no URL, because celld routes nothing, and no |
| 187 | 306 | /// startup time, because deploying does not start an isolate. |
| 188 | 307 | pub fn report(&self) { |
| 189 | - println!(" celld {}", env!("CARGO_PKG_VERSION")); | |
| 190 | - println!("{}", "─".repeat(47)); | |
| 191 | - println!( | |
| 308 | + note!(" celld {}", env!("CARGO_PKG_VERSION")); | |
| 309 | + note!("{}", "─".repeat(47)); | |
| 310 | + note!( | |
| 192 | 311 | "Total Upload: {} / gzip: {}", |
| 193 | 312 | kib(self.bytes()), |
| 194 | 313 | kib(gzipped(&self.modules)), |
| 195 | 314 | ); |
| 196 | 315 | if let Some(assets) = &self.assets { |
| 197 | - println!( | |
| 316 | + note!( | |
| 198 | 317 | "Static Assets: {} files / {} ({} unique bodies)", |
| 199 | 318 | assets.file_count, |
| 200 | 319 | kib(assets.total_bytes as usize), |
| @@ -203,7 +322,7 @@ | ||
| 203 | 322 | } |
| 204 | 323 | let bindings = self.bindings(); |
| 205 | 324 | if bindings.is_empty() { |
| 206 | - println!("Your Worker has no bindings."); | |
| 325 | + note!("Your Worker has no bindings."); | |
| 207 | 326 | } else { |
| 208 | 327 | let width = bindings |
| 209 | 328 | .iter() |
| @@ -212,13 +331,13 @@ | ||
| 212 | 331 | .max() |
| 213 | 332 | .unwrap_or_default() |
| 214 | 333 | + 6; |
| 215 | - println!("Your Worker has access to the following bindings:"); | |
| 216 | - println!("{:width$}Resource", "Binding"); | |
| 334 | + note!("Your Worker has access to the following bindings:"); | |
| 335 | + note!("{:width$}Resource", "Binding"); | |
| 217 | 336 | for (binding, resource) in bindings { |
| 218 | - println!("{binding:width$}{resource}"); | |
| 337 | + note!("{binding:width$}{resource}"); | |
| 219 | 338 | } |
| 220 | 339 | } |
| 221 | - println!( | |
| 340 | + note!( | |
| 222 | 341 | "Bundled {} ({})", |
| 223 | 342 | self.script_name, |
| 224 | 343 | seconds(self.bundled_in) |
| @@ -267,6 +386,22 @@ | ||
| 267 | 386 | let database = binding.get("database_name").and_then(Value::as_str)?; |
| 268 | 387 | Some((format!("env.{name} (D1)"), database.to_string())) |
| 269 | 388 | } |
| 389 | + Some("workflow") => { | |
| 390 | + let workflow = binding.get("workflow_name").and_then(Value::as_str)?; | |
| 391 | + Some((format!("env.{name} (Workflow)"), workflow.to_string())) | |
| 392 | + } | |
| 393 | + Some("kv") => { | |
| 394 | + let id = binding.get("id").and_then(Value::as_str)?; | |
| 395 | + Some((format!("env.{name} (KV)"), id.to_string())) | |
| 396 | + } | |
| 397 | + Some("queue") => { | |
| 398 | + let queue = binding.get("queue").and_then(Value::as_str)?; | |
| 399 | + Some((format!("env.{name} (Queue)"), queue.to_string())) | |
| 400 | + } | |
| 401 | + Some("r2_bucket") => { | |
| 402 | + let bucket = binding.get("bucket_name").and_then(Value::as_str)?; | |
| 403 | + Some((format!("env.{name} (R2)"), bucket.to_string())) | |
| 404 | + } | |
| 270 | 405 | Some("plain_text") => Some(( |
| 271 | 406 | format!("env.{name} (Text)"), |
| 272 | 407 | "Environment Variable".to_string(), |
| @@ -375,6 +510,7 @@ | ||
| 375 | 510 | .collect(), |
| 376 | 511 | assets: asset_reference, |
| 377 | 512 | crons: project.crons.clone(), |
| 513 | + queue_consumers: project.queue_consumers, | |
| 378 | 514 | // Each capability the manifest depends on is named here, so a node |
| 379 | 515 | // that predates it rejects the deployment up front instead of |
| 380 | 516 | // partially deserializing the manifest and failing at worker load. |
| @@ -389,6 +525,18 @@ | ||
| 389 | 525 | if uses_d1 { |
| 390 | 526 | features.push(FEATURE_D1_V1.to_string()); |
| 391 | 527 | } |
| 528 | + if project.has_workflows { | |
| 529 | + features.push(FEATURE_WORKFLOWS_V1.to_string()); | |
| 530 | + } | |
| 531 | + if project.has_kv { | |
| 532 | + features.push(FEATURE_KV_V1.to_string()); | |
| 533 | + } | |
| 534 | + if project.has_queues { | |
| 535 | + features.push(FEATURE_QUEUES_V1.to_string()); | |
| 536 | + } | |
| 537 | + if project.has_r2 { | |
| 538 | + features.push(FEATURE_R2_V1.to_string()); | |
| 539 | + } | |
| 392 | 540 | if sqlite_vec { |
| 393 | 541 | features.push(FEATURE_SQLITE_VEC_V1.to_string()); |
| 394 | 542 | } |
| @@ -411,6 +559,11 @@ | ||
| 411 | 559 | } |
| 412 | 560 | |
| 413 | 561 | pub async fn write(bucket: &Bucket, built: &Built) -> anyhow::Result<()> { |
| 562 | + // Read every attachment before uploading immutable deployment objects. | |
| 563 | + // A competing consumer is a deploy refusal, so it must not leave a new | |
| 564 | + // version in the bucket that an operator can mistake for a published one. | |
| 565 | + let queue_attachments = prepare_queue_attachments(bucket, &built.manifest).await?; | |
| 566 | + | |
| 414 | 567 | // Asset bodies are fleet-wide and content-addressed. Finish every body |
| 415 | 568 | // before publishing the deployment-local index or manifest so a reader |
| 416 | 569 | // can never observe a pointer whose assets are incomplete. |
| @@ -440,6 +593,13 @@ | ||
| 440 | 593 | serde_json::to_vec_pretty(&built.manifest)?, |
| 441 | 594 | ) |
| 442 | 595 | .await?; |
| 596 | + | |
| 597 | + // An attachment names this exact immutable prefix. Publish it only after | |
| 598 | + // the prefix is complete, so a node can never resolve a consumer to a | |
| 599 | + // half-uploaded deployment. The named and fleet pointers can move later | |
| 600 | + // without tearing this queue-to-consumer relationship. | |
| 601 | + publish_queue_attachments(bucket, &built.manifest, &built.prefix, queue_attachments).await?; | |
| 602 | + | |
| 443 | 603 | let pointer = DeployPointer { |
| 444 | 604 | script_name: Some(built.script_name.clone()), |
| 445 | 605 | version: built.version.clone(), |
| @@ -460,6 +620,152 @@ | ||
| 460 | 620 | Ok(()) |
| 461 | 621 | } |
| 462 | 622 | |
| 623 | +pub(crate) struct QueueAttachmentState { | |
| 624 | + queue: String, | |
| 625 | + key: String, | |
| 626 | + current: Option<QueueConsumerAttachment>, | |
| 627 | + token: Option<String>, | |
| 628 | + desired: bool, | |
| 629 | +} | |
| 630 | + | |
| 631 | +pub(crate) async fn prepare_queue_attachments( | |
| 632 | + bucket: &Bucket, | |
| 633 | + manifest: &Manifest, | |
| 634 | +) -> anyhow::Result<Vec<QueueAttachmentState>> { | |
| 635 | + let desired = manifest | |
| 636 | + .queue_consumers | |
| 637 | + .iter() | |
| 638 | + .map(|consumer| consumer.queue.clone()) | |
| 639 | + .collect::<BTreeSet<_>>(); | |
| 640 | + let previous = current_queue_consumers(bucket, &manifest.script_name).await?; | |
| 641 | + let queues = desired.union(&previous).cloned().collect::<Vec<_>>(); | |
| 642 | + let mut states = Vec::with_capacity(queues.len()); | |
| 643 | + | |
| 644 | + for queue in queues { | |
| 645 | + let key = crate::protocol::queue_consumer_attachment_key(&queue) | |
| 646 | + .expect("deploy validated the queue name"); | |
| 647 | + let (current, token) = match bucket.get(&key).await? { | |
| 648 | + Some((body, token)) => { | |
| 649 | + let attachment: QueueConsumerAttachment = serde_json::from_slice(&body) | |
| 650 | + .with_context(|| format!("decode queue consumer attachment {key}"))?; | |
| 651 | + crate::protocol::validate_queue_consumer_attachment(&queue, &attachment)?; | |
| 652 | + (Some(attachment), Some(token)) | |
| 653 | + } | |
| 654 | + None => (None, None), | |
| 655 | + }; | |
| 656 | + let is_desired = desired.contains(&queue); | |
| 657 | + if is_desired { | |
| 658 | + if let Some(owner) = current | |
| 659 | + .as_ref() | |
| 660 | + .and_then(|attachment| attachment.consumer.as_ref()) | |
| 661 | + .filter(|consumer| consumer.script_name != manifest.script_name) | |
| 662 | + { | |
| 663 | + bail!( | |
| 664 | + "queue {:?} already has consumer script {:?}; remove that consumer before deploying {}", | |
| 665 | + queue, | |
| 666 | + owner.script_name, | |
| 667 | + manifest.script_name | |
| 668 | + ); | |
| 669 | + } | |
| 670 | + } | |
| 671 | + states.push(QueueAttachmentState { | |
| 672 | + queue, | |
| 673 | + key, | |
| 674 | + current, | |
| 675 | + token, | |
| 676 | + desired: is_desired, | |
| 677 | + }); | |
| 678 | + } | |
| 679 | + Ok(states) | |
| 680 | +} | |
| 681 | + | |
| 682 | +async fn current_queue_consumers( | |
| 683 | + bucket: &Bucket, | |
| 684 | + script_name: &str, | |
| 685 | +) -> anyhow::Result<BTreeSet<String>> { | |
| 686 | + let pointer_key = format!("deploy/{script_name}/current.json"); | |
| 687 | + let Some((pointer_body, _)) = bucket.get(&pointer_key).await? else { | |
| 688 | + return Ok(BTreeSet::new()); | |
| 689 | + }; | |
| 690 | + let pointer: DeployPointer = | |
| 691 | + serde_json::from_slice(&pointer_body).with_context(|| format!("decode {pointer_key}"))?; | |
| 692 | + anyhow::ensure!( | |
| 693 | + pointer.script_name.as_deref() == Some(script_name), | |
| 694 | + "named deployment pointer {pointer_key} does not identify script {script_name:?}" | |
| 695 | + ); | |
| 696 | + let manifest_key = format!("{}/manifest.json", pointer.prefix); | |
| 697 | + let (manifest_body, _) = bucket | |
| 698 | + .get(&manifest_key) | |
| 699 | + .await? | |
| 700 | + .with_context(|| format!("read {manifest_key}"))?; | |
| 701 | + let manifest: Manifest = | |
| 702 | + serde_json::from_slice(&manifest_body).with_context(|| format!("decode {manifest_key}"))?; | |
| 703 | + anyhow::ensure!( | |
| 704 | + manifest.script_name == script_name, | |
| 705 | + "named deployment pointer {pointer_key} resolved script {:?}", | |
| 706 | + manifest.script_name | |
| 707 | + ); | |
| 708 | + Ok(manifest | |
| 709 | + .queue_consumers | |
| 710 | + .into_iter() | |
| 711 | + .map(|consumer| consumer.queue) | |
| 712 | + .collect()) | |
| 713 | +} | |
| 714 | + | |
| 715 | +pub(crate) async fn publish_queue_attachments( | |
| 716 | + bucket: &Bucket, | |
| 717 | + manifest: &Manifest, | |
| 718 | + prefix: &str, | |
| 719 | + states: Vec<QueueAttachmentState>, | |
| 720 | +) -> anyhow::Result<()> { | |
| 721 | + let consumer = QueueConsumerDeployment { | |
| 722 | + script_name: manifest.script_name.clone(), | |
| 723 | + version: manifest.version.clone(), | |
| 724 | + prefix: prefix.to_string(), | |
| 725 | + }; | |
| 726 | + for state in states { | |
| 727 | + let next_consumer = if state.desired { | |
| 728 | + Some(consumer.clone()) | |
| 729 | + } else if state | |
| 730 | + .current | |
| 731 | + .as_ref() | |
| 732 | + .and_then(|attachment| attachment.consumer.as_ref()) | |
| 733 | + .is_some_and(|owner| owner.script_name == manifest.script_name) | |
| 734 | + { | |
| 735 | + None | |
| 736 | + } else { | |
| 737 | + continue; | |
| 738 | + }; | |
| 739 | + let next = QueueConsumerAttachment { | |
| 740 | + schema_version: QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION, | |
| 741 | + queue: state.queue, | |
| 742 | + consumer: next_consumer, | |
| 743 | + }; | |
| 744 | + if state.current.as_ref() == Some(&next) { | |
| 745 | + continue; | |
| 746 | + } | |
| 747 | + let body = serde_json::to_vec_pretty(&next)?; | |
| 748 | + match bucket | |
| 749 | + .put_cas(&state.key, body, state.token.as_deref()) | |
| 750 | + .await | |
| 751 | + { | |
| 752 | + Ok(Some(_)) => {} | |
| 753 | + Ok(None) => { | |
| 754 | + bail!( | |
| 755 | + "queue consumer attachment {} lost a race; another deploy may have landed first; re-run `celld deploy`", | |
| 756 | + state.key | |
| 757 | + ) | |
| 758 | + } | |
| 759 | + Err(error) => { | |
| 760 | + return Err(error.context( | |
| 761 | + "a queue consumer attachment write may have committed; re-run `celld deploy`", | |
| 762 | + )); | |
| 763 | + } | |
| 764 | + } | |
| 765 | + } | |
| 766 | + Ok(()) | |
| 767 | +} | |
| 768 | + | |
| 463 | 769 | async fn ensure_asset_blob(bucket: &Bucket, sha256: &str, body: &[u8]) -> anyhow::Result<()> { |
| 464 | 770 | let key = asset_blob_key(sha256).expect("built asset digest is valid"); |
| 465 | 771 | if let Ok(Some((size, meta))) = bucket.head_with_meta(&key, "sha256").await { |
| @@ -622,7 +928,7 @@ | ||
| 622 | 928 | |
| 623 | 929 | /// A path may name the config itself or the directory holding it; with no |
| 624 | 930 | /// path at all, the working directory. |
| 625 | -fn resolve_config(given: Option<PathBuf>) -> anyhow::Result<PathBuf> { | |
| 931 | +pub(crate) fn resolve_config(given: Option<PathBuf>) -> anyhow::Result<PathBuf> { | |
| 626 | 932 | let directory = match given { |
| 627 | 933 | Some(path) if path.is_dir() => path, |
| 628 | 934 | Some(path) if path.exists() => return Ok(path), |
| @@ -718,8 +1024,8 @@ | ||
| 718 | 1024 | } |
| 719 | 1025 | |
| 720 | 1026 | let mut sqlite_classes = read_sqlite_classes(object)?; |
| 721 | - if sqlite_classes.iter().any(|class| class == D1_CLASS) { | |
| 722 | - bail!("`{D1_CLASS}` is reserved for D1; remove it from `migrations`"); | |
| 1027 | + if let Some(class) = sqlite_classes.iter().find(|class| is_reserved_class(class)) { | |
| 1028 | + bail!("`{class}` is a runtime class; remove it from `migrations`"); | |
| 723 | 1029 | } |
| 724 | 1030 | let crons = read_crons(object)?; |
| 725 | 1031 | if !crons.is_empty() && main.is_none() { |
| @@ -798,10 +1104,9 @@ | ||
| 798 | 1104 | // any `d1_databases`: the harness registers its own `__D1Database` class |
| 799 | 1105 | // in every isolate, so a durable_objects binding naming it would silently |
| 800 | 1106 | // resolve to the D1 database cell instead of the user's class. |
| 801 | - if do_classes.iter().any(|class| class == D1_CLASS) { | |
| 802 | - bail!("`{D1_CLASS}` is reserved for D1; rename the Durable Object class"); | |
| 1107 | + if let Some(class) = do_classes.iter().find(|class| is_reserved_class(class)) { | |
| 1108 | + bail!("`{class}` is a runtime class; rename the Durable Object class"); | |
| 803 | 1109 | } |
| 804 | - let mut d1_binding_names = BTreeSet::new(); | |
| 805 | 1110 | for database in d1_databases { |
| 806 | 1111 | let binding = database |
| 807 | 1112 | .get("binding") |
| @@ -810,9 +1115,6 @@ | ||
| 810 | 1115 | if !valid_binding(binding) { |
| 811 | 1116 | bail!("invalid d1 binding name: {binding:?}"); |
| 812 | 1117 | } |
| 813 | - if !d1_binding_names.insert(binding.to_string()) { | |
| 814 | - bail!("duplicate d1 binding name: {binding:?}"); | |
| 815 | - } | |
| 816 | 1118 | let database_name = database |
| 817 | 1119 | .get("database_name") |
| 818 | 1120 | .and_then(Value::as_str) |
| @@ -843,6 +1145,331 @@ | ||
| 843 | 1145 | do_classes.push(D1_CLASS.to_string()); |
| 844 | 1146 | sqlite_classes.push(D1_CLASS.to_string()); |
| 845 | 1147 | } |
| 1148 | + let kv_namespaces = match object.get("kv_namespaces") { | |
| 1149 | + None => &[][..], | |
| 1150 | + Some(Value::Array(namespaces)) => namespaces.as_slice(), | |
| 1151 | + Some(_) => bail!("config `kv_namespaces` must be an array"), | |
| 1152 | + }; | |
| 1153 | + let mut kv_ids = BTreeSet::new(); | |
| 1154 | + for namespace in kv_namespaces { | |
| 1155 | + // Every key celld does not model stops the deploy, per the loud-gap | |
| 1156 | + // rule. `preview_id` is the exception and is accepted below: it selects | |
| 1157 | + // a different namespace under `wrangler dev`, which celld does not run, | |
| 1158 | + // so ignoring it costs a developer nothing at deploy time. | |
| 1159 | + let unsupported = namespace | |
| 1160 | + .as_object() | |
| 1161 | + .map(|object| { | |
| 1162 | + object | |
| 1163 | + .keys() | |
| 1164 | + .filter(|key| !matches!(key.as_str(), "binding" | "id" | "preview_id")) | |
| 1165 | + .cloned() | |
| 1166 | + .collect::<Vec<_>>() | |
| 1167 | + }) | |
| 1168 | + .unwrap_or_default(); | |
| 1169 | + if let Some(key) = unsupported.first() { | |
| 1170 | + bail!( | |
| 1171 | + "kv namespace declares `{key}`, which celld does not model; \ | |
| 1172 | + celld models `binding`, `id`, and `preview_id`" | |
| 1173 | + ); | |
| 1174 | + } | |
| 1175 | + let binding = namespace | |
| 1176 | + .get("binding") | |
| 1177 | + .and_then(Value::as_str) | |
| 1178 | + .ok_or_else(|| anyhow!("kv namespace has no `binding`"))?; | |
| 1179 | + if !valid_binding(binding) { | |
| 1180 | + bail!("invalid kv binding name: {binding:?}"); | |
| 1181 | + } | |
| 1182 | + // `id` is the namespace identity, verbatim, and celld invents no | |
| 1183 | + // `namespace_name` key beside it. Upstream's `kv_namespaces` carries no | |
| 1184 | + // human-readable name at all -- only `binding`, `id` and `preview_id` -- | |
| 1185 | + // and celld's accepted configuration is a strict subset of Wrangler's: | |
| 1186 | + // a key celld accepts and Wrangler diagnoses would make the file | |
| 1187 | + // unportable, which is the one property the deploy story rests on. A | |
| 1188 | + // project ported from Cloudflare therefore keeps its hex id and works; | |
| 1189 | + // a project that was never there writes a readable string. | |
| 1190 | + let id = namespace.get("id").and_then(Value::as_str).ok_or_else(|| { | |
| 1191 | + anyhow!( | |
| 1192 | + "kv binding {binding} has no `id`; celld uses the id as the \ | |
| 1193 | + namespace identity, so any stable string serves" | |
| 1194 | + ) | |
| 1195 | + })?; | |
| 1196 | + if id.is_empty() { | |
| 1197 | + bail!("kv binding {binding} has an empty `id`"); | |
| 1198 | + } | |
| 1199 | + // The id becomes a cell name and therefore a path component and an | |
| 1200 | + // object-store key, so it answers to the same charset fence every cell | |
| 1201 | + // scope does rather than to a looser one invented here. | |
| 1202 | + if !celld_logic::cell::valid_cell_scope(id) { | |
| 1203 | + bail!( | |
| 1204 | + "kv binding {binding} has an `id` that cannot name a cell: {id:?}; \ | |
| 1205 | + use ASCII letters, digits, and `_ - . : $`" | |
| 1206 | + ); | |
| 1207 | + } | |
| 1208 | + if !kv_ids.insert(id.to_string()) { | |
| 1209 | + bail!("duplicate kv namespace id: {id:?}"); | |
| 1210 | + } | |
| 1211 | + bindings.push(json!({ | |
| 1212 | + "type": "kv", | |
| 1213 | + "name": binding, | |
| 1214 | + "id": id, | |
| 1215 | + })); | |
| 1216 | + } | |
| 1217 | + if !kv_namespaces.is_empty() { | |
| 1218 | + // A KV namespace is a cell of a runtime-supplied class, declared here | |
| 1219 | + // so its namespace key is minted and its cells are SQLite-backed. Like | |
| 1220 | + // D1's, it is never a worker export and stays out of `ctx.exports`. | |
| 1221 | + do_classes.push(KV_CLASS.to_string()); | |
| 1222 | + sqlite_classes.push(KV_CLASS.to_string()); | |
| 1223 | + } | |
| 1224 | + let queues = match object.get("queues") { | |
| 1225 | + None => None, | |
| 1226 | + Some(Value::Object(queues)) => Some(queues), | |
| 1227 | + Some(_) => bail!("config `queues` must be an object"), | |
| 1228 | + }; | |
| 1229 | + if let Some(key) = queues | |
| 1230 | + .into_iter() | |
| 1231 | + .flat_map(|queues| queues.keys()) | |
| 1232 | + .find(|key| !matches!(key.as_str(), "producers" | "consumers")) | |
| 1233 | + { | |
| 1234 | + bail!("config `queues` declares `{key}`, which celld does not model"); | |
| 1235 | + } | |
| 1236 | + let queue_producers = match queues.and_then(|queues| queues.get("producers")) { | |
| 1237 | + None => &[][..], | |
| 1238 | + Some(Value::Array(producers)) => producers.as_slice(), | |
| 1239 | + Some(_) => bail!("config `queues.producers` must be an array"), | |
| 1240 | + }; | |
| 1241 | + for producer in queue_producers { | |
| 1242 | + reject_queue_keys( | |
| 1243 | + producer, | |
| 1244 | + &["binding", "queue", "delivery_delay"], | |
| 1245 | + "producer", | |
| 1246 | + )?; | |
| 1247 | + let binding = producer | |
| 1248 | + .get("binding") | |
| 1249 | + .and_then(Value::as_str) | |
| 1250 | + .ok_or_else(|| anyhow!("queue producer has no `binding`"))?; | |
| 1251 | + if !valid_binding(binding) { | |
| 1252 | + bail!("invalid queue binding name: {binding:?}"); | |
| 1253 | + } | |
| 1254 | + let queue = queue_name(producer, "producer")?; | |
| 1255 | + let delivery_delay = optional_queue_u32(producer, "delivery_delay")?.unwrap_or(0); | |
| 1256 | + if delivery_delay > celld_logic::queue::MAX_DELAY_SECONDS { | |
| 1257 | + bail!("queue producer delivery_delay must be between 0 and 86400 seconds"); | |
| 1258 | + } | |
| 1259 | + let mut encoded = json!({ | |
| 1260 | + "type": "queue", | |
| 1261 | + "name": binding, | |
| 1262 | + "queue": queue, | |
| 1263 | + }); | |
| 1264 | + if producer.get("delivery_delay").is_some() { | |
| 1265 | + encoded["delivery_delay"] = json!(delivery_delay); | |
| 1266 | + } | |
| 1267 | + bindings.push(encoded); | |
| 1268 | + } | |
| 1269 | + let queue_consumers_raw = match queues.and_then(|queues| queues.get("consumers")) { | |
| 1270 | + None => &[][..], | |
| 1271 | + Some(Value::Array(consumers)) => consumers.as_slice(), | |
| 1272 | + Some(_) => bail!("config `queues.consumers` must be an array"), | |
| 1273 | + }; | |
| 1274 | + let mut queue_consumers = Vec::new(); | |
| 1275 | + let mut consumed_queues = BTreeSet::new(); | |
| 1276 | + for consumer in queue_consumers_raw { | |
| 1277 | + if consumer.get("script_name").is_some() { | |
| 1278 | + bail!("queue consumer declares `script_name`; celld attaches it to the current script"); | |
| 1279 | + } | |
| 1280 | + reject_queue_keys( | |
| 1281 | + consumer, | |
| 1282 | + &[ | |
| 1283 | + "queue", | |
| 1284 | + "max_batch_size", | |
| 1285 | + "max_batch_timeout", | |
| 1286 | + "max_retries", | |
| 1287 | + "dead_letter_queue", | |
| 1288 | + "max_concurrency", | |
| 1289 | + "retry_delay", | |
| 1290 | + ], | |
| 1291 | + "consumer", | |
| 1292 | + )?; | |
| 1293 | + let queue = queue_name(consumer, "consumer")?.to_string(); | |
| 1294 | + if !consumed_queues.insert(queue.clone()) { | |
| 1295 | + bail!("duplicate queue consumer: {queue:?}"); | |
| 1296 | + } | |
| 1297 | + let dead_letter_queue = consumer | |
| 1298 | + .get("dead_letter_queue") | |
| 1299 | + .map(|value| { | |
| 1300 | + let name = value | |
| 1301 | + .as_str() | |
| 1302 | + .ok_or_else(|| anyhow!("queue consumer dead_letter_queue must be a string"))?; | |
| 1303 | + validate_queue_name(name, "dead-letter queue")?; | |
| 1304 | + anyhow::ensure!( | |
| 1305 | + name != queue, | |
| 1306 | + "a queue cannot use itself as its dead-letter queue" | |
| 1307 | + ); | |
| 1308 | + Ok::<_, anyhow::Error>(name.to_string()) | |
| 1309 | + }) | |
| 1310 | + .transpose()?; | |
| 1311 | + let config = QueueConsumerConfig { | |
| 1312 | + queue, | |
| 1313 | + max_batch_size: optional_queue_u16(consumer, "max_batch_size")? | |
| 1314 | + .unwrap_or(celld_logic::queue::DEFAULT_MAX_BATCH_SIZE), | |
| 1315 | + max_batch_timeout: optional_queue_u16(consumer, "max_batch_timeout")? | |
| 1316 | + .unwrap_or(celld_logic::queue::DEFAULT_MAX_BATCH_TIMEOUT_SECONDS), | |
| 1317 | + max_retries: optional_queue_u16(consumer, "max_retries")? | |
| 1318 | + .unwrap_or(celld_logic::queue::DEFAULT_MAX_RETRIES), | |
| 1319 | + dead_letter_queue, | |
| 1320 | + max_concurrency: optional_queue_u16(consumer, "max_concurrency")?, | |
| 1321 | + retry_delay: optional_queue_u32(consumer, "retry_delay")?, | |
| 1322 | + }; | |
| 1323 | + celld_logic::queue::validate_config(&celld_logic::queue::QueueConfig { | |
| 1324 | + max_batch_size: config.max_batch_size, | |
| 1325 | + max_batch_timeout_seconds: config.max_batch_timeout, | |
| 1326 | + max_retries: config.max_retries, | |
| 1327 | + max_concurrency: config.max_concurrency, | |
| 1328 | + delivery_delay_seconds: 0, | |
| 1329 | + retry_delay_seconds: config.retry_delay, | |
| 1330 | + }) | |
| 1331 | + .map_err(anyhow::Error::new)?; | |
| 1332 | + queue_consumers.push(config); | |
| 1333 | + } | |
| 1334 | + if !queue_producers.is_empty() || !queue_consumers.is_empty() { | |
| 1335 | + if !queue_consumers.is_empty() && main.is_none() { | |
| 1336 | + bail!("config declares a queue consumer without `main`; a consumer needs a Worker module with a queue handler"); | |
| 1337 | + } | |
| 1338 | + do_classes.push(QUEUE_CLASS.to_string()); | |
| 1339 | + sqlite_classes.push(QUEUE_CLASS.to_string()); | |
| 1340 | + } | |
| 1341 | + let workflows = match object.get("workflows") { | |
| 1342 | + None => &[][..], | |
| 1343 | + Some(Value::Array(workflows)) => workflows.as_slice(), | |
| 1344 | + Some(_) => bail!("config `workflows` must be an array"), | |
| 1345 | + }; | |
| 1346 | + let mut workflow_names = BTreeSet::new(); | |
| 1347 | + for workflow in workflows { | |
| 1348 | + // Any key celld does not model stops the deploy, per the loud-gap | |
| 1349 | + // rule: an unread knob (`schedules` is the notable one) must be a | |
| 1350 | + // refusal, never a workflow that silently lacks the behavior it | |
| 1351 | + // declares. | |
| 1352 | + let unsupported = workflow | |
| 1353 | + .as_object() | |
| 1354 | + .map(|object| { | |
| 1355 | + object | |
| 1356 | + .keys() | |
| 1357 | + .filter(|key| { | |
| 1358 | + !matches!( | |
| 1359 | + key.as_str(), | |
| 1360 | + "name" | "binding" | "class_name" | "script_name" | |
| 1361 | + ) | |
| 1362 | + }) | |
| 1363 | + .cloned() | |
| 1364 | + .collect::<Vec<_>>() | |
| 1365 | + }) | |
| 1366 | + .unwrap_or_default(); | |
| 1367 | + if !unsupported.is_empty() { | |
| 1368 | + bail!( | |
| 1369 | + "`celld deploy` does not support these workflow keys: {}.\n\ | |
| 1370 | + celld models `name`, `binding`, `class_name`, and `script_name`; \ | |
| 1371 | + remove the rest (`schedules` included).", | |
| 1372 | + unsupported.join(", ") | |
| 1373 | + ); | |
| 1374 | + } | |
| 1375 | + let binding = workflow | |
| 1376 | + .get("binding") | |
| 1377 | + .and_then(Value::as_str) | |
| 1378 | + .ok_or_else(|| anyhow!("workflow has no `binding`"))?; | |
| 1379 | + if !valid_binding(binding) { | |
| 1380 | + bail!("invalid workflow binding name: {binding:?}"); | |
| 1381 | + } | |
| 1382 | + let workflow_name = workflow | |
| 1383 | + .get("name") | |
| 1384 | + .and_then(Value::as_str) | |
| 1385 | + .ok_or_else(|| anyhow!("workflow binding {binding} has no `name`"))?; | |
| 1386 | + if !valid_resource_name(workflow_name) { | |
| 1387 | + bail!( | |
| 1388 | + "invalid workflow name {workflow_name:?}: use letters, digits, `-` and `_` \ | |
| 1389 | + (not starting with `-`), at most 64 characters" | |
| 1390 | + ); | |
| 1391 | + } | |
| 1392 | + if !workflow_names.insert(workflow_name.to_string()) { | |
| 1393 | + bail!("duplicate workflow name: {workflow_name:?}"); | |
| 1394 | + } | |
| 1395 | + let class_name = workflow | |
| 1396 | + .get("class_name") | |
| 1397 | + .and_then(Value::as_str) | |
| 1398 | + .filter(|class| !class.is_empty()) | |
| 1399 | + .ok_or_else(|| anyhow!("workflow binding {binding} has no `class_name`"))?; | |
| 1400 | + if is_reserved_class(class_name) { | |
| 1401 | + bail!( | |
| 1402 | + "workflow {workflow_name:?} names the reserved class {class_name:?} as its \ | |
| 1403 | + `class_name`; export a WorkflowEntrypoint subclass of your own" | |
| 1404 | + ); | |
| 1405 | + } | |
| 1406 | + if let Some(script) = workflow.get("script_name").and_then(Value::as_str) { | |
| 1407 | + if script != script_name { | |
| 1408 | + bail!( | |
| 1409 | + "workflow {workflow_name:?} sets `script_name` {script:?}; celld runs a \ | |
| 1410 | + workflow only in the script that declares it" | |
| 1411 | + ); | |
| 1412 | + } | |
| 1413 | + } | |
| 1414 | + bindings.push(json!({ | |
| 1415 | + "type": "workflow", | |
| 1416 | + "name": binding, | |
| 1417 | + "workflow_name": workflow_name, | |
| 1418 | + "class_name": class_name, | |
| 1419 | + })); | |
| 1420 | + } | |
| 1421 | + if !workflows.is_empty() { | |
| 1422 | + if main.is_none() { | |
| 1423 | + bail!("config declares `workflows` without `main`; a workflow needs a Worker module to export its class"); | |
| 1424 | + } | |
| 1425 | + do_classes.push(workflow_class(&script_name)); | |
| 1426 | + sqlite_classes.push(workflow_class(&script_name)); | |
| 1427 | + } | |
| 1428 | + let r2_buckets = match object.get("r2_buckets") { | |
| 1429 | + None => &[][..], | |
| 1430 | + Some(Value::Array(buckets)) => buckets.as_slice(), | |
| 1431 | + Some(_) => bail!("config `r2_buckets` must be an array"), | |
| 1432 | + }; | |
| 1433 | + let mut r2_binding_names = BTreeSet::new(); | |
| 1434 | + let mut r2_bucket_names = BTreeSet::new(); | |
| 1435 | + for bucket in r2_buckets { | |
| 1436 | + let binding = bucket | |
| 1437 | + .get("binding") | |
| 1438 | + .and_then(Value::as_str) | |
| 1439 | + .ok_or_else(|| anyhow!("r2 bucket has no `binding`"))?; | |
| 1440 | + if !valid_binding(binding) { | |
| 1441 | + bail!("invalid r2 binding name: {binding:?}"); | |
| 1442 | + } | |
| 1443 | + if !r2_binding_names.insert(binding.to_string()) { | |
| 1444 | + bail!("duplicate r2 binding name: {binding:?}"); | |
| 1445 | + } | |
| 1446 | + let bucket_name = bucket | |
| 1447 | + .get("bucket_name") | |
| 1448 | + .and_then(Value::as_str) | |
| 1449 | + .ok_or_else(|| { | |
| 1450 | + anyhow!("r2 binding {binding} has no `bucket_name`; celld uses the name to place the bucket's keys in the fleet bucket") | |
| 1451 | + })?; | |
| 1452 | + if !valid_resource_name(bucket_name) { | |
| 1453 | + bail!( | |
| 1454 | + "invalid r2 bucket name {bucket_name:?}: use letters, digits, `-` and `_` \ | |
| 1455 | + (not starting with `-`), at most 64 characters" | |
| 1456 | + ); | |
| 1457 | + } | |
| 1458 | + if !r2_bucket_names.insert(bucket_name.to_string()) { | |
| 1459 | + bail!("two r2 bindings name the same bucket: {bucket_name:?}"); | |
| 1460 | + } | |
| 1461 | + // Cloudflare scopes a jurisdiction to an account's R2; celld has | |
| 1462 | + // neither, and silently ignoring it would put the keys somewhere | |
| 1463 | + // the operator did not ask for. | |
| 1464 | + if bucket.get("jurisdiction").is_some() { | |
| 1465 | + bail!("r2 binding {binding} sets `jurisdiction`, which celld does not have"); | |
| 1466 | + } | |
| 1467 | + bindings.push(json!({ | |
| 1468 | + "type": "r2_bucket", | |
| 1469 | + "name": binding, | |
| 1470 | + "bucket_name": bucket_name, | |
| 1471 | + })); | |
| 1472 | + } | |
| 846 | 1473 | let vars = match object.get("vars") { |
| 847 | 1474 | None => None, |
| 848 | 1475 | Some(Value::Object(vars)) => Some(vars), |
| @@ -867,7 +1494,8 @@ | ||
| 867 | 1494 | && (!do_classes.is_empty() |
| 868 | 1495 | || !sqlite_classes.is_empty() |
| 869 | 1496 | || service_count > 0 |
| 870 | - || var_count > 0) | |
| 1497 | + || var_count > 0 | |
| 1498 | + || !r2_binding_names.is_empty()) | |
| 871 | 1499 | { |
| 872 | 1500 | bail!("an asset-only project cannot declare Worker bindings"); |
| 873 | 1501 | } |
| @@ -880,18 +1508,17 @@ | ||
| 880 | 1508 | "name": binding, |
| 881 | 1509 | })); |
| 882 | 1510 | } |
| 883 | - // A name declared as a D1 binding and as anything else would deploy | |
| 884 | - // cleanly and then resolve to whichever `env` assignment ran last, so a | |
| 885 | - // Worker reading `env.DB` could get a service stub where it expected a | |
| 886 | - // database. Collisions between the other binding types are still not | |
| 887 | - // refused here — a known gap, left for a check over every binding type. | |
| 1511 | + // build_env installs every binding into one JavaScript object. Validate | |
| 1512 | + // that structural invariant once here, after every binding source has | |
| 1513 | + // contributed, so a new binding kind cannot silently shadow an old one. | |
| 1514 | + let mut binding_names = BTreeMap::new(); | |
| 888 | 1515 | for binding in &bindings { |
| 889 | 1516 | let name = binding.get("name").and_then(Value::as_str).unwrap_or(""); |
| 890 | 1517 | let kind = binding.get("type").and_then(Value::as_str).unwrap_or(""); |
| 891 | - if kind != "d1" && d1_binding_names.contains(name) { | |
| 1518 | + if let Some(previous) = binding_names.insert(name, kind) { | |
| 892 | 1519 | bail!( |
| 893 | - "binding name {name:?} is declared both in `d1_databases` and as a \ | |
| 894 | - {kind} binding; every binding needs its own name" | |
| 1520 | + "binding name {name:?} is declared by both a {previous} and a {kind} \ | |
| 1521 | + binding; every name in `env` must be unique" | |
| 895 | 1522 | ); |
| 896 | 1523 | } |
| 897 | 1524 | } |
| @@ -909,6 +1536,12 @@ | ||
| 909 | 1536 | metadata.insert("compatibility_flags".into(), flags.clone()); |
| 910 | 1537 | } |
| 911 | 1538 | metadata.insert("bindings".into(), Value::Array(bindings)); |
| 1539 | + if !queue_consumers.is_empty() { | |
| 1540 | + // Include consumer policy in deployment identity. The typed manifest | |
| 1541 | + // field below is the runtime contract; this copy keeps a settings-only | |
| 1542 | + // deploy from reusing the previous code-and-bindings version. | |
| 1543 | + metadata.insert("queue_consumers".into(), json!(queue_consumers)); | |
| 1544 | + } | |
| 912 | 1545 | if !sqlite_classes.is_empty() { |
| 913 | 1546 | metadata.insert( |
| 914 | 1547 | "migrations".into(), |
| @@ -925,9 +1558,87 @@ | ||
| 925 | 1558 | do_classes, |
| 926 | 1559 | sqlite_classes, |
| 927 | 1560 | crons, |
| 1561 | + has_workflows: !workflows.is_empty(), | |
| 1562 | + has_kv: !kv_namespaces.is_empty(), | |
| 1563 | + has_queues: !queue_producers.is_empty() || !queue_consumers.is_empty(), | |
| 1564 | + queue_consumers, | |
| 1565 | + has_r2: !r2_buckets.is_empty(), | |
| 928 | 1566 | }) |
| 929 | 1567 | } |
| 930 | 1568 | |
| 1569 | +fn reject_queue_keys(value: &Value, accepted: &[&str], kind: &str) -> anyhow::Result<()> { | |
| 1570 | + let object = value | |
| 1571 | + .as_object() | |
| 1572 | + .ok_or_else(|| anyhow!("queue {kind} must be an object"))?; | |
| 1573 | + if let Some(key) = object.keys().find(|key| !accepted.contains(&key.as_str())) { | |
| 1574 | + bail!("queue {kind} declares `{key}`, which celld does not model"); | |
| 1575 | + } | |
| 1576 | + Ok(()) | |
| 1577 | +} | |
| 1578 | + | |
| 1579 | +fn queue_name<'a>(value: &'a Value, kind: &str) -> anyhow::Result<&'a str> { | |
| 1580 | + let name = value | |
| 1581 | + .get("queue") | |
| 1582 | + .and_then(Value::as_str) | |
| 1583 | + .ok_or_else(|| anyhow!("queue {kind} has no `queue` name"))?; | |
| 1584 | + validate_queue_name(name, kind)?; | |
| 1585 | + Ok(name) | |
| 1586 | +} | |
| 1587 | + | |
| 1588 | +fn validate_queue_name(name: &str, kind: &str) -> anyhow::Result<()> { | |
| 1589 | + anyhow::ensure!(!name.is_empty(), "queue {kind} has an empty queue name"); | |
| 1590 | + anyhow::ensure!( | |
| 1591 | + celld_logic::cell::valid_cell_scope(name), | |
| 1592 | + "queue {kind} has a name that cannot name a cell: {name:?}; use ASCII letters, digits, and `_ - . : $`" | |
| 1593 | + ); | |
| 1594 | + Ok(()) | |
| 1595 | +} | |
| 1596 | + | |
| 1597 | +fn optional_queue_u64(value: &Value, field: &str) -> anyhow::Result<Option<u64>> { | |
| 1598 | + value | |
| 1599 | + .get(field) | |
| 1600 | + .map(|value| { | |
| 1601 | + value | |
| 1602 | + .as_u64() | |
| 1603 | + .ok_or_else(|| anyhow!("queue {field} must be a non-negative integer")) | |
| 1604 | + }) | |
| 1605 | + .transpose() | |
| 1606 | +} | |
| 1607 | + | |
| 1608 | +fn optional_queue_u16(value: &Value, field: &str) -> anyhow::Result<Option<u16>> { | |
| 1609 | + optional_queue_u64(value, field)? | |
| 1610 | + .map(|value| { | |
| 1611 | + u16::try_from(value).map_err(|_| anyhow!("queue {field} is too large: {value}")) | |
| 1612 | + }) | |
| 1613 | + .transpose() | |
| 1614 | +} | |
| 1615 | + | |
| 1616 | +fn optional_queue_u32(value: &Value, field: &str) -> anyhow::Result<Option<u32>> { | |
| 1617 | + optional_queue_u64(value, field)? | |
| 1618 | + .map(|value| { | |
| 1619 | + u32::try_from(value).map_err(|_| anyhow!("queue {field} is too large: {value}")) | |
| 1620 | + }) | |
| 1621 | + .transpose() | |
| 1622 | +} | |
| 1623 | + | |
| 1624 | +/// The upstream workflow-name rule (`^[a-zA-Z0-9_][a-zA-Z0-9-_]*$`, at most 64 | |
| 1625 | +/// characters). Instance ids follow the same rule; the harness validates those | |
| 1626 | +/// because they arrive at run time, not at deploy. An R2 `bucket_name` takes | |
| 1627 | +/// the same rule for a second reason: the name becomes a key prefix inside the | |
| 1628 | +/// fleet bucket, and this rule is what keeps it a single path segment, so a | |
| 1629 | +/// binding cannot address the fleet's own deployment, cell, or lease keys. | |
| 1630 | +fn valid_resource_name(name: &str) -> bool { | |
| 1631 | + name.len() <= 64 | |
| 1632 | + && name | |
| 1633 | + .chars() | |
| 1634 | + .next() | |
| 1635 | + .is_some_and(|first| first == '_' || first.is_ascii_alphanumeric()) | |
| 1636 | + && name | |
| 1637 | + .chars() | |
| 1638 | + .skip(1) | |
| 1639 | + .all(|value| value == '_' || value == '-' || value.is_ascii_alphanumeric()) | |
| 1640 | +} | |
| 1641 | + | |
| 931 | 1642 | /// `triggers.crons`, validated here so a malformed expression stops the deploy |
| 932 | 1643 | /// the developer is watching instead of an activation an hour later. Wrangler |
| 933 | 1644 | /// accepts `triggers` with other keys we do not model; only `crons` is read. |
addedcrates/celld/dev.rs+621−0View file
| @@ -1,0 +1,621 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! The local application stack behind `celld dev`. | |
| 4 | +//! | |
| 5 | +//! Development still uses the standalone deployment, ownership, and LTX | |
| 6 | +//! paths. This module supplies only the infrastructure those paths require: | |
| 7 | +//! one persisted local object store and one supervised celld node. | |
| 8 | + | |
| 9 | +use crate::bucket::Bucket; | |
| 10 | +use crate::{deploy, fleet}; | |
| 11 | +use anyhow::{bail, Context as _}; | |
| 12 | +use notify::{RecursiveMode, Watcher as _}; | |
| 13 | +use nu_ansi_term::{Color, Style}; | |
| 14 | +use sha2::{Digest as _, Sha256}; | |
| 15 | +use std::io::IsTerminal as _; | |
| 16 | +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; | |
| 17 | +use std::path::{Path, PathBuf}; | |
| 18 | +use std::process::Stdio; | |
| 19 | +use std::time::Duration; | |
| 20 | +use tokio::io::{AsyncBufReadExt as _, BufReader}; | |
| 21 | +use tokio::process::{Child, Command}; | |
| 22 | +use tokio::sync::{mpsc, oneshot}; | |
| 23 | + | |
| 24 | +pub const DEFAULT_PORT: u16 = 9876; | |
| 25 | +const BUCKET: &str = "celld-dev"; | |
| 26 | + | |
| 27 | +/// The narrow bridge used by the supervised binary process. The public fleet | |
| 28 | +/// parser never receives this path, so no regular subcommand can select it. | |
| 29 | +#[doc(hidden)] | |
| 30 | +pub fn open_local_bucket(database: &Path) -> anyhow::Result<Bucket> { | |
| 31 | + Bucket::open_dev(database) | |
| 32 | +} | |
| 33 | + | |
| 34 | +struct Options { | |
| 35 | + project: Option<PathBuf>, | |
| 36 | + listener: SocketAddr, | |
| 37 | + logs: bool, | |
| 38 | +} | |
| 39 | + | |
| 40 | +struct Store { | |
| 41 | + database: PathBuf, | |
| 42 | +} | |
| 43 | + | |
| 44 | +#[derive(Clone, Copy)] | |
| 45 | +struct Console { | |
| 46 | + color: bool, | |
| 47 | +} | |
| 48 | + | |
| 49 | +impl Console { | |
| 50 | + fn new() -> Self { | |
| 51 | + let force = std::env::var_os("FORCE_COLOR").is_some_and(|value| value != "0"); | |
| 52 | + let color = | |
| 53 | + std::env::var_os("NO_COLOR").is_none() && (force || std::io::stdout().is_terminal()); | |
| 54 | + Self { color } | |
| 55 | + } | |
| 56 | + | |
| 57 | + fn paint(&self, style: Style, value: &str) -> String { | |
| 58 | + if self.color { | |
| 59 | + style.paint(value).to_string() | |
| 60 | + } else { | |
| 61 | + value.to_string() | |
| 62 | + } | |
| 63 | + } | |
| 64 | + | |
| 65 | + fn header(&self) { | |
| 66 | + crate::note!("{}", self.paint(Color::Cyan.bold(), "celld dev")); | |
| 67 | + } | |
| 68 | + | |
| 69 | + fn detail(&self, label: &str, value: &str) { | |
| 70 | + crate::note!( | |
| 71 | + " {} {value}", | |
| 72 | + self.paint(Style::new().dimmed(), &format!("{label:<7}")) | |
| 73 | + ); | |
| 74 | + } | |
| 75 | + | |
| 76 | + fn progress(&self, message: &str) { | |
| 77 | + crate::note!(" {} {message}", self.paint(Color::Yellow.normal(), "●")); | |
| 78 | + } | |
| 79 | + | |
| 80 | + fn ready(&self, origin: &str) { | |
| 81 | + crate::note!( | |
| 82 | + " {} {}", | |
| 83 | + self.paint(Color::Green.bold(), "ready"), | |
| 84 | + self.paint(Color::Cyan.bold(), origin) | |
| 85 | + ); | |
| 86 | + } | |
| 87 | + | |
| 88 | + fn log(&self, line: &str) { | |
| 89 | + let style = if line.contains(" ERROR ") { | |
| 90 | + Color::Red.normal() | |
| 91 | + } else if line.contains(" WARN ") { | |
| 92 | + Color::Yellow.normal() | |
| 93 | + } else { | |
| 94 | + Style::new().dimmed() | |
| 95 | + }; | |
| 96 | + crate::note!("{}", self.paint(style, line)); | |
| 97 | + } | |
| 98 | + | |
| 99 | + fn failure(&self, message: &str) { | |
| 100 | + crate::note!(" {} {message}", self.paint(Color::Red.bold(), "error")); | |
| 101 | + } | |
| 102 | +} | |
| 103 | + | |
| 104 | +struct ProjectWatcher { | |
| 105 | + project: PathBuf, | |
| 106 | + _watcher: notify::RecommendedWatcher, | |
| 107 | + changes: mpsc::UnboundedReceiver<notify::Result<notify::Event>>, | |
| 108 | +} | |
| 109 | + | |
| 110 | +impl ProjectWatcher { | |
| 111 | + fn new(project: &Path) -> anyhow::Result<Self> { | |
| 112 | + let (sender, changes) = mpsc::unbounded_channel(); | |
| 113 | + let mut watcher = notify::recommended_watcher(move |event| { | |
| 114 | + let _ = sender.send(event); | |
| 115 | + }) | |
| 116 | + .context("create the project watcher")?; | |
| 117 | + watcher | |
| 118 | + .watch(project, RecursiveMode::Recursive) | |
| 119 | + .with_context(|| format!("watch the project directory {}", project.display()))?; | |
| 120 | + Ok(Self { | |
| 121 | + project: project.to_path_buf(), | |
| 122 | + _watcher: watcher, | |
| 123 | + changes, | |
| 124 | + }) | |
| 125 | + } | |
| 126 | + | |
| 127 | + #[allow(clippy::disallowed_methods)] // Host-side debounce time is outside the Actor domain. | |
| 128 | + async fn changed(&mut self) -> anyhow::Result<()> { | |
| 129 | + self.next_relevant_change().await?; | |
| 130 | + loop { | |
| 131 | + // An editor can replace one save through several writes and a | |
| 132 | + // rename. Wait for one quiet interval so esbuild never reads the | |
| 133 | + // temporary middle of that transaction. | |
| 134 | + match tokio::time::timeout(Duration::from_millis(150), self.next_relevant_change()) | |
| 135 | + .await | |
| 136 | + { | |
| 137 | + Ok(result) => result?, | |
| 138 | + Err(_) => return Ok(()), | |
| 139 | + } | |
| 140 | + } | |
| 141 | + } | |
| 142 | + | |
| 143 | + async fn next_relevant_change(&mut self) -> anyhow::Result<()> { | |
| 144 | + loop { | |
| 145 | + match self | |
| 146 | + .changes | |
| 147 | + .recv() | |
| 148 | + .await | |
| 149 | + .context("the project watcher stopped")? | |
| 150 | + { | |
| 151 | + Ok(event) | |
| 152 | + if event | |
| 153 | + .paths | |
| 154 | + .iter() | |
| 155 | + .any(|path| !ignored_project_path(&self.project, path)) => | |
| 156 | + { | |
| 157 | + return Ok(()) | |
| 158 | + } | |
| 159 | + Ok(_) => {} | |
| 160 | + Err(error) => return Err(error).context("watch the project directory"), | |
| 161 | + } | |
| 162 | + } | |
| 163 | + } | |
| 164 | +} | |
| 165 | + | |
| 166 | +fn ignored_project_path(project: &Path, path: &Path) -> bool { | |
| 167 | + const IGNORED_DIRECTORIES: &[&str] = &[ | |
| 168 | + ".cache", | |
| 169 | + ".celld", | |
| 170 | + ".git", | |
| 171 | + ".hg", | |
| 172 | + ".next", | |
| 173 | + ".nuxt", | |
| 174 | + ".parcel-cache", | |
| 175 | + ".pnpm-store", | |
| 176 | + ".svn", | |
| 177 | + ".turbo", | |
| 178 | + ".yarn", | |
| 179 | + "bower_components", | |
| 180 | + "coverage", | |
| 181 | + "node_modules", | |
| 182 | + "target", | |
| 183 | + ]; | |
| 184 | + path.strip_prefix(project) | |
| 185 | + .unwrap_or(path) | |
| 186 | + .components() | |
| 187 | + .filter_map(|component| match component { | |
| 188 | + std::path::Component::Normal(name) => Some(name), | |
| 189 | + _ => None, | |
| 190 | + }) | |
| 191 | + .any(|name| IGNORED_DIRECTORIES.iter().any(|ignored| name == *ignored)) | |
| 192 | +} | |
| 193 | + | |
| 194 | +struct ShutdownSignals { | |
| 195 | + #[cfg(unix)] | |
| 196 | + interrupt: tokio::signal::unix::Signal, | |
| 197 | + #[cfg(unix)] | |
| 198 | + terminate: tokio::signal::unix::Signal, | |
| 199 | +} | |
| 200 | + | |
| 201 | +impl ShutdownSignals { | |
| 202 | + fn install() -> anyhow::Result<Self> { | |
| 203 | + #[cfg(unix)] | |
| 204 | + { | |
| 205 | + Ok(Self { | |
| 206 | + interrupt: tokio::signal::unix::signal( | |
| 207 | + tokio::signal::unix::SignalKind::interrupt(), | |
| 208 | + )?, | |
| 209 | + terminate: tokio::signal::unix::signal( | |
| 210 | + tokio::signal::unix::SignalKind::terminate(), | |
| 211 | + )?, | |
| 212 | + }) | |
| 213 | + } | |
| 214 | + #[cfg(not(unix))] | |
| 215 | + { | |
| 216 | + Ok(Self {}) | |
| 217 | + } | |
| 218 | + } | |
| 219 | + | |
| 220 | + async fn received(&mut self) { | |
| 221 | + #[cfg(unix)] | |
| 222 | + crate::asyncrt::select! { | |
| 223 | + _ = self.interrupt.recv() => {} | |
| 224 | + _ = self.terminate.recv() => {} | |
| 225 | + } | |
| 226 | + #[cfg(not(unix))] | |
| 227 | + let _ = tokio::signal::ctrl_c().await; | |
| 228 | + } | |
| 229 | +} | |
| 230 | + | |
| 231 | +pub fn print_help() -> anyhow::Result<()> { | |
| 232 | + crate::cli_output::Output::new(crate::cli_output::Format::Text).help( | |
| 233 | + &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\ | |
| 235 | +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" | |
| 238 | + ), | |
| 239 | + ) | |
| 240 | +} | |
| 241 | + | |
| 242 | +fn options_from_arguments(arguments: Vec<String>) -> anyhow::Result<Option<Options>> { | |
| 243 | + let mut project = None; | |
| 244 | + let mut host = IpAddr::V4(Ipv4Addr::LOCALHOST); | |
| 245 | + let mut port = DEFAULT_PORT; | |
| 246 | + let mut logs = false; | |
| 247 | + let mut arguments = arguments.into_iter(); | |
| 248 | + while let Some(argument) = arguments.next() { | |
| 249 | + match argument.as_str() { | |
| 250 | + "--help" | "-h" => return Ok(None), | |
| 251 | + "--logs" => logs = true, | |
| 252 | + "--host" => { | |
| 253 | + let value = arguments.next().context("--host requires a value")?; | |
| 254 | + host = value | |
| 255 | + .parse::<IpAddr>() | |
| 256 | + .with_context(|| format!("invalid --host value {value:?}"))?; | |
| 257 | + } | |
| 258 | + "--port" => { | |
| 259 | + let value = arguments.next().context("--port requires a value")?; | |
| 260 | + port = value | |
| 261 | + .parse::<u16>() | |
| 262 | + .with_context(|| format!("invalid --port value {value:?}"))?; | |
| 263 | + if port == 0 { | |
| 264 | + bail!("--port must be between 1 and 65535"); | |
| 265 | + } | |
| 266 | + } | |
| 267 | + other if other.starts_with('-') => bail!("unknown argument for `celld dev`: {other}"), | |
| 268 | + value if project.is_none() => project = Some(PathBuf::from(value)), | |
| 269 | + value => bail!("celld dev accepts one PROJECT, but also received {value:?}"), | |
| 270 | + } | |
| 271 | + } | |
| 272 | + Ok(Some(Options { | |
| 273 | + project, | |
| 274 | + listener: SocketAddr::new(host, port), | |
| 275 | + logs, | |
| 276 | + })) | |
| 277 | +} | |
| 278 | + | |
| 279 | +#[allow(clippy::disallowed_methods)] // Project resolution uses the operator's host filesystem. | |
| 280 | +pub async fn run(arguments: Vec<String>) -> anyhow::Result<()> { | |
| 281 | + let Some(options) = options_from_arguments(arguments)? else { | |
| 282 | + print_help()?; | |
| 283 | + return Ok(()); | |
| 284 | + }; | |
| 285 | + let config = deploy::resolve_config(options.project)?; | |
| 286 | + let config = std::fs::canonicalize(&config) | |
| 287 | + .with_context(|| format!("resolve Wrangler config {}", config.display()))?; | |
| 288 | + let project = config | |
| 289 | + .parent() | |
| 290 | + .context("the Wrangler config has no project directory")?; | |
| 291 | + let state = project.join(".celld/dev"); | |
| 292 | + prepare_state(&state)?; | |
| 293 | + let console = Console::new(); | |
| 294 | + console.header(); | |
| 295 | + console.detail("Project", &config.display().to_string()); | |
| 296 | + console.detail("State", &state.display().to_string()); | |
| 297 | + if !options.logs { | |
| 298 | + console.detail("Logs", "hidden (use --logs)"); | |
| 299 | + } | |
| 300 | + | |
| 301 | + let project_hash = format!( | |
| 302 | + "{:x}", | |
| 303 | + Sha256::digest(project.as_os_str().as_encoded_bytes()) | |
| 304 | + ); | |
| 305 | + let store = open_store(&state, &console).await?; | |
| 306 | + run_stack( | |
| 307 | + &config, | |
| 308 | + &state, | |
| 309 | + options.listener, | |
| 310 | + options.logs, | |
| 311 | + &project_hash, | |
| 312 | + &store, | |
| 313 | + &console, | |
| 314 | + ) | |
| 315 | + .await | |
| 316 | +} | |
| 317 | + | |
| 318 | +#[allow(clippy::disallowed_methods)] // Local development state is an operator-owned host path. | |
| 319 | +fn prepare_state(state: &Path) -> anyhow::Result<()> { | |
| 320 | + for directory in [state.to_path_buf(), state.join("runtime")] { | |
| 321 | + std::fs::create_dir_all(&directory) | |
| 322 | + .with_context(|| format!("create local state directory {}", directory.display()))?; | |
| 323 | + } | |
| 324 | + Ok(()) | |
| 325 | +} | |
| 326 | + | |
| 327 | +#[allow(clippy::disallowed_methods)] // Local development state is an operator-owned host path. | |
| 328 | +async fn open_store(state: &Path, console: &Console) -> anyhow::Result<Store> { | |
| 329 | + console.progress("opening the local storage"); | |
| 330 | + let database = std::fs::canonicalize(state) | |
| 331 | + .context("resolve the local state directory")? | |
| 332 | + .join("objects.sqlite3"); | |
| 333 | + let bucket = open_local_bucket(&database)?; | |
| 334 | + fleet::validate_bucket(&bucket).await?; | |
| 335 | + bucket.probe_cas().await?; | |
| 336 | + Ok(Store { database }) | |
| 337 | +} | |
| 338 | + | |
| 339 | +async fn deploy_project(config: &Path, store: &Store, logs: bool) -> anyhow::Result<()> { | |
| 340 | + let bucket = open_local_bucket(&store.database)?; | |
| 341 | + let built = deploy::build(&deploy::Options { | |
| 342 | + config: Some(config.to_path_buf()), | |
| 343 | + bucket: None, | |
| 344 | + endpoint: None, | |
| 345 | + region: None, | |
| 346 | + dry_run: false, | |
| 347 | + json: false, | |
| 348 | + })?; | |
| 349 | + if logs { | |
| 350 | + built.report(); | |
| 351 | + } | |
| 352 | + deploy::write(&bucket, &built).await | |
| 353 | +} | |
| 354 | + | |
| 355 | +async fn run_stack( | |
| 356 | + config: &Path, | |
| 357 | + state: &Path, | |
| 358 | + listener: SocketAddr, | |
| 359 | + logs: bool, | |
| 360 | + project_hash: &str, | |
| 361 | + store: &Store, | |
| 362 | + console: &Console, | |
| 363 | +) -> anyhow::Result<()> { | |
| 364 | + // Install both handlers before the child can become ready. A caller can | |
| 365 | + // send SIGTERM as soon as the readiness request answers, and installing a | |
| 366 | + // handler afterwards leaves the new node orphaned under the default Unix | |
| 367 | + // signal action. | |
| 368 | + let mut signals = ShutdownSignals::install()?; | |
| 369 | + let project = config | |
| 370 | + .parent() | |
| 371 | + .context("the Wrangler config has no project directory")?; | |
| 372 | + let mut watcher = ProjectWatcher::new(project)?; | |
| 373 | + | |
| 374 | + 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?; | |
| 377 | + | |
| 378 | + loop { | |
| 379 | + match wait_for_node_event(&mut running.child, &mut signals, &mut watcher).await? { | |
| 380 | + NodeEvent::Exited(status) => { | |
| 381 | + let _ = running.output.await; | |
| 382 | + if status.success() { | |
| 383 | + return Ok(()); | |
| 384 | + } | |
| 385 | + bail!("the local celld node exited with {status}"); | |
| 386 | + } | |
| 387 | + NodeEvent::Shutdown => { | |
| 388 | + stop_running_node(running).await; | |
| 389 | + return Ok(()); | |
| 390 | + } | |
| 391 | + NodeEvent::Reload => { | |
| 392 | + console.progress("change detected; rebuilding the application"); | |
| 393 | + if let Err(error) = deploy_project(config, store, logs).await { | |
| 394 | + console.failure(&format!("reload failed: {error:#}")); | |
| 395 | + continue; | |
| 396 | + } | |
| 397 | + console.progress("restarting the application"); | |
| 398 | + stop_running_node(running).await; | |
| 399 | + running = start_node(state, listener, logs, project_hash, store, console).await?; | |
| 400 | + } | |
| 401 | + } | |
| 402 | + } | |
| 403 | +} | |
| 404 | + | |
| 405 | +struct RunningNode { | |
| 406 | + child: Child, | |
| 407 | + internal: String, | |
| 408 | + output: tokio::task::JoinHandle<()>, | |
| 409 | +} | |
| 410 | + | |
| 411 | +enum NodeEvent { | |
| 412 | + Exited(std::process::ExitStatus), | |
| 413 | + Reload, | |
| 414 | + Shutdown, | |
| 415 | +} | |
| 416 | + | |
| 417 | +#[allow(clippy::disallowed_methods)] // Child supervision uses real host process and time APIs. | |
| 418 | +async fn start_node( | |
| 419 | + state: &Path, | |
| 420 | + listener: SocketAddr, | |
| 421 | + logs: bool, | |
| 422 | + project_hash: &str, | |
| 423 | + store: &Store, | |
| 424 | + console: &Console, | |
| 425 | +) -> anyhow::Result<RunningNode> { | |
| 426 | + let executable = std::env::current_exe().context("locate the celld executable")?; | |
| 427 | + let listen = listener.to_string(); | |
| 428 | + let mut command = Command::new(executable); | |
| 429 | + // The supervisor owns the child's complete storage and listener topology. | |
| 430 | + // Inherited fleet settings can otherwise override that private topology or | |
| 431 | + // make its guard reject a valid `celld dev` invocation. | |
| 432 | + for variable in [ | |
| 433 | + "AWS_DEFAULT_REGION", | |
| 434 | + "AWS_REGION", | |
| 435 | + "CELLD_ADDR", | |
| 436 | + "CELLD_ADVERTISE", | |
| 437 | + "CELLD_BUCKET", | |
| 438 | + "CELLD_CLOUD", | |
| 439 | + "CELLD_INTERNAL_ADDR", | |
| 440 | + "CELLD_STORAGE_PROBE", | |
| 441 | + "CELLD_TEST_BUCKET", | |
| 442 | + "CELLD_TRUST_FORWARDED_HEADERS", | |
| 443 | + "CELLD_UNSAFE_PUBLIC_ADVERTISE", | |
| 444 | + "S3_ENDPOINT", | |
| 445 | + ] { | |
| 446 | + command.env_remove(variable); | |
| 447 | + } | |
| 448 | + command | |
| 449 | + .args([ | |
| 450 | + "--no-control-plane", | |
| 451 | + "--bucket", | |
| 452 | + BUCKET, | |
| 453 | + "--listen", | |
| 454 | + &listen, | |
| 455 | + "--internal-listen", | |
| 456 | + "127.0.0.1:0", | |
| 457 | + ]) | |
| 458 | + .env("CELLD_INTERNAL_DEV_STORE", &store.database) | |
| 459 | + .env("CELLD_WATCH", state.join("runtime")) | |
| 460 | + .env("CELLD_NODE", format!("dev-{}", &project_hash[..12])) | |
| 461 | + .stdin(Stdio::null()) | |
| 462 | + .stdout(Stdio::piped()) | |
| 463 | + .stderr(Stdio::inherit()); | |
| 464 | + if !logs { | |
| 465 | + // The supervisor still forwards ERROR records and the child's stderr. | |
| 466 | + // INFO and WARN records stay hidden until the operator asks for them. | |
| 467 | + command.env("RUST_LOG", "error"); | |
| 468 | + } | |
| 469 | + #[cfg(unix)] | |
| 470 | + { | |
| 471 | + use std::os::unix::process::CommandExt as _; | |
| 472 | + // A terminal sends Ctrl-C to its foreground process group. Keep the | |
| 473 | + // node in a child group so only this supervisor selects the shutdown | |
| 474 | + // mode; otherwise the node can begin a slow fleet handoff before the | |
| 475 | + // supervisor asks for the fast same-node preserve path. | |
| 476 | + command.as_std_mut().process_group(0); | |
| 477 | + } | |
| 478 | + let mut child = command.spawn().context("start the local celld node")?; | |
| 479 | + | |
| 480 | + let stdout = child | |
| 481 | + .stdout | |
| 482 | + .take() | |
| 483 | + .expect("the local node was configured with piped output"); | |
| 484 | + let (internal_tx, internal_rx) = oneshot::channel(); | |
| 485 | + let output_console = *console; | |
| 486 | + let output = tokio::spawn(async move { | |
| 487 | + let mut lines = BufReader::new(stdout).lines(); | |
| 488 | + let mut internal_tx = Some(internal_tx); | |
| 489 | + while let Ok(Some(line)) = lines.next_line().await { | |
| 490 | + if let Some(origin) = internal_origin(&line) { | |
| 491 | + if let Some(sender) = internal_tx.take() { | |
| 492 | + let _ = sender.send(origin); | |
| 493 | + } | |
| 494 | + } | |
| 495 | + if logs || line.contains(" ERROR ") { | |
| 496 | + output_console.log(&line); | |
| 497 | + } | |
| 498 | + } | |
| 499 | + }); | |
| 500 | + let internal = match tokio::time::timeout(Duration::from_secs(30), internal_rx).await { | |
| 501 | + Ok(Ok(internal)) => internal, | |
| 502 | + result => { | |
| 503 | + stop_child(&mut child, None).await; | |
| 504 | + let _ = output.await; | |
| 505 | + match result { | |
| 506 | + Err(_) => bail!("the local node did not announce its operator listener"), | |
| 507 | + Ok(Err(_)) => { | |
| 508 | + bail!("the local node exited before it announced its operator listener") | |
| 509 | + } | |
| 510 | + Ok(Ok(_)) => unreachable!(), | |
| 511 | + } | |
| 512 | + } | |
| 513 | + }; | |
| 514 | + | |
| 515 | + if let Err(error) = wait_for_node(&mut child, listener).await { | |
| 516 | + stop_child(&mut child, Some(&internal)).await; | |
| 517 | + let _ = output.await; | |
| 518 | + return Err(error); | |
| 519 | + } | |
| 520 | + console.ready(&format!("http://{listener}")); | |
| 521 | + Ok(RunningNode { | |
| 522 | + child, | |
| 523 | + internal, | |
| 524 | + output, | |
| 525 | + }) | |
| 526 | +} | |
| 527 | + | |
| 528 | +fn internal_origin(line: &str) -> Option<String> { | |
| 529 | + let address = line | |
| 530 | + .strip_prefix("celld internal listening on ")? | |
| 531 | + .split_once(' ')? | |
| 532 | + .0; | |
| 533 | + Some(format!("http://{address}")) | |
| 534 | +} | |
| 535 | + | |
| 536 | +#[allow(clippy::disallowed_methods)] // Readiness waits on a real child and wall-clock deadline. | |
| 537 | +async fn wait_for_node(child: &mut Child, listener: SocketAddr) -> anyhow::Result<()> { | |
| 538 | + let client = reqwest::Client::builder() | |
| 539 | + .connect_timeout(Duration::from_millis(200)) | |
| 540 | + .timeout(Duration::from_secs(1)) | |
| 541 | + .build()?; | |
| 542 | + let readiness_host = match listener.ip() { | |
| 543 | + IpAddr::V4(address) if address.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST), | |
| 544 | + IpAddr::V6(address) if address.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST), | |
| 545 | + address => address, | |
| 546 | + }; | |
| 547 | + let url = format!( | |
| 548 | + "http://{}/.well-known/celld/health", | |
| 549 | + SocketAddr::new(readiness_host, listener.port()) | |
| 550 | + ); | |
| 551 | + let mut last = "the node did not answer".to_string(); | |
| 552 | + for _ in 0..300 { | |
| 553 | + if let Some(status) = child.try_wait().context("read the local node status")? { | |
| 554 | + bail!("the local celld node exited during startup with {status}"); | |
| 555 | + } | |
| 556 | + match client.get(&url).send().await { | |
| 557 | + Ok(response) if response.status().is_success() => return Ok(()), | |
| 558 | + Ok(response) => last = format!("the readiness endpoint returned {}", response.status()), | |
| 559 | + Err(error) => last = error.to_string(), | |
| 560 | + } | |
| 561 | + tokio::time::sleep(Duration::from_millis(100)).await; | |
| 562 | + } | |
| 563 | + bail!("the local celld node did not become ready: {last}") | |
| 564 | +} | |
| 565 | + | |
| 566 | +async fn wait_for_node_event( | |
| 567 | + child: &mut Child, | |
| 568 | + signals: &mut ShutdownSignals, | |
| 569 | + watcher: &mut ProjectWatcher, | |
| 570 | +) -> anyhow::Result<NodeEvent> { | |
| 571 | + crate::asyncrt::select! { | |
| 572 | + status = child.wait() => { | |
| 573 | + let status = status.context("wait for the local celld node")?; | |
| 574 | + Ok(NodeEvent::Exited(status)) | |
| 575 | + } | |
| 576 | + _ = signals.received() => Ok(NodeEvent::Shutdown), | |
| 577 | + changed = watcher.changed() => { | |
| 578 | + changed?; | |
| 579 | + Ok(NodeEvent::Reload) | |
| 580 | + } | |
| 581 | + } | |
| 582 | +} | |
| 583 | + | |
| 584 | +async fn stop_running_node(mut running: RunningNode) { | |
| 585 | + stop_child(&mut running.child, Some(&running.internal)).await; | |
| 586 | + let _ = running.output.await; | |
| 587 | +} | |
| 588 | + | |
| 589 | +#[allow(clippy::disallowed_methods)] // Shutdown deadlines govern a real child process. | |
| 590 | +async fn stop_child(child: &mut Child, internal: Option<&str>) { | |
| 591 | + let requested = if let Some(internal) = internal { | |
| 592 | + match reqwest::Client::builder() | |
| 593 | + .timeout(Duration::from_secs(2)) | |
| 594 | + .build() | |
| 595 | + { | |
| 596 | + Ok(client) => client | |
| 597 | + .post(format!("{internal}/shutdown?handoff=preserve")) | |
| 598 | + .send() | |
| 599 | + .await | |
| 600 | + .is_ok_and(|response| response.status().is_success()), | |
| 601 | + Err(_) => false, | |
| 602 | + } | |
| 603 | + } else { | |
| 604 | + false | |
| 605 | + }; | |
| 606 | + #[cfg(unix)] | |
| 607 | + if !requested { | |
| 608 | + if let Some(id) = child.id() { | |
| 609 | + // The child installs SIGTERM as its graceful durability handoff. The | |
| 610 | + // supervisor sends that signal instead of Child::kill, which is a | |
| 611 | + // SIGKILL on Unix and can leave the last local transaction unflushed. | |
| 612 | + unsafe { | |
| 613 | + libc::kill(id as libc::pid_t, libc::SIGTERM); | |
| 614 | + } | |
| 615 | + } | |
| 616 | + } | |
| 617 | + let waited = tokio::time::timeout(Duration::from_secs(35), child.wait()).await; | |
| 618 | + if waited.is_err() { | |
| 619 | + let _ = child.kill().await; | |
| 620 | + } | |
| 621 | +} |
addedcrates/celld/drain_token.rs+223−0View file
| @@ -1,0 +1,223 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! The fleet drain token: one bucket object that serializes donors. | |
| 4 | +//! | |
| 5 | +//! `celld_logic::drain` owns the claim and settled decisions; this module | |
| 6 | +//! adds the bucket IO, the bounded acquisition wait, the renewal, and the | |
| 7 | +//! structured events. The token is advisory. A donor that cannot claim it | |
| 8 | +//! within its wait bound proceeds anyway, because the orchestrator grace is | |
| 9 | +//! finite and an unserialized handoff is strictly better than a forced | |
| 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. | |
| 12 | + | |
| 13 | +use crate::bucket::Bucket; | |
| 14 | +use celld_logic::drain::DrainToken; | |
| 15 | +use serde::{Deserialize, Serialize}; | |
| 16 | +use std::time::Duration; | |
| 17 | + | |
| 18 | +/// The well-known token key. It lives outside `nodes/` so lease listings | |
| 19 | +/// and dead-node GC never see it. | |
| 20 | +pub const TOKEN_KEY: &str = "drain/token.json"; | |
| 21 | + | |
| 22 | +/// How long one claim lives without a renewal. The drain loop renews well | |
| 23 | +/// before expiry, so only a dead holder lets the token lapse. | |
| 24 | +pub const TOKEN_TTL_MS: u64 = 120_000; | |
| 25 | + | |
| 26 | +/// Delay between claim attempts while another donor holds the token. | |
| 27 | +const RETRY_DELAY: Duration = Duration::from_millis(1_000); | |
| 28 | + | |
| 29 | +#[derive(Serialize, Deserialize)] | |
| 30 | +struct Wire { | |
| 31 | + #[serde(default)] | |
| 32 | + node: String, | |
| 33 | + #[serde(default)] | |
| 34 | + expires_ms: u64, | |
| 35 | +} | |
| 36 | + | |
| 37 | +/// The token object as read from the bucket. `token: None` with an etag is | |
| 38 | +/// an unparseable body: claimable, and settled for the ready gate. | |
| 39 | +pub struct Current { | |
| 40 | + pub token: Option<DrainToken>, | |
| 41 | + pub etag: String, | |
| 42 | +} | |
| 43 | + | |
| 44 | +/// A held claim. The etag guards renewals and the release, so a claim that | |
| 45 | +/// another donor legitimately took over cannot be clobbered. | |
| 46 | +pub struct Hold { | |
| 47 | + etag: String, | |
| 48 | + expires_ms: u64, | |
| 49 | +} | |
| 50 | + | |
| 51 | +/// The acquisition result carried into the drain loop. | |
| 52 | +pub enum Outcome { | |
| 53 | + /// The claim succeeded; the drain owns the token until release. | |
| 54 | + Acquired(Hold), | |
| 55 | + /// The wait bound expired first; the drain proceeds unserialized. | |
| 56 | + Bypassed, | |
| 57 | + /// No fleet bucket, or the wait bound is configured to zero. | |
| 58 | + Disabled, | |
| 59 | +} | |
| 60 | + | |
| 61 | +/// Read the current token. `Ok(None)` is an absent object; an error is an | |
| 62 | +/// unreadable store, which the claim path treats as absent and the ready | |
| 63 | +/// gate treats as unsettled. | |
| 64 | +pub async fn read(bucket: &Bucket) -> anyhow::Result<Option<Current>> { | |
| 65 | + let Some((bytes, etag)) = bucket.get(TOKEN_KEY).await? else { | |
| 66 | + return Ok(None); | |
| 67 | + }; | |
| 68 | + let token = serde_json::from_slice::<Wire>(&bytes) | |
| 69 | + .ok() | |
| 70 | + .map(|wire| DrainToken { | |
| 71 | + node: wire.node, | |
| 72 | + expires_ms: wire.expires_ms, | |
| 73 | + }); | |
| 74 | + Ok(Some(Current { token, etag })) | |
| 75 | +} | |
| 76 | + | |
| 77 | +/// One claim attempt. `None` means another donor holds a live claim or the | |
| 78 | +/// conditional write lost a race; the caller retries within its bound. An | |
| 79 | +/// ambiguous write also returns `None`: if it committed, the next attempt | |
| 80 | +/// 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> { | |
| 82 | + let current = read(bucket).await.ok().flatten(); | |
| 83 | + if !celld_logic::drain::may_claim( | |
| 84 | + current.as_ref().and_then(|current| current.token.as_ref()), | |
| 85 | + node, | |
| 86 | + now_ms, | |
| 87 | + ) { | |
| 88 | + return None; | |
| 89 | + } | |
| 90 | + let expires_ms = now_ms + TOKEN_TTL_MS; | |
| 91 | + let body = serde_json::to_vec(&Wire { | |
| 92 | + node: node.to_string(), | |
| 93 | + expires_ms, | |
| 94 | + }) | |
| 95 | + .expect("encode drain token"); | |
| 96 | + let guard = current.as_ref().map(|current| current.etag.as_str()); | |
| 97 | + match bucket.put_cas(TOKEN_KEY, body, guard).await { | |
| 98 | + Ok(Some(etag)) => Some(Hold { etag, expires_ms }), | |
| 99 | + Ok(None) | Err(_) => None, | |
| 100 | + } | |
| 101 | +} | |
| 102 | + | |
| 103 | +/// Claim the token, retrying until `wait` elapses. The wait is this | |
| 104 | +/// function's own budget: the caller's drain deadline never covers it. | |
| 105 | +pub async fn acquire(bucket: &Bucket, node: &str, wait: Duration) -> Outcome { | |
| 106 | + let started_mono_ms = crate::asyncrt::mono_ms(); | |
| 107 | + let wait_ms = wait.as_millis() as u64; | |
| 108 | + loop { | |
| 109 | + let now_ms = crate::ownership_store::now_ms(); | |
| 110 | + if let Some(hold) = try_claim(bucket, node, now_ms).await { | |
| 111 | + tracing::info!( | |
| 112 | + event = "drain_token_acquired", | |
| 113 | + waited_ms = crate::asyncrt::mono_ms().saturating_sub(started_mono_ms), | |
| 114 | + expires_ms = hold.expires_ms, | |
| 115 | + "acquired the fleet drain token" | |
| 116 | + ); | |
| 117 | + return Outcome::Acquired(hold); | |
| 118 | + } | |
| 119 | + let waited_ms = crate::asyncrt::mono_ms().saturating_sub(started_mono_ms); | |
| 120 | + if waited_ms >= wait_ms { | |
| 121 | + let holder = read(bucket) | |
| 122 | + .await | |
| 123 | + .ok() | |
| 124 | + .flatten() | |
| 125 | + .and_then(|current| current.token) | |
| 126 | + .map(|token| token.node) | |
| 127 | + .unwrap_or_default(); | |
| 128 | + tracing::warn!( | |
| 129 | + event = "drain_token_bypassed", | |
| 130 | + holder, | |
| 131 | + waited_ms, | |
| 132 | + "the drain token wait expired; handing off unserialized" | |
| 133 | + ); | |
| 134 | + return Outcome::Bypassed; | |
| 135 | + } | |
| 136 | + let remaining = Duration::from_millis(wait_ms.saturating_sub(waited_ms)); | |
| 137 | + crate::asyncrt::sleep(RETRY_DELAY.min(remaining)).await; | |
| 138 | + } | |
| 139 | +} | |
| 140 | + | |
| 141 | +/// Whether a held claim is due for renewal. | |
| 142 | +pub fn renew_due(hold: &Hold, now_ms: u64) -> bool { | |
| 143 | + now_ms + TOKEN_TTL_MS / 2 >= hold.expires_ms | |
| 144 | +} | |
| 145 | + | |
| 146 | +/// Extend a held claim. `false` means another donor took the token over, so | |
| 147 | +/// the caller continues its drain without it. | |
| 148 | +pub async fn renew(bucket: &Bucket, node: &str, hold: &mut Hold) -> bool { | |
| 149 | + let now_ms = crate::ownership_store::now_ms(); | |
| 150 | + let expires_ms = now_ms + TOKEN_TTL_MS; | |
| 151 | + let body = serde_json::to_vec(&Wire { | |
| 152 | + node: node.to_string(), | |
| 153 | + expires_ms, | |
| 154 | + }) | |
| 155 | + .expect("encode drain token"); | |
| 156 | + match bucket.put_cas(TOKEN_KEY, body, Some(&hold.etag)).await { | |
| 157 | + Ok(Some(etag)) => { | |
| 158 | + hold.etag = etag; | |
| 159 | + hold.expires_ms = expires_ms; | |
| 160 | + true | |
| 161 | + } | |
| 162 | + Ok(None) => { | |
| 163 | + tracing::warn!( | |
| 164 | + event = "drain_token_renew_lost", | |
| 165 | + "another donor took the drain token over; continuing unserialized" | |
| 166 | + ); | |
| 167 | + false | |
| 168 | + } | |
| 169 | + // Ambiguous: the write may have committed. Read the object back; a | |
| 170 | + // record naming this node adopts the new etag, anything else is a | |
| 171 | + // lost claim. | |
| 172 | + Err(_) => match read(bucket).await.ok().flatten() { | |
| 173 | + Some(current) | |
| 174 | + if current | |
| 175 | + .token | |
| 176 | + .as_ref() | |
| 177 | + .is_some_and(|token| token.node == node) => | |
| 178 | + { | |
| 179 | + hold.expires_ms = current | |
| 180 | + .token | |
| 181 | + .as_ref() | |
| 182 | + .map(|token| token.expires_ms) | |
| 183 | + .unwrap_or(expires_ms); | |
| 184 | + hold.etag = current.etag; | |
| 185 | + true | |
| 186 | + } | |
| 187 | + _ => { | |
| 188 | + tracing::warn!( | |
| 189 | + event = "drain_token_renew_lost", | |
| 190 | + "the drain token renewal was lost; continuing unserialized" | |
| 191 | + ); | |
| 192 | + false | |
| 193 | + } | |
| 194 | + }, | |
| 195 | + } | |
| 196 | +} | |
| 197 | + | |
| 198 | +/// Release a held claim by writing an expired record under the etag guard. | |
| 199 | +/// An unconditional delete could erase a successor's live claim; a rejected | |
| 200 | +/// release means exactly that and needs nothing further. An ambiguous | |
| 201 | +/// release is bounded by the TTL. | |
| 202 | +pub async fn release(bucket: &Bucket, node: &str, hold: Hold) { | |
| 203 | + let body = serde_json::to_vec(&Wire { | |
| 204 | + node: node.to_string(), | |
| 205 | + expires_ms: 0, | |
| 206 | + }) | |
| 207 | + .expect("encode drain token"); | |
| 208 | + match bucket.put_cas(TOKEN_KEY, body, Some(&hold.etag)).await { | |
| 209 | + Ok(Some(_)) => tracing::info!( | |
| 210 | + event = "drain_token_released", | |
| 211 | + "released the fleet drain token" | |
| 212 | + ), | |
| 213 | + Ok(None) => tracing::debug!( | |
| 214 | + event = "drain_token_release_superseded", | |
| 215 | + "the drain token already has a new holder" | |
| 216 | + ), | |
| 217 | + Err(error) => tracing::warn!( | |
| 218 | + event = "drain_token_release_ambiguous", | |
| 219 | + %error, | |
| 220 | + "the drain token release did not confirm; the TTL bounds the residue" | |
| 221 | + ), | |
| 222 | + } | |
| 223 | +} |
modifiedcrates/celld/env_vars.rs+20−0View file
| @@ -28,19 +28,26 @@ | ||
| 28 | 28 | |
| 29 | 29 | for name in [ |
| 30 | 30 | "CELLD_ACTIVATIONS", |
| 31 | + "CELLD_DEPLOY_POLL_S", | |
| 31 | 32 | "CELLD_EVICTIONS", |
| 32 | 33 | "CELLD_FETCH_TIMEOUT_S", |
| 33 | 34 | "CELLD_HANDLER_BUDGET_S", |
| 34 | 35 | "CELLD_IDLE_EVICT_S", |
| 36 | + "CELLD_LOG_CAPTURE_WORKERS", | |
| 37 | + "CELLD_LOG_PIPELINE", | |
| 35 | 38 | "CELLD_LTX_COMPACTIONS", |
| 36 | 39 | "CELLD_LTX_COMPACTION_MIN_TXIDS", |
| 40 | + "CELLD_LTX_DURABILITY_TIMEOUT_SECS", | |
| 37 | 41 | "CELLD_MAX_LOADED_WORKERS", |
| 42 | + "CELLD_MAX_CELL_REQUESTS", | |
| 38 | 43 | "CELLD_MAX_OUTBOUND_WEBSOCKETS", |
| 44 | + "CELLD_MAX_REQUEST_BODY_BYTES", | |
| 39 | 45 | "CELLD_MAX_REQUESTS", |
| 40 | 46 | "CELLD_MAX_STATELESS_ISOLATES", |
| 41 | 47 | "CELLD_OPERATION_DEADLINE_MS", |
| 42 | 48 | "CELLD_RELEASES", |
| 43 | 49 | "CELLD_SHUTDOWN_DRAIN_MS", |
| 50 | + "CELLD_SHUTDOWN_TOTAL_MS", | |
| 44 | 51 | "CELLD_TOKIO_THREADS", |
| 45 | 52 | "CELLD_TTL_MS", |
| 46 | 53 | "CELLD_WAKER_TICK_MS", |
| @@ -52,9 +59,16 @@ | ||
| 52 | 59 | "CELLD_ADMISSION_WAIT_MS", |
| 53 | 60 | "CELLD_ALARM_RESIDENT_MS", |
| 54 | 61 | "CELLD_ASSET_CACHE_BYTES", |
| 62 | + "CELLD_DEPLOY_MAX_AGE_S", | |
| 63 | + "CELLD_DRAIN_TOKEN_WAIT_MS", | |
| 55 | 64 | "CELLD_LOCAL_CACHE_MAX_BYTES", |
| 65 | + "CELLD_LTX_TRUNCATE_PAGES", | |
| 66 | + "CELLD_LOG_HEDGE_MS", | |
| 67 | + "CELLD_LOG_WINDOW", | |
| 68 | + "CELLD_LOG_WINDOW_BYTES", | |
| 56 | 69 | "CELLD_MAX_RESIDENT_CELLS", |
| 57 | 70 | "CELLD_MAX_RSS_MB", |
| 71 | + "CELLD_READY_FLEET_GATE_MS", | |
| 58 | 72 | ] { |
| 59 | 73 | optional::<u64>(name)?; |
| 60 | 74 | } |
| @@ -71,6 +85,12 @@ | ||
| 71 | 85 | } |
| 72 | 86 | } |
| 73 | 87 | |
| 88 | + if let Some(value) = value("CELLD_LOG_TRANSPORT")? { | |
| 89 | + if !matches!(value.as_str(), "http" | "stream") { | |
| 90 | + bail!("CELLD_LOG_TRANSPORT must be http or stream, not {value:?}"); | |
| 91 | + } | |
| 92 | + } | |
| 93 | + | |
| 74 | 94 | if let Some(value) = value("CELLD_PRESSURE_OWNERSHIP")? { |
| 75 | 95 | if !matches!(value.as_str(), "release" | "sticky") { |
| 76 | 96 | bail!("CELLD_PRESSURE_OWNERSHIP must be release or sticky, not {value:?}"); |
modifiedcrates/celld/fleet.rs+381−80View file
| @@ -1,7 +1,10 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -// Fleet CLI and peer-diagnostic work is outside the Actor-backed World. | |
| 3 | +// Fleet CLI and peer-diagnostic work executes outside the Actor execution | |
| 4 | +// domain. | |
| 4 | 5 | #![allow(clippy::disallowed_methods)] |
| 6 | +// Diagnose used to split by verdict rather than by kind, so a redirect kept | |
| 7 | +// the passes and lost the failures. Every check now goes through `Output`. | |
| 5 | 8 | |
| 6 | 9 | //! Production bucket deployment adapters reused by the clean-sheet host. |
| 7 | 10 | |
| @@ -9,8 +12,101 @@ | ||
| 9 | 12 | use crate::deploy; |
| 10 | 13 | use crate::js::{ModuleSource, WorkerConfigOptions}; |
| 11 | 14 | use crate::ownership_store::NodeLeaseWire; |
| 12 | -use crate::protocol::{DeployPointer, Manifest, ModuleKind}; | |
| 15 | +use crate::protocol::{DeployPointer, Manifest, ModuleKind, Rollout}; | |
| 13 | 16 | use anyhow::{bail, Context}; |
| 17 | +use std::borrow::Cow; | |
| 18 | + | |
| 19 | +use crate::cli_output::Format; | |
| 20 | +use crate::cli_output::Output; | |
| 21 | +use crate::cli_output::Record; | |
| 22 | +use crate::note; | |
| 23 | + | |
| 24 | +/// What a deployment produced. | |
| 25 | +/// | |
| 26 | +/// Deploy is a narrative, so its progress belongs on stderr — but the | |
| 27 | +/// version is the datum a release script reads back, so it stays a row on | |
| 28 | +/// stdout rather than a line to grep out of the prose. | |
| 29 | +pub(crate) struct Deployed { | |
| 30 | + worker: String, | |
| 31 | + version: String, | |
| 32 | + location: String, | |
| 33 | + dry_run: bool, | |
| 34 | +} | |
| 35 | + | |
| 36 | +impl Record for Deployed { | |
| 37 | + fn json(&self) -> serde_json::Value { | |
| 38 | + serde_json::json!({ | |
| 39 | + "worker": self.worker, | |
| 40 | + "version": self.version, | |
| 41 | + "location": self.location, | |
| 42 | + "dry_run": self.dry_run, | |
| 43 | + }) | |
| 44 | + } | |
| 45 | + | |
| 46 | + fn text(&self) -> Cow<'_, str> { | |
| 47 | + Cow::Owned(if self.dry_run { | |
| 48 | + format!( | |
| 49 | + "Current Version ID: {} (dry run; nothing written)", | |
| 50 | + self.version | |
| 51 | + ) | |
| 52 | + } else { | |
| 53 | + format!("Current Version ID: {}", self.version) | |
| 54 | + }) | |
| 55 | + } | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// One diagnostic verdict. | |
| 59 | +/// | |
| 60 | +/// Every check is a row, whatever its verdict. The old shape sent `ok` and | |
| 61 | +/// `skip` to stdout and `fail` to stderr, so `celld diagnose > report.txt` | |
| 62 | +/// saved the passes and lost the failures. The exit code still carries the | |
| 63 | +/// summary, so a redirect and `$?` together say everything. | |
| 64 | +pub struct Check { | |
| 65 | + verdict: &'static str, | |
| 66 | + subject: String, | |
| 67 | + detail: String, | |
| 68 | +} | |
| 69 | + | |
| 70 | +impl Check { | |
| 71 | + fn new(verdict: &'static str, subject: impl Into<String>, detail: impl Into<String>) -> Self { | |
| 72 | + Self { | |
| 73 | + verdict, | |
| 74 | + subject: subject.into(), | |
| 75 | + detail: detail.into(), | |
| 76 | + } | |
| 77 | + } | |
| 78 | + | |
| 79 | + pub fn ok(subject: impl Into<String>, detail: impl Into<String>) -> Self { | |
| 80 | + Self::new("ok", subject, detail) | |
| 81 | + } | |
| 82 | + | |
| 83 | + pub fn fail(subject: impl Into<String>, detail: impl Into<String>) -> Self { | |
| 84 | + Self::new("fail", subject, detail) | |
| 85 | + } | |
| 86 | + | |
| 87 | + pub fn skip(subject: impl Into<String>, detail: impl Into<String>) -> Self { | |
| 88 | + Self::new("skip", subject, detail) | |
| 89 | + } | |
| 90 | +} | |
| 91 | + | |
| 92 | +impl Record for Check { | |
| 93 | + fn json(&self) -> serde_json::Value { | |
| 94 | + serde_json::json!({ | |
| 95 | + "verdict": self.verdict, | |
| 96 | + "check": self.subject, | |
| 97 | + "detail": self.detail, | |
| 98 | + }) | |
| 99 | + } | |
| 100 | + | |
| 101 | + fn text(&self) -> Cow<'_, str> { | |
| 102 | + // The long-standing shape: `ok bucket ...`, `fail peer X: ...`. | |
| 103 | + Cow::Owned(if self.detail.is_empty() { | |
| 104 | + format!("{} {}", self.verdict, self.subject) | |
| 105 | + } else { | |
| 106 | + format!("{} {}: {}", self.verdict, self.subject, self.detail) | |
| 107 | + }) | |
| 108 | + } | |
| 109 | +} | |
| 14 | 110 | use std::collections::BTreeMap; |
| 15 | 111 | use std::time::Duration; |
| 16 | 112 | use tracing::info; |
| @@ -138,26 +234,28 @@ | ||
| 138 | 234 | /// |
| 139 | 235 | /// The probe writes and deletes one small object, which a read-only |
| 140 | 236 | /// credential cannot do; `--read-only` skips it for that operator. |
| 141 | -async fn probe_storage(bucket: &Bucket, read_only: bool) -> anyhow::Result<()> { | |
| 237 | +async fn probe_storage(out: &mut Output, bucket: &Bucket, read_only: bool) -> anyhow::Result<()> { | |
| 142 | 238 | if read_only { |
| 143 | - println!("skip bucket write probe (--read-only)"); | |
| 239 | + out.row(&Check::skip("bucket write probe", "--read-only"))?; | |
| 144 | 240 | return Ok(()); |
| 145 | 241 | } |
| 146 | 242 | match bucket.probe_cas().await { |
| 147 | 243 | Ok(()) => { |
| 148 | - println!("ok bucket conditional write (create, reject-create, update, reject-stale)"); | |
| 244 | + out.row(&Check::ok( | |
| 245 | + "bucket conditional write", | |
| 246 | + "create, reject-create, update, reject-stale", | |
| 247 | + ))?; | |
| 149 | 248 | Ok(()) |
| 150 | 249 | } |
| 151 | 250 | Err(error) => { |
| 152 | - if crate::bucket::is_unauthorized(&error) { | |
| 153 | - eprintln!( | |
| 154 | - "fail bucket conditional write: the credential cannot write to the bucket, \ | |
| 155 | - and a celld node requires write access; pass --read-only to diagnose with a \ | |
| 156 | - read-only credential" | |
| 157 | - ); | |
| 251 | + let detail = if crate::bucket::is_unauthorized(&error) { | |
| 252 | + "the credential cannot write to the bucket, and a celld node requires write \ | |
| 253 | + access; pass --read-only to diagnose with a read-only credential" | |
| 254 | + .to_string() | |
| 158 | 255 | } else { |
| 159 | - eprintln!("fail bucket conditional write: {error:#}"); | |
| 160 | - } | |
| 256 | + format!("{error:#}") | |
| 257 | + }; | |
| 258 | + out.row(&Check::fail("bucket conditional write", detail))?; | |
| 161 | 259 | bail!("bucket failed the storage conformance probe") |
| 162 | 260 | } |
| 163 | 261 | } |
| @@ -210,17 +308,48 @@ | ||
| 210 | 308 | peers: Vec<String>, |
| 211 | 309 | unsafe_public_advertise: bool, |
| 212 | 310 | read_only: bool, |
| 311 | + json: bool, | |
| 312 | + // Checks the caller already made, printed through this command's one | |
| 313 | + // `Output`. The listener binds happen before a bucket is even opened, | |
| 314 | + // and printing them from there put three text lines in front of the | |
| 315 | + // JSON, which broke `celld diagnose --json | jq` at its first line. | |
| 316 | + preamble: Vec<Check>, | |
| 213 | 317 | ) -> anyhow::Result<()> { |
| 318 | + let mut out = Output::new(if json { Format::Json } else { Format::Text }); | |
| 319 | + for check in &preamble { | |
| 320 | + out.row(check)?; | |
| 321 | + } | |
| 322 | + // Every verdict is flushed before the exit status is decided, so a | |
| 323 | + // failing diagnosis still leaves the operator the checks that passed. | |
| 324 | + let verdict = | |
| 325 | + diagnose_checks(&mut out, bucket, peers, unsafe_public_advertise, read_only).await; | |
| 326 | + out.finish()?; | |
| 327 | + verdict | |
| 328 | +} | |
| 329 | + | |
| 330 | +async fn diagnose_checks( | |
| 331 | + out: &mut Output, | |
| 332 | + bucket: &Bucket, | |
| 333 | + peers: Vec<String>, | |
| 334 | + unsafe_public_advertise: bool, | |
| 335 | + read_only: bool, | |
| 336 | +) -> anyhow::Result<()> { | |
| 214 | 337 | validate_bucket(bucket).await?; |
| 215 | - println!("ok bucket {}://{}", bucket.scheme(), bucket.name); | |
| 338 | + out.row(&Check::ok( | |
| 339 | + format!("bucket {}://{}", bucket.scheme(), bucket.name), | |
| 340 | + "", | |
| 341 | + ))?; | |
| 216 | 342 | // A store that cannot fence makes every peer result moot, so the |
| 217 | 343 | // storage verdict comes before the fleet walk. |
| 218 | - probe_storage(bucket, read_only).await?; | |
| 344 | + probe_storage(out, bucket, read_only).await?; | |
| 219 | 345 | |
| 220 | 346 | let enumerated = peers.is_empty(); |
| 221 | 347 | let peers = if enumerated { |
| 222 | 348 | let peers = node_lease_ids(bucket).await?; |
| 223 | - println!("ok fleet {} node lease(s) enumerated", peers.len()); | |
| 349 | + out.row(&Check::ok( | |
| 350 | + "fleet", | |
| 351 | + format!("{} node lease(s) enumerated", peers.len()), | |
| 352 | + ))?; | |
| 224 | 353 | peers |
| 225 | 354 | } else { |
| 226 | 355 | peers |
| @@ -245,17 +374,20 @@ | ||
| 245 | 374 | Ok(Some(node)) => node, |
| 246 | 375 | Ok(None) if enumerated => { |
| 247 | 376 | expired += 1; |
| 248 | - println!("skip peer {peer}: lease is expired"); | |
| 377 | + out.row(&Check::skip(format!("peer {peer}"), "lease is expired"))?; | |
| 249 | 378 | continue; |
| 250 | 379 | } |
| 251 | 380 | Ok(None) => { |
| 252 | 381 | failures += 1; |
| 253 | - eprintln!("fail peer {peer}: node {peer} lease is expired"); | |
| 382 | + out.row(&Check::fail( | |
| 383 | + format!("peer {peer}"), | |
| 384 | + format!("node {peer} lease is expired"), | |
| 385 | + ))?; | |
| 254 | 386 | continue; |
| 255 | 387 | } |
| 256 | 388 | Err(error) => { |
| 257 | 389 | failures += 1; |
| 258 | - eprintln!("fail peer {peer}: {error}"); | |
| 390 | + out.row(&Check::fail(format!("peer {peer}"), format!("{error}")))?; | |
| 259 | 391 | continue; |
| 260 | 392 | } |
| 261 | 393 | }; |
| @@ -263,24 +395,31 @@ | ||
| 263 | 395 | Ok(advertise) => advertise, |
| 264 | 396 | Err(error) => { |
| 265 | 397 | failures += 1; |
| 266 | - eprintln!( | |
| 267 | - "fail peer {peer}: malformed advertise address {:?}: {error}", | |
| 268 | - node.addr | |
| 269 | - ); | |
| 398 | + out.row(&Check::fail( | |
| 399 | + format!("peer {peer}"), | |
| 400 | + format!("malformed advertise address {:?}: {error}", node.addr), | |
| 401 | + ))?; | |
| 270 | 402 | continue; |
| 271 | 403 | } |
| 272 | 404 | }; |
| 273 | 405 | if advertise.is_public_ip() && !unsafe_public_advertise { |
| 274 | 406 | failures += 1; |
| 275 | - eprintln!( | |
| 276 | - "fail peer {peer}: unsafe public advertise address {}; use a private overlay or --unsafe-public-advertise", | |
| 277 | - node.addr | |
| 278 | - ); | |
| 407 | + out.row(&Check::fail( | |
| 408 | + format!("peer {peer}"), | |
| 409 | + format!( | |
| 410 | + "unsafe public advertise address {}; use a private overlay or \ | |
| 411 | + --unsafe-public-advertise", | |
| 412 | + node.addr | |
| 413 | + ), | |
| 414 | + ))?; | |
| 279 | 415 | continue; |
| 280 | 416 | } |
| 281 | 417 | if let Err(error) = crate::peer_probe::probe(&http, &node, &auth).await { |
| 282 | 418 | failures += 1; |
| 283 | - eprintln!("fail peer {peer} at {}: {error}", node.addr); | |
| 419 | + out.row(&Check::fail( | |
| 420 | + format!("peer {peer} at {}", node.addr), | |
| 421 | + format!("{error}"), | |
| 422 | + ))?; | |
| 284 | 423 | continue; |
| 285 | 424 | } |
| 286 | 425 | let load_age_ms = if node.load.sampled_ms == 0 { |
| @@ -306,28 +445,32 @@ | ||
| 306 | 445 | .load |
| 307 | 446 | .in_use_bytes |
| 308 | 447 | .map_or_else(|| "unknown".to_string(), |bytes| bytes.to_string()); |
| 309 | - println!( | |
| 310 | - "ok peer {} at {} (signed direct probe) protocol={} resident_cells={} \ | |
| 311 | - websockets={} rss_bytes={} in_use_bytes={} cpu_percent={:.2} fds={}/{} \ | |
| 312 | - pressured={} shed_cells={} restoring={} load_age_ms={}", | |
| 313 | - node.node, | |
| 314 | - node.addr, | |
| 315 | - node.peer_protocol, | |
| 316 | - node.load.resident_cells, | |
| 317 | - node.load.host_websockets, | |
| 318 | - rss_bytes, | |
| 319 | - in_use_bytes, | |
| 320 | - node.load.cpu_percent_x100 as f64 / 100.0, | |
| 321 | - node.load.open_fds, | |
| 322 | - node.load.fd_limit, | |
| 323 | - node.load.pressured, | |
| 324 | - node.load.shed_cells, | |
| 325 | - node.load.restoring, | |
| 326 | - load_age_ms, | |
| 327 | - ); | |
| 448 | + out.row(&Check::ok( | |
| 449 | + format!("peer {} at {}", node.node, node.addr), | |
| 450 | + format!( | |
| 451 | + "(signed direct probe) protocol={} resident_cells={} \ | |
| 452 | + websockets={} rss_bytes={} in_use_bytes={} cpu_percent={:.2} fds={}/{} \ | |
| 453 | + pressured={} shed_cells={} restoring={} load_age_ms={}", | |
| 454 | + node.peer_protocol, | |
| 455 | + node.load.resident_cells, | |
| 456 | + node.load.host_websockets, | |
| 457 | + rss_bytes, | |
| 458 | + in_use_bytes, | |
| 459 | + node.load.cpu_percent_x100 as f64 / 100.0, | |
| 460 | + node.load.open_fds, | |
| 461 | + node.load.fd_limit, | |
| 462 | + node.load.pressured, | |
| 463 | + node.load.shed_cells, | |
| 464 | + node.load.restoring, | |
| 465 | + load_age_ms, | |
| 466 | + ), | |
| 467 | + ))?; | |
| 328 | 468 | } |
| 329 | 469 | if expired > 0 { |
| 330 | - println!("ok fleet skipped {expired} expired node lease(s)"); | |
| 470 | + out.row(&Check::ok( | |
| 471 | + "fleet", | |
| 472 | + format!("skipped {expired} expired node lease(s)"), | |
| 473 | + ))?; | |
| 331 | 474 | } |
| 332 | 475 | if failures > 0 { |
| 333 | 476 | bail!("fleet diagnostics failed for {failures} peer(s)"); |
| @@ -381,23 +524,39 @@ | ||
| 381 | 524 | Ok(nodes) |
| 382 | 525 | } |
| 383 | 526 | |
| 384 | -pub async fn run_deploy(arguments: Vec<String>) -> anyhow::Result<()> { | |
| 385 | - let Some(mut options) = deploy::options_from_arguments(arguments)? else { | |
| 386 | - deploy::print_help(); | |
| 387 | - return Ok(()); | |
| 388 | - }; | |
| 527 | +pub(crate) fn resolve_storage_location( | |
| 528 | + bucket: &mut Option<String>, | |
| 529 | + endpoint: &mut Option<String>, | |
| 530 | + region: Option<&str>, | |
| 531 | +) -> String { | |
| 389 | 532 | let env = |name: &str| { |
| 390 | 533 | std::env::var(name) |
| 391 | 534 | .ok() |
| 392 | 535 | .filter(|value| !value.trim().is_empty()) |
| 393 | 536 | }; |
| 394 | - if options.bucket.is_none() { | |
| 395 | - options.bucket = | |
| 396 | - env("CELLD_BUCKET").map(|value| value.trim_start_matches("s3://").to_string()); | |
| 537 | + if bucket.is_none() { | |
| 538 | + *bucket = env("CELLD_BUCKET").map(|value| value.trim_start_matches("s3://").to_string()); | |
| 397 | 539 | } |
| 398 | - if options.endpoint.is_none() { | |
| 399 | - options.endpoint = env("S3_ENDPOINT"); | |
| 540 | + if endpoint.is_none() { | |
| 541 | + *endpoint = env("S3_ENDPOINT"); | |
| 400 | 542 | } |
| 543 | + region | |
| 544 | + .map(str::to_string) | |
| 545 | + .or_else(|| env("AWS_REGION")) | |
| 546 | + .or_else(|| env("AWS_DEFAULT_REGION")) | |
| 547 | + .unwrap_or_else(|| "us-east-1".to_string()) | |
| 548 | +} | |
| 549 | + | |
| 550 | +pub async fn run_deploy(arguments: Vec<String>) -> anyhow::Result<()> { | |
| 551 | + let Some(mut options) = deploy::options_from_arguments(arguments)? else { | |
| 552 | + deploy::print_help(); | |
| 553 | + return Ok(()); | |
| 554 | + }; | |
| 555 | + let region = resolve_storage_location( | |
| 556 | + &mut options.bucket, | |
| 557 | + &mut options.endpoint, | |
| 558 | + options.region.as_deref(), | |
| 559 | + ); | |
| 401 | 560 | if !options.dry_run && options.bucket.is_none() { |
| 402 | 561 | bail!( |
| 403 | 562 | "celld deploy requires --bucket s3://NAME, gs://NAME or az://CONTAINER \ |
| @@ -406,39 +565,47 @@ | ||
| 406 | 565 | } |
| 407 | 566 | let built = deploy::build(&options)?; |
| 408 | 567 | built.report(); |
| 568 | + let mut out = Output::new(if options.json { | |
| 569 | + Format::Json | |
| 570 | + } else { | |
| 571 | + Format::Text | |
| 572 | + }); | |
| 409 | 573 | if options.dry_run { |
| 410 | - println!( | |
| 411 | - "Current Version ID: {} (dry run; nothing written)", | |
| 412 | - built.version | |
| 413 | - ); | |
| 414 | - return Ok(()); | |
| 574 | + out.row(&Deployed { | |
| 575 | + worker: built.script_name.clone(), | |
| 576 | + version: built.version.clone(), | |
| 577 | + location: String::new(), | |
| 578 | + dry_run: true, | |
| 579 | + })?; | |
| 580 | + return out.finish(); | |
| 415 | 581 | } |
| 416 | 582 | |
| 417 | 583 | let bucket = options.bucket.expect("validated deployment bucket"); |
| 418 | - let region = options | |
| 419 | - .region | |
| 420 | - .or_else(|| env("AWS_REGION")) | |
| 421 | - .or_else(|| env("AWS_DEFAULT_REGION")) | |
| 422 | - .unwrap_or_else(|| "us-east-1".to_string()); | |
| 423 | 584 | let store = bucket_client(&bucket, options.endpoint.as_deref(), ®ion)?; |
| 424 | 585 | validate_bucket(&store).await?; |
| 425 | 586 | let started = std::time::Instant::now(); |
| 426 | 587 | deploy::write(&store, &built).await?; |
| 427 | - println!( | |
| 428 | - "Uploaded {} ({:.2} sec)", | |
| 429 | - built.script_name, | |
| 430 | - started.elapsed().as_secs_f64() | |
| 431 | - ); | |
| 432 | - println!( | |
| 433 | - " {}://{}/{}{}", | |
| 588 | + let location = format!( | |
| 589 | + "{}://{}/{}{}", | |
| 434 | 590 | store.scheme(), |
| 435 | 591 | store.name, |
| 436 | 592 | store.prefix, |
| 437 | 593 | built.prefix |
| 438 | 594 | ); |
| 439 | - println!("Current Version ID: {}", built.version); | |
| 440 | - println!("Nodes load a deployment at startup; restart them to serve this version."); | |
| 441 | - Ok(()) | |
| 595 | + note!( | |
| 596 | + "Uploaded {} ({:.2} sec)", | |
| 597 | + built.script_name, | |
| 598 | + started.elapsed().as_secs_f64() | |
| 599 | + ); | |
| 600 | + note!(" {location}"); | |
| 601 | + out.row(&Deployed { | |
| 602 | + worker: built.script_name.clone(), | |
| 603 | + version: built.version.clone(), | |
| 604 | + location, | |
| 605 | + dry_run: false, | |
| 606 | + })?; | |
| 607 | + note!("Nodes adopt this version at their next pointer poll, without a restart."); | |
| 608 | + out.finish() | |
| 442 | 609 | } |
| 443 | 610 | |
| 444 | 611 | async fn get_string(bucket: &Bucket, key: &str) -> anyhow::Result<String> { |
| @@ -457,13 +624,23 @@ | ||
| 457 | 624 | Ok(bytes) |
| 458 | 625 | } |
| 459 | 626 | |
| 627 | +/// The fleet-wide pointer: the bucket's only application commit point. | |
| 628 | +pub const CURRENT_POINTER_KEY: &str = "deploy/current.json"; | |
| 629 | + | |
| 460 | 630 | pub async fn load_current_worker( |
| 461 | 631 | bucket: &Bucket, |
| 462 | 632 | node: String, |
| 463 | 633 | ) -> anyhow::Result<LoadedDeployment> { |
| 464 | - load_worker_from_pointer(bucket, "deploy/current.json", node).await | |
| 634 | + load_worker_from_pointer(bucket, CURRENT_POINTER_KEY, node).await | |
| 465 | 635 | } |
| 466 | 636 | |
| 637 | +/// Read the fleet-wide pointer without loading what it names. The watcher | |
| 638 | +/// compares it with the serving generation before it loads anything. | |
| 639 | +pub async fn read_current_pointer(bucket: &Bucket) -> anyhow::Result<DeployPointer> { | |
| 640 | + serde_json::from_str(&get_string(bucket, CURRENT_POINTER_KEY).await?) | |
| 641 | + .with_context(|| format!("decode {CURRENT_POINTER_KEY}")) | |
| 642 | +} | |
| 643 | + | |
| 467 | 644 | pub async fn load_named_worker( |
| 468 | 645 | bucket: &Bucket, |
| 469 | 646 | script: &str, |
| @@ -472,6 +649,48 @@ | ||
| 472 | 649 | load_worker_from_pointer(bucket, &format!("deploy/{script}/current.json"), node).await |
| 473 | 650 | } |
| 474 | 651 | |
| 652 | +pub async fn load_queue_consumer_attachment( | |
| 653 | + bucket: &Bucket, | |
| 654 | + queue: &str, | |
| 655 | +) -> anyhow::Result<Option<crate::protocol::QueueConsumerDeployment>> { | |
| 656 | + let key = crate::protocol::queue_consumer_attachment_key(queue) | |
| 657 | + .with_context(|| format!("invalid queue name {queue:?} in deployment manifest"))?; | |
| 658 | + let Some((body, _)) = bucket.get(&key).await? else { | |
| 659 | + return Ok(None); | |
| 660 | + }; | |
| 661 | + let attachment: crate::protocol::QueueConsumerAttachment = serde_json::from_slice(&body) | |
| 662 | + .with_context(|| format!("decode queue consumer attachment {key}"))?; | |
| 663 | + crate::protocol::validate_queue_consumer_attachment(queue, &attachment)?; | |
| 664 | + Ok(attachment.consumer) | |
| 665 | +} | |
| 666 | + | |
| 667 | +pub async fn load_queue_consumer_worker( | |
| 668 | + bucket: &Bucket, | |
| 669 | + queue: &str, | |
| 670 | + consumer: &crate::protocol::QueueConsumerDeployment, | |
| 671 | + node: String, | |
| 672 | +) -> anyhow::Result<LoadedDeployment> { | |
| 673 | + let pointer = DeployPointer { | |
| 674 | + script_name: Some(consumer.script_name.clone()), | |
| 675 | + version: consumer.version.clone(), | |
| 676 | + prefix: consumer.prefix.clone(), | |
| 677 | + rollout: Rollout { percent: 100 }, | |
| 678 | + }; | |
| 679 | + let pointer_key = format!("deploy/{}/current.json", consumer.script_name); | |
| 680 | + let loaded = load_worker_at_pointer(bucket, pointer, &pointer_key, node).await?; | |
| 681 | + anyhow::ensure!( | |
| 682 | + loaded | |
| 683 | + .options | |
| 684 | + .queue_consumers | |
| 685 | + .iter() | |
| 686 | + .any(|config| config.queue == queue), | |
| 687 | + "queue {queue:?} attachment resolved deployment {} of script {:?}, which does not consume that queue", | |
| 688 | + consumer.version, | |
| 689 | + consumer.script_name | |
| 690 | + ); | |
| 691 | + Ok(loaded) | |
| 692 | +} | |
| 693 | + | |
| 475 | 694 | async fn load_worker_from_pointer( |
| 476 | 695 | bucket: &Bucket, |
| 477 | 696 | pointer_key: &str, |
| @@ -479,11 +698,34 @@ | ||
| 479 | 698 | ) -> anyhow::Result<LoadedDeployment> { |
| 480 | 699 | let pointer: DeployPointer = serde_json::from_str(&get_string(bucket, pointer_key).await?) |
| 481 | 700 | .with_context(|| format!("decode {pointer_key}"))?; |
| 701 | + load_worker_at_pointer(bucket, pointer, pointer_key, node).await | |
| 702 | +} | |
| 703 | + | |
| 704 | +async fn load_worker_at_pointer( | |
| 705 | + bucket: &Bucket, | |
| 706 | + pointer: DeployPointer, | |
| 707 | + pointer_key: &str, | |
| 708 | + node: String, | |
| 709 | +) -> anyhow::Result<LoadedDeployment> { | |
| 482 | 710 | let manifest: Manifest = serde_json::from_str( |
| 483 | 711 | &get_string(bucket, &format!("{}/manifest.json", pointer.prefix)).await?, |
| 484 | 712 | ) |
| 485 | 713 | .context("decode deployment manifest")?; |
| 714 | + anyhow::ensure!( | |
| 715 | + manifest.version == pointer.version, | |
| 716 | + "deployment pointer for version {:?} resolved manifest version {:?}", | |
| 717 | + pointer.version, | |
| 718 | + manifest.version | |
| 719 | + ); | |
| 720 | + if let Some(script_name) = &pointer.script_name { | |
| 721 | + anyhow::ensure!( | |
| 722 | + manifest.script_name == *script_name, | |
| 723 | + "deployment pointer for script {script_name:?} resolved script {:?}", | |
| 724 | + manifest.script_name | |
| 725 | + ); | |
| 726 | + } | |
| 486 | 727 | crate::protocol::validate_required_features(&manifest.required_features)?; |
| 728 | + crate::protocol::validate_queue_manifest(&manifest)?; | |
| 487 | 729 | let src = match manifest.main_module.as_deref() { |
| 488 | 730 | Some(main) => get_string(bucket, &format!("{}/{main}", pointer.prefix)).await?, |
| 489 | 731 | None if manifest.assets.is_some() => { |
| @@ -528,8 +770,15 @@ | ||
| 528 | 770 | )) |
| 529 | 771 | }) |
| 530 | 772 | .collect(); |
| 773 | + // (env name, bucket name). The bucket name is the key space the | |
| 774 | + // binding owns inside the fleet bucket; see [[r2]]. | |
| 531 | 775 | let r2_bindings = bindings(&manifest, "r2_bucket") |
| 532 | - .filter_map(|binding| binding.get("name")?.as_str().map(str::to_string)) | |
| 776 | + .filter_map(|binding| { | |
| 777 | + Some(( | |
| 778 | + binding.get("name")?.as_str()?.to_string(), | |
| 779 | + binding.get("bucket_name")?.as_str()?.to_string(), | |
| 780 | + )) | |
| 781 | + }) | |
| 533 | 782 | .collect(); |
| 534 | 783 | // (env name, stable database identity). A Cloudflare database_id survives |
| 535 | 784 | // Worker renames and lets several Workers share the resource. A celld-only |
| @@ -546,6 +795,39 @@ | ||
| 546 | 795 | )) |
| 547 | 796 | }) |
| 548 | 797 | .collect(); |
| 798 | + // (env name, namespace identity). The identity is the config's `id` | |
| 799 | + // verbatim: upstream's `kv_namespaces` has no human-readable name field, so | |
| 800 | + // there is no second key to fall back to and none is invented. | |
| 801 | + let kv_bindings = bindings(&manifest, "kv") | |
| 802 | + .filter_map(|binding| { | |
| 803 | + Some(( | |
| 804 | + binding.get("name")?.as_str()?.to_string(), | |
| 805 | + binding.get("id")?.as_str()?.to_string(), | |
| 806 | + )) | |
| 807 | + }) | |
| 808 | + .collect(); | |
| 809 | + let queue_bindings = bindings(&manifest, "queue") | |
| 810 | + .filter_map(|binding| { | |
| 811 | + Some(crate::js::QueueBinding { | |
| 812 | + environment: binding.get("name")?.as_str()?.to_string(), | |
| 813 | + queue: binding.get("queue")?.as_str()?.to_string(), | |
| 814 | + delivery_delay: binding | |
| 815 | + .get("delivery_delay") | |
| 816 | + .and_then(serde_json::Value::as_u64) | |
| 817 | + .and_then(|value| u32::try_from(value).ok()) | |
| 818 | + .unwrap_or(0), | |
| 819 | + }) | |
| 820 | + }) | |
| 821 | + .collect(); | |
| 822 | + let workflow_bindings = bindings(&manifest, "workflow") | |
| 823 | + .filter_map(|binding| { | |
| 824 | + Some(crate::js::WorkflowBinding { | |
| 825 | + environment: binding.get("name")?.as_str()?.to_string(), | |
| 826 | + workflow: binding.get("workflow_name")?.as_str()?.to_string(), | |
| 827 | + class: binding.get("class_name")?.as_str()?.to_string(), | |
| 828 | + }) | |
| 829 | + }) | |
| 830 | + .collect(); | |
| 549 | 831 | let ai_binding = configured_ai_binding( |
| 550 | 832 | bindings(&manifest, "ai") |
| 551 | 833 | .find_map(|binding| binding.get("name")?.as_str().map(str::to_string)), |
| @@ -560,6 +842,15 @@ | ||
| 560 | 842 | &pointer.prefix, |
| 561 | 843 | reference, |
| 562 | 844 | manifest.main_module.is_none(), |
| 845 | + // The resolver can consult this pointer again later: a | |
| 846 | + // rolling restart serves new HTML from upgraded nodes while | |
| 847 | + // this process still holds the boot index, and the fallback | |
| 848 | + // is what keeps the new content-hashed assets servable | |
| 849 | + // everywhere (denoland/celld#161). | |
| 850 | + Some(crate::assets::FallbackSource { | |
| 851 | + pointer_key: pointer_key.to_string(), | |
| 852 | + boot_prefix: pointer.prefix.clone(), | |
| 853 | + }), | |
| 563 | 854 | ) |
| 564 | 855 | .await?, |
| 565 | 856 | ), |
| @@ -570,6 +861,8 @@ | ||
| 570 | 861 | .and_then(crate::assets::AssetResolver::binding_name) |
| 571 | 862 | .map(str::to_string); |
| 572 | 863 | let script_name = manifest.script_name.clone(); |
| 864 | + let version = manifest.version.clone(); | |
| 865 | + let prefix = pointer.prefix.clone(); | |
| 573 | 866 | let crons = manifest.crons.clone(); |
| 574 | 867 | Ok(LoadedDeployment { |
| 575 | 868 | options: WorkerConfigOptions { |
| @@ -579,6 +872,10 @@ | ||
| 579 | 872 | bindings: do_bindings, |
| 580 | 873 | r2_bindings, |
| 581 | 874 | d1_bindings, |
| 875 | + kv_bindings, | |
| 876 | + queue_bindings, | |
| 877 | + queue_consumers: manifest.queue_consumers, | |
| 878 | + workflow_bindings, | |
| 582 | 879 | ai_binding, |
| 583 | 880 | vars, |
| 584 | 881 | node, |
| @@ -586,6 +883,8 @@ | ||
| 586 | 883 | compat, |
| 587 | 884 | }, |
| 588 | 885 | script_name, |
| 886 | + version, | |
| 887 | + prefix, | |
| 589 | 888 | asset_binding, |
| 590 | 889 | assets, |
| 591 | 890 | services, |
| @@ -603,6 +902,8 @@ | ||
| 603 | 902 | pub struct LoadedDeployment { |
| 604 | 903 | pub options: WorkerConfigOptions, |
| 605 | 904 | pub script_name: String, |
| 905 | + pub version: String, | |
| 906 | + pub prefix: String, | |
| 606 | 907 | pub asset_binding: Option<String>, |
| 607 | 908 | pub assets: Option<crate::assets::AssetResolver>, |
| 608 | 909 | pub services: Vec<(String, String, Option<String>)>, |
addedcrates/celld/generation.rs+420−0View file
| @@ -1,0 +1,420 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! One application deployment as the running process holds it. | |
| 4 | +//! | |
| 5 | +//! A [`Generation`] is everything a node derives from a deployment: the | |
| 6 | +//! compiled Worker configurations, the isolate pools they run in, the | |
| 7 | +//! Durable Object class registry, the service-binding graph, the asset | |
| 8 | +//! resolvers, and the cron schedule. A node serves exactly one current | |
| 9 | +//! generation and reaches it through a snapshot, so a request that started | |
| 10 | +//! on one generation finishes on it even after the node adopts another. | |
| 11 | +//! | |
| 12 | +//! Boot and reload construct a generation through the same two functions, | |
| 13 | +//! [`DeploymentGraph::load`] and `Generation::build`. Nothing else reads a | |
| 14 | +//! deployment manifest into runtime state. A value a deployment implies | |
| 15 | +//! therefore has one place it can be computed, and a reload cannot miss what | |
| 16 | +//! a boot did, because there is no second path for it to miss. | |
| 17 | + | |
| 18 | +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; | |
| 19 | +use std::sync::Arc; | |
| 20 | + | |
| 21 | +use anyhow::Context; | |
| 22 | + | |
| 23 | +use crate::assets::AssetResolver; | |
| 24 | +use crate::bucket::Bucket; | |
| 25 | +use crate::fleet::{self, LoadedDeployment}; | |
| 26 | +use crate::js::{WorkerConfig, WorkerConfigOptions}; | |
| 27 | + | |
| 28 | +/// Which generation, within this process. Monotonic from one at boot; never | |
| 29 | +/// reused, never persisted, and never compared across nodes — the fleet-wide | |
| 30 | +/// identity of a deployment is its version string. | |
| 31 | +pub type GenerationId = u64; | |
| 32 | + | |
| 33 | +/// The generation a node boots on. Later generations count up from it. | |
| 34 | +pub const FIRST_GENERATION: GenerationId = 1; | |
| 35 | + | |
| 36 | +/// Ask the node to adopt the deployment `deploy/current.json` names now. | |
| 37 | +pub struct ReloadRequest { | |
| 38 | + /// Rebuild even when the pointer names the current deployment, so the | |
| 39 | + /// manifest and `CELLD_VARS_FILE` are read again. `POST /reload` sets it; | |
| 40 | + /// a poll tick and a managed nudge do not. | |
| 41 | + pub force: bool, | |
| 42 | + /// Where to report the outcome. A poll tick has nobody to tell. | |
| 43 | + pub reply: Option<tokio::sync::oneshot::Sender<ReloadOutcome>>, | |
| 44 | +} | |
| 45 | + | |
| 46 | +/// What one adoption attempt concluded. | |
| 47 | +#[derive(Clone, Debug, PartialEq, Eq)] | |
| 48 | +pub enum ReloadOutcome { | |
| 49 | + /// A new generation serves. Requests admitted from now on use it. | |
| 50 | + Adopted { | |
| 51 | + generation: GenerationId, | |
| 52 | + version: String, | |
| 53 | + prefix: String, | |
| 54 | + }, | |
| 55 | + /// The pointer names the deployment already serving and the request did | |
| 56 | + /// not force a rebuild. | |
| 57 | + Unchanged { | |
| 58 | + generation: GenerationId, | |
| 59 | + version: String, | |
| 60 | + }, | |
| 61 | + /// The deployment did not build. The current generation is untouched. | |
| 62 | + Failed { | |
| 63 | + version: String, | |
| 64 | + prefix: String, | |
| 65 | + error: String, | |
| 66 | + }, | |
| 67 | +} | |
| 68 | + | |
| 69 | +pub type ReloadSender = tokio::sync::mpsc::UnboundedSender<ReloadRequest>; | |
| 70 | +pub type ReloadReceiver = tokio::sync::mpsc::UnboundedReceiver<ReloadRequest>; | |
| 71 | + | |
| 72 | +pub fn reload_channel() -> (ReloadSender, ReloadReceiver) { | |
| 73 | + tokio::sync::mpsc::unbounded_channel() | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// Ask for a poll now, without waiting for the outcome. A managed | |
| 77 | +/// `deployment_current` message and a successful apply both end here: the | |
| 78 | +/// pointer is the authority, and the nudge only shortens the wait for it. | |
| 79 | +pub fn nudge(reload: &ReloadSender) { | |
| 80 | + let _ = reload.send(ReloadRequest { | |
| 81 | + force: false, | |
| 82 | + reply: None, | |
| 83 | + }); | |
| 84 | +} | |
| 85 | + | |
| 86 | +/// How often a node re-reads the pointer without a nudge. For a standalone | |
| 87 | +/// node this is the deploy latency; for a managed node it is the backstop | |
| 88 | +/// behind the push. `CELLD_DEPLOY_POLL_S`, default 30. | |
| 89 | +pub fn poll_interval() -> std::time::Duration { | |
| 90 | + let seconds = crate::env_vars::positive_or("CELLD_DEPLOY_POLL_S", 30u64) | |
| 91 | + .expect("validated CELLD_DEPLOY_POLL_S"); | |
| 92 | + std::time::Duration::from_secs(seconds) | |
| 93 | +} | |
| 94 | + | |
| 95 | +/// How long a resident cell may keep running a superseded generation after | |
| 96 | +/// the node adopts a new one, before its swap is forced: its activity | |
| 97 | +/// cancelled and its regular WebSockets closed with 1012. Zero forces every | |
| 98 | +/// resident cell at the flip, which is what a Cloudflare deployment does. | |
| 99 | +/// `CELLD_DEPLOY_MAX_AGE_S`, default 60. | |
| 100 | +pub fn max_age() -> std::time::Duration { | |
| 101 | + // Not `positive_or`: zero is meaningful here. | |
| 102 | + let seconds = crate::env_vars::with_default("CELLD_DEPLOY_MAX_AGE_S", 60u64) | |
| 103 | + .expect("validated CELLD_DEPLOY_MAX_AGE_S"); | |
| 104 | + std::time::Duration::from_secs(seconds) | |
| 105 | +} | |
| 106 | + | |
| 107 | +/// The scripts one deployment reaches: the primary script plus every | |
| 108 | +/// service-binding target and queue consumer it declares, transitively. | |
| 109 | +/// | |
| 110 | +/// [`DeploymentGraph::load`] is the only bucket walk, so the boot path and | |
| 111 | +/// the reload path cannot resolve a deployment's dependencies differently. | |
| 112 | +pub struct DeploymentGraph { | |
| 113 | + pub primary: LoadedDeployment, | |
| 114 | + pub cohosted: Vec<LoadedDeployment>, | |
| 115 | +} | |
| 116 | + | |
| 117 | +impl DeploymentGraph { | |
| 118 | + /// One script and nothing else: the local-script mode a runtime test | |
| 119 | + /// starts from a file, which declares no services and has no bucket to | |
| 120 | + /// resolve them from. | |
| 121 | + pub fn single(primary: LoadedDeployment) -> Self { | |
| 122 | + Self { | |
| 123 | + primary, | |
| 124 | + cohosted: Vec::new(), | |
| 125 | + } | |
| 126 | + } | |
| 127 | + | |
| 128 | + /// Resolve the fleet-wide pointer and every script it depends on. | |
| 129 | + /// | |
| 130 | + /// A service binding names a script, and that script's own pointer names | |
| 131 | + /// its deployment. A queue dependency names a queue, and the queue's | |
| 132 | + /// consumer attachment names an exact deployment. The walk refuses a | |
| 133 | + /// script that resolves twice and a queue attached to a deployment other | |
| 134 | + /// than the one already loaded, because either would give one script two | |
| 135 | + /// bodies in one process. | |
| 136 | + pub async fn load(bucket: &Bucket, node: String) -> anyhow::Result<Self> { | |
| 137 | + let primary = fleet::load_current_worker(bucket, node.clone()).await?; | |
| 138 | + let primary_script = primary.script_name.clone(); | |
| 139 | + let mut loaded_scripts = BTreeMap::from([(primary_script.clone(), primary.prefix.clone())]); | |
| 140 | + let mut loaded_consumers = | |
| 141 | + BTreeMap::from([(primary_script.clone(), consumed_queues(&primary.options))]); | |
| 142 | + let mut visited_queues = BTreeSet::new(); | |
| 143 | + let mut dependencies = dependencies_of(&primary); | |
| 144 | + let mut cohosted = Vec::new(); | |
| 145 | + while let Some(dependency) = dependencies.pop_front() { | |
| 146 | + let loaded = match dependency { | |
| 147 | + Dependency::Service(target) => { | |
| 148 | + if target == primary_script || loaded_scripts.contains_key(&target) { | |
| 149 | + continue; | |
| 150 | + } | |
| 151 | + let loaded = fleet::load_named_worker(bucket, &target, node.clone()) | |
| 152 | + .await | |
| 153 | + .with_context(|| format!("load service binding target {target}"))?; | |
| 154 | + if loaded.script_name != target { | |
| 155 | + anyhow::bail!( | |
| 156 | + "service pointer {target} resolved script {}", | |
| 157 | + loaded.script_name | |
| 158 | + ); | |
| 159 | + } | |
| 160 | + loaded | |
| 161 | + } | |
| 162 | + Dependency::Queue(queue) => { | |
| 163 | + if !visited_queues.insert(queue.clone()) { | |
| 164 | + continue; | |
| 165 | + } | |
| 166 | + let declared_by = loaded_consumers | |
| 167 | + .iter() | |
| 168 | + .find_map(|(script, queues)| queues.contains(&queue).then_some(script)); | |
| 169 | + let Some(consumer) = | |
| 170 | + fleet::load_queue_consumer_attachment(bucket, &queue).await? | |
| 171 | + else { | |
| 172 | + if let Some(script) = declared_by { | |
| 173 | + anyhow::bail!( | |
| 174 | + "script {script:?} consumes queue {queue:?}, but the queue has no active consumer attachment; re-run `celld deploy`" | |
| 175 | + ); | |
| 176 | + } | |
| 177 | + continue; | |
| 178 | + }; | |
| 179 | + if let Some(script) = declared_by { | |
| 180 | + anyhow::ensure!( | |
| 181 | + script == &consumer.script_name, | |
| 182 | + "queue {queue:?} is attached to script {:?}, but loaded script {script:?} also consumes it", | |
| 183 | + consumer.script_name | |
| 184 | + ); | |
| 185 | + } | |
| 186 | + if let Some(prefix) = loaded_scripts.get(&consumer.script_name) { | |
| 187 | + anyhow::ensure!( | |
| 188 | + prefix == &consumer.prefix, | |
| 189 | + "queue {queue:?} is attached to deployment {} of script {:?}, but deployment {prefix} is already loaded; re-run `celld deploy`", | |
| 190 | + consumer.version, | |
| 191 | + consumer.script_name | |
| 192 | + ); | |
| 193 | + anyhow::ensure!( | |
| 194 | + loaded_consumers | |
| 195 | + .get(&consumer.script_name) | |
| 196 | + .is_some_and(|queues| queues.contains(&queue)), | |
| 197 | + "queue {queue:?} is attached to script {:?}, but its loaded deployment does not consume that queue", | |
| 198 | + consumer.script_name | |
| 199 | + ); | |
| 200 | + continue; | |
| 201 | + } | |
| 202 | + fleet::load_queue_consumer_worker(bucket, &queue, &consumer, node.clone()) | |
| 203 | + .await | |
| 204 | + .with_context(|| format!("load consumer for queue {queue:?}"))? | |
| 205 | + } | |
| 206 | + }; | |
| 207 | + let target = loaded.script_name.clone(); | |
| 208 | + anyhow::ensure!( | |
| 209 | + loaded_scripts | |
| 210 | + .insert(target.clone(), loaded.prefix.clone()) | |
| 211 | + .is_none(), | |
| 212 | + "script {target:?} was loaded twice" | |
| 213 | + ); | |
| 214 | + loaded_consumers.insert(target.clone(), consumed_queues(&loaded.options)); | |
| 215 | + dependencies.extend(dependencies_of(&loaded)); | |
| 216 | + // A node runs the schedule of the deployment it was given and of | |
| 217 | + // no other. The reserved class is one key, so a second script's | |
| 218 | + // cron cell would resolve to the first script's config and run | |
| 219 | + // the wrong `scheduled` handler. Dropping the schedule is the | |
| 220 | + // safe half of that trade and this says so out loud, because a | |
| 221 | + // trigger that never fires and says nothing is the failure the | |
| 222 | + // whole feature is built to avoid. Deploy the script as a node's | |
| 223 | + // own deployment to run its crons. | |
| 224 | + if !loaded.crons.is_empty() { | |
| 225 | + tracing::warn!( | |
| 226 | + script = %target, | |
| 227 | + crons = %loaded.crons.join(", "), | |
| 228 | + "a service binding target declares cron triggers; a node fires only its own deployment's schedule, so these never run here" | |
| 229 | + ); | |
| 230 | + } | |
| 231 | + cohosted.push(loaded); | |
| 232 | + } | |
| 233 | + Ok(Self { primary, cohosted }) | |
| 234 | + } | |
| 235 | +} | |
| 236 | + | |
| 237 | +enum Dependency { | |
| 238 | + Service(String), | |
| 239 | + Queue(String), | |
| 240 | +} | |
| 241 | + | |
| 242 | +fn consumed_queues(options: &WorkerConfigOptions) -> BTreeSet<String> { | |
| 243 | + options | |
| 244 | + .queue_consumers | |
| 245 | + .iter() | |
| 246 | + .map(|consumer| consumer.queue.clone()) | |
| 247 | + .collect() | |
| 248 | +} | |
| 249 | + | |
| 250 | +fn dependencies_of(loaded: &LoadedDeployment) -> VecDeque<Dependency> { | |
| 251 | + let queues = loaded | |
| 252 | + .options | |
| 253 | + .queue_bindings | |
| 254 | + .iter() | |
| 255 | + .map(|binding| binding.queue.clone()) | |
| 256 | + .chain(loaded.options.queue_consumers.iter().flat_map(|consumer| { | |
| 257 | + std::iter::once(consumer.queue.clone()).chain(consumer.dead_letter_queue.clone()) | |
| 258 | + })) | |
| 259 | + .collect::<BTreeSet<_>>(); | |
| 260 | + loaded | |
| 261 | + .services | |
| 262 | + .iter() | |
| 263 | + .map(|(_, script, _)| Dependency::Service(script.clone())) | |
| 264 | + .chain(queues.into_iter().map(Dependency::Queue)) | |
| 265 | + .collect() | |
| 266 | +} | |
| 267 | + | |
| 268 | +/// Node-level inputs `Generation::build` needs beside the deployment itself. | |
| 269 | +pub struct GenerationOptions { | |
| 270 | + pub loader_binding: Option<String>, | |
| 271 | + pub node: String, | |
| 272 | + pub region: String, | |
| 273 | +} | |
| 274 | + | |
| 275 | +/// A deployment, built and ready to serve. | |
| 276 | +/// | |
| 277 | +/// The fields are the four maps `RuntimeManager` once held for the life of | |
| 278 | +/// the process, plus the asset resolvers and the cron schedule that lived on | |
| 279 | +/// the application handle. They are private and reached through | |
| 280 | +/// `RuntimeManager`, which hands out this struct only as a snapshot. | |
| 281 | +pub struct Generation { | |
| 282 | + pub(crate) id: GenerationId, | |
| 283 | + pub(crate) version: String, | |
| 284 | + pub(crate) prefix: String, | |
| 285 | + pub(crate) script_name: String, | |
| 286 | + pub(crate) stateless: crate::runtime::StatelessRuntime, | |
| 287 | + pub(crate) services: HashMap<String, crate::runtime::StatelessRuntime>, | |
| 288 | + pub(crate) cell_configs: HashMap<String, Arc<WorkerConfig>>, | |
| 289 | + /// The isolates a Worker script's cells live in — the same `Pool` the | |
| 290 | + /// stateless path admits into, because an isolate is an isolate. Cells | |
| 291 | + /// of one script share them, so cells of one class share module scope | |
| 292 | + /// exactly when they are colocated, which is what Durable Objects do. | |
| 293 | + pub(crate) cell_isolates: HashMap<String, Arc<crate::pool::Pool>>, | |
| 294 | + pub(crate) default_do_class: Option<Arc<str>>, | |
| 295 | + pub(crate) assets: HashMap<String, AssetResolver>, | |
| 296 | + /// `triggers.crons` of the primary script, so an adoption can tell | |
| 297 | + /// whether the schedule changed without re-reading the manifest. | |
| 298 | + #[allow(dead_code)] | |
| 299 | + pub(crate) crons: Vec<String>, | |
| 300 | +} | |
| 301 | + | |
| 302 | +impl Generation { | |
| 303 | + pub fn id(&self) -> GenerationId { | |
| 304 | + self.id | |
| 305 | + } | |
| 306 | + | |
| 307 | + pub fn version(&self) -> &str { | |
| 308 | + &self.version | |
| 309 | + } | |
| 310 | + | |
| 311 | + pub fn prefix(&self) -> &str { | |
| 312 | + &self.prefix | |
| 313 | + } | |
| 314 | + | |
| 315 | + /// The primary script: the one ingress serves and whose assets ingress | |
| 316 | + /// consults before running the Worker. | |
| 317 | + pub fn script_name(&self) -> &str { | |
| 318 | + &self.script_name | |
| 319 | + } | |
| 320 | + | |
| 321 | + /// The asset resolver of the named script, if that script deployed | |
| 322 | + /// assets. | |
| 323 | + pub fn assets(&self, script: &str) -> Option<&AssetResolver> { | |
| 324 | + self.assets.get(script) | |
| 325 | + } | |
| 326 | + | |
| 327 | + /// The primary script's asset resolver, which ingress consults. | |
| 328 | + pub fn ingress_assets(&self) -> Option<&AssetResolver> { | |
| 329 | + self.assets.get(&self.script_name) | |
| 330 | + } | |
| 331 | + | |
| 332 | + pub fn has_cell_classes(&self) -> bool { | |
| 333 | + !self.cell_configs.is_empty() | |
| 334 | + } | |
| 335 | + | |
| 336 | + /// The reserved cell carrying this deployment's cron schedule, or `None` | |
| 337 | + /// when the deployment declares no `triggers.crons`. Derived from the | |
| 338 | + /// registered class rather than plumbed separately, so it cannot | |
| 339 | + /// disagree with what `start_cell` will accept. | |
| 340 | + pub fn cron_cell(&self) -> Option<String> { | |
| 341 | + self.cell_configs | |
| 342 | + .get(celld_logic::cron::RESERVED_CLASS) | |
| 343 | + .map(|config| celld_logic::cron::reserved_cell(&config.script_name)) | |
| 344 | + } | |
| 345 | + | |
| 346 | + pub(crate) fn cell_config(&self, class: &str) -> Option<Arc<WorkerConfig>> { | |
| 347 | + self.cell_configs.get(class).cloned() | |
| 348 | + } | |
| 349 | + | |
| 350 | + /// The engine's reserved Durable Object classes this generation | |
| 351 | + /// registers: cron, queue, workflow, D1, KV. Their cells hold no | |
| 352 | + /// application state worth waiting for, so an adoption moves them at | |
| 353 | + /// once — and the cron cell must run the new schedule before the | |
| 354 | + /// adoption arms it. | |
| 355 | + /// | |
| 356 | + /// The cron class is named beside `deploy::is_reserved_class` rather | |
| 357 | + /// than added to it. That predicate also decides which classes refuse an | |
| 358 | + /// unauthenticated operator route, and the cron cell is not one of them, | |
| 359 | + /// so widening it to reach this list would widen that refusal too. | |
| 360 | + pub fn reserved_classes(&self) -> Vec<String> { | |
| 361 | + self.cell_configs | |
| 362 | + .keys() | |
| 363 | + .filter(|class| { | |
| 364 | + crate::deploy::is_reserved_class(class) | |
| 365 | + || class.as_str() == celld_logic::cron::RESERVED_CLASS | |
| 366 | + }) | |
| 367 | + .cloned() | |
| 368 | + .collect() | |
| 369 | + } | |
| 370 | + | |
| 371 | + pub(crate) fn cell_isolates(&self, script: &str) -> Option<Arc<crate::pool::Pool>> { | |
| 372 | + self.cell_isolates.get(script).cloned() | |
| 373 | + } | |
| 374 | + | |
| 375 | + pub(crate) fn service(&self, script: &str) -> Option<crate::runtime::StatelessRuntime> { | |
| 376 | + self.services.get(script).cloned() | |
| 377 | + } | |
| 378 | + | |
| 379 | + pub(crate) fn default_do_class(&self) -> Option<&str> { | |
| 380 | + self.default_do_class.as_deref() | |
| 381 | + } | |
| 382 | + | |
| 383 | + /// Stop every isolate of this generation from taking new work. Stateless | |
| 384 | + /// isolates free as their affiliations drop; cell isolates free as their | |
| 385 | + /// cells move to a newer generation. | |
| 386 | + pub(crate) fn retire(&self) { | |
| 387 | + for service in self.services.values() { | |
| 388 | + service.isolates.retire_all(); | |
| 389 | + } | |
| 390 | + for pool in self.cell_isolates.values() { | |
| 391 | + pool.retire_all(); | |
| 392 | + } | |
| 393 | + } | |
| 394 | + | |
| 395 | + /// Whether every isolate of this generation has been freed, so the | |
| 396 | + /// generation itself can be dropped. | |
| 397 | + pub(crate) fn is_drained(&self) -> bool { | |
| 398 | + self.services | |
| 399 | + .values() | |
| 400 | + .all(|service| service.isolates.is_drained()) | |
| 401 | + && self.cell_isolates.values().all(|pool| pool.is_drained()) | |
| 402 | + } | |
| 403 | + | |
| 404 | + /// One maintenance pass over the cell pools: retire and free every empty | |
| 405 | + /// isolate. An empty cell heap carries no warm request capacity worth | |
| 406 | + /// preserving, unlike a stateless one. | |
| 407 | + pub(crate) fn reap_cell_pools(&self) { | |
| 408 | + for pool in self.cell_isolates.values() { | |
| 409 | + pool.reap_empty(); | |
| 410 | + } | |
| 411 | + } | |
| 412 | +} | |
| 413 | + | |
| 414 | +/// The generation an isolate was built for, installed as an isolate slot by | |
| 415 | +/// `Worker::load_config` so a call the isolate makes into the host — a | |
| 416 | +/// service binding, an assets binding, a queue dispatch — resolves against | |
| 417 | +/// the graph the caller was built with rather than whichever generation is | |
| 418 | +/// current when the call lands. | |
| 419 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 420 | +pub struct GenerationTag(pub GenerationId); |
modifiedcrates/celld/host_services.rs+8−56View file
| @@ -1,7 +1,5 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -#![warn(clippy::disallowed_macros)] | |
| 4 | - | |
| 5 | 3 | //! Process services that an engine incarnation can observe. |
| 6 | 4 | //! |
| 7 | 5 | //! Production installs one service set. A deterministic domain installs one |
| @@ -9,54 +7,21 @@ | ||
| 9 | 7 | //! host measurements. |
| 10 | 8 | |
| 11 | 9 | use crate::ownership_store::LiveLoad; |
| 12 | -#[cfg(all(test, celld_internal_tests))] | |
| 13 | -use std::collections::BTreeSet; | |
| 14 | 10 | use std::sync::{Arc, Mutex, OnceLock}; |
| 15 | 11 | |
| 16 | -/// Test-only faults planted in production adapter transitions. Each value is | |
| 17 | -/// scoped to one simulation domain, so parallel corpus tests cannot arm one | |
| 18 | -/// another's teeth. | |
| 19 | -#[cfg(all(test, celld_internal_tests))] | |
| 20 | -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] | |
| 21 | -pub enum EngineSabotage { | |
| 22 | - SuppressResetStop, | |
| 23 | - CoverTicketEarly, | |
| 24 | - MisreportGatePosition, | |
| 25 | - RestoreSupersededEpoch, | |
| 26 | - FreshCreateOverwrites, | |
| 27 | - DropCompactionInput, | |
| 28 | - HideDirtyCell, | |
| 29 | - DropTimerArm, | |
| 30 | - IgnoreTookOver, | |
| 31 | - SkipArmTimeWakePut, | |
| 32 | - IgnoreAlarmConsumeOnRestore, | |
| 33 | - SuppressReleasingDecrement, | |
| 34 | - SkipBucketProofOwnershipRead, | |
| 35 | - SkipTakeoverInterlock, | |
| 36 | - SkipBundleCreditRecordRead, | |
| 37 | - SkipObserveLogEpoch, | |
| 38 | - ClearShipInFlightEarly, | |
| 39 | - DeleteUncoveredBundle, | |
| 40 | - CollectOpenFragment, | |
| 41 | - GracefulSealUsesCreditedCoverage, | |
| 42 | - AcceptAppendPastSeal, | |
| 43 | - FilterRecoveryBundlesByRecordEpoch, | |
| 44 | - SealAmnesiacWithoutLossRecord, | |
| 45 | - SkipActivationFenceCas, | |
| 46 | - SkipAlarmWriteGate, | |
| 47 | -} | |
| 48 | - | |
| 49 | 12 | /// One resource observation used by the pressure path. |
| 50 | 13 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 51 | 14 | pub struct HostMetricsSample { |
| 52 | 15 | pub cpu_percent_x100: u64, |
| 53 | 16 | pub rss_bytes: u64, |
| 54 | 17 | pub in_use_bytes: u64, |
| 18 | + pub cgroup_working_set_bytes: Option<u64>, | |
| 19 | + pub cgroup_current_bytes: Option<u64>, | |
| 55 | 20 | } |
| 56 | 21 | |
| 57 | 22 | enum MetricsBackend { |
| 58 | 23 | Production(Mutex<ProcessLoadSampler>), |
| 59 | - #[cfg(all(test, celld_internal_tests))] | |
| 24 | + #[cfg(celld_internal_tests)] | |
| 60 | 25 | Scripted(Mutex<HostMetricsSample>), |
| 61 | 26 | } |
| 62 | 27 | |
| @@ -66,8 +31,6 @@ | ||
| 66 | 31 | wake_entry: crate::js::WakeEntryService, |
| 67 | 32 | websockets: crate::js::WebSocketService, |
| 68 | 33 | metrics: MetricsBackend, |
| 69 | - #[cfg(all(test, celld_internal_tests))] | |
| 70 | - sabotages: Mutex<BTreeSet<EngineSabotage>>, | |
| 71 | 34 | } |
| 72 | 35 | |
| 73 | 36 | impl HostServices { |
| @@ -77,19 +40,16 @@ | ||
| 77 | 40 | wake_entry: crate::js::WakeEntryService::default(), |
| 78 | 41 | websockets: crate::js::WebSocketService::default(), |
| 79 | 42 | metrics: MetricsBackend::Production(Mutex::new(ProcessLoadSampler::default())), |
| 80 | - #[cfg(all(test, celld_internal_tests))] | |
| 81 | - sabotages: Mutex::new(BTreeSet::new()), | |
| 82 | 43 | } |
| 83 | 44 | } |
| 84 | 45 | |
| 85 | - #[cfg(all(test, celld_internal_tests))] | |
| 46 | + #[cfg(celld_internal_tests)] | |
| 86 | 47 | pub fn scripted() -> Self { |
| 87 | 48 | Self { |
| 88 | 49 | node_load: OnceLock::new(), |
| 89 | 50 | wake_entry: crate::js::WakeEntryService::default(), |
| 90 | 51 | websockets: crate::js::WebSocketService::default(), |
| 91 | 52 | metrics: MetricsBackend::Scripted(Mutex::new(HostMetricsSample::default())), |
| 92 | - sabotages: Mutex::new(BTreeSet::new()), | |
| 93 | 53 | } |
| 94 | 54 | } |
| 95 | 55 | |
| @@ -118,30 +78,22 @@ | ||
| 118 | 78 | cpu_percent_x100: sampler.sample_cpu_percent_x100(), |
| 119 | 79 | rss_bytes: memory.rss_bytes, |
| 120 | 80 | in_use_bytes: memory.in_use_bytes, |
| 81 | + cgroup_working_set_bytes: memory.cgroup_working_set_bytes, | |
| 82 | + cgroup_current_bytes: memory.cgroup_current_bytes, | |
| 121 | 83 | } |
| 122 | 84 | } |
| 123 | - #[cfg(all(test, celld_internal_tests))] | |
| 85 | + #[cfg(celld_internal_tests)] | |
| 124 | 86 | MetricsBackend::Scripted(sample) => *sample.lock().unwrap(), |
| 125 | 87 | } |
| 126 | 88 | } |
| 127 | 89 | |
| 128 | - #[cfg(all(test, celld_internal_tests))] | |
| 90 | + #[cfg(celld_internal_tests)] | |
| 129 | 91 | pub fn set_scripted_metrics(&self, sample: HostMetricsSample) { |
| 130 | 92 | let MetricsBackend::Scripted(current) = &self.metrics else { |
| 131 | 93 | panic!("scripted metrics require a simulation HostServices instance"); |
| 132 | 94 | }; |
| 133 | 95 | *current.lock().unwrap() = sample; |
| 134 | 96 | } |
| 135 | - | |
| 136 | - #[cfg(all(test, celld_internal_tests))] | |
| 137 | - pub fn arm_sabotage(&self, sabotage: EngineSabotage) { | |
| 138 | - self.sabotages.lock().unwrap().insert(sabotage); | |
| 139 | - } | |
| 140 | - | |
| 141 | - #[cfg(all(test, celld_internal_tests))] | |
| 142 | - pub(crate) fn sabotage_active(&self, sabotage: EngineSabotage) -> bool { | |
| 143 | - self.sabotages.lock().unwrap().contains(&sabotage) | |
| 144 | - } | |
| 145 | 97 | } |
| 146 | 98 | |
| 147 | 99 | #[derive(Default)] |
modifiedcrates/celld/js.rs+9050−6260View file
| @@ -1,6262 +1,9052 @@ | ||
| 1 | 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | 2 | |
| 3 | -// The raw V8 adapter and its child modules remain outside the World. The | |
| 4 | -// Actor-reachable wake and WebSocket state is injected through HostServices. | |
| 5 | -#![allow( | |
| 6 | - clippy::disallowed_macros, | |
| 7 | - clippy::disallowed_methods, | |
| 8 | - clippy::disallowed_types | |
| 9 | -)] | |
| 10 | - | |
| 11 | -//! The JS engine: rusty_v8 directly. One isolate per cell. | |
| 12 | -//! | |
| 13 | -//! This slice runs actual Durable Objects: the worker's default-export `fetch` | |
| 14 | -//! receives an `env` whose bindings are DO namespaces; `env.NS.get(id).fetch()` | |
| 15 | -//! instantiates the exported DO class (once per id) with a `state` whose | |
| 16 | -//! `storage` is backed by the cell's SQLite (crate::storage). DO storage is | |
| 17 | -//! async in JS, synchronous underneath — the ops are sync Rust, wrapped in | |
| 18 | -//! `async` by the JS harness. | |
| 19 | -use crate::asyncrt; | |
| 20 | -use crate::storage; | |
| 21 | -use anyhow::{anyhow, Context as _, Result}; | |
| 22 | -use futures_util::StreamExt as _; | |
| 23 | -use std::cell::RefCell; | |
| 24 | -use std::collections::{HashMap, HashSet}; | |
| 25 | -use std::pin::Pin; | |
| 26 | -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | |
| 27 | -use std::sync::{Arc, Mutex, OnceLock}; | |
| 28 | -use std::time::{Duration, Instant}; | |
| 29 | -use v8::{ValueDeserializerHelper, ValueSerializerHelper}; | |
| 30 | - | |
| 31 | -/// Bare Node builtin specifiers that the bundler leaves for the runtime. | |
| 32 | -/// Root entries also match subpaths in esbuild and in module resolution. | |
| 33 | -pub(crate) const BARE_NODE_BUILTINS: &[&str] = &[ | |
| 34 | - "assert", | |
| 35 | - "async_hooks", | |
| 36 | - "buffer", | |
| 37 | - "child_process", | |
| 38 | - "cluster", | |
| 39 | - "constants", | |
| 40 | - "crypto", | |
| 41 | - "dgram", | |
| 42 | - "diagnostics_channel", | |
| 43 | - "dns", | |
| 44 | - "events", | |
| 45 | - "fs", | |
| 46 | - "fs/promises", | |
| 47 | - "http", | |
| 48 | - "http2", | |
| 49 | - "https", | |
| 50 | - "inspector", | |
| 51 | - "module", | |
| 52 | - "net", | |
| 53 | - "os", | |
| 54 | - "path", | |
| 55 | - "perf_hooks", | |
| 56 | - "process", | |
| 57 | - "punycode", | |
| 58 | - "querystring", | |
| 59 | - "readline", | |
| 60 | - "sqlite", | |
| 61 | - "stream", | |
| 62 | - "string_decoder", | |
| 63 | - "timers", | |
| 64 | - "tls", | |
| 65 | - "tty", | |
| 66 | - "url", | |
| 67 | - "util", | |
| 68 | - "util/types", | |
| 69 | - "v8", | |
| 70 | - "vm", | |
| 71 | - "worker_threads", | |
| 72 | - "zlib", | |
| 73 | -]; | |
| 74 | - | |
| 75 | -/// The pending exception text from a TryCatch scope (a macro so it needs no | |
| 76 | -/// bound on the crate-private scope traits). | |
| 77 | -macro_rules! exc { | |
| 78 | - ($tc:expr) => { | |
| 79 | - $tc.exception() | |
| 80 | - .map(|e| e.to_rust_string_lossy(&*$tc)) | |
| 81 | - .unwrap_or_else(|| "<none>".into()) | |
| 82 | - }; | |
| 83 | -} | |
| 84 | - | |
| 85 | -/// A cross-node dispatch: the isolate hit `env.NS.get(id)` for a cell this node | |
| 86 | -/// does not own. The op hands this to the tokio runtime, which resolves the | |
| 87 | -/// owner and HTTP-proxies the fetch, replying on `reply` (an async oneshot the | |
| 88 | -/// async-op future awaits — the JS thread is never blocked). | |
| 89 | -pub struct DoCallReq { | |
| 90 | - pub request_id: Option<RequestId>, | |
| 91 | - pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, | |
| 92 | - /// An explicit JavaScript AbortSignal must reach the target handler, even | |
| 93 | - /// when it fires before cold routing completes. Transport cancellation has | |
| 94 | - /// no handler contract and can stop the cold route immediately. | |
| 95 | - pub deliver_abort_to_handler: bool, | |
| 96 | - pub scope: String, | |
| 97 | - pub name: Option<String>, | |
| 98 | - pub url: String, | |
| 99 | - pub method: String, | |
| 100 | - pub body: Vec<u8>, | |
| 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 | -struct Place(Option<Box<tokio::sync::oneshot::Receiver<Place>>>); | |
| 159 | - | |
| 160 | -impl CallOrder { | |
| 161 | - /// Wait for every call before this one to be delivered. | |
| 162 | - /// | |
| 163 | - /// A loop rather than one await because a call that died hands back | |
| 164 | - /// what *it* was waiting for. `Err` is the chain ahead going away | |
| 165 | - /// entirely, which is nothing left to wait for. | |
| 166 | - pub async fn wait(&mut self) { | |
| 167 | - let mut ahead = self.ahead.take(); | |
| 168 | - while let Some(place) = ahead { | |
| 169 | - ahead = match place.await { | |
| 170 | - Ok(Place(forward)) => forward.map(|boxed| *boxed), | |
| 171 | - Err(_) => None, | |
| 172 | - }; | |
| 173 | - } | |
| 174 | - } | |
| 175 | - | |
| 176 | - /// This call has been delivered; the one behind it may go. | |
| 177 | - pub fn delivered(&mut self) { | |
| 178 | - self.delivered = true; | |
| 179 | - } | |
| 180 | -} | |
| 181 | - | |
| 182 | -impl Drop for CallOrder { | |
| 183 | - fn drop(&mut self) { | |
| 184 | - // Nothing followed this call, so the chain is empty and its tail is | |
| 185 | - // only a leak. A caller's chains outlive its calls otherwise, and a | |
| 186 | - // cell isolate's default caller outlives everything. | |
| 187 | - let mut chains = self.caller.call_chains.lock().unwrap(); | |
| 188 | - if chains | |
| 189 | - .tails | |
| 190 | - .get(&self.cell) | |
| 191 | - .is_some_and(|(seq, _)| *seq == self.seq) | |
| 192 | - { | |
| 193 | - chains.tails.remove(&self.cell); | |
| 194 | - } | |
| 195 | - drop(chains); | |
| 196 | - if let Some(release) = self.release.take() { | |
| 197 | - let forward = (!self.delivered).then(|| self.ahead.take()).flatten(); | |
| 198 | - let _ = release.send(Place(forward.map(Box::new))); | |
| 199 | - } | |
| 200 | - } | |
| 201 | -} | |
| 202 | - | |
| 203 | -/// One caller's chains, one per cell it has called. | |
| 204 | -#[derive(Default)] | |
| 205 | -struct CallChains { | |
| 206 | - next_seq: u64, | |
| 207 | - tails: HashMap<String, (u64, tokio::sync::oneshot::Receiver<Place>)>, | |
| 208 | -} | |
| 209 | - | |
| 210 | -/// Take this call's place in its caller's chain for `cell`. Synchronous, so | |
| 211 | -/// the places are taken in the order the script made the calls. | |
| 212 | -fn enter_call_order(caller: Arc<IoContext>, cell: &str) -> CallOrder { | |
| 213 | - let (release, next) = tokio::sync::oneshot::channel(); | |
| 214 | - let (seq, ahead) = { | |
| 215 | - let mut chains = caller.call_chains.lock().unwrap(); | |
| 216 | - chains.next_seq += 1; | |
| 217 | - let seq = chains.next_seq; | |
| 218 | - let ahead = chains | |
| 219 | - .tails | |
| 220 | - .insert(cell.to_string(), (seq, next)) | |
| 221 | - .map(|(_, ahead)| ahead); | |
| 222 | - (seq, ahead) | |
| 223 | - }; | |
| 224 | - CallOrder { | |
| 225 | - ahead, | |
| 226 | - release: Some(release), | |
| 227 | - caller, | |
| 228 | - cell: cell.to_string(), | |
| 229 | - seq, | |
| 230 | - delivered: false, | |
| 231 | - } | |
| 232 | -} | |
| 233 | - | |
| 234 | -/// An output-gate request for the co-hosted (same-isolate) Durable Object fast | |
| 235 | -/// path. That path runs a resident DO's `fetch` inline, bypassing | |
| 236 | -/// `dispatch_do_call` where the gate lives; the inline handler samples the | |
| 237 | -/// cell's committed-write position and asks the actor whether the response can | |
| 238 | -/// leave. `position` is present for a write and absent for a read. | |
| 239 | -pub struct GateReq { | |
| 240 | - pub scope: String, | |
| 241 | - pub position: Option<u64>, | |
| 242 | - pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>, | |
| 243 | -} | |
| 244 | -static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new(); | |
| 245 | -pub fn set_gate_tx(tx: tokio::sync::mpsc::UnboundedSender<GateReq>) { | |
| 246 | - let _ = GATE_TX.set(tx); | |
| 247 | -} | |
| 248 | - | |
| 249 | -/// A service-binding call: `env.NAME.fetch()`. Unlike a Durable Object call | |
| 250 | -/// there is no identity to resolve — any isolate running `script` will do — so | |
| 251 | -/// the runtime hands this straight to that script's stateless isolate pool. | |
| 252 | -pub struct SvcCallReq { | |
| 253 | - /// Fires when the caller's request signal aborts, so the router stops | |
| 254 | - /// waiting on the target instead of leaving the call outstanding. | |
| 255 | - pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, | |
| 256 | - pub script: String, | |
| 257 | - pub url: String, | |
| 258 | - pub method: String, | |
| 259 | - pub body: Vec<u8>, | |
| 260 | - pub headers: Vec<(String, String)>, | |
| 261 | - pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 262 | -} | |
| 263 | -static SVC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcCallReq>> = OnceLock::new(); | |
| 264 | - | |
| 265 | -/// A Worker assets-binding call. The script name selects the immutable asset | |
| 266 | -/// index loaded for that Worker; unlike ingress this never falls back into the | |
| 267 | -/// Worker and therefore cannot recurse. | |
| 268 | -pub struct AssetCallReq { | |
| 269 | - pub script: String, | |
| 270 | - pub url: String, | |
| 271 | - pub method: String, | |
| 272 | - pub headers: Vec<(String, String)>, | |
| 273 | - pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 274 | -} | |
| 275 | -static ASSET_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<AssetCallReq>> = OnceLock::new(); | |
| 276 | - | |
| 277 | -/// An RPC call on a named `WorkerEntrypoint` of another script. Arguments and | |
| 278 | -/// the result cross as V8 structured-clone bytes. | |
| 279 | -pub struct SvcRpcReq { | |
| 280 | - pub script: String, | |
| 281 | - pub entrypoint: String, | |
| 282 | - pub method: String, | |
| 283 | - pub args: Vec<u8>, | |
| 284 | - pub reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>, | |
| 285 | -} | |
| 286 | -static SVC_RPC_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcRpcReq>> = OnceLock::new(); | |
| 287 | -pub fn set_svc_rpc_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcRpcReq>) { | |
| 288 | - let _ = SVC_RPC_TX.set(tx); | |
| 289 | -} | |
| 290 | -pub fn set_svc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcCallReq>) { | |
| 291 | - let _ = SVC_CALL_TX.set(tx); | |
| 292 | -} | |
| 293 | -pub fn set_asset_call_tx(tx: tokio::sync::mpsc::UnboundedSender<AssetCallReq>) { | |
| 294 | - let _ = ASSET_CALL_TX.set(tx); | |
| 295 | -} | |
| 296 | -pub fn set_do_call_tx(tx: tokio::sync::mpsc::UnboundedSender<DoCallReq>) { | |
| 297 | - let _ = DO_CALL_TX.set(tx); | |
| 298 | -} | |
| 299 | - | |
| 300 | -/// Hand a Durable Object call to the dispatcher. Public HTTP ingress uses the | |
| 301 | -/// same queue a Worker's `env.NAME.get(id).fetch()` does, so both resolve | |
| 302 | -/// ownership, forward, and redispatch by one policy rather than two. | |
| 303 | -#[must_use] | |
| 304 | -pub fn submit_do_call(call: DoCallReq) -> bool { | |
| 305 | - DO_CALL_TX.get().is_some_and(|tx| tx.send(call).is_ok()) | |
| 306 | -} | |
| 307 | - | |
| 308 | -/// The arm-time wake-entry gate, output-gate style (matching Durable | |
| 309 | -/// Objects): `setAlarm()` resolves optimistically on the committed local | |
| 310 | -/// write — it never yields the cell's event scheduling to remote I/O — and | |
| 311 | -/// the cell's response edge is withheld until every pending wake-entry PUT | |
| 312 | -/// has landed. Invariant: an arm the caller has OBSERVED acknowledged | |
| 313 | -/// (received the response) is covered by a durable entry. | |
| 314 | -pub struct ArmGate { | |
| 315 | - pub bucket: crate::bucket::Bucket, | |
| 316 | - pub flusher: Arc<crate::wake::WakeFlusher>, | |
| 317 | -} | |
| 318 | - | |
| 319 | -type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>; | |
| 320 | - | |
| 321 | -#[derive(Default)] | |
| 322 | -pub(crate) struct WakeEntryService { | |
| 323 | - gate: OnceLock<ArmGate>, | |
| 324 | - pending: Mutex<HashMap<String, Vec<ArmGateRx>>>, | |
| 325 | -} | |
| 326 | - | |
| 327 | -pub fn set_arm_gate(gate: ArmGate) { | |
| 328 | - let _ = asyncrt::services().wake_entry().gate.set(gate); | |
| 329 | -} | |
| 330 | - | |
| 331 | -/// Whether this node still holds a wake entry for `cell`. | |
| 332 | -pub fn wake_entry_tracked(cell: &str) -> bool { | |
| 333 | - asyncrt::services() | |
| 334 | - .wake_entry() | |
| 335 | - .gate | |
| 336 | - .get() | |
| 337 | - .is_some_and(|gate| gate.flusher.tracks(cell)) | |
| 338 | -} | |
| 339 | - | |
| 340 | -/// Drop this node's belief about `cell`'s wake entry — the cell fenced or | |
| 341 | -/// resolved to a remote owner, so the entry is no longer ours to manage. | |
| 342 | -/// Defined since the wake audit and now actually called (it was dead code, | |
| 343 | -/// which meant a node that lost a cell kept believing in its entry). | |
| 344 | -pub fn forget_wake_entry(cell: &str) { | |
| 345 | - let services = asyncrt::services(); | |
| 346 | - if let Some(gate) = services.wake_entry().gate.get() { | |
| 347 | - gate.flusher.forget(cell); | |
| 348 | - } | |
| 349 | -} | |
| 350 | - | |
| 351 | -/// Adopt the wake entry a restored alarm implies, so consuming that alarm | |
| 352 | -/// deletes it rather than orphaning it. | |
| 353 | -pub fn adopt_wake_entry(cell: &str, at_ms: i64) { | |
| 354 | - let services = asyncrt::services(); | |
| 355 | - if let Some(gate) = services.wake_entry().gate.get() { | |
| 356 | - gate.flusher.adopt(cell, at_ms); | |
| 357 | - } | |
| 358 | -} | |
| 359 | - | |
| 360 | -/// Bring the bucket's wake entry for `cell` into line with its alarm. | |
| 361 | -/// | |
| 362 | -/// Arming writes an entry; something has to take it away again once the alarm | |
| 363 | -/// has been consumed, or the entry outlives its alarm and every later due scan | |
| 364 | -/// finds it and wakes a cell with nothing to do. `consume_durable` gates that | |
| 365 | -/// final delete on the consuming commit being replicated -- removing the hint | |
| 366 | -/// while the commit that consumed the alarm is still only local would lose | |
| 367 | -/// both the alarm and the record that could have revived it. | |
| 368 | -pub async fn reconcile_wake_entry(cell: &str, next_alarm_ms: i64, consume_durable: bool) { | |
| 369 | - let services = asyncrt::services(); | |
| 370 | - let Some(gate) = services.wake_entry().gate.get() else { | |
| 371 | - return; | |
| 372 | - }; | |
| 373 | - gate.flusher | |
| 374 | - .reconcile(&gate.bucket, cell, next_alarm_ms, consume_durable) | |
| 375 | - .await; | |
| 376 | -} | |
| 377 | - | |
| 378 | -/// A committed alarm tightened the durable wake bound: launch the entry PUT | |
| 379 | -/// and register it against the cell's output gate. No-op when the bound | |
| 380 | -/// already covers it or no gate is configured (unit tests). | |
| 381 | -fn spawn_arm_gate(cell: &str, at_ms: i64) { | |
| 382 | - #[cfg(all(test, celld_internal_tests))] | |
| 383 | - if asyncrt::sabotage_active(crate::host_services::EngineSabotage::SkipArmTimeWakePut) { | |
| 384 | - return; | |
| 385 | - } | |
| 386 | - let services = asyncrt::services(); | |
| 387 | - let Some(gate) = services.wake_entry().gate.get() else { | |
| 388 | - return; | |
| 389 | - }; | |
| 390 | - let Some(celld_logic::wake::Op::Put { key, due_ms }) = gate.flusher.arm_op(cell, at_ms) else { | |
| 391 | - return; | |
| 392 | - }; | |
| 393 | - let cell_ = cell.to_string(); | |
| 394 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 395 | - { | |
| 396 | - let mut pending = services.wake_entry().pending.lock().unwrap(); | |
| 397 | - let gates = pending.entry(cell_.clone()).or_default(); | |
| 398 | - // Arms with no response edge to drain them (alarm handlers, | |
| 399 | - // WebSocket events) must not accumulate: drop already-settled gates. | |
| 400 | - gates.retain_mut(|gate| { | |
| 401 | - matches!( | |
| 402 | - gate.try_recv(), | |
| 403 | - Err(tokio::sync::oneshot::error::TryRecvError::Empty) | |
| 404 | - ) | |
| 405 | - }); | |
| 406 | - gates.push(rx); | |
| 407 | - } | |
| 408 | - asyncrt::spawn(async move { | |
| 409 | - let gate = services.wake_entry().gate.get().unwrap(); | |
| 410 | - // A delete of this exact key may already be on the wire — the tracked | |
| 411 | - // entry's consume-delete, or the move-delete of a key this arm is | |
| 412 | - // about to re-PUT. Either way the PUT must land after that delete, | |
| 413 | - // not race it (S3 orders concurrent same-key writes arbitrarily). | |
| 414 | - // Deletes of the cell's OTHER keys cannot touch this PUT, and waiting | |
| 415 | - // on them would hold the response behind unrelated store latency. | |
| 416 | - gate.flusher.await_key_deletable(&cell_, &key).await; | |
| 417 | - let body = format!("{{\"cell\":{cell_:?},\"due_ms\":{due_ms}}}"); | |
| 418 | - let result = gate | |
| 419 | - .bucket | |
| 420 | - .put(&key, body.into_bytes()) | |
| 421 | - .await | |
| 422 | - .map(|_| gate.flusher.confirm_arm(&cell_, due_ms, key)) | |
| 423 | - .map_err(|e| format!("setAlarm wake entry: {e}")); | |
| 424 | - let _ = tx.send(result); | |
| 425 | - }) | |
| 426 | - .detach(); | |
| 427 | -} | |
| 428 | - | |
| 429 | -#[cfg(all(test, celld_internal_tests))] | |
| 430 | -pub(crate) fn spawn_arm_gate_for_test(cell: &str, at_ms: i64) { | |
| 431 | - spawn_arm_gate(cell, at_ms); | |
| 432 | -} | |
| 433 | - | |
| 434 | -/// Await the cell's pending wake-entry PUTs — the output-gate drain a | |
| 435 | -/// response edge performs before releasing its reply. An error means an arm | |
| 436 | -/// the response would acknowledge is not durably covered; the caller must | |
| 437 | -/// fail the response rather than lie (the flusher retries the entry). | |
| 438 | -pub async fn drain_arm_gates(cell: &str) -> Result<(), String> { | |
| 439 | - let services = asyncrt::services(); | |
| 440 | - let gates = services.wake_entry().pending.lock().unwrap().remove(cell); | |
| 441 | - let Some(gates) = gates else { return Ok(()) }; | |
| 442 | - for gate in gates { | |
| 443 | - match gate.await { | |
| 444 | - Ok(Ok(())) => {} | |
| 445 | - Ok(Err(error)) => return Err(error), | |
| 446 | - Err(_) => return Err("wake-entry gate task dropped".into()), | |
| 447 | - } | |
| 448 | - } | |
| 449 | - Ok(()) | |
| 450 | -} | |
| 451 | - | |
| 452 | -pub type RequestId = u128; | |
| 453 | - | |
| 454 | -#[derive(Clone, Copy)] | |
| 455 | -pub struct FetchRequest<'a> { | |
| 456 | - pub url: &'a str, | |
| 457 | - pub method: &'a str, | |
| 458 | - pub body: &'a [u8], | |
| 459 | - pub headers: &'a [(String, String)], | |
| 460 | - pub request_id: Option<RequestId>, | |
| 461 | -} | |
| 462 | - | |
| 463 | -/// Allocate an id for an ingress or service-binding request so it can be | |
| 464 | -/// aborted mid-flight. | |
| 465 | -pub fn next_request_id() -> RequestId { | |
| 466 | - next_do_request_id() | |
| 467 | -} | |
| 468 | - | |
| 469 | -static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1); | |
| 470 | -static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new(); | |
| 471 | -static DO_CALL_CANCELS: OnceLock< | |
| 472 | - std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>>, | |
| 473 | -> = OnceLock::new(); | |
| 474 | -fn do_call_cancels( | |
| 475 | -) -> &'static std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>> { | |
| 476 | - DO_CALL_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 477 | -} | |
| 478 | - | |
| 479 | -fn next_do_request_id() -> RequestId { | |
| 480 | - let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| { | |
| 481 | - let mut bytes = [0; 8]; | |
| 482 | - getrandom::fill(&mut bytes).expect("OS random source unavailable"); | |
| 483 | - u64::from_ne_bytes(bytes) | |
| 484 | - }); | |
| 485 | - let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed); | |
| 486 | - (u128::from(prefix) << 64) | u128::from(sequence) | |
| 487 | -} | |
| 488 | - | |
| 489 | -pub fn request_id_string(request_id: RequestId) -> String { | |
| 490 | - format!("{request_id:032x}") | |
| 491 | -} | |
| 492 | - | |
| 493 | -pub fn parse_request_id(value: &str) -> Option<RequestId> { | |
| 494 | - u128::from_str_radix(value, 16).ok() | |
| 495 | -} | |
| 496 | - | |
| 497 | -struct DoCallCancelGuard(Option<RequestId>); | |
| 498 | - | |
| 499 | -impl DoCallCancelGuard { | |
| 500 | - fn new(request: RequestId) -> Self { | |
| 501 | - Self(Some(request)) | |
| 502 | - } | |
| 503 | - | |
| 504 | - fn disarm(&mut self) { | |
| 505 | - if let Some(request) = self.0.take() { | |
| 506 | - do_call_cancels().lock().unwrap().remove(&request); | |
| 507 | - } | |
| 508 | - } | |
| 509 | -} | |
| 510 | - | |
| 511 | -impl Drop for DoCallCancelGuard { | |
| 512 | - fn drop(&mut self) { | |
| 513 | - let Some(request) = self.0.take() else { | |
| 514 | - return; | |
| 515 | - }; | |
| 516 | - if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request) { | |
| 517 | - let _ = cancel.send(()); | |
| 518 | - } | |
| 519 | - } | |
| 520 | -} | |
| 521 | - | |
| 522 | -/// An RPC payload crossing the host boundary. JS stubs marshal by V8 | |
| 523 | -/// structured clone (`V8`); the legacy cross-node JSON envelope and the test | |
| 524 | -/// harness use `Json`. `__dispatchRpc` answers in the flavor it was asked in. | |
| 525 | -pub enum RpcData { | |
| 526 | - Json(String), | |
| 527 | - V8(Vec<u8>), | |
| 528 | -} | |
| 529 | - | |
| 530 | -/// A native Durable Object RPC call (`stub.someMethod(...args)`). | |
| 531 | -/// Routing/activation is identical to fetch calls. | |
| 532 | -pub struct RpcCallReq { | |
| 533 | - pub scope: String, | |
| 534 | - pub name: Option<String>, | |
| 535 | - pub method: String, | |
| 536 | - pub args: RpcData, | |
| 537 | - pub reply: tokio::sync::oneshot::Sender<Result<RpcData>>, | |
| 538 | -} | |
| 539 | -static RPC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<RpcCallReq>> = OnceLock::new(); | |
| 540 | -pub fn set_rpc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<RpcCallReq>) { | |
| 541 | - let _ = RPC_CALL_TX.set(tx); | |
| 542 | -} | |
| 543 | - | |
| 544 | -pub struct OutboundWsReq { | |
| 545 | - pub scope: String, | |
| 546 | - pub id: u64, | |
| 547 | - pub url: String, | |
| 548 | - pub protocols: Vec<String>, | |
| 549 | - /// Present for an isolate-polled (Worker) socket. Created and registered | |
| 550 | - /// on the JS thread before the request is sent, so `__ws_next` can never | |
| 551 | - /// run ahead of its own queue. | |
| 552 | - pub pull: Option<WsPullSender>, | |
| 553 | - /// Extra request headers, for the `fetch()` upgrade form. | |
| 554 | - pub headers: Vec<(String, String)>, | |
| 555 | - /// A `fetch()` upgrade wants the whole handshake outcome, including the | |
| 556 | - /// ordinary response a server that declines to upgrade sent instead. | |
| 557 | - pub want_response: bool, | |
| 558 | - /// A socket already upgraded in this process, which this request joins | |
| 559 | - /// instead of dialing `url`. It is the cell end of a Durable Object | |
| 560 | - /// subrequest whose caller kept the client end, so there is no handshake | |
| 561 | - /// to run and no connection to open: the host only has to carry frames | |
| 562 | - /// between two isolates. | |
| 563 | - pub target: Option<WsTarget>, | |
| 564 | - pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>, | |
| 565 | -} | |
| 566 | - | |
| 567 | -/// The ordinary HTTP response a server sent instead of upgrading. `fetch()` | |
| 568 | -/// returns it verbatim rather than turning it into a connection error. | |
| 569 | -pub struct DeclinedUpgrade { | |
| 570 | - pub status: u16, | |
| 571 | - pub headers: Vec<(String, String)>, | |
| 572 | - pub body: Vec<u8>, | |
| 573 | -} | |
| 574 | - | |
| 575 | -/// What an outbound handshake produced. | |
| 576 | -pub struct OutboundWsOpen { | |
| 577 | - pub protocol: Option<String>, | |
| 578 | - pub declined: Option<DeclinedUpgrade>, | |
| 579 | -} | |
| 580 | -static OUTBOUND_WS_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> = | |
| 581 | - OnceLock::new(); | |
| 582 | -pub fn set_outbound_ws_tx(tx: tokio::sync::mpsc::UnboundedSender<OutboundWsReq>) { | |
| 583 | - let _ = OUTBOUND_WS_TX.set(tx); | |
| 584 | -} | |
| 585 | - | |
| 586 | -static NEXT_TIMER_ID: AtomicU64 = AtomicU64::new(1); | |
| 587 | -static TIMER_CANCELS: OnceLock<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>> = | |
| 588 | - OnceLock::new(); | |
| 589 | -fn timer_cancels() -> &'static std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>> { | |
| 590 | - TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 591 | -} | |
| 592 | -static NEXT_HTTP_STREAM_ID: AtomicU64 = AtomicU64::new(1); | |
| 593 | -/// What `__http_stream_read` resolves with at end of stream. | |
| 594 | -/// | |
| 595 | -/// The reader identifies the end by type, not by value. A chunk always | |
| 596 | -/// resolves as a `Uint8Array`, therefore body bytes can never look like | |
| 597 | -/// this marker. The value stays distinctive, so a reader that does compare | |
| 598 | -/// the value cannot match a plausible body. | |
| 599 | -const HTTP_STREAM_DONE: &str = "__celld_http_stream_end__"; | |
| 600 | -enum HttpStreamSource { | |
| 601 | - Response(reqwest::Response), | |
| 602 | - Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>), | |
| 603 | - Stream(HttpChunkStream), | |
| 604 | -} | |
| 605 | -struct HttpStreamEntry { | |
| 606 | - created: Instant, | |
| 607 | - source: Option<HttpStreamSource>, | |
| 608 | - cancelled: tokio::sync::watch::Sender<bool>, | |
| 609 | -} | |
| 610 | -static HTTP_STREAMS: OnceLock<std::sync::Mutex<HashMap<u64, HttpStreamEntry>>> = OnceLock::new(); | |
| 611 | -fn http_streams() -> &'static std::sync::Mutex<HashMap<u64, HttpStreamEntry>> { | |
| 612 | - HTTP_STREAMS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 613 | -} | |
| 614 | -fn register_http_stream(stream_id: u64, source: HttpStreamSource) { | |
| 615 | - let (cancelled, _) = tokio::sync::watch::channel(false); | |
| 616 | - let mut streams = http_streams().lock().unwrap(); | |
| 617 | - streams.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60)); | |
| 618 | - streams.insert( | |
| 619 | - stream_id, | |
| 620 | - HttpStreamEntry { | |
| 621 | - created: Instant::now(), | |
| 622 | - source: Some(source), | |
| 623 | - cancelled, | |
| 624 | - }, | |
| 625 | - ); | |
| 626 | -} | |
| 627 | -struct ResponseStreamWriter { | |
| 628 | - created: Instant, | |
| 629 | - writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 630 | - finished: tokio::sync::watch::Sender<bool>, | |
| 631 | -} | |
| 632 | -static RESPONSE_STREAM_WRITERS: OnceLock<std::sync::Mutex<HashMap<u64, ResponseStreamWriter>>> = | |
| 633 | - OnceLock::new(); | |
| 634 | -fn response_stream_writers() -> &'static std::sync::Mutex<HashMap<u64, ResponseStreamWriter>> { | |
| 635 | - RESPONSE_STREAM_WRITERS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 636 | -} | |
| 637 | - | |
| 638 | -pub type HttpChunkStream = | |
| 639 | - Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>; | |
| 640 | - | |
| 641 | -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] | |
| 642 | -pub struct WsTarget { | |
| 643 | - pub id: u64, | |
| 644 | - pub scope: String, | |
| 645 | - #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 646 | - pub peer_node: Option<String>, | |
| 647 | - #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 648 | - pub peer_addr: Option<String>, | |
| 649 | - #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 650 | - pub peer_epoch: Option<u64>, | |
| 651 | -} | |
| 652 | - | |
| 653 | -/// Encode a host response for the JS side. A text body crosses as a | |
| 654 | -/// JS string (cheap, lossless), binary as a byte array, and a streaming body | |
| 655 | -/// by id — serializing a Vec<u8> as a JSON number array is the dominant cost | |
| 656 | -/// for real DO responses. `ws_target` is carried by the paths that can answer | |
| 657 | -/// with a WebSocket upgrade: a Durable Object call and a service-binding call. | |
| 658 | -fn encode_http_response(mut response: HttpResponse, ws_target: bool) -> String { | |
| 659 | - let mut obj = serde_json::json!({ | |
| 660 | - "status": response.status, | |
| 661 | - "headers": response.headers, | |
| 662 | - }); | |
| 663 | - if ws_target { | |
| 664 | - obj["wsTarget"] = serde_json::json!(response.ws); | |
| 665 | - } | |
| 666 | - if let Some(stream) = response.stream.take() { | |
| 667 | - let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 668 | - register_http_stream(stream_id, HttpStreamSource::Stream(stream)); | |
| 669 | - obj["streamId"] = serde_json::json!(stream_id); | |
| 670 | - } else { | |
| 671 | - match std::str::from_utf8(&response.body) { | |
| 672 | - Ok(text) => obj["body"] = serde_json::Value::String(text.into()), | |
| 673 | - Err(_) => obj["bodyBytes"] = serde_json::json!(response.body), | |
| 674 | - } | |
| 675 | - } | |
| 676 | - obj.to_string() | |
| 677 | -} | |
| 678 | - | |
| 679 | -pub struct HttpResponse { | |
| 680 | - pub status: u16, | |
| 681 | - pub body: Vec<u8>, | |
| 682 | - /// A response body forwarded without materializing it in memory. | |
| 683 | - pub stream: Option<HttpChunkStream>, | |
| 684 | - pub headers: Vec<(String, String)>, | |
| 685 | - pub ws: Option<WsTarget>, | |
| 686 | - /// The cell's committed-write position after the handler ran, for a local | |
| 687 | - /// Durable Object request. The shell gates the response on durability when | |
| 688 | - /// this advanced past the cell's last seen position. `None` for responses | |
| 689 | - /// with no cell storage (Worker, asset, or proxied remote). | |
| 690 | - pub write_position: Option<u64>, | |
| 691 | -} | |
| 692 | - | |
| 693 | -/// Which alarm a dispatch runs, and who owns its bookkeeping. | |
| 694 | -pub enum AlarmDispatch { | |
| 695 | - /// Claim whatever is due now, and record the outcome. Production only | |
| 696 | - /// ever asks for this. | |
| 697 | - Due, | |
| 698 | - /// Claim whatever is armed, however far ahead its deadline. Test-only: | |
| 699 | - /// the corpus asserts on retry accounting without waiting out real | |
| 700 | - /// deadlines. | |
| 701 | - Armed, | |
| 702 | - /// The caller has already claimed it. Dispatch with this retry count and | |
| 703 | - /// leave the bookkeeping to them. Test-only, so the corpus can assert on | |
| 704 | - /// the claim and the handler separately. | |
| 705 | - Claimed(i64), | |
| 706 | -} | |
| 707 | - | |
| 708 | -/// One event a cell receives. | |
| 709 | -/// | |
| 710 | -/// Every variant is something the outside world did to the cell, and each | |
| 711 | -/// becomes an `InFlight` entry driven by its own tokio task. Lifecycle — | |
| 712 | -/// taking a cell in, giving it back, cancelling a request — is not here: it | |
| 713 | -/// is a direct call on the isolate, because it is not an event and has no | |
| 714 | -/// handler to run. | |
| 715 | -pub enum CellJob { | |
| 716 | - Fetch { | |
| 717 | - request_id: Option<RequestId>, | |
| 718 | - scope: String, | |
| 719 | - name: Option<String>, | |
| 720 | - url: String, | |
| 721 | - method: String, | |
| 722 | - body: Vec<u8>, | |
| 723 | - headers: Vec<(String, String)>, | |
| 724 | - reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 725 | - /// Where this call sits in its caller's order for this cell, if it | |
| 726 | - /// came from a script rather than from a peer or the ingress. | |
| 727 | - order: Option<CallOrder>, | |
| 728 | - }, | |
| 729 | - Rpc { | |
| 730 | - scope: String, | |
| 731 | - name: Option<String>, | |
| 732 | - method: String, | |
| 733 | - args: RpcData, | |
| 734 | - reply: tokio::sync::oneshot::Sender<Result<RpcOutcome>>, | |
| 735 | - }, | |
| 736 | - WsOpen { | |
| 737 | - scope: String, | |
| 738 | - ws_id: u64, | |
| 739 | - protocol: String, | |
| 740 | - reply: tokio::sync::oneshot::Sender<Result<()>>, | |
| 741 | - }, | |
| 742 | - WsMessage { | |
| 743 | - scope: String, | |
| 744 | - ws_id: u64, | |
| 745 | - data: WsIn, | |
| 746 | - reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>, | |
| 747 | - }, | |
| 748 | - WsClosed { | |
| 749 | - scope: String, | |
| 750 | - ws_id: u64, | |
| 751 | - code: u16, | |
| 752 | - reason: String, | |
| 753 | - was_clean: bool, | |
| 754 | - reply: tokio::sync::oneshot::Sender<Result<()>>, | |
| 755 | - }, | |
| 756 | - Alarm { | |
| 757 | - scope: String, | |
| 758 | - scheduled_ms: i64, | |
| 759 | - /// Which alarm to run, and who owns the bookkeeping. | |
| 760 | - claim: AlarmDispatch, | |
| 761 | - /// Replies with (next alarm, the handler's write delta). The delta is | |
| 762 | - /// sampled inside the turn — cell storage must never be reached from | |
| 763 | - /// the shell — and the shell uses it to prove the consuming commit | |
| 764 | - /// durable before the core settles. Every answer shape samples it the | |
| 765 | - /// same way now, in `InFlight::answer_settled`. | |
| 766 | - reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 767 | - }, | |
| 768 | -} | |
| 769 | - | |
| 770 | -impl CellJob { | |
| 771 | - /// The cell this event addresses, which is also the realm it runs in. | |
| 772 | - pub fn scope(&self) -> &str { | |
| 773 | - match self { | |
| 774 | - CellJob::Fetch { scope, .. } | |
| 775 | - | CellJob::Rpc { scope, .. } | |
| 776 | - | CellJob::WsOpen { scope, .. } | |
| 777 | - | CellJob::WsMessage { scope, .. } | |
| 778 | - | CellJob::WsClosed { scope, .. } | |
| 779 | - | CellJob::Alarm { scope, .. } => scope, | |
| 780 | - } | |
| 781 | - } | |
| 782 | - | |
| 783 | - /// This event's place in its caller's order, taken out so the drive can | |
| 784 | - /// wait on it and then release the call behind it. | |
| 785 | - pub fn take_order(&mut self) -> Option<CallOrder> { | |
| 786 | - match self { | |
| 787 | - CellJob::Fetch { order, .. } => order.take(), | |
| 788 | - _ => None, | |
| 789 | - } | |
| 790 | - } | |
| 791 | - | |
| 792 | - /// Fail this event without running it. | |
| 793 | - pub fn fail(self, error: anyhow::Error) { | |
| 794 | - match self { | |
| 795 | - CellJob::Fetch { reply, .. } => drop(reply.send(Err(error))), | |
| 796 | - CellJob::Rpc { reply, .. } => drop(reply.send(Err(error))), | |
| 797 | - CellJob::WsOpen { reply, .. } => drop(reply.send(Err(error))), | |
| 798 | - CellJob::WsMessage { reply, .. } => drop(reply.send(Err(error))), | |
| 799 | - CellJob::WsClosed { reply, .. } => drop(reply.send(Err(error))), | |
| 800 | - CellJob::Alarm { reply, .. } => drop(reply.send(Err(error))), | |
| 801 | - } | |
| 802 | - } | |
| 803 | -} | |
| 804 | - | |
| 805 | -thread_local! { | |
| 806 | - // One outbound HTTP client per JS thread — building it per fetch rebuilds | |
| 807 | - // the TLS stack every call (async-op-hazards.md). | |
| 808 | - static HTTP: reqwest::Client = reqwest::Client::new(); | |
| 809 | - static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder() | |
| 810 | - .redirect(reqwest::redirect::Policy::none()).build().unwrap(); | |
| 811 | - static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new()); | |
| 812 | -} | |
| 813 | - | |
| 814 | -mod websocket; | |
| 815 | -pub(crate) use websocket::WebSocketService; | |
| 816 | -pub use websocket::*; | |
| 817 | -use websocket::{ws_capture_begin, ws_capture_take}; | |
| 818 | - | |
| 819 | -/// Held for the duration of one cell event; pops on every exit path. | |
| 820 | -pub struct EgressGateScope; | |
| 821 | - | |
| 822 | -impl Drop for EgressGateScope { | |
| 823 | - fn drop(&mut self) { | |
| 824 | - current_context().egress.lock().unwrap().pop(); | |
| 825 | - } | |
| 826 | -} | |
| 827 | - | |
| 828 | -pub fn egress_gate_enter(cell: &str, position: Option<u64>) -> EgressGateScope { | |
| 829 | - current_context() | |
| 830 | - .egress | |
| 831 | - .lock() | |
| 832 | - .unwrap() | |
| 833 | - .push((cell.to_string(), position.unwrap_or(0))); | |
| 834 | - EgressGateScope | |
| 835 | -} | |
| 836 | - | |
| 837 | -/// What an outbound effect must trail before it leaves the process. | |
| 838 | -/// | |
| 839 | -/// The three cases are named rather than nested inside one another because | |
| 840 | -/// two of them once shared a representation, and that is what issue #144 was: | |
| 841 | -/// a reader that starts after another request committed samples the new | |
| 842 | -/// position as its own baseline and advances nothing, so a two-state gate read | |
| 843 | -/// it as code that owns no cell at all and let its side effect out ungated. | |
| 844 | -/// A variant per case makes the distinction one the compiler keeps. | |
| 845 | -enum EgressGate { | |
| 846 | - /// No cell event is running. Stateless Worker code owns no cell state, so | |
| 847 | - /// its egress reveals nothing that can still be lost and leaves directly. | |
| 848 | - NoCell, | |
| 849 | - /// This event wrote through the position. The effect waits for that write. | |
| 850 | - Wrote(String, u64), | |
| 851 | - /// A read-only output. It reveals whatever the cell holds, so it trails | |
| 852 | - /// the newest write barrier still open on the cell. Only the core knows | |
| 853 | - /// which writes are outstanding, so this asks rather than guesses. | |
| 854 | - ReadOnly(String), | |
| 855 | -} | |
| 856 | - | |
| 857 | -impl EgressGate { | |
| 858 | - /// Whether the effect must consult the gate before it leaves. True for a | |
| 859 | - /// read as well as a write: a read whose cell has no barrier is released | |
| 860 | - /// at once, but only the core can say so. | |
| 861 | - fn is_gated(&self) -> bool { | |
| 862 | - !matches!(self, EgressGate::NoCell) | |
| 863 | - } | |
| 864 | -} | |
| 865 | - | |
| 866 | -/// Sample what the running handler's outbound effects must trail. Answers for | |
| 867 | -/// every active cell event, including a read whose core lookup can settle | |
| 868 | -/// immediately. | |
| 869 | -fn egress_gate_request() -> EgressGate { | |
| 870 | - let context = current_context(); | |
| 871 | - let stack = context.egress.lock().unwrap(); | |
| 872 | - let Some((cell, before)) = stack.last() else { | |
| 873 | - return EgressGate::NoCell; | |
| 874 | - }; | |
| 875 | - match storage::write_position(cell).filter(|position| position > before) { | |
| 876 | - Some(position) => EgressGate::Wrote(cell.clone(), position), | |
| 877 | - // A read-only output in a process that configured no output gate has | |
| 878 | - // nothing to trail. Such a process cannot acknowledge a write either | |
| 879 | - // -- `op_gate_write` refuses one for want of the same channel -- so no | |
| 880 | - // committed-but-unproven write exists for a read to reveal. Answer as | |
| 881 | - // if no cell event were running, which keeps the effect on the direct, | |
| 882 | - // synchronous path it has always taken; a WebSocket frame in | |
| 883 | - // particular must not join a deferred queue whose flush needs a gate | |
| 884 | - // to release it. A write still takes a ticket and still fails closed. | |
| 885 | - None if GATE_TX.get().is_none() => EgressGate::NoCell, | |
| 886 | - None => EgressGate::ReadOnly(cell.clone()), | |
| 887 | - } | |
| 888 | -} | |
| 889 | - | |
| 890 | -/// Wait for the writes an outbound effect can reveal to be proven durable | |
| 891 | -/// before it leaves the process. | |
| 892 | -/// | |
| 893 | -/// This is the output gate applied to egress rather than to the response. | |
| 894 | -/// It cannot deadlock the handler that is awaiting it: the ticket is served by | |
| 895 | -/// `dispatch_gate` on the host's own loop and resolved by the replicator's | |
| 896 | -/// independent task, neither of which needs the isolate's event loop to run. | |
| 897 | -/// A read-only ticket carries `None` and the core releases it at once when the | |
| 898 | -/// cell has no barrier open, so an ordinary read pays one actor hop and no | |
| 899 | -/// replica write. | |
| 900 | -async fn await_egress_gate(gate: EgressGate) -> std::result::Result<(), String> { | |
| 901 | - let (cell, position) = match gate { | |
| 902 | - EgressGate::NoCell => return Ok(()), | |
| 903 | - EgressGate::Wrote(cell, position) => (cell, Some(position)), | |
| 904 | - EgressGate::ReadOnly(cell) => (cell, None), | |
| 905 | - }; | |
| 906 | - let (tx, receive) = tokio::sync::oneshot::channel(); | |
| 907 | - let sent = GATE_TX | |
| 908 | - .get() | |
| 909 | - .map(|gate| { | |
| 910 | - gate.send(GateReq { | |
| 911 | - scope: cell, | |
| 912 | - position, | |
| 913 | - reply: tx, | |
| 914 | - }) | |
| 915 | - .is_ok() | |
| 916 | - }) | |
| 917 | - .unwrap_or(false); | |
| 918 | - if !sent { | |
| 919 | - return Err("no output-gate channel".into()); | |
| 920 | - } | |
| 921 | - match receive.await { | |
| 922 | - Ok(Ok(())) => Ok(()), | |
| 923 | - Ok(Err(error)) => Err(format!( | |
| 924 | - "refusing to send: the write this request follows is not durable ({error:?})" | |
| 925 | - )), | |
| 926 | - Err(_) => Err("output gate dropped".into()), | |
| 927 | - } | |
| 928 | -} | |
| 929 | - | |
| 930 | -/// Hold an outbound request until the write it follows is durable, then hand | |
| 931 | -/// it to the host. | |
| 932 | -/// | |
| 933 | -/// The send moves inside the future deliberately. These channels dispatch as | |
| 934 | -/// soon as `send` is called, so gating anywhere after it would let the effect | |
| 935 | -/// leave first -- the request would already be on its way while the caller | |
| 936 | -/// waited for a durability answer that no longer decides anything. | |
| 937 | -async fn gated_channel_send<T>( | |
| 938 | - gate: EgressGate, | |
| 939 | - channel: &'static OnceLock<tokio::sync::mpsc::UnboundedSender<T>>, | |
| 940 | - request: T, | |
| 941 | - missing: &'static str, | |
| 942 | -) -> std::result::Result<(), String> { | |
| 943 | - await_egress_gate(gate).await?; | |
| 944 | - match channel.get() { | |
| 945 | - Some(tx) if tx.send(request).is_ok() => Ok(()), | |
| 946 | - _ => Err(missing.to_string()), | |
| 947 | - } | |
| 948 | -} | |
| 949 | - | |
| 950 | -/// One `celld_logic::gate::InputGate` per cell. | |
| 951 | -/// | |
| 952 | -/// The logic decides; this is only the map and the ids. It replaces the | |
| 953 | -/// promise chain that used to live in `harness.js`, which serialised blocks | |
| 954 | -/// against each other but did nothing about *delivery* — so a second event | |
| 955 | -/// could arrive mid-block, and under real concurrency that wedged the cell. | |
| 956 | -/// | |
| 957 | -/// Keyed by cell scope rather than held on the isolate, because a gate | |
| 958 | -/// belongs to a cell and cells share isolates. | |
| 959 | -static CELL_GATES: OnceLock<Mutex<HashMap<String, celld_logic::gate::InputGate>>> = OnceLock::new(); | |
| 960 | -static NEXT_GATE_EVENT: AtomicU64 = AtomicU64::new(1); | |
| 961 | - | |
| 962 | -fn cell_gates() -> &'static Mutex<HashMap<String, celld_logic::gate::InputGate>> { | |
| 963 | - CELL_GATES.get_or_init(|| Mutex::new(HashMap::new())) | |
| 964 | -} | |
| 965 | - | |
| 966 | -/// What a waiting event is told when the gate finally opens: nothing, or | |
| 967 | -/// the reason the holder failed. | |
| 968 | -type GateWake = tokio::sync::oneshot::Sender<Result<(), String>>; | |
| 969 | - | |
| 970 | -static GATE_WAITERS: OnceLock<Mutex<HashMap<String, Vec<GateWake>>>> = OnceLock::new(); | |
| 971 | - | |
| 972 | -/// Events waiting for a cell's input gate to open, in arrival order. | |
| 973 | -/// | |
| 974 | -/// Step 6 deleted this queue, correctly at the time: an event the gate | |
| 975 | -/// refused stayed on the cell's job channel until a later delivery point | |
| 976 | -/// took it, so the channel *was* the queue and a second one could disagree | |
| 977 | -/// with it. Drives have no channel, so a refused event needs somewhere to | |
| 978 | -/// wait, and workerd keeps the same structure for the same reason | |
| 979 | -/// (`io-gate.h`, `kj::List<Waiter, &Waiter::link> waiters`). | |
| 980 | -/// | |
| 981 | -/// In the shell rather than in `celld_logic::gate`, because what waits is a | |
| 982 | -/// tokio task and the core is sans-IO. The core still owns the decision — | |
| 983 | -/// `is_open` — and this owns only the waking. | |
| 984 | -fn gate_waiters() -> &'static Mutex<HashMap<String, Vec<GateWake>>> { | |
| 985 | - GATE_WAITERS.get_or_init(|| Mutex::new(HashMap::new())) | |
| 986 | -} | |
| 987 | - | |
| 988 | -/// Take a ticket to be woken when `cell`'s gate opens, or `None` if it is | |
| 989 | -/// open now. | |
| 990 | -/// | |
| 991 | -/// The gate's lock is held across the check and the enqueue, so a release | |
| 992 | -/// that lands between the two cannot leave an event waiting on a gate that | |
| 993 | -/// is already open. | |
| 994 | -pub fn cell_gate_wait(cell: &str) -> Option<tokio::sync::oneshot::Receiver<Result<(), String>>> { | |
| 995 | - let gates = cell_gates().lock().unwrap(); | |
| 996 | - if gates.get(cell).is_none_or(|gate| gate.is_open()) { | |
| 997 | - return None; | |
| 998 | - } | |
| 999 | - let (wake, waiter) = tokio::sync::oneshot::channel(); | |
| 1000 | - gate_waiters() | |
| 1001 | - .lock() | |
| 1002 | - .unwrap() | |
| 1003 | - .entry(cell.to_string()) | |
| 1004 | - .or_default() | |
| 1005 | - .push(wake); | |
| 1006 | - drop(gates); | |
| 1007 | - Some(waiter) | |
| 1008 | -} | |
| 1009 | - | |
| 1010 | -/// Wake everything waiting on `cell`'s gate. Each re-checks and re-queues if | |
| 1011 | -/// another block took the gate first, so waking all of them is correct and | |
| 1012 | -/// the order they resume in is theirs to lose, not this function's to keep. | |
| 1013 | -fn wake_gate_waiters(cell: &str, outcome: Result<(), String>) { | |
| 1014 | - let waiters = gate_waiters().lock().unwrap().remove(cell); | |
| 1015 | - for wake in waiters.into_iter().flatten() { | |
| 1016 | - let _ = wake.send(outcome.clone()); | |
| 1017 | - } | |
| 1018 | -} | |
| 1019 | - | |
| 1020 | -/// The event holding this cell's gate died without releasing it. | |
| 1021 | -/// | |
| 1022 | -/// Only execution termination reaches here: every other exit from a block | |
| 1023 | -/// runs the `finally` in `harness.js`. Without it a cell whose blocking | |
| 1024 | -/// request was killed would refuse every later event forever. | |
| 1025 | -fn cell_gate_abandon(scope: &str) { | |
| 1026 | - if let Some(gate) = cell_gates().lock().unwrap().get_mut(scope) { | |
| 1027 | - gate.abandon(); | |
| 1028 | - } | |
| 1029 | - // The holder died without running its `finally`, so nobody can say why. | |
| 1030 | - // Refuse the waiters anyway: the cell it queued behind is gone. | |
| 1031 | - wake_gate_waiters( | |
| 1032 | - scope, | |
| 1033 | - Err("the cell's critical section ended without releasing".to_string()), | |
| 1034 | - ); | |
| 1035 | -} | |
| 1036 | - | |
| 1037 | -/// JS promise resolvers awaiting an async op, keyed by the op's id. | |
| 1038 | -/// | |
| 1039 | -/// **Per isolate, and shared across threads.** Under D1 a request's turns run | |
| 1040 | -/// on whichever tokio worker picks them up, so a resolver registered on one | |
| 1041 | -/// thread is resolved from another; a thread-local map loses it, and | |
| 1042 | -/// `resolve_res` fails to find the resolver and returns silently, leaving the | |
| 1043 | -/// handler awaiting a promise nothing will ever settle. The `Mutex` is what | |
| 1044 | -/// makes that safe, not the map's location. | |
| 1045 | -/// | |
| 1046 | -/// It lives on `ActorRuntimeState` — one per isolate, reached from a scope — | |
| 1047 | -/// so a resolver is only ever looked up in the heap that owns it. One map for | |
| 1048 | -/// the whole process would also work, because op ids come from a single | |
| 1049 | -/// counter (`asyncrt::NEXT_ID`) and an id names exactly one resolver. But that | |
| 1050 | -/// makes an id-allocation bug into cross-isolate handle confusion, where this | |
| 1051 | -/// makes it a miss. | |
| 1052 | -type PromiseMap = HashMap<u64, v8::Global<v8::PromiseResolver>>; | |
| 1053 | - | |
| 1054 | -/// Requests cancelled by a reentrant `AbortFetch`. Global for the same reason | |
| 1055 | -/// as [`promises`]: the turn that observes a cancellation need not be on the | |
| 1056 | -/// thread that recorded it. | |
| 1057 | -static CANCELLED_REQUESTS: OnceLock<Mutex<HashSet<RequestId>>> = OnceLock::new(); | |
| 1058 | - | |
| 1059 | -fn cancelled_requests() -> &'static Mutex<HashSet<RequestId>> { | |
| 1060 | - CANCELLED_REQUESTS.get_or_init(|| Mutex::new(HashSet::new())) | |
| 1061 | -} | |
| 1062 | - | |
| 1063 | -fn promise_store(scope: &mut v8::PinScope, id: u64, r: v8::Global<v8::PromiseResolver>) { | |
| 1064 | - actor_runtime_state(scope) | |
| 1065 | - .promises | |
| 1066 | - .lock() | |
| 1067 | - .unwrap() | |
| 1068 | - .insert(id, r); | |
| 1069 | -} | |
| 1070 | - | |
| 1071 | -/// Resolve or reject op `id`'s promise with its outcome. | |
| 1072 | -fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) { | |
| 1073 | - let g = match actor_runtime_state(tc).promises.lock().unwrap().remove(&id) { | |
| 1074 | - Some(g) => g, | |
| 1075 | - None => return, | |
| 1076 | - }; | |
| 1077 | - let r = v8::Local::new(tc, g); | |
| 1078 | - match res { | |
| 1079 | - Ok(asyncrt::OpOut::Str(v)) => { | |
| 1080 | - let s = v8::String::new(tc, &v).unwrap(); | |
| 1081 | - r.resolve(tc, s.into()); | |
| 1082 | - } | |
| 1083 | - Ok(asyncrt::OpOut::Bytes(b)) => { | |
| 1084 | - let v = bytes_value(tc, b); | |
| 1085 | - r.resolve(tc, v); | |
| 1086 | - } | |
| 1087 | - Err(e) => { | |
| 1088 | - let s = v8::String::new(tc, &e).unwrap(); | |
| 1089 | - let ex = v8::Exception::error(tc, s); | |
| 1090 | - r.reject(tc, ex); | |
| 1091 | - } | |
| 1092 | - } | |
| 1093 | -} | |
| 1094 | - | |
| 1095 | -/// Move `bytes` into a `Uint8Array` without copying. | |
| 1096 | -fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> { | |
| 1097 | - let len = bytes.len(); | |
| 1098 | - let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared(); | |
| 1099 | - let buffer = v8::ArrayBuffer::with_backing_store(scope, &store); | |
| 1100 | - v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into() | |
| 1101 | -} | |
| 1102 | - | |
| 1103 | -pub fn handler_budget() -> Duration { | |
| 1104 | - static BUDGET: OnceLock<Duration> = OnceLock::new(); | |
| 1105 | - *BUDGET.get_or_init(|| { | |
| 1106 | - Duration::from_secs( | |
| 1107 | - crate::env_vars::positive_or("CELLD_HANDLER_BUDGET_S", 300) | |
| 1108 | - .expect("validated CELLD_HANDLER_BUDGET_S"), | |
| 1109 | - ) | |
| 1110 | - }) | |
| 1111 | -} | |
| 1112 | - | |
| 1113 | -/// Aborts raised by an HTTP or service-binding caller disconnecting while the | |
| 1114 | -/// target runs in the stateless isolate pool. Durable Object aborts can also | |
| 1115 | -/// arrive as a reentrant `CellJob::AbortFetch`, so the abort has to be visible | |
| 1116 | -/// from whichever turn observes it. | |
| 1117 | -/// | |
| 1118 | -/// The counter keeps the common path to one relaxed atomic load per loop turn: | |
| 1119 | -/// with nothing pending, the mutex is never taken. | |
| 1120 | -static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> = | |
| 1121 | - OnceLock::new(); | |
| 1122 | -static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | |
| 1123 | - | |
| 1124 | -fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> { | |
| 1125 | - PENDING_ABORTS.get_or_init(Default::default) | |
| 1126 | -} | |
| 1127 | - | |
| 1128 | -/// Mark an in-flight request cancelled from any thread. | |
| 1129 | -pub fn abort_request(request_id: RequestId) { | |
| 1130 | - if pending_aborts().lock().unwrap().insert(request_id) { | |
| 1131 | - PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed); | |
| 1132 | - } | |
| 1133 | -} | |
| 1134 | - | |
| 1135 | -fn clear_request_cancellation(request_id: RequestId) { | |
| 1136 | - let _ = take_pending_abort(request_id); | |
| 1137 | -} | |
| 1138 | - | |
| 1139 | -fn take_pending_abort(request_id: RequestId) -> bool { | |
| 1140 | - if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 { | |
| 1141 | - return false; | |
| 1142 | - } | |
| 1143 | - if pending_aborts().lock().unwrap().remove(&request_id) { | |
| 1144 | - PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed); | |
| 1145 | - return true; | |
| 1146 | - } | |
| 1147 | - false | |
| 1148 | -} | |
| 1149 | - | |
| 1150 | -pub fn take_request_cancellation(request_id: Option<RequestId>) -> bool { | |
| 1151 | - request_id.is_some_and(|request_id| { | |
| 1152 | - cancelled_requests().lock().unwrap().remove(&request_id) || take_pending_abort(request_id) | |
| 1153 | - }) | |
| 1154 | -} | |
| 1155 | - | |
| 1156 | -fn resolved_promise<'s>( | |
| 1157 | - tc: &mut v8::PinScope<'s, '_>, | |
| 1158 | - value: v8::Local<'s, v8::Value>, | |
| 1159 | -) -> Result<v8::Local<'s, v8::Promise>> { | |
| 1160 | - let resolver = | |
| 1161 | - v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?; | |
| 1162 | - resolver.resolve(tc, value); | |
| 1163 | - Ok(resolver.get_promise(tc)) | |
| 1164 | -} | |
| 1165 | - | |
| 1166 | -fn abort_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) -> Result<bool> { | |
| 1167 | - let global = tc.get_current_context().global(tc); | |
| 1168 | - let key = v8::String::new(tc, "__abortIncomingRequest").unwrap(); | |
| 1169 | - let function: v8::Local<v8::Function> = global | |
| 1170 | - .get(tc, key.into()) | |
| 1171 | - .ok_or_else(|| anyhow!("no __abortIncomingRequest"))? | |
| 1172 | - .try_into() | |
| 1173 | - .map_err(|_| anyhow!("__abortIncomingRequest is not a function"))?; | |
| 1174 | - let request_id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 1175 | - let recv = v8::undefined(tc).into(); | |
| 1176 | - let result = function | |
| 1177 | - .call(tc, recv, &[request_id.into()]) | |
| 1178 | - .ok_or_else(|| anyhow!("__abortIncomingRequest threw"))?; | |
| 1179 | - Ok(result.boolean_value(tc)) | |
| 1180 | -} | |
| 1181 | - | |
| 1182 | -/// The rejection reason of a settled-rejected promise, with a little stack. | |
| 1183 | -fn reject_reason(tc: &mut v8::PinScope, p: v8::Local<v8::Promise>) -> String { | |
| 1184 | - let r = p.result(tc); | |
| 1185 | - let msg = r.to_rust_string_lossy(tc); | |
| 1186 | - let stk = r | |
| 1187 | - .to_object(tc) | |
| 1188 | - .and_then(|o| { | |
| 1189 | - let k = v8::String::new(tc, "stack")?; | |
| 1190 | - o.get(tc, k.into()) | |
| 1191 | - }) | |
| 1192 | - .map(|s| s.to_rust_string_lossy(tc)) | |
| 1193 | - .unwrap_or_default(); | |
| 1194 | - let tail = stk | |
| 1195 | - .lines() | |
| 1196 | - .skip(1) | |
| 1197 | - .take(3) | |
| 1198 | - .map(|l| l.trim()) | |
| 1199 | - .collect::<Vec<_>>() | |
| 1200 | - .join(" <- "); | |
| 1201 | - if tail.is_empty() { | |
| 1202 | - msg | |
| 1203 | - } else { | |
| 1204 | - format!("{msg} [{tail}]") | |
| 1205 | - } | |
| 1206 | -} | |
| 1207 | - | |
| 1208 | -pub struct Engine; | |
| 1209 | -impl Engine { | |
| 1210 | - pub fn init() { | |
| 1211 | - // No `v8::icu::set_common_data_78` call: the rusty_v8 152 prebuilt | |
| 1212 | - // statically links the complete ICU data (full locale tables and | |
| 1213 | - // regex property-of-strings, e.g. /\p{RGI_Emoji}/v — verified | |
| 1214 | - // empirically), so overriding it with an embedded icudtl.dat only | |
| 1215 | - // duplicated 10.8 MB in the binary. A test pins that coverage, so a | |
| 1216 | - // future v8 bump that reduces the builtin data fails rather than | |
| 1217 | - // silently narrowing it; the fix would be to re-embed rusty_v8's | |
| 1218 | - // `third_party/icu/common/icudtl.dat`, 16-byte-aligned. | |
| 1219 | - let platform = v8::new_default_platform(0, false).make_shared(); | |
| 1220 | - v8::V8::initialize_platform(platform); | |
| 1221 | - v8::V8::initialize(); | |
| 1222 | - } | |
| 1223 | -} | |
| 1224 | - | |
| 1225 | -/// Per-worker compatibility switches, derived from the manifest's | |
| 1226 | -/// compatibility date and flags (Workerd compatibility-date.capnp). `Default` | |
| 1227 | -/// is every switch off; production derives real values in `main`. | |
| 1228 | -#[derive(Clone, Copy, Default)] | |
| 1229 | -pub struct Compat { | |
| 1230 | - pub delete_all_deletes_alarm: bool, | |
| 1231 | - /// `js_rpc`: RPC on a Durable Object class that does not extend | |
| 1232 | - /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()). | |
| 1233 | - pub js_rpc: bool, | |
| 1234 | - /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`, | |
| 1235 | - /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/ | |
| 1236 | - /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher). | |
| 1237 | - pub fetcher_get_put_delete: bool, | |
| 1238 | - /// `sqlite_vec`: expose the pre-v1 sqlite-vec extension to SQLite-backed | |
| 1239 | - /// Durable Objects. This switch is explicit and has no date default. | |
| 1240 | - pub sqlite_vec: bool, | |
| 1241 | - /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and | |
| 1242 | - /// a binary message arrives as a `Blob`, per the WHATWG default. Without | |
| 1243 | - /// it celld keeps the historical `"arraybuffer"`. | |
| 1244 | - pub websocket_standard_binary_type: bool, | |
| 1245 | -} | |
| 1246 | - | |
| 1247 | -/// A non-main module the worker's main module may import, tagged by how the | |
| 1248 | -/// runtime materializes it. | |
| 1249 | -pub enum ModuleSource { | |
| 1250 | - /// UTF-8 content served as `export default "<content>"` (wrangler's Text | |
| 1251 | - /// rule), registered under the given specifier verbatim. | |
| 1252 | - Text(String), | |
| 1253 | - /// JS source compiled as a sibling ES module (Worker Loader multi-module | |
| 1254 | - /// bundles), registered under both `name` and `./name`. | |
| 1255 | - EsModule(String), | |
| 1256 | - /// Wasm bytes served as a module whose default export is the compiled | |
| 1257 | - /// `WebAssembly.Module` (Wrangler's `CompiledWasm` rule), registered | |
| 1258 | - /// under both `name` and `./name`. | |
| 1259 | - Wasm(bytes::Bytes), | |
| 1260 | -} | |
| 1261 | - | |
| 1262 | -pub struct WorkerConfig { | |
| 1263 | - src: String, | |
| 1264 | - pub script_name: String, | |
| 1265 | - do_classes: Vec<String>, | |
| 1266 | - bindings: Vec<(String, String)>, | |
| 1267 | - r2_bindings: Vec<String>, | |
| 1268 | - /// `d1_databases`: (environment name, stable database identity). The | |
| 1269 | - /// identity addresses the cell that holds the database; see [[d1]]. | |
| 1270 | - d1_bindings: Vec<(String, String)>, | |
| 1271 | - ai_binding: Option<String>, | |
| 1272 | - vars: Vec<(String, String)>, | |
| 1273 | - node: String, | |
| 1274 | - /// The worker's non-main modules, so the main module can import siblings. | |
| 1275 | - modules: Vec<(String, ModuleSource)>, | |
| 1276 | - compat: Compat, | |
| 1277 | - /// `[[services]]`: (binding name, target script, optional entrypoint). | |
| 1278 | - /// The target runs in this process; see [[service-bindings]]. | |
| 1279 | - services: Vec<(String, String, Option<String>)>, | |
| 1280 | - asset_binding: Option<String>, | |
| 1281 | - /// `env` name of the Worker Loader binding, if this Worker may spawn | |
| 1282 | - /// dynamic isolates. | |
| 1283 | - loader_binding: Option<String>, | |
| 1284 | - /// Ambient outbound authority. Loaded workers may be denied. | |
| 1285 | - egress: EgressPolicy, | |
| 1286 | - /// Extra `env` values a loaded worker was handed, as a JSON object string | |
| 1287 | - /// merged onto its `env`. Loader-only; empty for normal workers. | |
| 1288 | - loader_env: Option<String>, | |
| 1289 | - /// `triggers.crons` from the deployment. Empty for a loaded worker and for | |
| 1290 | - /// any script without cron triggers. | |
| 1291 | - pub crons: Vec<String>, | |
| 1292 | -} | |
| 1293 | - | |
| 1294 | -pub struct WorkerConfigOptions { | |
| 1295 | - pub src: String, | |
| 1296 | - pub script_name: String, | |
| 1297 | - pub do_classes: Vec<String>, | |
| 1298 | - pub bindings: Vec<(String, String)>, | |
| 1299 | - pub r2_bindings: Vec<String>, | |
| 1300 | - pub d1_bindings: Vec<(String, String)>, | |
| 1301 | - pub ai_binding: Option<String>, | |
| 1302 | - pub vars: Vec<(String, String)>, | |
| 1303 | - pub node: String, | |
| 1304 | - pub modules: Vec<(String, ModuleSource)>, | |
| 1305 | - pub compat: Compat, | |
| 1306 | -} | |
| 1307 | - | |
| 1308 | -impl WorkerConfig { | |
| 1309 | - pub fn new(options: WorkerConfigOptions) -> Self { | |
| 1310 | - let WorkerConfigOptions { | |
| 1311 | - src, | |
| 1312 | - script_name, | |
| 1313 | - do_classes, | |
| 1314 | - bindings, | |
| 1315 | - r2_bindings, | |
| 1316 | - d1_bindings, | |
| 1317 | - ai_binding, | |
| 1318 | - vars, | |
| 1319 | - node, | |
| 1320 | - modules, | |
| 1321 | - compat, | |
| 1322 | - } = options; | |
| 1323 | - Self { | |
| 1324 | - src, | |
| 1325 | - script_name, | |
| 1326 | - do_classes, | |
| 1327 | - bindings, | |
| 1328 | - r2_bindings, | |
| 1329 | - d1_bindings, | |
| 1330 | - ai_binding, | |
| 1331 | - vars, | |
| 1332 | - node, | |
| 1333 | - modules, | |
| 1334 | - compat, | |
| 1335 | - services: Vec::new(), | |
| 1336 | - asset_binding: None, | |
| 1337 | - loader_binding: None, | |
| 1338 | - egress: EgressPolicy::Allow, | |
| 1339 | - loader_env: None, | |
| 1340 | - crons: Vec::new(), | |
| 1341 | - } | |
| 1342 | - } | |
| 1343 | - | |
| 1344 | - /// Give this Worker the deployment's cron trigger expressions. | |
| 1345 | - pub fn with_crons(mut self, crons: Vec<String>) -> Self { | |
| 1346 | - self.crons = crons; | |
| 1347 | - self | |
| 1348 | - } | |
| 1349 | - | |
| 1350 | - /// Grant this Worker a Worker Loader binding at `env` name `binding`. | |
| 1351 | - pub fn with_loader(mut self, binding: Option<String>) -> Self { | |
| 1352 | - self.loader_binding = binding; | |
| 1353 | - self | |
| 1354 | - } | |
| 1355 | - | |
| 1356 | - /// Set this Worker's ambient outbound authority (loaded workers only). | |
| 1357 | - fn with_egress(mut self, egress: EgressPolicy) -> Self { | |
| 1358 | - self.egress = egress; | |
| 1359 | - self | |
| 1360 | - } | |
| 1361 | - | |
| 1362 | - /// Merge `env` (a JSON object string) onto a loaded worker's `env`. | |
| 1363 | - fn with_loader_env(mut self, env: Option<String>) -> Self { | |
| 1364 | - self.loader_env = env; | |
| 1365 | - self | |
| 1366 | - } | |
| 1367 | - | |
| 1368 | - /// Declare the service bindings this Worker may call. | |
| 1369 | - pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self { | |
| 1370 | - self.services = services; | |
| 1371 | - self | |
| 1372 | - } | |
| 1373 | - | |
| 1374 | - pub fn with_asset_binding(mut self, binding: Option<String>) -> Self { | |
| 1375 | - self.asset_binding = binding; | |
| 1376 | - self | |
| 1377 | - } | |
| 1378 | -} | |
| 1379 | - | |
| 1380 | -pub struct Worker { | |
| 1381 | - inner: Option<WorkerIsolate>, | |
| 1382 | -} | |
| 1383 | - | |
| 1384 | -pub struct WorkerIsolate { | |
| 1385 | - /// Shared rather than owned: under D1 an isolate belongs to no thread, | |
| 1386 | - /// and a worker enters it by taking its `v8::Locker`. | |
| 1387 | - /// | |
| 1388 | - /// Every `lock()` below blocks until the current holder releases. That is | |
| 1389 | - /// only safe because the pool takes an async permit for this isolate | |
| 1390 | - /// first, so the lock is uncontended by construction; a `lock()` reached | |
| 1391 | - /// without that permit would be a blocking call on a tokio worker. | |
| 1392 | - isolate: v8::SharedIsolate, | |
| 1393 | - /// The one realm this isolate has: its context, and the entry `fetch` | |
| 1394 | - /// that lives in it. | |
| 1395 | - /// | |
| 1396 | - /// It was a `HashMap` keyed by cell, on the premise that a cell needs a | |
| 1397 | - /// realm of its own. It does not, and nothing ever put a second one in. | |
| 1398 | - /// The harness already keys instances by scope (`__cell.instances`), and | |
| 1399 | - /// Durable Objects **share** a context per script rather than getting one | |
| 1400 | - /// each — a context per cell would also duplicate the compiled module per | |
| 1401 | - /// cell, which is most of what sharing an isolate saves. | |
| 1402 | - realm: Realm, | |
| 1403 | - original_heap_limit: usize, | |
| 1404 | - compat: Compat, | |
| 1405 | - /// The storage of the cells this isolate hosts. | |
| 1406 | - /// | |
| 1407 | - /// It lives here, and not in a thread-local, because a driven cell's | |
| 1408 | - /// turns run on whatever tokio worker holds the isolate. See | |
| 1409 | - /// `storage::Cells`. | |
| 1410 | - cells: storage::Cells, | |
| 1411 | -} | |
| 1412 | - | |
| 1413 | -/// An isolate's context and the entry `fetch` that lives in it. | |
| 1414 | -/// | |
| 1415 | -/// `fetch` is here rather than beside the isolate because a function is a | |
| 1416 | -/// value in the realm that created it. | |
| 1417 | -struct Realm { | |
| 1418 | - context: v8::Global<v8::Context>, | |
| 1419 | - fetch: v8::Global<v8::Function>, | |
| 1420 | -} | |
| 1421 | - | |
| 1422 | -impl WorkerIsolate { | |
| 1423 | - /// Take the isolate for one turn, and make the cells it hosts reachable | |
| 1424 | - /// while it is held. | |
| 1425 | - /// | |
| 1426 | - /// The two belong together. The lock is what makes this thread the only | |
| 1427 | - /// one that can touch the isolate, and a cell's SQLite handles are part | |
| 1428 | - /// of what it may touch — so a locker taken without installing them | |
| 1429 | - /// would let a turn reach no storage at all, or another isolate's. | |
| 1430 | - /// Pairing them here is why no call site has to remember. | |
| 1431 | - fn lock(&self) -> (v8::Locker<'_>, storage::Installed) { | |
| 1432 | - (self.isolate.lock(), self.cells.install()) | |
| 1433 | - } | |
| 1434 | - | |
| 1435 | - /// Lift condemnation from an isolate whose heap has drained. | |
| 1436 | - /// | |
| 1437 | - /// `near_heap_limit` latches a flag that nothing used to clear, so a cell | |
| 1438 | - /// that reached its limit once stayed condemned until the process | |
| 1439 | - /// restarted. The flag is re-read here, between turns rather than inside | |
| 1440 | - /// one, because a handler must not see the isolate recover halfway | |
| 1441 | - /// through. | |
| 1442 | - /// | |
| 1443 | - /// A heap still over the line buys one `low_memory_notification` and a | |
| 1444 | - /// second reading. V8 stops collecting once it is past the limit, so a | |
| 1445 | - /// drained isolate holds the dead heap until something allocates again — | |
| 1446 | - /// without the forced collection the reading that decides recovery is a | |
| 1447 | - /// reading of garbage. `HEAP_GC_NUDGE_INTERVAL` bounds the cost. | |
| 1448 | - /// | |
| 1449 | - /// Removing the callback with the original limit puts back the limit | |
| 1450 | - /// `near_heap_limit` raised; re-adding it re-arms the guard. | |
| 1451 | - fn recover_heap(&self, locker: &mut v8::Locker<'_>) { | |
| 1452 | - let Some(state) = locker.get_slot::<Arc<HeapLimitState>>().cloned() else { | |
| 1453 | - return; | |
| 1454 | - }; | |
| 1455 | - if !state.excessively_exceeded.load(Ordering::Relaxed) { | |
| 1456 | - return; | |
| 1457 | - } | |
| 1458 | - if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE { | |
| 1459 | - if !state.due_for_gc_nudge() { | |
| 1460 | - return; | |
| 1461 | - } | |
| 1462 | - locker.low_memory_notification(); | |
| 1463 | - if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE { | |
| 1464 | - return; | |
| 1465 | - } | |
| 1466 | - } | |
| 1467 | - state.excessively_exceeded.store(false, Ordering::Relaxed); | |
| 1468 | - let data = Arc::as_ptr(&state) as *mut HeapLimitState as *mut std::ffi::c_void; | |
| 1469 | - locker.remove_near_heap_limit_callback(near_heap_limit, state.limit); | |
| 1470 | - locker.add_near_heap_limit_callback(near_heap_limit, data); | |
| 1471 | - tracing::info!( | |
| 1472 | - event = "isolate_heap_recovered", | |
| 1473 | - limit_bytes = state.limit, | |
| 1474 | - "isolate heap fell back under its limit, so it serves again" | |
| 1475 | - ); | |
| 1476 | - } | |
| 1477 | - | |
| 1478 | - /// Localise the realm for one turn. | |
| 1479 | - /// | |
| 1480 | - /// **Taking the scope is the point.** Reaching a realm means touching | |
| 1481 | - /// `Global` handles, which on a shared isolate is only legal while its | |
| 1482 | - /// `Locker` is held — and there is no scope to pass until the isolate is | |
| 1483 | - /// locked. So the requirement is structural rather than a comment asking | |
| 1484 | - /// callers to remember it. It was a comment, and the one call site that | |
| 1485 | - /// forgot cloned two `Global`s a line too early; the panic happened | |
| 1486 | - /// inside a spawned request task, where tokio swallowed it and it | |
| 1487 | - /// surfaced only as a poisoned mutex on every later request. | |
| 1488 | - fn realm<'s>(&self, hs: &mut v8::PinScope<'s, '_, ()>) -> Entered<'s> { | |
| 1489 | - Entered { | |
| 1490 | - context: v8::Local::new(hs, &self.realm.context), | |
| 1491 | - fetch: v8::Local::new(hs, &self.realm.fetch), | |
| 1492 | - } | |
| 1493 | - } | |
| 1494 | -} | |
| 1495 | - | |
| 1496 | -/// One realm, entered. Valid only for the scope that produced it, which is | |
| 1497 | -/// what ties it to the isolate being locked. | |
| 1498 | -struct Entered<'s> { | |
| 1499 | - context: v8::Local<'s, v8::Context>, | |
| 1500 | - fetch: v8::Local<'s, v8::Function>, | |
| 1501 | -} | |
| 1502 | - | |
| 1503 | -impl std::ops::Deref for Worker { | |
| 1504 | - type Target = WorkerIsolate; | |
| 1505 | - | |
| 1506 | - fn deref(&self) -> &Self::Target { | |
| 1507 | - self.inner.as_ref().expect("Worker isolate unavailable") | |
| 1508 | - } | |
| 1509 | -} | |
| 1510 | - | |
| 1511 | -impl std::ops::DerefMut for Worker { | |
| 1512 | - fn deref_mut(&mut self) -> &mut Self::Target { | |
| 1513 | - self.inner.as_mut().expect("Worker isolate unavailable") | |
| 1514 | - } | |
| 1515 | -} | |
| 1516 | - | |
| 1517 | -const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024; | |
| 1518 | -const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024; | |
| 1519 | - | |
| 1520 | -/// Share of the heap limit past which an isolate takes on no more retained | |
| 1521 | -/// state. It sits below the near-limit callback on purpose: this refuses one | |
| 1522 | -/// hibernatable socket while the isolate still works, where the callback | |
| 1523 | -/// fires once it no longer does. | |
| 1524 | -const HEAP_ADMISSION_SHARE: f64 = 0.9; | |
| 1525 | - | |
| 1526 | -/// Share of the heap limit under which a condemned isolate is condemned no | |
| 1527 | -/// more. Under `HEAP_ADMISSION_SHARE` by enough that recovery does not | |
| 1528 | -/// immediately re-admit into a heap that is about to fail again. | |
| 1529 | -const HEAP_RECOVERY_SHARE: f64 = 0.75; | |
| 1530 | - | |
| 1531 | -/// The shortest gap between two collections forced by `recover_heap`. A full | |
| 1532 | -/// collection of a 128 MB heap costs tens of milliseconds and a loaded cell | |
| 1533 | -/// begins many turns each second, so an unbounded nudge would spend more of a | |
| 1534 | -/// condemned isolate on collecting than on serving. | |
| 1535 | -const HEAP_GC_NUDGE_INTERVAL: Duration = Duration::from_secs(1); | |
| 1536 | - | |
| 1537 | -struct HeapLimitState { | |
| 1538 | - excessively_exceeded: AtomicBool, | |
| 1539 | - /// The limit V8 gave this isolate, before any emergency extension. | |
| 1540 | - /// Recovery measures against this one because `near_heap_limit` raises | |
| 1541 | - /// the current one. | |
| 1542 | - limit: usize, | |
| 1543 | - last_gc_nudge: Mutex<Option<Instant>>, | |
| 1544 | - /// Test-only: a real heap over the admission share is unreachable from a | |
| 1545 | - /// test, and the condemnation flag cannot stand in for it because | |
| 1546 | - /// recovery clears that one at the next turn. | |
| 1547 | - #[cfg(all(test, celld_internal_tests))] | |
| 1548 | - forced_admission_refusal: AtomicBool, | |
| 1549 | -} | |
| 1550 | - | |
| 1551 | -impl HeapLimitState { | |
| 1552 | - /// Whether a condemned isolate can pay for another forced collection. | |
| 1553 | - /// | |
| 1554 | - /// Rate-limited rather than once for each condemnation: the load can | |
| 1555 | - /// still be live at the first reading and gone by the second, so a | |
| 1556 | - /// one-shot nudge would leave the cell condemned exactly as before. | |
| 1557 | - fn due_for_gc_nudge(&self) -> bool { | |
| 1558 | - let Ok(mut last) = self.last_gc_nudge.lock() else { | |
| 1559 | - return false; | |
| 1560 | - }; | |
| 1561 | - let now = Instant::now(); | |
| 1562 | - if last.is_some_and(|at| now.duration_since(at) < HEAP_GC_NUDGE_INTERVAL) { | |
| 1563 | - return false; | |
| 1564 | - } | |
| 1565 | - *last = Some(now); | |
| 1566 | - true | |
| 1567 | - } | |
| 1568 | -} | |
| 1569 | - | |
| 1570 | -#[cfg(all(test, celld_internal_tests))] | |
| 1571 | -fn admission_refusal_forced(state: &HeapLimitState) -> bool { | |
| 1572 | - state.forced_admission_refusal.load(Ordering::Relaxed) | |
| 1573 | -} | |
| 1574 | - | |
| 1575 | -#[cfg(not(all(test, celld_internal_tests)))] | |
| 1576 | -fn admission_refusal_forced(_state: &HeapLimitState) -> bool { | |
| 1577 | - false | |
| 1578 | -} | |
| 1579 | - | |
| 1580 | -type SerializedPut = (String, Vec<u8>); | |
| 1581 | -type PendingPuts = HashMap<String, Vec<SerializedPut>>; | |
| 1582 | - | |
| 1583 | -/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a | |
| 1584 | -/// Worker Loader can hand a loaded worker `Deny` (globalOutbound: null) so its | |
| 1585 | -/// global `fetch()` throws and it must reach the world through `env` | |
| 1586 | -/// capabilities. | |
| 1587 | -#[derive(Clone, Copy, Default, PartialEq)] | |
| 1588 | -enum EgressPolicy { | |
| 1589 | - #[default] | |
| 1590 | - Allow, | |
| 1591 | - Deny, | |
| 1592 | -} | |
| 1593 | - | |
| 1594 | -#[derive(Default)] | |
| 1595 | -struct ActorRuntimeState { | |
| 1596 | - promises: std::sync::Mutex<PromiseMap>, | |
| 1597 | - termination: std::sync::Mutex<Option<ExecutionTermination>>, | |
| 1598 | - pending_puts: std::sync::Mutex<PendingPuts>, | |
| 1599 | - egress: EgressPolicy, | |
| 1600 | -} | |
| 1601 | - | |
| 1602 | -struct ExecutionTermination { | |
| 1603 | - error: String, | |
| 1604 | - actor_scope: Option<String>, | |
| 1605 | -} | |
| 1606 | - | |
| 1607 | -fn finish_terminated_actor_event(scope: &mut v8::PinScope, actor_scope: &str) { | |
| 1608 | - // The one exit from a block that runs no JS, so the `finally` in | |
| 1609 | - // harness.js never releases. Leave it and the cell refuses everything | |
| 1610 | - // from here on. | |
| 1611 | - cell_gate_abandon(actor_scope); | |
| 1612 | - let global = scope.get_current_context().global(scope); | |
| 1613 | - let key = v8::String::new(scope, "__endTerminatedActorEvent").unwrap(); | |
| 1614 | - let Some(value) = global.get(scope, key.into()) else { | |
| 1615 | - return; | |
| 1616 | - }; | |
| 1617 | - let Ok(function) = v8::Local::<v8::Function>::try_from(value) else { | |
| 1618 | - return; | |
| 1619 | - }; | |
| 1620 | - let actor_scope = v8::String::new(scope, actor_scope).unwrap(); | |
| 1621 | - let recv = v8::undefined(scope).into(); | |
| 1622 | - let _ = function.call(scope, recv, &[actor_scope.into()]); | |
| 1623 | -} | |
| 1624 | - | |
| 1625 | -/// Compile and run a JS expression that evaluates to a function. | |
| 1626 | -fn compile_fn<'s>( | |
| 1627 | - scope: &mut v8::PinScope<'s, '_>, | |
| 1628 | - src: &str, | |
| 1629 | -) -> Result<v8::Local<'s, v8::Function>> { | |
| 1630 | - let code = v8::String::new(scope, src).unwrap(); | |
| 1631 | - let script = | |
| 1632 | - v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compile shim: {src}"))?; | |
| 1633 | - let value = script | |
| 1634 | - .run(scope) | |
| 1635 | - .ok_or_else(|| anyhow!("run shim: {src}"))?; | |
| 1636 | - value | |
| 1637 | - .try_into() | |
| 1638 | - .map_err(|_| anyhow!("shim is not a function: {src}")) | |
| 1639 | -} | |
| 1640 | - | |
| 1641 | -/// Whether `register_entrypoints` put `name` in the `__cell.<registry>` | |
| 1642 | -/// object (e.g. `entrypoints`, `doExports`). | |
| 1643 | -fn cell_registry_has(scope: &mut v8::PinScope, registry: &str, name: &str) -> Result<bool> { | |
| 1644 | - let context = scope.get_current_context(); | |
| 1645 | - let global = context.global(scope); | |
| 1646 | - let cell_key = v8::String::new(scope, "__cell").unwrap(); | |
| 1647 | - let registry_key = v8::String::new(scope, registry).unwrap(); | |
| 1648 | - let registry_obj = global | |
| 1649 | - .get(scope, cell_key.into()) | |
| 1650 | - .and_then(|value| value.to_object(scope)) | |
| 1651 | - .and_then(|cell| cell.get(scope, registry_key.into())) | |
| 1652 | - .and_then(|value| value.to_object(scope)) | |
| 1653 | - .ok_or_else(|| anyhow!("missing __cell.{registry} registry"))?; | |
| 1654 | - let name_key = v8::String::new(scope, name).unwrap(); | |
| 1655 | - Ok(registry_obj | |
| 1656 | - .has_own_property(scope, name_key.into()) | |
| 1657 | - .unwrap_or(false)) | |
| 1658 | -} | |
| 1659 | - | |
| 1660 | -fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> { | |
| 1661 | - let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned(); | |
| 1662 | - let termination = state.and_then(|state| state.termination.lock().ok()?.take()); | |
| 1663 | - let is_terminating = scope.is_execution_terminating(); | |
| 1664 | - if termination.is_some() || is_terminating { | |
| 1665 | - scope.cancel_terminate_execution(); | |
| 1666 | - } | |
| 1667 | - if let Some(termination) = termination { | |
| 1668 | - if let Some(actor_scope) = termination.actor_scope { | |
| 1669 | - finish_terminated_actor_event(scope, &actor_scope); | |
| 1670 | - } | |
| 1671 | - return Some(anyhow!(termination.error)); | |
| 1672 | - } | |
| 1673 | - is_terminating.then(|| anyhow!("JavaScript execution was terminated")) | |
| 1674 | -} | |
| 1675 | - | |
| 1676 | -extern "C" fn near_heap_limit( | |
| 1677 | - data: *mut std::ffi::c_void, | |
| 1678 | - current_heap_limit: usize, | |
| 1679 | - _initial_heap_limit: usize, | |
| 1680 | -) -> usize { | |
| 1681 | - // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop | |
| 1682 | - // removes this callback before the isolate (and its slots) are destroyed. | |
| 1683 | - let state = unsafe { &*(data as *const HeapLimitState) }; | |
| 1684 | - state.excessively_exceeded.store(true, Ordering::Relaxed); | |
| 1685 | - // V8 fatally aborts the process if a near-limit callback does not extend | |
| 1686 | - // the limit. This reserve lets JS observe condemnation and unwind. | |
| 1687 | - // | |
| 1688 | - // The extension must also cover one allocation as large as the limit | |
| 1689 | - // itself: flattening a 128 MiB cons string asks V8 for a single 128 MiB | |
| 1690 | - // block, and V8 re-invokes this callback across last-resort GC rounds | |
| 1691 | - // only unreliably (under parallel load it often stops after one round | |
| 1692 | - // and aborts the process). Doubling the original limit makes the first | |
| 1693 | - // invocation sufficient on its own; `recover_heap` and `Drop` still | |
| 1694 | - // restore the original limit, so nothing else changes. | |
| 1695 | - current_heap_limit | |
| 1696 | - .saturating_add(V8_HEAP_EMERGENCY_BYTES) | |
| 1697 | - .max(state.limit.saturating_mul(2)) | |
| 1698 | -} | |
| 1699 | - | |
| 1700 | -/// Live heap use, as a share of `limit`. | |
| 1701 | -fn heap_share(isolate: &mut v8::Isolate, limit: usize) -> f64 { | |
| 1702 | - if limit == 0 { | |
| 1703 | - return 0.0; | |
| 1704 | - } | |
| 1705 | - isolate.get_heap_statistics().used_heap_size() as f64 / limit as f64 | |
| 1706 | -} | |
| 1707 | - | |
| 1708 | -fn v8_heap_limit_bytes() -> usize { | |
| 1709 | - crate::env_vars::positive::<usize>("CELLD_V8_HEAP_LIMIT_MB") | |
| 1710 | - .expect("validated CELLD_V8_HEAP_LIMIT_MB") | |
| 1711 | - .map(|megabytes| { | |
| 1712 | - megabytes | |
| 1713 | - .checked_mul(1024 * 1024) | |
| 1714 | - .expect("validated CELLD_V8_HEAP_LIMIT_MB range") | |
| 1715 | - }) | |
| 1716 | - .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES) | |
| 1717 | -} | |
| 1718 | - | |
| 1719 | -impl Drop for WorkerIsolate { | |
| 1720 | - fn drop(&mut self) { | |
| 1721 | - let limit = self.original_heap_limit; | |
| 1722 | - let (mut locker, _cells) = self.lock(); | |
| 1723 | - locker.remove_near_heap_limit_callback(near_heap_limit, limit); | |
| 1724 | - } | |
| 1725 | -} | |
| 1726 | - | |
| 1727 | -/// One in-flight request inside a shared isolate. | |
| 1728 | -/// | |
| 1729 | -/// Owned by the request's own tokio task, which is why every field is | |
| 1730 | -/// `Send`: the task suspends between turns and can resume on any worker, | |
| 1731 | -/// then re-enters the isolate it is affiliated with. | |
| 1732 | -/// Where a finished handler's result goes, and in what shape. | |
| 1733 | -/// | |
| 1734 | -/// A fetch answers an `HttpResponse` and an entrypoint RPC answers bytes. | |
| 1735 | -/// Everything between — the turn loop, the op region, cancellation, the | |
| 1736 | -/// budget — is identical, so the difference lives here rather than in two | |
| 1737 | -/// copies of `drive`. | |
| 1738 | -pub enum Answer { | |
| 1739 | - Fetch(tokio::sync::oneshot::Sender<Result<HttpResponse>>), | |
| 1740 | - Rpc(tokio::sync::oneshot::Sender<Result<Vec<u8>>>), | |
| 1741 | - /// A DO method call, which answers a value rather than a response. | |
| 1742 | - CellRpc(tokio::sync::oneshot::Sender<Result<RpcOutcome>>), | |
| 1743 | - /// A `webSocketMessage`, which answers the frames the output gate held | |
| 1744 | - /// and the write they are gated on. | |
| 1745 | - WsMessage(tokio::sync::oneshot::Sender<Result<WsDispatch>>), | |
| 1746 | - /// An event whose result is that it finished: `webSocketOpen`, | |
| 1747 | - /// `webSocketClose`. | |
| 1748 | - Ack(tokio::sync::oneshot::Sender<Result<()>>), | |
| 1749 | - /// An alarm, which answers whatever alarm the handler left armed. | |
| 1750 | - Alarm(tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>), | |
| 1751 | -} | |
| 1752 | - | |
| 1753 | -impl Answer { | |
| 1754 | - /// Send an error, whichever shape the caller is waiting for. | |
| 1755 | - fn fail(self, error: anyhow::Error) { | |
| 1756 | - match self { | |
| 1757 | - Answer::Fetch(reply) => drop(reply.send(Err(error))), | |
| 1758 | - Answer::Rpc(reply) => drop(reply.send(Err(error))), | |
| 1759 | - Answer::CellRpc(reply) => drop(reply.send(Err(error))), | |
| 1760 | - Answer::WsMessage(reply) => drop(reply.send(Err(error))), | |
| 1761 | - Answer::Ack(reply) => drop(reply.send(Err(error))), | |
| 1762 | - Answer::Alarm(reply) => drop(reply.send(Err(error))), | |
| 1763 | - } | |
| 1764 | - } | |
| 1765 | -} | |
| 1766 | - | |
| 1767 | -pub struct InFlight { | |
| 1768 | - /// The handler's promise. A `Global` because it outlives the turn that | |
| 1769 | - /// created it: Locals never cross a turn, exactly as workerd's | |
| 1770 | - /// `Worker::Lock` never does. | |
| 1771 | - promise: v8::Global<v8::Promise>, | |
| 1772 | - context: Arc<IoContext>, | |
| 1773 | - /// The cell this event belongs to, and `None` for stateless work. | |
| 1774 | - /// | |
| 1775 | - /// It is what the storage-shaped parts of settling — the durability | |
| 1776 | - /// position, a fatal SQL error — are read against. | |
| 1777 | - scope: Option<String>, | |
| 1778 | - /// The cell's committed-write position before the handler ran. | |
| 1779 | - /// | |
| 1780 | - /// The answer carries a write position only if the handler advanced it, | |
| 1781 | - /// so the output gate sees a write this event made and ignores celld's | |
| 1782 | - /// own activation writes (the actor name, alarm bookkeeping). | |
| 1783 | - writes_before: Option<u64>, | |
| 1784 | - request_id: Option<RequestId>, | |
| 1785 | - active_request_id: Option<RequestId>, | |
| 1786 | - reply: Option<Answer>, | |
| 1787 | - /// `waitUntil` work still running after the response was sent. The | |
| 1788 | - /// request stays in flight until it settles, as the single-request loop | |
| 1789 | - /// keeps driving it. | |
| 1790 | - background: Option<v8::Global<v8::Promise>>, | |
| 1791 | - /// Ops this request is waiting on, so a completion can be attributed to | |
| 1792 | - /// the request whose context must be current while its continuation runs. | |
| 1793 | - ops: std::collections::HashSet<u64>, | |
| 1794 | - /// The alarm bookkeeping this entry still owes, if it is one. | |
| 1795 | - alarm: Option<AlarmClaim>, | |
| 1796 | - started: Instant, | |
| 1797 | - /// The sampled trace this entry records into, `None` when telemetry | |
| 1798 | - /// is off or the trace was not sampled. Installed into the isolate's | |
| 1799 | - /// CPED slot for every turn, so promise continuations carry it. | |
| 1800 | - trace: Option<crate::telemetry::TraceIds>, | |
| 1801 | - /// Why a handler that did not finish failed, captured for the span's | |
| 1802 | - /// `error` so a query sees the reason, not only that it failed. Set | |
| 1803 | - /// only when a trace is sampled. | |
| 1804 | - failure: Option<String>, | |
| 1805 | - /// The isolate this entry's ops belong to, so `abandon` can drop their | |
| 1806 | - /// resolvers without a scope to reach the isolate through. | |
| 1807 | - runtime_state: Arc<ActorRuntimeState>, | |
| 1808 | -} | |
| 1809 | - | |
| 1810 | -impl InFlight { | |
| 1811 | - /// Read the handler's settled value in the shape this entry answers, end | |
| 1812 | - /// the event, and reply. | |
| 1813 | - /// | |
| 1814 | - /// Every shape ends the event exactly once, whether it produced a value | |
| 1815 | - /// or an error — ending it is what yields the `waitUntil` work the entry | |
| 1816 | - /// keeps driving afterwards, and a shape that skipped it on the error | |
| 1817 | - /// path would leave the context open. | |
| 1818 | - fn answer_settled<'s>( | |
| 1819 | - &mut self, | |
| 1820 | - tc: &mut v8::PinScope<'s, '_>, | |
| 1821 | - value: v8::Local<'s, v8::Value>, | |
| 1822 | - ) { | |
| 1823 | - let Some(reply) = self.reply.take() else { | |
| 1824 | - return; | |
| 1825 | - }; | |
| 1826 | - // A cell whose SQL failed fatally cannot answer whatever the handler | |
| 1827 | - // returned: the storage the handler read may not be what the cell | |
| 1828 | - // has. | |
| 1829 | - if let Some(error) = self.scope.as_deref().and_then(storage::sql_critical_error) { | |
| 1830 | - let _ = end_event_context(tc); | |
| 1831 | - if self.trace.is_some() { | |
| 1832 | - self.failure = Some(crate::telemetry::cap_error(error.to_string())); | |
| 1833 | - } | |
| 1834 | - reply.fail(anyhow!(error)); | |
| 1835 | - return; | |
| 1836 | - } | |
| 1837 | - self.background = match reply { | |
| 1838 | - Answer::Fetch(reply) => { | |
| 1839 | - let read = read_response(tc, value).map(|mut response| { | |
| 1840 | - response.write_position = self.write_delta(); | |
| 1841 | - response | |
| 1842 | - }); | |
| 1843 | - send_and_end(tc, reply, read) | |
| 1844 | - } | |
| 1845 | - Answer::Rpc(reply) => { | |
| 1846 | - let read = | |
| 1847 | - view_bytes(value).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes")); | |
| 1848 | - send_and_end(tc, reply, read) | |
| 1849 | - } | |
| 1850 | - Answer::CellRpc(reply) => { | |
| 1851 | - let outcome = RpcOutcome { | |
| 1852 | - data: rpc_data_ret(tc, value), | |
| 1853 | - write_position: self.write_delta(), | |
| 1854 | - }; | |
| 1855 | - send_and_end(tc, reply, Ok(outcome)) | |
| 1856 | - } | |
| 1857 | - Answer::WsMessage(reply) => { | |
| 1858 | - let dispatch = WsDispatch { | |
| 1859 | - frames: ws_capture_take(), | |
| 1860 | - write_position: self.write_delta(), | |
| 1861 | - }; | |
| 1862 | - send_and_end(tc, reply, Ok(dispatch)) | |
| 1863 | - } | |
| 1864 | - Answer::Ack(reply) => send_and_end(tc, reply, Ok(())), | |
| 1865 | - Answer::Alarm(reply) => { | |
| 1866 | - // The handler ran and returned, so close the claim as a | |
| 1867 | - // success. This is the only path that does: every other | |
| 1868 | - // `settle_alarm` call site records a failure, and without | |
| 1869 | - // this one a *successful* alarm was recorded as one to | |
| 1870 | - // retry — which re-armed it forever, kept the cell busy, | |
| 1871 | - // and meant an eviction waiting for the cell to go quiet | |
| 1872 | - // never got its turn. | |
| 1873 | - self.settle_alarm(true, false); | |
| 1874 | - // Read what stands *after* that cleanup, and take the delta | |
| 1875 | - // last so it covers the cleanup's own commit — which is the | |
| 1876 | - // write the core must prove durable before it settles the | |
| 1877 | - // alarm. | |
| 1878 | - let alarm = self | |
| 1879 | - .scope | |
| 1880 | - .as_deref() | |
| 1881 | - .map(storage::get_alarm) | |
| 1882 | - .unwrap_or(None); | |
| 1883 | - send_and_end(tc, reply, Ok((alarm, self.write_delta()))) | |
| 1884 | - } | |
| 1885 | - }; | |
| 1886 | - } | |
| 1887 | - | |
| 1888 | - /// The write position to gate this answer on: `None` unless the handler | |
| 1889 | - /// advanced the cell's committed writes past where they were. | |
| 1890 | - fn write_delta(&self) -> Option<u64> { | |
| 1891 | - write_delta( | |
| 1892 | - self.writes_before, | |
| 1893 | - self.scope.as_deref().and_then(storage::write_position), | |
| 1894 | - ) | |
| 1895 | - } | |
| 1896 | - | |
| 1897 | - /// Fail whichever shape is waiting, without knowing which. | |
| 1898 | - /// | |
| 1899 | - /// An alarm that fails here failed for a reason that is not the | |
| 1900 | - /// handler's — a budget overrun, a disconnect — so it does not count | |
| 1901 | - /// against the retry limit. A handler that threw is recorded by | |
| 1902 | - /// `settle`, which knows that it did, before it reaches this. | |
| 1903 | - fn fail(&mut self, error: anyhow::Error) { | |
| 1904 | - if let Some(reply) = self.reply.take() { | |
| 1905 | - self.settle_alarm(false, false); | |
| 1906 | - if self.trace.is_some() { | |
| 1907 | - self.failure = Some(crate::telemetry::cap_error(error.to_string())); | |
| 1908 | - } | |
| 1909 | - reply.fail(error); | |
| 1910 | - } | |
| 1911 | - } | |
| 1912 | - | |
| 1913 | - /// Record how a claimed alarm ended. Runs once; later calls do nothing. | |
| 1914 | - fn settle_alarm(&mut self, ok: bool, counts_against_limit: bool) { | |
| 1915 | - let (Some(scope), Some(claim)) = (self.scope.as_deref(), self.alarm.take()) else { | |
| 1916 | - return; | |
| 1917 | - }; | |
| 1918 | - if ok { | |
| 1919 | - storage::finish_alarm_handler(scope, true, claim.now_ms); | |
| 1920 | - } else { | |
| 1921 | - storage::finish_alarm_handler_with_retry_policy( | |
| 1922 | - scope, | |
| 1923 | - false, | |
| 1924 | - claim.now_ms, | |
| 1925 | - counts_against_limit, | |
| 1926 | - ); | |
| 1927 | - } | |
| 1928 | - } | |
| 1929 | - | |
| 1930 | - /// Whether a claimed alarm's outcome is still unrecorded. True only | |
| 1931 | - /// where the event ended without ever entering the isolate again. | |
| 1932 | - pub fn owes_alarm(&self) -> bool { | |
| 1933 | - self.alarm.is_some() | |
| 1934 | - } | |
| 1935 | - | |
| 1936 | - /// Done when the response has been sent and nothing is left running. | |
| 1937 | - pub fn finished(&self) -> bool { | |
| 1938 | - self.reply.is_none() && self.background.is_none() && self.ops.is_empty() | |
| 1939 | - } | |
| 1940 | - | |
| 1941 | - /// Why the handler failed, when a sampled trace captured it. | |
| 1942 | - pub fn failure(&self) -> Option<&str> { | |
| 1943 | - self.failure.as_deref() | |
| 1944 | - } | |
| 1945 | - | |
| 1946 | - /// How long this handler may still run, or `None` once it has answered. | |
| 1947 | - /// | |
| 1948 | - /// The budget bounds the *response*, not the request: `waitUntil` work | |
| 1949 | - /// continues after the client has been served and is not charged for the | |
| 1950 | - /// time the handler already spent. | |
| 1951 | - pub fn remaining(&self, budget: Duration) -> Option<Duration> { | |
| 1952 | - self.reply | |
| 1953 | - .is_some() | |
| 1954 | - .then(|| budget.saturating_sub(self.started.elapsed())) | |
| 1955 | - } | |
| 1956 | - | |
| 1957 | - /// Give up on a handler that will not settle. | |
| 1958 | - pub fn time_out(&mut self, budget: Duration) { | |
| 1959 | - self.fail(anyhow!("handler exceeded {}s budget", budget.as_secs())); | |
| 1960 | - } | |
| 1961 | - | |
| 1962 | - /// Nothing this request awaits can move it, so it will never settle on | |
| 1963 | - /// its own. Reachable when a handler awaits a promise only some *other* | |
| 1964 | - /// request could resolve — which the pump concealed, because it settled | |
| 1965 | - /// every entry on every turn whoever the turn belonged to. | |
| 1966 | - pub fn stuck(&mut self) { | |
| 1967 | - self.fail(anyhow!("handler is waiting on nothing")); | |
| 1968 | - self.background = None; | |
| 1969 | - } | |
| 1970 | - | |
| 1971 | - /// Has the client been answered? `waitUntil` work can still be running. | |
| 1972 | - pub fn answered(&self) -> bool { | |
| 1973 | - self.reply.is_none() | |
| 1974 | - } | |
| 1975 | - | |
| 1976 | - /// Whether a client can still disconnect from this request. A request | |
| 1977 | - /// with no id is internal and has no client to hang up. | |
| 1978 | - pub fn cancellable(&self) -> bool { | |
| 1979 | - self.reply.is_some() && self.request_id.is_some() | |
| 1980 | - } | |
| 1981 | - | |
| 1982 | - pub fn request_id(&self) -> Option<RequestId> { | |
| 1983 | - self.request_id | |
| 1984 | - } | |
| 1985 | - | |
| 1986 | - /// The request is over and its remaining ops are being dropped. Purge | |
| 1987 | - /// their resolvers. | |
| 1988 | - /// | |
| 1989 | - /// An op that never completes would otherwise leave its | |
| 1990 | - /// `Global<PromiseResolver>` in the isolate's map for as long as the | |
| 1991 | - /// isolate lives. A request that drives itself has to purge them on its | |
| 1992 | - /// own way out. | |
| 1993 | - pub fn abandon(&mut self) { | |
| 1994 | - if self.ops.is_empty() { | |
| 1995 | - return; | |
| 1996 | - } | |
| 1997 | - let mut promises = self.runtime_state.promises.lock().unwrap(); | |
| 1998 | - for id in self.ops.drain() { | |
| 1999 | - promises.remove(&id); | |
| 2000 | - } | |
| 2001 | - } | |
| 2002 | -} | |
| 2003 | - | |
| 2004 | -/// The CPED slot carries two riders in one immutable record: the | |
| 2005 | -/// harness's async-context frame (`__als_get`/`__als_set` — ALS and | |
| 2006 | -/// request-context confinement) and telemetry's trace context. Each | |
| 2007 | -/// write builds a fresh two-element array preserving the other rider, | |
| 2008 | -/// so V8's per-reaction snapshots restore both atomically and neither | |
| 2009 | -/// feature can stomp the other — the collision the trace-join test | |
| 2010 | -/// caught when telemetry first took the whole slot. | |
| 2011 | -/// | |
| 2012 | -/// The empty state stays *empty*: when both riders are absent the slot | |
| 2013 | -/// is undefined, which V8 fast-paths, and "off is structural" holds. | |
| 2014 | -fn cped_parts<'s>( | |
| 2015 | - scope: &mut v8::PinScope<'s, '_>, | |
| 2016 | -) -> (v8::Local<'s, v8::Value>, v8::Local<'s, v8::Value>) { | |
| 2017 | - let data = scope.get_continuation_preserved_embedder_data(); | |
| 2018 | - if let Ok(record) = v8::Local::<v8::Array>::try_from(data) { | |
| 2019 | - if record.length() == 2 { | |
| 2020 | - let undefined = v8::undefined(scope).into(); | |
| 2021 | - return ( | |
| 2022 | - record.get_index(scope, 0).unwrap_or(undefined), | |
| 2023 | - record.get_index(scope, 1).unwrap_or(undefined), | |
| 2024 | - ); | |
| 2025 | - } | |
| 2026 | - } | |
| 2027 | - // Any non-record value is a bare frame from before this scheme, or | |
| 2028 | - // the empty slot. | |
| 2029 | - (data, v8::undefined(scope).into()) | |
| 2030 | -} | |
| 2031 | - | |
| 2032 | -fn cped_frame<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { | |
| 2033 | - cped_parts(scope).0 | |
| 2034 | -} | |
| 2035 | - | |
| 2036 | -fn cped_trace<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { | |
| 2037 | - cped_parts(scope).1 | |
| 2038 | -} | |
| 2039 | - | |
| 2040 | -fn set_cped(scope: &mut v8::PinScope, frame: v8::Local<v8::Value>, trace: v8::Local<v8::Value>) { | |
| 2041 | - if frame.is_undefined() && trace.is_undefined() { | |
| 2042 | - let undefined = v8::undefined(scope).into(); | |
| 2043 | - scope.set_continuation_preserved_embedder_data(undefined); | |
| 2044 | - return; | |
| 2045 | - } | |
| 2046 | - let record = v8::Array::new(scope, 2); | |
| 2047 | - record.set_index(scope, 0, frame); | |
| 2048 | - record.set_index(scope, 1, trace); | |
| 2049 | - scope.set_continuation_preserved_embedder_data(record.into()); | |
| 2050 | -} | |
| 2051 | - | |
| 2052 | -/// Install a trace context into the isolate's CPED slot for one turn. | |
| 2053 | -/// | |
| 2054 | -/// V8 snapshots continuation-preserved embedder data when a promise | |
| 2055 | -/// reaction is registered and restores it while the reaction runs. That | |
| 2056 | -/// is the exactness `console.log` correlation needs: a continuation | |
| 2057 | -/// belonging to a *different* entry that runs during this turn's | |
| 2058 | -/// microtask checkpoint carries its own context, not this turn's. The | |
| 2059 | -/// layout is 16 trace-id bytes then 8 span-id bytes in one 24-byte | |
| 2060 | -/// ArrayBuffer, fresh per turn — cheap at sampled rates, and nothing | |
| 2061 | -/// outlives V8's own snapshots. | |
| 2062 | -/// | |
| 2063 | -/// Returns the previous slot value *only when something was installed*; | |
| 2064 | -/// the caller restores it before releasing the isolate. An untraced | |
| 2065 | -/// turn touches CPED not at all — every traced turn restores what it | |
| 2066 | -/// found, so the ambient slot between turns is always empty, and "off | |
| 2067 | -/// is structural" stays true at the V8 boundary too (the -13% the | |
| 2068 | -/// always-read version cost at 1% sampling was measured, not guessed). | |
| 2069 | -fn install_trace<'s>( | |
| 2070 | - scope: &mut v8::PinScope<'s, '_>, | |
| 2071 | - trace: Option<&crate::telemetry::TraceIds>, | |
| 2072 | -) -> Option<v8::Local<'s, v8::Value>> { | |
| 2073 | - let ids = trace?; | |
| 2074 | - let previous = scope.get_continuation_preserved_embedder_data(); | |
| 2075 | - let buffer = v8::ArrayBuffer::new(scope, 24); | |
| 2076 | - let data = buffer.get_backing_store().data()?; | |
| 2077 | - let bytes = data.as_ptr() as *mut u8; | |
| 2078 | - // SAFETY: a freshly created 24-byte buffer, written before any JS | |
| 2079 | - // can see it. | |
| 2080 | - unsafe { | |
| 2081 | - std::ptr::copy_nonoverlapping(ids.trace_id.as_ptr(), bytes, 16); | |
| 2082 | - std::ptr::copy_nonoverlapping(ids.span_id.as_ptr(), bytes.add(16), 8); | |
| 2083 | - } | |
| 2084 | - let frame = cped_frame(scope); | |
| 2085 | - set_cped(scope, frame, buffer.into()); | |
| 2086 | - Some(previous) | |
| 2087 | -} | |
| 2088 | - | |
| 2089 | -fn restore_trace(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) { | |
| 2090 | - if let Some(previous) = previous { | |
| 2091 | - scope.set_continuation_preserved_embedder_data(previous); | |
| 2092 | - } | |
| 2093 | -} | |
| 2094 | - | |
| 2095 | -/// The trace context current at this exact point of JS execution, read | |
| 2096 | -/// from CPED — the running turn's, or the running continuation's if V8 | |
| 2097 | -/// restored one. `None` when telemetry is off, the trace was unsampled, | |
| 2098 | -/// or execution is outside any entry. | |
| 2099 | -pub(crate) fn current_trace_ids(scope: &mut v8::PinScope) -> Option<crate::telemetry::TraceIds> { | |
| 2100 | - if !crate::telemetry::active() { | |
| 2101 | - return None; | |
| 2102 | - } | |
| 2103 | - let data = cped_trace(scope); | |
| 2104 | - let buffer = v8::Local::<v8::ArrayBuffer>::try_from(data).ok()?; | |
| 2105 | - if buffer.byte_length() != 24 { | |
| 2106 | - return None; | |
| 2107 | - } | |
| 2108 | - let data = buffer.get_backing_store().data()?; | |
| 2109 | - let bytes = data.as_ptr() as *const u8; | |
| 2110 | - let mut trace_id = [0u8; 16]; | |
| 2111 | - let mut span_id = [0u8; 8]; | |
| 2112 | - // SAFETY: length checked; the buffer is alive for this scope. | |
| 2113 | - unsafe { | |
| 2114 | - std::ptr::copy_nonoverlapping(bytes, trace_id.as_mut_ptr(), 16); | |
| 2115 | - std::ptr::copy_nonoverlapping(bytes.add(16), span_id.as_mut_ptr(), 8); | |
| 2116 | - } | |
| 2117 | - Some(crate::telemetry::TraceIds { trace_id, span_id }) | |
| 2118 | -} | |
| 2119 | - | |
| 2120 | -/// The isolate, entered for one turn. Everything a request does to a shared | |
| 2121 | -/// isolate goes through one of these, and none of them may be held across an | |
| 2122 | -/// await: the caller takes the pool's async permit first, runs a turn, and | |
| 2123 | -/// leaves. | |
| 2124 | -impl Worker { | |
| 2125 | - /// Run a request's first turn. | |
| 2126 | - /// | |
| 2127 | - /// Returns what is now in flight — `None` when nothing is, the reply | |
| 2128 | - /// already carrying the error — and the ops the handler enqueued, which | |
| 2129 | - /// the caller awaits with no isolate held. | |
| 2130 | - pub fn turn_begin( | |
| 2131 | - &mut self, | |
| 2132 | - job: crate::WorkerJob, | |
| 2133 | - trace: Option<crate::telemetry::TraceIds>, | |
| 2134 | - ) -> (Option<InFlight>, Vec<Op>) { | |
| 2135 | - let Some(inner) = self.inner.as_mut() else { | |
| 2136 | - return (None, Vec::new()); | |
| 2137 | - }; | |
| 2138 | - let (mut locker, _cells) = inner.lock(); | |
| 2139 | - inner.recover_heap(&mut locker); | |
| 2140 | - v8::scope!(let hs, &mut *locker); | |
| 2141 | - let realm = inner.realm(hs); | |
| 2142 | - let context = realm.context; | |
| 2143 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 2144 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 2145 | - let tc = &mut tc.init(); | |
| 2146 | - | |
| 2147 | - let previous = install_trace(tc, trace.as_ref()); | |
| 2148 | - let out = match begin(tc, realm.fetch, job) { | |
| 2149 | - Begun::Running(mut entry) => { | |
| 2150 | - entry.trace = trace; | |
| 2151 | - // A handler that returned an already-resolved promise is | |
| 2152 | - // finished before it ever suspends, and must not wait for an | |
| 2153 | - // op it will never start. | |
| 2154 | - let ops = finish_turn(tc, &mut entry); | |
| 2155 | - (Some(*entry), ops) | |
| 2156 | - } | |
| 2157 | - Begun::Threw(answer) => { | |
| 2158 | - answer.fail(anyhow!("fetch threw: {}", exc!(tc))); | |
| 2159 | - (None, Vec::new()) | |
| 2160 | - } | |
| 2161 | - Begun::Nothing => (None, Vec::new()), | |
| 2162 | - }; | |
| 2163 | - restore_trace(tc, previous); | |
| 2164 | - out | |
| 2165 | - } | |
| 2166 | - | |
| 2167 | - /// Enter the isolate solely to end a request whose client has hung up. | |
| 2168 | - /// | |
| 2169 | - /// A suspended request notices the disconnect without any isolate — the | |
| 2170 | - /// flag is host state — so this is reached only when it has actually | |
| 2171 | - /// fired, rather than on a timer as the blocking run loop did. | |
| 2172 | - pub fn turn_cancel(&mut self, entry: &mut InFlight) -> Vec<Op> { | |
| 2173 | - let Some(inner) = self.inner.as_mut() else { | |
| 2174 | - return Vec::new(); | |
| 2175 | - }; | |
| 2176 | - let (mut locker, _cells) = inner.lock(); | |
| 2177 | - v8::scope!(let hs, &mut *locker); | |
| 2178 | - let realm = inner.realm(hs); | |
| 2179 | - let context = realm.context; | |
| 2180 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 2181 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 2182 | - let tc = &mut tc.init(); | |
| 2183 | - | |
| 2184 | - let previous = install_trace(tc, entry.trace.as_ref()); | |
| 2185 | - cancel(tc, entry); | |
| 2186 | - let ops = finish_turn(tc, entry); | |
| 2187 | - restore_trace(tc, previous); | |
| 2188 | - ops | |
| 2189 | - } | |
| 2190 | - | |
| 2191 | - /// Run a later turn: resolve one of this request's ops, drain the | |
| 2192 | - /// microtasks that follow, and answer if the handler settled. | |
| 2193 | - pub fn turn_deliver( | |
| 2194 | - &mut self, | |
| 2195 | - entry: &mut InFlight, | |
| 2196 | - op: u64, | |
| 2197 | - res: Result<asyncrt::OpOut, String>, | |
| 2198 | - ) -> Vec<Op> { | |
| 2199 | - let Some(inner) = self.inner.as_mut() else { | |
| 2200 | - return Vec::new(); | |
| 2201 | - }; | |
| 2202 | - let (mut locker, _cells) = inner.lock(); | |
| 2203 | - v8::scope!(let hs, &mut *locker); | |
| 2204 | - let realm = inner.realm(hs); | |
| 2205 | - let context = realm.context; | |
| 2206 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 2207 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 2208 | - let tc = &mut tc.init(); | |
| 2209 | - | |
| 2210 | - let previous = install_trace(tc, entry.trace.as_ref()); | |
| 2211 | - deliver(tc, entry, op, res); | |
| 2212 | - cancelled(tc, entry); | |
| 2213 | - let ops = finish_turn(tc, entry); | |
| 2214 | - restore_trace(tc, previous); | |
| 2215 | - ops | |
| 2216 | - } | |
| 2217 | -} | |
| 2218 | - | |
| 2219 | -/// Close a turn, whatever the turn did. | |
| 2220 | -/// | |
| 2221 | -/// Every step earns its place and the order is the whole point: | |
| 2222 | -/// | |
| 2223 | -/// 1. **settle** — the handler's promise may have resolved, so marshal the | |
| 2224 | -/// response and answer. Marshalling can start a JS-to-host body pump and | |
| 2225 | -/// register it with `waitUntil`. | |
| 2226 | -/// 2. **checkpoint** — that pump's native ops exist only once the microtasks | |
| 2227 | -/// which create them run. | |
| 2228 | -/// 3. **settle again** — the checkpoint may itself have settled the promise, | |
| 2229 | -/// or the `waitUntil` aggregate. | |
| 2230 | -/// 4. **adopt** — only now is the set of ops this request waits on complete. | |
| 2231 | -/// | |
| 2232 | -/// Draining before step 2 is the bug that made a streaming handler answer | |
| 2233 | -/// with nothing outstanding and conclude it was waiting on nothing. | |
| 2234 | -/// The checkpoint before adoption is what makes response-body pumps visible. | |
| 2235 | -fn finish_turn(tc: &mut v8::PinScope, entry: &mut InFlight) -> Vec<Op> { | |
| 2236 | - settle(tc, entry); | |
| 2237 | - tc.perform_microtask_checkpoint(); | |
| 2238 | - // `abort()` and `process.exit()` terminate execution without settling | |
| 2239 | - // the handler's promise, so an entry that only watched the promise would | |
| 2240 | - // wait on it forever and then report that it was waiting on nothing. | |
| 2241 | - // The blocking loop broke out of its loop here; an entry fails here. | |
| 2242 | - if let Some(error) = take_execution_termination(tc) { | |
| 2243 | - entry.fail(error); | |
| 2244 | - entry.background = None; | |
| 2245 | - entry.abandon(); | |
| 2246 | - return Vec::new(); | |
| 2247 | - } | |
| 2248 | - settle(tc, entry); | |
| 2249 | - adopt(entry) | |
| 2250 | -} | |
| 2251 | - | |
| 2252 | -/// An op the JS enqueued, and the id whose promise it resolves. | |
| 2253 | -pub type Op = (u64, asyncrt::OpFuture); | |
| 2254 | - | |
| 2255 | -/// Take the ops this turn enqueued, recording them as the request's own. | |
| 2256 | -/// | |
| 2257 | -/// Drained after `settle`, not before: ending an event runs JS, and anything | |
| 2258 | -/// that starts there belongs to this request too. The pump drained first and | |
| 2259 | -/// so could attribute those to whichever entry it settled next. | |
| 2260 | -fn adopt(entry: &mut InFlight) -> Vec<Op> { | |
| 2261 | - let spawns = asyncrt::drain_spawns(); | |
| 2262 | - for (id, _) in &spawns { | |
| 2263 | - entry.ops.insert(*id); | |
| 2264 | - } | |
| 2265 | - spawns | |
| 2266 | -} | |
| 2267 | - | |
| 2268 | -/// What starting a request produced. | |
| 2269 | -enum Begun { | |
| 2270 | - /// In flight. Its ops must be adopted and its promise driven. | |
| 2271 | - Running(Box<InFlight>), | |
| 2272 | - /// The handler threw before it could suspend, so nothing is in flight. | |
| 2273 | - /// The exception belongs to the caller's `TryCatch` — an unnameable type | |
| 2274 | - /// no signature here can take — so the caller reads it and answers. | |
| 2275 | - Threw(Answer), | |
| 2276 | - /// Nothing started: the job was not a fetch, or the reply already | |
| 2277 | - /// carries the error. | |
| 2278 | - Nothing, | |
| 2279 | -} | |
| 2280 | - | |
| 2281 | -/// Start a request: build it, call the Worker's `fetch`, and hand back what | |
| 2282 | -/// is now in flight. | |
| 2283 | -/// | |
| 2284 | -/// The half of a turn that runs *before* anything can suspend. | |
| 2285 | -fn begin<'s>( | |
| 2286 | - tc: &mut v8::PinScope<'s, '_>, | |
| 2287 | - fetch: v8::Local<'s, v8::Function>, | |
| 2288 | - job: crate::WorkerJob, | |
| 2289 | -) -> Begun { | |
| 2290 | - let job = match job { | |
| 2291 | - crate::WorkerJob::Rpc { | |
| 2292 | - entrypoint, | |
| 2293 | - method, | |
| 2294 | - args, | |
| 2295 | - reply, | |
| 2296 | - } => return begin_entrypoint_rpc(tc, &entrypoint, &method, args, reply), | |
| 2297 | - job => job, | |
| 2298 | - }; | |
| 2299 | - let crate::WorkerJob::Fetch { | |
| 2300 | - url, | |
| 2301 | - method, | |
| 2302 | - body, | |
| 2303 | - headers, | |
| 2304 | - request_id, | |
| 2305 | - reply, | |
| 2306 | - .. | |
| 2307 | - } = job | |
| 2308 | - else { | |
| 2309 | - return Begun::Nothing; | |
| 2310 | - }; | |
| 2311 | - | |
| 2312 | - let context = IoContext::new(); | |
| 2313 | - let guard = CurrentGuard::enter(context.clone()); | |
| 2314 | - let started = start_fetch(tc, fetch, &url, &method, &body, &headers, request_id); | |
| 2315 | - let promise = match started { | |
| 2316 | - Ok(Started::Running(ret, active)) => match ret.try_cast::<v8::Promise>() { | |
| 2317 | - Ok(promise) => Ok((promise, active)), | |
| 2318 | - Err(_) => resolved_promise(tc, ret).map(|promise| (promise, active)), | |
| 2319 | - }, | |
| 2320 | - Ok(Started::Threw) => { | |
| 2321 | - drop(guard); | |
| 2322 | - return Begun::Threw(Answer::Fetch(reply)); | |
| 2323 | - } | |
| 2324 | - Err(error) => Err(error), | |
| 2325 | - }; | |
| 2326 | - match promise { | |
| 2327 | - Ok((promise, active_request_id)) => { | |
| 2328 | - tc.perform_microtask_checkpoint(); | |
| 2329 | - let entry = InFlight { | |
| 2330 | - runtime_state: actor_runtime_state(tc), | |
| 2331 | - promise: v8::Global::new(tc, promise), | |
| 2332 | - context, | |
| 2333 | - scope: None, | |
| 2334 | - writes_before: None, | |
| 2335 | - request_id, | |
| 2336 | - active_request_id, | |
| 2337 | - reply: Some(Answer::Fetch(reply)), | |
| 2338 | - background: None, | |
| 2339 | - ops: std::collections::HashSet::new(), | |
| 2340 | - alarm: None, | |
| 2341 | - started: Instant::now(), | |
| 2342 | - trace: None, | |
| 2343 | - failure: None, | |
| 2344 | - }; | |
| 2345 | - drop(guard); | |
| 2346 | - Begun::Running(Box::new(entry)) | |
| 2347 | - } | |
| 2348 | - Err(error) => { | |
| 2349 | - drop(guard); | |
| 2350 | - let _ = reply.send(Err(error)); | |
| 2351 | - Begun::Nothing | |
| 2352 | - } | |
| 2353 | - } | |
| 2354 | -} | |
| 2355 | - | |
| 2356 | -/// Start an entrypoint RPC's first turn. | |
| 2357 | -/// | |
| 2358 | -/// The same shape as a fetch and deliberately so: call the handler, keep the | |
| 2359 | -/// promise, and let `drive` pump it with no isolate held across the awaits. | |
| 2360 | -/// The old dispatcher blocked until the promise settled, which is why RPC | |
| 2361 | -/// needed a thread of its own and why `WorkerPool` outlived the fetch path. | |
| 2362 | -fn begin_entrypoint_rpc( | |
| 2363 | - tc: &mut v8::PinScope, | |
| 2364 | - entrypoint: &str, | |
| 2365 | - method: &str, | |
| 2366 | - args: Vec<u8>, | |
| 2367 | - reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>, | |
| 2368 | -) -> Begun { | |
| 2369 | - let context = IoContext::new(); | |
| 2370 | - let guard = CurrentGuard::enter(context.clone()); | |
| 2371 | - let global = tc.get_current_context().global(tc); | |
| 2372 | - let started = (|| { | |
| 2373 | - let key = v8::String::new(tc, "__dispatchEntrypointRpc").unwrap(); | |
| 2374 | - let f: v8::Local<v8::Function> = global | |
| 2375 | - .get(tc, key.into()) | |
| 2376 | - .ok_or_else(|| anyhow!("no __dispatchEntrypointRpc"))? | |
| 2377 | - .try_into() | |
| 2378 | - .map_err(|_| anyhow!("__dispatchEntrypointRpc is not a function"))?; | |
| 2379 | - let entrypoint = v8::String::new(tc, entrypoint).unwrap(); | |
| 2380 | - let method = v8::String::new(tc, method).unwrap(); | |
| 2381 | - let args = bytes_value(tc, args); | |
| 2382 | - let recv = v8::undefined(tc).into(); | |
| 2383 | - begin_event_context(tc)?; | |
| 2384 | - let ret = f | |
| 2385 | - .call(tc, recv, &[entrypoint.into(), method.into(), args]) | |
| 2386 | - .ok_or_else(|| anyhow!("entrypoint RPC threw"))?; | |
| 2387 | - match ret.try_cast::<v8::Promise>() { | |
| 2388 | - Ok(promise) => Ok(promise), | |
| 2389 | - Err(_) => resolved_promise(tc, ret), | |
| 2390 | - } | |
| 2391 | - })(); | |
| 2392 | - match started { | |
| 2393 | - Ok(promise) => { | |
| 2394 | - tc.perform_microtask_checkpoint(); | |
| 2395 | - let entry = InFlight { | |
| 2396 | - runtime_state: actor_runtime_state(tc), | |
| 2397 | - promise: v8::Global::new(tc, promise), | |
| 2398 | - context, | |
| 2399 | - scope: None, | |
| 2400 | - writes_before: None, | |
| 2401 | - request_id: None, | |
| 2402 | - active_request_id: None, | |
| 2403 | - reply: Some(Answer::Rpc(reply)), | |
| 2404 | - background: None, | |
| 2405 | - ops: std::collections::HashSet::new(), | |
| 2406 | - alarm: None, | |
| 2407 | - started: Instant::now(), | |
| 2408 | - trace: None, | |
| 2409 | - failure: None, | |
| 2410 | - }; | |
| 2411 | - drop(guard); | |
| 2412 | - Begun::Running(Box::new(entry)) | |
| 2413 | - } | |
| 2414 | - Err(error) => { | |
| 2415 | - let _ = end_event_context(tc); | |
| 2416 | - drop(guard); | |
| 2417 | - let _ = reply.send(Err(error)); | |
| 2418 | - Begun::Nothing | |
| 2419 | - } | |
| 2420 | - } | |
| 2421 | -} | |
| 2422 | - | |
| 2423 | -/// for the JSON flavor, a `Uint8Array` for structured clone. | |
| 2424 | -fn rpc_data_value<'s>(scope: &mut v8::PinScope<'s, '_>, data: RpcData) -> v8::Local<'s, v8::Value> { | |
| 2425 | - match data { | |
| 2426 | - RpcData::Json(json) => v8::String::new(scope, &json).unwrap().into(), | |
| 2427 | - RpcData::V8(bytes) => bytes_value(scope, bytes), | |
| 2428 | - } | |
| 2429 | -} | |
| 2430 | - | |
| 2431 | -/// The inverse: `__dispatchRpc` answers in the flavor it was asked in. | |
| 2432 | -fn rpc_data_ret(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> RpcData { | |
| 2433 | - match view_bytes(ret) { | |
| 2434 | - Some(bytes) => RpcData::V8(bytes), | |
| 2435 | - None => RpcData::Json(ret.to_rust_string_lossy(scope)), | |
| 2436 | - } | |
| 2437 | -} | |
| 2438 | - | |
| 2439 | -fn unix_now_ms() -> i64 { | |
| 2440 | - std::time::SystemTime::now() | |
| 2441 | - .duration_since(std::time::UNIX_EPOCH) | |
| 2442 | - .unwrap_or_default() | |
| 2443 | - .as_millis() | |
| 2444 | - .min(i64::MAX as u128) as i64 | |
| 2445 | -} | |
| 2446 | - | |
| 2447 | -/// End the event, then answer with what the handler produced. | |
| 2448 | -/// | |
| 2449 | -/// Ending it is what yields the `waitUntil` aggregate the entry keeps | |
| 2450 | -/// driving after the caller has been served, so it happens for every answer | |
| 2451 | -/// shape and on the error path too. | |
| 2452 | -fn send_and_end<T>( | |
| 2453 | - tc: &mut v8::PinScope, | |
| 2454 | - reply: tokio::sync::oneshot::Sender<Result<T>>, | |
| 2455 | - value: Result<T>, | |
| 2456 | -) -> Option<v8::Global<v8::Promise>> { | |
| 2457 | - let background = end_event_context(tc).ok().flatten(); | |
| 2458 | - let _ = reply.send(value); | |
| 2459 | - background.map(|promise| v8::Global::new(tc, promise)) | |
| 2460 | -} | |
| 2461 | - | |
| 2462 | -/// A committed-write position only counts when the handler advanced it; celld's | |
| 2463 | -/// own activation writes are already below `before`. | |
| 2464 | -pub(crate) fn write_delta(before: Option<u64>, after: Option<u64>) -> Option<u64> { | |
| 2465 | - match (before, after) { | |
| 2466 | - (Some(before), Some(after)) if after > before => Some(after), | |
| 2467 | - _ => None, | |
| 2468 | - } | |
| 2469 | -} | |
| 2470 | - | |
| 2471 | -/// What a Durable Object RPC method returned, plus the position its writes | |
| 2472 | -/// reached, so the caller can hold the reply behind durability. | |
| 2473 | -pub struct RpcOutcome { | |
| 2474 | - pub data: RpcData, | |
| 2475 | - pub write_position: Option<u64>, | |
| 2476 | -} | |
| 2477 | - | |
| 2478 | -/// What a claimed alarm still owes its bookkeeping. | |
| 2479 | -/// | |
| 2480 | -/// `finish_alarm_handler` must run exactly once however the event ends, and | |
| 2481 | -/// an event can now end without running JS at all — a budget overrun, a | |
| 2482 | -/// handler waiting on nothing — so the entry carries the claim rather than | |
| 2483 | -/// the caller that made it. | |
| 2484 | -struct AlarmClaim { | |
| 2485 | - /// The instant the dispatch was judged due against, so the outcome is | |
| 2486 | - /// recorded against the same one. | |
| 2487 | - now_ms: i64, | |
| 2488 | -} | |
| 2489 | - | |
| 2490 | -/// Start one cell event: the half that runs before the handler can suspend. | |
| 2491 | -/// | |
| 2492 | -/// Every cell event does the same four things — name the cell it belongs to, | |
| 2493 | -/// sample the writes its answer will be gated on, open an event context, and | |
| 2494 | -/// keep the promise the dispatcher returned. Only the call and the shape of | |
| 2495 | -/// the answer differ, which is what the arguments say. | |
| 2496 | -fn start_cell_event<'s>( | |
| 2497 | - tc: &mut v8::PinScope<'s, '_>, | |
| 2498 | - scope: &str, | |
| 2499 | - answer: Answer, | |
| 2500 | - request_id: Option<RequestId>, | |
| 2501 | - capture_frames: bool, | |
| 2502 | - call: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>>, | |
| 2503 | -) -> Begun { | |
| 2504 | - let context = IoContext::new(); | |
| 2505 | - let guard = CurrentGuard::enter(context.clone()); | |
| 2506 | - // Sampled before the handler runs so the output gate can tell a write | |
| 2507 | - // this event made from celld's own activation writes. | |
| 2508 | - let writes_before = storage::write_position(scope); | |
| 2509 | - // No guard: this frame is the context's outermost one and the context | |
| 2510 | - // ends with the event, so there is nothing to pop it before. | |
| 2511 | - context | |
| 2512 | - .egress | |
| 2513 | - .lock() | |
| 2514 | - .unwrap() | |
| 2515 | - .push((scope.to_string(), writes_before.unwrap_or(0))); | |
| 2516 | - if capture_frames { | |
| 2517 | - ws_capture_begin(); | |
| 2518 | - } | |
| 2519 | - let started = (|| { | |
| 2520 | - begin_event_context(tc)?; | |
| 2521 | - let ret = call(tc)?; | |
| 2522 | - match ret.try_cast::<v8::Promise>() { | |
| 2523 | - Ok(promise) => Ok(promise), | |
| 2524 | - Err(_) => resolved_promise(tc, ret), | |
| 2525 | - } | |
| 2526 | - })(); | |
| 2527 | - match started { | |
| 2528 | - Ok(promise) => { | |
| 2529 | - tc.perform_microtask_checkpoint(); | |
| 2530 | - let entry = InFlight { | |
| 2531 | - runtime_state: actor_runtime_state(tc), | |
| 2532 | - promise: v8::Global::new(tc, promise), | |
| 2533 | - context, | |
| 2534 | - scope: Some(scope.to_string()), | |
| 2535 | - writes_before, | |
| 2536 | - request_id, | |
| 2537 | - // A cell's dispatcher registers the incoming request itself, | |
| 2538 | - // so there is nothing for the shell to finish; `cancel` | |
| 2539 | - // aborts by the job's own id. | |
| 2540 | - active_request_id: None, | |
| 2541 | - reply: Some(answer), | |
| 2542 | - background: None, | |
| 2543 | - ops: std::collections::HashSet::new(), | |
| 2544 | - alarm: None, | |
| 2545 | - started: Instant::now(), | |
| 2546 | - trace: None, | |
| 2547 | - failure: None, | |
| 2548 | - }; | |
| 2549 | - drop(guard); | |
| 2550 | - Begun::Running(Box::new(entry)) | |
| 2551 | - } | |
| 2552 | - Err(error) => { | |
| 2553 | - let _ = end_event_context(tc); | |
| 2554 | - drop(guard); | |
| 2555 | - answer.fail(error); | |
| 2556 | - Begun::Nothing | |
| 2557 | - } | |
| 2558 | - } | |
| 2559 | -} | |
| 2560 | - | |
| 2561 | -/// Look one of the harness dispatchers up on the current realm's global. | |
| 2562 | -fn dispatcher<'s>( | |
| 2563 | - tc: &mut v8::PinScope<'s, '_>, | |
| 2564 | - name: &str, | |
| 2565 | -) -> Result<v8::Local<'s, v8::Function>> { | |
| 2566 | - let global = tc.get_current_context().global(tc); | |
| 2567 | - let key = v8::String::new(tc, name).unwrap(); | |
| 2568 | - global | |
| 2569 | - .get(tc, key.into()) | |
| 2570 | - .ok_or_else(|| anyhow!("no {name}"))? | |
| 2571 | - .try_into() | |
| 2572 | - .map_err(|_| anyhow!("{name} is not a function")) | |
| 2573 | -} | |
| 2574 | - | |
| 2575 | -/// Start a cell event's first turn. | |
| 2576 | -/// | |
| 2577 | -/// The counterpart of `begin` for the events a cell receives. Where the | |
| 2578 | -/// blocking loop ran each of these to completion inside one call — and | |
| 2579 | -/// serviced other cells' events inside *that* — each is now an entry a tokio | |
| 2580 | -/// task drives, so two events of one cell interleave by suspending rather | |
| 2581 | -/// than by nesting. | |
| 2582 | -fn begin_cell(tc: &mut v8::PinScope, job: CellJob) -> Begun { | |
| 2583 | - match job { | |
| 2584 | - CellJob::Fetch { | |
| 2585 | - request_id, | |
| 2586 | - scope, | |
| 2587 | - name, | |
| 2588 | - url, | |
| 2589 | - method, | |
| 2590 | - body, | |
| 2591 | - headers, | |
| 2592 | - reply, | |
| 2593 | - order: _, | |
| 2594 | - } => { | |
| 2595 | - if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) { | |
| 2596 | - let _ = reply.send(Err(error)); | |
| 2597 | - return Begun::Nothing; | |
| 2598 | - } | |
| 2599 | - start_cell_event(tc, &scope, Answer::Fetch(reply), request_id, false, |tc| { | |
| 2600 | - let f = dispatcher(tc, "__dispatchTo")?; | |
| 2601 | - let arguments = [ | |
| 2602 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 2603 | - v8::String::new(tc, &url).unwrap().into(), | |
| 2604 | - v8::String::new(tc, &method).unwrap().into(), | |
| 2605 | - bytes_value(tc, body), | |
| 2606 | - v8::String::new(tc, &serde_json::to_string(&headers)?) | |
| 2607 | - .unwrap() | |
| 2608 | - .into(), | |
| 2609 | - match request_id { | |
| 2610 | - Some(id) => v8::String::new(tc, &request_id_string(id)).unwrap().into(), | |
| 2611 | - None => v8::null(tc).into(), | |
| 2612 | - }, | |
| 2613 | - ]; | |
| 2614 | - let recv = v8::undefined(tc).into(); | |
| 2615 | - f.call(tc, recv, &arguments) | |
| 2616 | - .ok_or_else(|| anyhow!("dispatchTo threw")) | |
| 2617 | - }) | |
| 2618 | - } | |
| 2619 | - CellJob::Rpc { | |
| 2620 | - scope, | |
| 2621 | - name, | |
| 2622 | - method, | |
| 2623 | - args, | |
| 2624 | - reply, | |
| 2625 | - } => { | |
| 2626 | - if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) { | |
| 2627 | - let _ = reply.send(Err(error)); | |
| 2628 | - return Begun::Nothing; | |
| 2629 | - } | |
| 2630 | - start_cell_event(tc, &scope, Answer::CellRpc(reply), None, false, |tc| { | |
| 2631 | - let f = dispatcher(tc, "__dispatchRpc")?; | |
| 2632 | - let arguments = [ | |
| 2633 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 2634 | - v8::String::new(tc, &method).unwrap().into(), | |
| 2635 | - rpc_data_value(tc, args), | |
| 2636 | - ]; | |
| 2637 | - let recv = v8::undefined(tc).into(); | |
| 2638 | - f.call(tc, recv, &arguments) | |
| 2639 | - .ok_or_else(|| anyhow!("dispatchRpc threw")) | |
| 2640 | - }) | |
| 2641 | - } | |
| 2642 | - CellJob::WsOpen { | |
| 2643 | - scope, | |
| 2644 | - ws_id, | |
| 2645 | - protocol, | |
| 2646 | - reply, | |
| 2647 | - } => start_cell_event(tc, &scope, Answer::Ack(reply), None, false, |tc| { | |
| 2648 | - let f = dispatcher(tc, "__wsOpen")?; | |
| 2649 | - let arguments = [ | |
| 2650 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 2651 | - v8::Number::new(tc, ws_id as f64).into(), | |
| 2652 | - v8::String::new(tc, &protocol).unwrap().into(), | |
| 2653 | - ]; | |
| 2654 | - let recv = v8::undefined(tc).into(); | |
| 2655 | - f.call(tc, recv, &arguments) | |
| 2656 | - .ok_or_else(|| anyhow!("wsOpen threw")) | |
| 2657 | - }), | |
| 2658 | - CellJob::WsMessage { | |
| 2659 | - scope, | |
| 2660 | - ws_id, | |
| 2661 | - data, | |
| 2662 | - reply, | |
| 2663 | - } => start_cell_event(tc, &scope, Answer::WsMessage(reply), None, true, |tc| { | |
| 2664 | - let (name, data) = match data { | |
| 2665 | - WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()), | |
| 2666 | - WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)), | |
| 2667 | - }; | |
| 2668 | - let f = dispatcher(tc, name)?; | |
| 2669 | - let arguments = [ | |
| 2670 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 2671 | - v8::Number::new(tc, ws_id as f64).into(), | |
| 2672 | - data, | |
| 2673 | - ]; | |
| 2674 | - let recv = v8::undefined(tc).into(); | |
| 2675 | - f.call(tc, recv, &arguments) | |
| 2676 | - .ok_or_else(|| anyhow!("WebSocket message dispatch threw")) | |
| 2677 | - }), | |
| 2678 | - CellJob::WsClosed { | |
| 2679 | - scope, | |
| 2680 | - ws_id, | |
| 2681 | - code, | |
| 2682 | - reason, | |
| 2683 | - was_clean, | |
| 2684 | - reply, | |
| 2685 | - } => start_cell_event(tc, &scope, Answer::Ack(reply), None, false, |tc| { | |
| 2686 | - let f = dispatcher(tc, "__wsClosed")?; | |
| 2687 | - let arguments = [ | |
| 2688 | - v8::String::new(tc, &scope).unwrap().into(), | |
| 2689 | - v8::Number::new(tc, ws_id as f64).into(), | |
| 2690 | - v8::Number::new(tc, f64::from(code)).into(), | |
| 2691 | - v8::String::new(tc, &reason).unwrap().into(), | |
| 2692 | - v8::Boolean::new(tc, was_clean).into(), | |
| 2693 | - ]; | |
| 2694 | - let recv = v8::undefined(tc).into(); | |
| 2695 | - f.call(tc, recv, &arguments) | |
| 2696 | - .ok_or_else(|| anyhow!("wsClosed threw")) | |
| 2697 | - }), | |
| 2698 | - CellJob::Alarm { | |
| 2699 | - scope, | |
| 2700 | - scheduled_ms, | |
| 2701 | - claim, | |
| 2702 | - reply, | |
| 2703 | - } => begin_alarm(tc, &scope, scheduled_ms, claim, reply), | |
| 2704 | - } | |
| 2705 | -} | |
| 2706 | - | |
| 2707 | -/// Start an alarm, claiming the due entry so nothing else fires it. | |
| 2708 | -/// | |
| 2709 | -/// The claim is recorded on the entry rather than closed here, because the | |
| 2710 | -/// handler has not run yet: the outcome is known only when the event ends, | |
| 2711 | -/// which is now many turns away. | |
| 2712 | -fn begin_alarm( | |
| 2713 | - tc: &mut v8::PinScope, | |
| 2714 | - scope: &str, | |
| 2715 | - scheduled_ms: i64, | |
| 2716 | - claim: AlarmDispatch, | |
| 2717 | - reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 2718 | -) -> Begun { | |
| 2719 | - let now = unix_now_ms(); | |
| 2720 | - if now < scheduled_ms { | |
| 2721 | - let _ = reply.send(Err(anyhow!("alarm dispatched before its deadline"))); | |
| 2722 | - return Begun::Nothing; | |
| 2723 | - } | |
| 2724 | - if let AlarmDispatch::Claimed(retry) = claim { | |
| 2725 | - let Some(scheduled_at) = storage::active_alarm_scheduled_time(scope) else { | |
| 2726 | - let _ = reply.send(Err(anyhow!("alarm dispatched without a claim"))); | |
| 2727 | - return Begun::Nothing; | |
| 2728 | - }; | |
| 2729 | - return fire_alarm_handler(tc, scope, scheduled_at, retry, None, reply); | |
| 2730 | - } | |
| 2731 | - let due_by = match claim { | |
| 2732 | - AlarmDispatch::Armed => i64::MAX, | |
| 2733 | - _ => now, | |
| 2734 | - }; | |
| 2735 | - let Some((scheduled_at, retry)) = storage::due_alarm_entry(scope, due_by) else { | |
| 2736 | - // Nothing is due: another dispatch already ran it, or the handler | |
| 2737 | - // that armed it cleared it. Answer what stands now, with no delta — | |
| 2738 | - // no handler ran, so there is nothing written to prove. | |
| 2739 | - let _ = reply.send(Ok((storage::get_alarm(scope), None))); | |
| 2740 | - return Begun::Nothing; | |
| 2741 | - }; | |
| 2742 | - storage::begin_alarm_handler(scope, scheduled_at); | |
| 2743 | - fire_alarm_handler( | |
| 2744 | - tc, | |
| 2745 | - scope, | |
| 2746 | - scheduled_at, | |
| 2747 | - retry, | |
| 2748 | - Some(AlarmClaim { now_ms: now }), | |
| 2749 | - reply, | |
| 2750 | - ) | |
| 2751 | -} | |
| 2752 | - | |
| 2753 | -/// Call `alarm()`, carrying whatever claim its outcome must close. | |
| 2754 | -fn fire_alarm_handler( | |
| 2755 | - tc: &mut v8::PinScope, | |
| 2756 | - scope: &str, | |
| 2757 | - scheduled_at: i64, | |
| 2758 | - retry: i64, | |
| 2759 | - claim: Option<AlarmClaim>, | |
| 2760 | - reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>, | |
| 2761 | -) -> Begun { | |
| 2762 | - let begun = start_cell_event(tc, scope, Answer::Alarm(reply), None, false, |tc| { | |
| 2763 | - let f = dispatcher(tc, "__fireAlarm")?; | |
| 2764 | - let arguments = [ | |
| 2765 | - v8::String::new(tc, scope).unwrap().into(), | |
| 2766 | - v8::Number::new(tc, scheduled_at as f64).into(), | |
| 2767 | - v8::Number::new(tc, retry as f64).into(), | |
| 2768 | - ]; | |
| 2769 | - let recv = v8::undefined(tc).into(); | |
| 2770 | - f.call(tc, recv, &arguments) | |
| 2771 | - .ok_or_else(|| anyhow!("alarm threw")) | |
| 2772 | - }); | |
| 2773 | - match begun { | |
| 2774 | - Begun::Running(mut entry) => { | |
| 2775 | - entry.alarm = claim; | |
| 2776 | - Begun::Running(entry) | |
| 2777 | - } | |
| 2778 | - // The dispatcher never ran, so nothing can have changed the alarm. | |
| 2779 | - // Give the claim back as a failure that does not count against the | |
| 2780 | - // retry limit: the handler is not what failed. | |
| 2781 | - begun => { | |
| 2782 | - if let Some(claim) = claim { | |
| 2783 | - storage::finish_alarm_handler_with_retry_policy(scope, false, claim.now_ms, false); | |
| 2784 | - } | |
| 2785 | - begun | |
| 2786 | - } | |
| 2787 | - } | |
| 2788 | -} | |
| 2789 | - | |
| 2790 | -/// Resolve one completed op and run the microtasks that follow, with the | |
| 2791 | -/// owning request's context current. | |
| 2792 | -/// | |
| 2793 | -/// The half of a turn that resumes a suspended request. It knows nothing | |
| 2794 | -/// about any other request: the caller has already established that this op | |
| 2795 | -/// is `entry`'s. | |
| 2796 | -fn deliver( | |
| 2797 | - tc: &mut v8::PinScope, | |
| 2798 | - entry: &mut InFlight, | |
| 2799 | - op: u64, | |
| 2800 | - res: Result<asyncrt::OpOut, String>, | |
| 2801 | -) { | |
| 2802 | - entry.ops.remove(&op); | |
| 2803 | - let guard = CurrentGuard::enter(entry.context.clone()); | |
| 2804 | - resolve_res(tc, op, res); | |
| 2805 | - tc.perform_microtask_checkpoint(); | |
| 2806 | - drop(guard); | |
| 2807 | -} | |
| 2808 | - | |
| 2809 | -/// End a request whose client has hung up, so its handler stops running. | |
| 2810 | -fn cancelled(tc: &mut v8::PinScope, entry: &mut InFlight) { | |
| 2811 | - if entry.reply.is_none() || !take_request_cancellation(entry.request_id) { | |
| 2812 | - return; | |
| 2813 | - } | |
| 2814 | - cancel(tc, entry); | |
| 2815 | -} | |
| 2816 | - | |
| 2817 | -/// End a request whose cancellation has already been taken. | |
| 2818 | -/// | |
| 2819 | -/// Split from [`cancelled`] because a suspended request observes the | |
| 2820 | -/// cancellation *outside* the isolate — the flag is host state and costs no | |
| 2821 | -/// V8 — and only then enters to act on it. | |
| 2822 | -fn cancel(tc: &mut v8::PinScope, entry: &mut InFlight) { | |
| 2823 | - let guard = CurrentGuard::enter(entry.context.clone()); | |
| 2824 | - // The id that names this request to the JS side. A stateless handler is | |
| 2825 | - // registered by the shell, and only once it suspends, so the shell holds | |
| 2826 | - // the id; a cell's dispatcher registers the request itself, so the job's | |
| 2827 | - // own id is the one to abort. Aborting the wrong one — or neither — | |
| 2828 | - // leaves the target's `request.signal` unfired while the caller is told | |
| 2829 | - // the client has gone. | |
| 2830 | - if let Some(id) = entry.active_request_id.or(entry.request_id) { | |
| 2831 | - let _ = abort_incoming_request(tc, id); | |
| 2832 | - } | |
| 2833 | - // Finishing is the shell's to undo only where the shell registered. | |
| 2834 | - if let Some(id) = entry.active_request_id { | |
| 2835 | - finish_incoming_request(tc, id); | |
| 2836 | - } | |
| 2837 | - let background = end_event_context(tc).ok().flatten(); | |
| 2838 | - entry.background = background.map(|promise| v8::Global::new(tc, promise)); | |
| 2839 | - drop(guard); | |
| 2840 | - entry.fail(anyhow!("The client has disconnected")); | |
| 2841 | - // A cancelled handler with no waitUntil work has nothing left to drive. | |
| 2842 | - // Drop its host ops now, so their guards cancel routed work. Explicit | |
| 2843 | - // waitUntil work keeps its ops and continues after the client disconnects. | |
| 2844 | - if entry.background.is_none() { | |
| 2845 | - entry.abandon(); | |
| 2846 | - } | |
| 2847 | -} | |
| 2848 | - | |
| 2849 | -/// Answer a request whose handler promise has settled, and retire its | |
| 2850 | -/// `waitUntil` work once that settles too. | |
| 2851 | -fn settle(tc: &mut v8::PinScope, entry: &mut InFlight) { | |
| 2852 | - if entry.reply.is_some() { | |
| 2853 | - let promise = v8::Local::new(tc, &entry.promise); | |
| 2854 | - match promise.state() { | |
| 2855 | - v8::PromiseState::Pending => {} | |
| 2856 | - v8::PromiseState::Fulfilled => { | |
| 2857 | - let guard = CurrentGuard::enter(entry.context.clone()); | |
| 2858 | - let value = promise.result(tc); | |
| 2859 | - entry.answer_settled(tc, value); | |
| 2860 | - if let Some(request_id) = entry.active_request_id { | |
| 2861 | - finish_incoming_request(tc, request_id); | |
| 2862 | - } | |
| 2863 | - drop(guard); | |
| 2864 | - } | |
| 2865 | - v8::PromiseState::Rejected => { | |
| 2866 | - let guard = CurrentGuard::enter(entry.context.clone()); | |
| 2867 | - let reason = reject_reason(tc, promise); | |
| 2868 | - // The handler is what failed, so an alarm's failure here | |
| 2869 | - // counts against its retry limit — unlike a budget overrun | |
| 2870 | - // or a disconnect, which `fail` records as not counting. | |
| 2871 | - entry.settle_alarm(false, true); | |
| 2872 | - let _ = end_event_context(tc); | |
| 2873 | - if let Some(request_id) = entry.active_request_id { | |
| 2874 | - finish_incoming_request(tc, request_id); | |
| 2875 | - } | |
| 2876 | - drop(guard); | |
| 2877 | - entry.fail(anyhow!("rejected: {reason}")); | |
| 2878 | - } | |
| 2879 | - } | |
| 2880 | - } | |
| 2881 | - if let Some(background) = &entry.background { | |
| 2882 | - let promise = v8::Local::new(tc, background); | |
| 2883 | - if !matches!(promise.state(), v8::PromiseState::Pending) { | |
| 2884 | - entry.background = None; | |
| 2885 | - } | |
| 2886 | - } | |
| 2887 | -} | |
| 2888 | - | |
| 2889 | -/// Begin a stateless request: build it, call the Worker's `fetch`, and hand | |
| 2890 | -/// back the promise it returned. | |
| 2891 | -/// | |
| 2892 | -/// The half of a request that runs *before* it can suspend. Split out from | |
| 2893 | -/// driving it to completion so a caller can start several and drive them | |
| 2894 | -/// together; the single-request path starts one and drives it immediately, | |
| 2895 | -/// which is what it always did. | |
| 2896 | -/// | |
| 2897 | -/// The caller owns the `IoContext` and must have it current: `__beginEvent` | |
| 2898 | -/// runs here, and the frame it pushes belongs to this request. | |
| 2899 | -fn start_fetch<'s>( | |
| 2900 | - tc: &mut v8::PinScope<'s, '_>, | |
| 2901 | - fetch: v8::Local<'s, v8::Function>, | |
| 2902 | - url: &str, | |
| 2903 | - method: &str, | |
| 2904 | - body: &RequestBody, | |
| 2905 | - headers: &[(String, String)], | |
| 2906 | - request_id: Option<RequestId>, | |
| 2907 | -) -> Result<Started<'s>> { | |
| 2908 | - let req = match request_id { | |
| 2909 | - Some(_) => make_incoming_request(tc, url, method, body, headers), | |
| 2910 | - None => make_request(tc, url, method, body.bytes(), headers), | |
| 2911 | - }?; | |
| 2912 | - let env = harness_env(tc)?; | |
| 2913 | - let recv = v8::undefined(tc).into(); | |
| 2914 | - let f = fetch; | |
| 2915 | - let execution_ctx = begin_event_context(tc)?; | |
| 2916 | - let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else { | |
| 2917 | - // The handler threw synchronously. Termination carries its own error; | |
| 2918 | - // otherwise the pending exception is on the caller's TryCatch, which | |
| 2919 | - // is the only scope that can read it, so it formats the message. | |
| 2920 | - let error = take_execution_termination(tc); | |
| 2921 | - let _ = end_event_context(tc); | |
| 2922 | - return match error { | |
| 2923 | - Some(error) => Err(error), | |
| 2924 | - None => Ok(Started::Threw), | |
| 2925 | - }; | |
| 2926 | - }; | |
| 2927 | - // A handler that suspends must be reachable by an abort: register it as an | |
| 2928 | - // incoming request so a client disconnect can cancel it. One that already | |
| 2929 | - // settled cannot be cancelled, so its registration is cleared instead. | |
| 2930 | - let active_request_id = match request_id { | |
| 2931 | - Some(request_id) | |
| 2932 | - if ret | |
| 2933 | - .try_cast::<v8::Promise>() | |
| 2934 | - .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) => | |
| 2935 | - { | |
| 2936 | - if let Err(error) = register_incoming_request(tc, request_id, req) { | |
| 2937 | - clear_request_cancellation(request_id); | |
| 2938 | - let _ = end_event_context(tc); | |
| 2939 | - return Err(error); | |
| 2940 | - } | |
| 2941 | - Some(request_id) | |
| 2942 | - } | |
| 2943 | - Some(request_id) => { | |
| 2944 | - clear_request_cancellation(request_id); | |
| 2945 | - None | |
| 2946 | - } | |
| 2947 | - None => None, | |
| 2948 | - }; | |
| 2949 | - Ok(Started::Running(ret, active_request_id)) | |
| 2950 | -} | |
| 2951 | - | |
| 2952 | -/// What `start_fetch` produced: a running handler, or a synchronous throw | |
| 2953 | -/// whose exception only the caller's `TryCatch` can read. | |
| 2954 | -enum Started<'s> { | |
| 2955 | - Running(v8::Local<'s, v8::Value>, Option<RequestId>), | |
| 2956 | - Threw, | |
| 2957 | -} | |
| 2958 | - | |
| 2959 | -impl Worker { | |
| 2960 | - /// Compile the worker module, wire the DO harness, and extract the entry | |
| 2961 | - /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding | |
| 2962 | - /// name to a DO class name (from wrangler metadata). | |
| 2963 | - /// | |
| 2964 | - /// The runtime builds a `WorkerConfig` directly; this helper is | |
| 2965 | - /// test-only. | |
| 2966 | - #[cfg(test)] | |
| 2967 | - pub fn load(options: WorkerConfigOptions, owned: &[String]) -> Result<Worker> { | |
| 2968 | - let config = Arc::new(WorkerConfig::new(options)); | |
| 2969 | - Self::load_config(config, owned) | |
| 2970 | - } | |
| 2971 | - | |
| 2972 | - pub fn load_config(config: Arc<WorkerConfig>, owned: &[String]) -> Result<Worker> { | |
| 2973 | - Self::load_config_owned(config, Arc::from(owned.to_vec())) | |
| 2974 | - } | |
| 2975 | - | |
| 2976 | - fn load_config_owned(config: Arc<WorkerConfig>, owned: Arc<[String]>) -> Result<Worker> { | |
| 2977 | - let src = config.src.as_str(); | |
| 2978 | - let script_name = config.script_name.as_str(); | |
| 2979 | - let do_classes = config.do_classes.as_slice(); | |
| 2980 | - let node = config.node.as_str(); | |
| 2981 | - let compat = config.compat; | |
| 2982 | - let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes()); | |
| 2983 | - let mut isolate = v8::Isolate::new(params); | |
| 2984 | - // Dynamic `import()` of builtin specifiers; per-import()-call only. | |
| 2985 | - isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically); | |
| 2986 | - let original_heap_limit = isolate.get_heap_statistics().heap_size_limit(); | |
| 2987 | - let heap_limit_state = Arc::new(HeapLimitState { | |
| 2988 | - excessively_exceeded: AtomicBool::new(false), | |
| 2989 | - limit: original_heap_limit, | |
| 2990 | - last_gc_nudge: Mutex::new(None), | |
| 2991 | - #[cfg(all(test, celld_internal_tests))] | |
| 2992 | - forced_admission_refusal: AtomicBool::new(false), | |
| 2993 | - }); | |
| 2994 | - let runtime_state = Arc::new(ActorRuntimeState { | |
| 2995 | - promises: std::sync::Mutex::new(PromiseMap::new()), | |
| 2996 | - egress: config.egress, | |
| 2997 | - ..Default::default() | |
| 2998 | - }); | |
| 2999 | - let heap_limit_state_ptr = | |
| 3000 | - Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void; | |
| 3001 | - isolate.set_slot(heap_limit_state); | |
| 3002 | - isolate.set_slot(runtime_state.clone()); | |
| 3003 | - isolate.set_slot(Arc::new(ModuleRegistry::default())); | |
| 3004 | - isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr); | |
| 3005 | - let (context, fetch) = { | |
| 3006 | - v8::scope!(let hs, &mut isolate); | |
| 3007 | - let context = v8::Context::new(hs, Default::default()); | |
| 3008 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 3009 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 3010 | - let scope = &mut tc.init(); | |
| 3011 | - | |
| 3012 | - install_ops(scope, context); | |
| 3013 | - install_prelude(scope)?; // Web Platform APIs | |
| 3014 | - install_harness(scope)?; // DO object model + minimal Response | |
| 3015 | - install_lazy_globals(scope)?; | |
| 3016 | - // A global, so it must exist before the module evaluates: bundles | |
| 3017 | - // read Cloudflare.compatibilityFlags at module scope. | |
| 3018 | - inject_compatibility_flags(scope, compat)?; | |
| 3019 | - inject_storage_compatibility(scope, compat)?; | |
| 3020 | - | |
| 3021 | - let module = match compile_module(scope, "worker.js", src) { | |
| 3022 | - Some(m) => m, | |
| 3023 | - None => return Err(anyhow!("compile: {}", exc!(scope))), | |
| 3024 | - }; | |
| 3025 | - register_stubs(scope, src, &config.modules); // cloudflare:*/node:* + text modules | |
| 3026 | - register_wasm_modules(scope, &config.modules); | |
| 3027 | - register_loader_modules(scope, &config.modules); | |
| 3028 | - module | |
| 3029 | - .instantiate_module(scope, resolve_external) | |
| 3030 | - .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?; | |
| 3031 | - let ev = match module.evaluate(scope) { | |
| 3032 | - Some(value) => value, | |
| 3033 | - None => { | |
| 3034 | - if let Some(error) = take_execution_termination(scope) { | |
| 3035 | - return Err(error); | |
| 3036 | - } | |
| 3037 | - return Err(anyhow!("evaluate: {}", exc!(scope))); | |
| 3038 | - } | |
| 3039 | - }; | |
| 3040 | - if let Some(error) = take_execution_termination(scope) { | |
| 3041 | - return Err(error); | |
| 3042 | - } | |
| 3043 | - if let Ok(p) = ev.try_cast::<v8::Promise>() { | |
| 3044 | - if p.state() == v8::PromiseState::Rejected { | |
| 3045 | - let r = p.result(scope); | |
| 3046 | - let stk = r | |
| 3047 | - .to_object(scope) | |
| 3048 | - .and_then(|o| { | |
| 3049 | - let k = v8::String::new(scope, "stack")?; | |
| 3050 | - o.get(scope, k.into()) | |
| 3051 | - }) | |
| 3052 | - .map(|s| s.to_rust_string_lossy(scope)) | |
| 3053 | - .unwrap_or_default(); | |
| 3054 | - return Err(anyhow!( | |
| 3055 | - "top-level rejected: {} | {}", | |
| 3056 | - r.to_rust_string_lossy(scope), | |
| 3057 | - stk.lines().take(4).collect::<Vec<_>>().join(" <- ") | |
| 3058 | - )); | |
| 3059 | - } | |
| 3060 | - } | |
| 3061 | - | |
| 3062 | - let ns = module | |
| 3063 | - .get_module_namespace() | |
| 3064 | - .to_object(scope) | |
| 3065 | - .ok_or_else(|| anyhow!("ns"))?; | |
| 3066 | - | |
| 3067 | - // register each exported DO class into the harness registry | |
| 3068 | - for cn in do_classes { | |
| 3069 | - // The D1 class is the runtime's own and is never a worker | |
| 3070 | - // export. It is in `do_classes` so that it gets a namespace | |
| 3071 | - // key; reading it off the module namespace would find | |
| 3072 | - // `undefined` and overwrite the harness's registration. | |
| 3073 | - if cn == crate::deploy::D1_CLASS { | |
| 3074 | - continue; | |
| 3075 | - } | |
| 3076 | - let key = v8::String::new(scope, cn).unwrap(); | |
| 3077 | - let cls = ns | |
| 3078 | - .get(scope, key.into()) | |
| 3079 | - .ok_or_else(|| anyhow!("DO class {cn} not exported"))?; | |
| 3080 | - register_class(scope, cn, cls)?; | |
| 3081 | - } | |
| 3082 | - inject_namespace_keys(scope, script_name, do_classes)?; | |
| 3083 | - inject_crons(scope, &config.crons)?; | |
| 3084 | - populate_cf_exports(scope, ns, do_classes)?; | |
| 3085 | - register_entrypoints(scope, ns)?; | |
| 3086 | - // build env from bindings and stash it in the harness | |
| 3087 | - build_env(scope, &config)?; | |
| 3088 | - // tell the harness which cells are local (route the rest cross-node) | |
| 3089 | - inject_routing(scope, owned.as_ref(), node)?; | |
| 3090 | - | |
| 3091 | - // entry fetch | |
| 3092 | - let dk = v8::String::new(scope, "default").unwrap(); | |
| 3093 | - let default = ns | |
| 3094 | - .get(scope, dk.into()) | |
| 3095 | - .ok_or_else(|| anyhow!("no default export"))? | |
| 3096 | - .to_object(scope) | |
| 3097 | - .ok_or_else(|| anyhow!("default not object"))?; | |
| 3098 | - let fk = v8::String::new(scope, "fetch").unwrap(); | |
| 3099 | - let fetch_value = default | |
| 3100 | - .get(scope, fk.into()) | |
| 3101 | - .ok_or_else(|| anyhow!("no fetch"))?; | |
| 3102 | - let default_is_entrypoint = | |
| 3103 | - default.is_function() && cell_registry_has(scope, "entrypoints", "default")?; | |
| 3104 | - let f: v8::Local<v8::Function> = if fetch_value.is_function() { | |
| 3105 | - fetch_value.try_into().expect("function casts to Function") | |
| 3106 | - } else if default_is_entrypoint { | |
| 3107 | - // A class-based default entrypoint (extends WorkerEntrypoint) | |
| 3108 | - // keeps fetch on the prototype, so route through the | |
| 3109 | - // harness's cached instance like a named entrypoint. Only a | |
| 3110 | - // registered entrypoint dispatches that way — any other | |
| 3111 | - // callable would load fine and then 500 on every request. | |
| 3112 | - compile_fn( | |
| 3113 | - scope, | |
| 3114 | - "(req) => globalThis.__dispatchEntrypointFetch('default', req)", | |
| 3115 | - )? | |
| 3116 | - } else if default.is_function() && cell_registry_has(scope, "doExports", "default")? { | |
| 3117 | - return Err(anyhow!( | |
| 3118 | - "the default export is a Durable Object class; export a fetch \ | |
| 3119 | - handler or a WorkerEntrypoint class as the default" | |
| 3120 | - )); | |
| 3121 | - } else { | |
| 3122 | - return Err(anyhow!("fetch not fn")); | |
| 3123 | - }; | |
| 3124 | - | |
| 3125 | - // Lets a self-targeted service binding invoke the handler in | |
| 3126 | - // this isolate instead of crossing to a pool thread. | |
| 3127 | - { | |
| 3128 | - let cell_key = v8::String::new(scope, "__cell").unwrap(); | |
| 3129 | - if let Some(cell) = context | |
| 3130 | - .global(scope) | |
| 3131 | - .get(scope, cell_key.into()) | |
| 3132 | - .and_then(|value| value.to_object(scope)) | |
| 3133 | - { | |
| 3134 | - let key = v8::String::new(scope, "selfFetch").unwrap(); | |
| 3135 | - cell.set(scope, key.into(), f.into()); | |
| 3136 | - // Optional scheduled handler, reached by a self-targeted | |
| 3137 | - // service binding's scheduled(). | |
| 3138 | - let sk = v8::String::new(scope, "scheduled").unwrap(); | |
| 3139 | - let key_ = v8::String::new(scope, "selfScheduled").unwrap(); | |
| 3140 | - let own = default | |
| 3141 | - .get(scope, sk.into()) | |
| 3142 | - .filter(|handler| handler.is_function()); | |
| 3143 | - if let Some(handler) = own { | |
| 3144 | - cell.set(scope, key_.into(), handler); | |
| 3145 | - } else if default_is_entrypoint { | |
| 3146 | - // A class-based default entrypoint keeps scheduled on | |
| 3147 | - // the prototype; dispatch through the cached instance | |
| 3148 | - // like fetch above. | |
| 3149 | - let pk = v8::String::new(scope, "prototype").unwrap(); | |
| 3150 | - let proto_scheduled = default | |
| 3151 | - .get(scope, pk.into()) | |
| 3152 | - .and_then(|proto| proto.to_object(scope)) | |
| 3153 | - .and_then(|proto| proto.get(scope, sk.into())); | |
| 3154 | - if proto_scheduled.is_some_and(|handler| handler.is_function()) { | |
| 3155 | - let shim = compile_fn( | |
| 3156 | - scope, | |
| 3157 | - "(ctrl) => globalThis.__dispatchEntrypointScheduled('default', ctrl)", | |
| 3158 | - )?; | |
| 3159 | - cell.set(scope, key_.into(), shim.into()); | |
| 3160 | - } | |
| 3161 | - } | |
| 3162 | - } | |
| 3163 | - } | |
| 3164 | - (v8::Global::new(scope, context), v8::Global::new(scope, f)) | |
| 3165 | - }; | |
| 3166 | - Ok(Worker { | |
| 3167 | - inner: Some(WorkerIsolate { | |
| 3168 | - // Every setup scope above has closed, so nothing is entered | |
| 3169 | - // on top of this isolate and it can be handed over. | |
| 3170 | - // SAFETY: `into_shared` requires every piece of embedder | |
| 3171 | - // state hanging off this isolate to be `Send`, because it | |
| 3172 | - // migrates between threads and is dropped on whichever one | |
| 3173 | - // holds the lock last. This isolate carries exactly: | |
| 3174 | - // | |
| 3175 | - // - three slots, whose types the assertion below pins as | |
| 3176 | - // `Send + Sync`; | |
| 3177 | - // - `near_heap_limit`, a bare fn pointer whose only captured | |
| 3178 | - // state is a raw pointer into the `HeapLimitState` above; | |
| 3179 | - // - `host_import_module_dynamically`, a bare fn pointer that | |
| 3180 | - // captures nothing; | |
| 3181 | - // - a default `CreateParams` allocator, owned by V8. | |
| 3182 | - // | |
| 3183 | - // Nothing else is attached, and the assertion fails the build | |
| 3184 | - // if a slot type ever stops being thread-safe. | |
| 3185 | - // | |
| 3186 | - // 152.1.0 made this fallible. None of the four refusals can | |
| 3187 | - // hold here — this isolate is entered, is not a snapshot | |
| 3188 | - // creator, has no C++ heap, and has taken no weak handles — | |
| 3189 | - // so a refusal is a bug in the setup above, not a condition | |
| 3190 | - // to recover from. It panics with the reason named. | |
| 3191 | - isolate: unsafe { isolate.try_into_shared() } | |
| 3192 | - .unwrap_or_else(|error| panic!("cell isolate cannot be shared: {error}")), | |
| 3193 | - realm: Realm { context, fetch }, | |
| 3194 | - original_heap_limit, | |
| 3195 | - compat, | |
| 3196 | - cells: storage::Cells::default(), | |
| 3197 | - }), | |
| 3198 | - }) | |
| 3199 | - } | |
| 3200 | - | |
| 3201 | - /// Restore an idFromName() actor's human-readable identity before its | |
| 3202 | - /// constructor runs. The host calls this on activation and before a named | |
| 3203 | - /// request is dispatched. | |
| 3204 | - /// Record whether this isolate hosts `cell`, so the harness can dispatch | |
| 3205 | - /// to it in-isolate instead of going back out through the host. | |
| 3206 | - /// | |
| 3207 | - /// Baked in at load time until cells shared isolates, when an isolate | |
| 3208 | - /// served exactly one cell for its whole life and the list could not | |
| 3209 | - /// change. Now a cell arrives at an isolate that already exists, so the | |
| 3210 | - /// list has to move with placement. | |
| 3211 | - /// | |
| 3212 | - /// Getting this wrong is not symmetric. A cell missing from the list | |
| 3213 | - /// still works: the dispatch goes out to the host, which routes it | |
| 3214 | - /// straight back here, costing a round trip. A cell wrongly *in* the | |
| 3215 | - /// list is a cell this isolate would try to serve without hosting it, so | |
| 3216 | - /// the shell sets it when it takes a residency and clears it when the | |
| 3217 | - /// residency ends. | |
| 3218 | - pub fn own_cell( | |
| 3219 | - &mut self, | |
| 3220 | - cell: &str, | |
| 3221 | - db_path: Option<&str>, | |
| 3222 | - owned: bool, | |
| 3223 | - ) -> Result<Option<i64>> { | |
| 3224 | - let compat = self.inner.as_ref().expect("live worker isolate").compat; | |
| 3225 | - let (mut locker, _cells) = self.lock(); | |
| 3226 | - v8::scope!(let hs, &mut *locker); | |
| 3227 | - let realm = self.realm(hs); | |
| 3228 | - let context = realm.context; | |
| 3229 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 3230 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 3231 | - adopt_cell(&mut tc.init(), cell, db_path, owned, compat) | |
| 3232 | - } | |
| 3233 | - | |
| 3234 | - /// Drain the alarm moves the last turn committed in this isolate. | |
| 3235 | - /// | |
| 3236 | - /// An alarm move is a turn output, exactly like the ops a turn starts: | |
| 3237 | - /// the drive that ran the turn reports it to the host, so a handler | |
| 3238 | - /// that arms an alarm and then awaits it is schedulable immediately, | |
| 3239 | - /// not when the request ends. A separate call rather than part of the | |
| 3240 | - /// turn methods' return because stateless turns cannot move an alarm | |
| 3241 | - /// and never pay for it. | |
| 3242 | - pub fn take_alarm_moves(&mut self) -> Vec<(String, i64)> { | |
| 3243 | - let Some(inner) = self.inner.as_mut() else { | |
| 3244 | - return Vec::new(); | |
| 3245 | - }; | |
| 3246 | - let (_locker, _cells) = inner.lock(); | |
| 3247 | - storage::take_alarm_moves() | |
| 3248 | - } | |
| 3249 | - | |
| 3250 | - pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> { | |
| 3251 | - let (mut locker, _cells) = self.lock(); | |
| 3252 | - v8::scope!(let hs, &mut *locker); | |
| 3253 | - let realm = self.realm(hs); | |
| 3254 | - let context = realm.context; | |
| 3255 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 3256 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 3257 | - register_actor_name(&mut tc.init(), scope, Some(name)) | |
| 3258 | - } | |
| 3259 | - | |
| 3260 | - /// Start a cell event's first turn. | |
| 3261 | - /// | |
| 3262 | - /// The cell counterpart of `turn_begin`: it hands back what is now in | |
| 3263 | - /// flight for `runtime::drive_cell` to pump. | |
| 3264 | - pub fn turn_begin_cell( | |
| 3265 | - &mut self, | |
| 3266 | - job: CellJob, | |
| 3267 | - trace: Option<crate::telemetry::TraceIds>, | |
| 3268 | - ) -> (Option<InFlight>, Vec<Op>) { | |
| 3269 | - let Some(inner) = self.inner.as_mut() else { | |
| 3270 | - return (None, Vec::new()); | |
| 3271 | - }; | |
| 3272 | - let (mut locker, _cells) = inner.lock(); | |
| 3273 | - inner.recover_heap(&mut locker); | |
| 3274 | - v8::scope!(let hs, &mut *locker); | |
| 3275 | - let realm = inner.realm(hs); | |
| 3276 | - let context = realm.context; | |
| 3277 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 3278 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 3279 | - let tc = &mut tc.init(); | |
| 3280 | - | |
| 3281 | - let previous = install_trace(tc, trace.as_ref()); | |
| 3282 | - let out = match begin_cell(tc, job) { | |
| 3283 | - Begun::Running(mut entry) => { | |
| 3284 | - entry.trace = trace; | |
| 3285 | - let ops = finish_turn(tc, &mut entry); | |
| 3286 | - (Some(*entry), ops) | |
| 3287 | - } | |
| 3288 | - Begun::Threw(answer) => { | |
| 3289 | - answer.fail(anyhow!("cell event threw: {}", exc!(tc))); | |
| 3290 | - (None, Vec::new()) | |
| 3291 | - } | |
| 3292 | - Begun::Nothing => (None, Vec::new()), | |
| 3293 | - }; | |
| 3294 | - restore_trace(tc, previous); | |
| 3295 | - out | |
| 3296 | - } | |
| 3297 | - | |
| 3298 | - /// Enter the isolate solely to see whether another event settled this | |
| 3299 | - /// one's promise. | |
| 3300 | - /// | |
| 3301 | - /// A promise resolved by a different entry has no waker pointing here, | |
| 3302 | - /// so the driving task cannot be told and has to look. That is why this | |
| 3303 | - /// is a poll and not an event, and it is the same reason the blocking | |
| 3304 | - /// loop woke every 10 ms. | |
| 3305 | - pub fn turn_poll(&mut self, entry: &mut InFlight) -> Vec<Op> { | |
| 3306 | - let Some(inner) = self.inner.as_mut() else { | |
| 3307 | - return Vec::new(); | |
| 3308 | - }; | |
| 3309 | - let (mut locker, _cells) = inner.lock(); | |
| 3310 | - v8::scope!(let hs, &mut *locker); | |
| 3311 | - let realm = inner.realm(hs); | |
| 3312 | - let context = realm.context; | |
| 3313 | - let cs = &mut v8::ContextScope::new(hs, context); | |
| 3314 | - let tc = std::pin::pin!(v8::TryCatch::new(cs)); | |
| 3315 | - let tc = &mut tc.init(); | |
| 3316 | - | |
| 3317 | - let previous = install_trace(tc, entry.trace.as_ref()); | |
| 3318 | - let ops = finish_turn(tc, entry); | |
| 3319 | - restore_trace(tc, previous); | |
| 3320 | - ops | |
| 3321 | - } | |
| 3322 | - | |
| 3323 | - /// Enter the isolate solely to record how a claimed alarm ended. | |
| 3324 | - /// | |
| 3325 | - /// Reached only when the event ended without running JS again — a budget | |
| 3326 | - /// overrun, or a handler waiting on nothing. The bookkeeping is storage | |
| 3327 | - /// the isolate owns, so it cannot be done from the driving task. | |
| 3328 | - pub fn turn_finish_alarm(&mut self, entry: &mut InFlight) { | |
| 3329 | - let Some(inner) = self.inner.as_mut() else { | |
| 3330 | - return; | |
| 3331 | - }; | |
| 3332 | - let (_locker, _cells) = inner.lock(); | |
| 3333 | - entry.settle_alarm(false, false); | |
| 3334 | - } | |
| 3335 | -} | |
| 3336 | - | |
| 3337 | -// ---- native ops exposed to JS ---- | |
| 3338 | - | |
| 3339 | -/// Host ops, defined non-enumerable. They are runtime internals: a bundle | |
| 3340 | -/// walking `globalThis` must not find them, let alone `new` one — `for (const | |
| 3341 | -/// k in globalThis) new globalThis[k]()` used to reach `__actor_abort` and | |
| 3342 | -/// kill the actor. | |
| 3343 | -macro_rules! ops { | |
| 3344 | - ($scope:expr, $global:expr, $($name:literal => $op:path),* $(,)?) => { | |
| 3345 | - $({ | |
| 3346 | - let f = v8::Function::new($scope, $op).unwrap(); | |
| 3347 | - let k = v8::String::new($scope, $name).unwrap(); | |
| 3348 | - $global.define_own_property( | |
| 3349 | - $scope, k.into(), f.into(), v8::PropertyAttribute::DONT_ENUM); | |
| 3350 | - })* | |
| 3351 | - }; | |
| 3352 | -} | |
| 3353 | - | |
| 3354 | -fn install_ops(scope: &mut v8::PinScope, context: v8::Local<v8::Context>) { | |
| 3355 | - let global = context.global(scope); | |
| 3356 | - ops! { scope, global, | |
| 3357 | - "__heap_limit_excessively_exceeded" => | |
| 3358 | - op_heap_limit_excessively_exceeded, | |
| 3359 | - "__heap_over_admission_share" => op_heap_over_admission_share, | |
| 3360 | - "__ws_send" => websocket::op_ws_send, | |
| 3361 | - "__ws_send_binary" => websocket::op_ws_send_binary, | |
| 3362 | - "__ws_close" => websocket::op_ws_close, | |
| 3363 | - "__ws_alloc" => websocket::op_ws_alloc, | |
| 3364 | - "__ws_accept" => websocket::op_ws_accept, | |
| 3365 | - "__ws_accept_regular" => websocket::op_ws_accept_regular, | |
| 3366 | - "__ws_list" => websocket::op_ws_list, | |
| 3367 | - "__ws_attachment_set" => websocket::op_ws_attachment_set, | |
| 3368 | - "__ws_auto_response_set" => websocket::op_ws_auto_response_set, | |
| 3369 | - "__ws_auto_response_get" => websocket::op_ws_auto_response_get, | |
| 3370 | - "__ws_auto_response_ts" => websocket::op_ws_auto_response_ts, | |
| 3371 | - "__ws_connect" => websocket::op_ws_connect, | |
| 3372 | - "__ws_bind_target" => websocket::op_ws_bind_target, | |
| 3373 | - "__ws_next" => websocket::op_ws_next, | |
| 3374 | - "__ws_upgrade" => websocket::op_ws_upgrade, | |
| 3375 | - "__storage_get" => storage_ops::op_storage_get, | |
| 3376 | - "__storage_get_many" => storage_ops::op_storage_get_many, | |
| 3377 | - "__sql_exec" => storage_ops::op_sql_exec, | |
| 3378 | - "__sql_ingest" => storage_ops::op_sql_ingest, | |
| 3379 | - "__sql_cursor_start" => storage_ops::op_sql_cursor_start, | |
| 3380 | - "__sql_cursor_next" => storage_ops::op_sql_cursor_next, | |
| 3381 | - "__sql_cursor_close" => storage_ops::op_sql_cursor_close, | |
| 3382 | - "__sql_database_size" => storage_ops::op_sql_database_size, | |
| 3383 | - "__d1_run" => storage_ops::op_d1_run, | |
| 3384 | - "__storage_transaction_control" => storage_ops::op_storage_transaction_control, | |
| 3385 | - "__log" => op_log, | |
| 3386 | - "__storage_put" => storage_ops::op_storage_put, | |
| 3387 | - "__storage_put_many" => storage_ops::op_storage_put_many, | |
| 3388 | - "__storage_queue_put" => storage_ops::op_storage_queue_put, | |
| 3389 | - "__storage_queue_put_many" => storage_ops::op_storage_queue_put_many, | |
| 3390 | - "__storage_put_serialized" => storage_ops::op_storage_put_serialized, | |
| 3391 | - "__storage_queue_put_serialized" => storage_ops::op_storage_queue_put_serialized, | |
| 3392 | - "__storage_flush_pending_puts" => storage_ops::op_storage_flush_pending_puts, | |
| 3393 | - "__storage_cancel_pending_puts" => storage_ops::op_storage_cancel_pending_puts, | |
| 3394 | - "__actor_abort" => op_actor_abort, | |
| 3395 | - "__cron_plan" => op_cron_plan, | |
| 3396 | - "__process_exit" => op_process_exit, | |
| 3397 | - "__storage_delete" => storage_ops::op_storage_delete, | |
| 3398 | - "__storage_delete_many" => storage_ops::op_storage_delete_many, | |
| 3399 | - "__storage_list" => storage_ops::op_storage_list, | |
| 3400 | - "__storage_sync_list_start" => storage_ops::op_storage_sync_list_start, | |
| 3401 | - "__storage_sync_list_next" => storage_ops::op_storage_sync_list_next, | |
| 3402 | - "__storage_delete_all" => storage_ops::op_storage_delete_all, | |
| 3403 | - "$$urlParse" => op_url_parse, | |
| 3404 | - "$$urlPatternParse" => op_urlpattern_parse, | |
| 3405 | - "$$urlPatternMatchInput" => op_urlpattern_match_input, | |
| 3406 | - "$$atob" => op_atob, | |
| 3407 | - "$$btoa" => op_btoa, | |
| 3408 | - "$$textDecoderLabel" => op_text_decoder_label, | |
| 3409 | - "$$textDecoderNew" => op_text_decoder_new, | |
| 3410 | - "$$textDecoderDecode" => op_text_decoder_decode, | |
| 3411 | - "$$textDecoderDecodeOnce" => op_text_decoder_decode_once, | |
| 3412 | - "$$textDecoderFree" => op_text_decoder_free, | |
| 3413 | - "__alarm_set" => op_alarm_set, | |
| 3414 | - "__alarm_get" => op_alarm_get, | |
| 3415 | - "__alarm_delete" => op_alarm_delete, | |
| 3416 | - "__loader_load" => op_loader_load, | |
| 3417 | - "__loader_fetch" => op_loader_fetch, | |
| 3418 | - "__loader_rpc" => op_loader_rpc, | |
| 3419 | - "__loader_drop" => op_loader_drop, | |
| 3420 | - "__do_call" => op_do_call, | |
| 3421 | - "__writePosition" => op_write_position, | |
| 3422 | - "__gateWrite" => op_gate_write, | |
| 3423 | - "__svc_call" => op_svc_call, | |
| 3424 | - "__svc_call_cancellable" => op_svc_call_cancellable, | |
| 3425 | - "__svc_rpc" => op_svc_rpc, | |
| 3426 | - "__do_call_cancellable" => op_do_call_cancellable, | |
| 3427 | - "__do_call_cancel" => op_do_call_cancel, | |
| 3428 | - "__do_id" => op_do_id, | |
| 3429 | - "__rpc_call" => op_rpc_call, | |
| 3430 | - "__sc_encode" => storage_ops::op_sc_encode, | |
| 3431 | - "__sc_decode" => storage_ops::op_sc_decode, | |
| 3432 | - "__op_fetch" => op_fetch, | |
| 3433 | - "__asset_fetch" => op_asset_fetch, | |
| 3434 | - "__http_stream_read" => op_http_stream_read, | |
| 3435 | - "__http_stream_cancel" => op_http_stream_cancel, | |
| 3436 | - "__http_stream_tee" => op_http_stream_tee, | |
| 3437 | - "__response_stream_create" => op_response_stream_create, | |
| 3438 | - "__response_stream_write" => op_response_stream_write, | |
| 3439 | - "__response_stream_closed" => op_response_stream_closed, | |
| 3440 | - "__response_stream_close" => op_response_stream_close, | |
| 3441 | - "__op_timer" => op_timer, | |
| 3442 | - "__timer_alloc" => op_timer_alloc, | |
| 3443 | - "__gate_acquire" => op_gate_acquire, | |
| 3444 | - "__gate_wait" => op_gate_wait, | |
| 3445 | - "__gate_release" => op_gate_release, | |
| 3446 | - "__timer_cancel" => op_timer_cancel, | |
| 3447 | - "__crypto_operation" => crypto::op_crypto_operation, | |
| 3448 | - "$$randomValues" => crypto::op_webcrypto_random, | |
| 3449 | - "$$digest" => crypto::op_webcrypto_digest, | |
| 3450 | - "$$hmacSign" => crypto::op_webcrypto_hmac_sign, | |
| 3451 | - "$$hmacVerify" => crypto::op_webcrypto_hmac_verify, | |
| 3452 | - "$$aesEncrypt" => crypto::op_webcrypto_aes_encrypt, | |
| 3453 | - "$$aesDecrypt" => crypto::op_webcrypto_aes_decrypt, | |
| 3454 | - "$$pbkdf2" => crypto::op_node_pbkdf2, | |
| 3455 | - "$$hkdf" => crypto::op_node_hkdf, | |
| 3456 | - "$$timingSafeEqual" => crypto::op_timing_safe_equal, | |
| 3457 | - "__event_begin" => op_event_begin, | |
| 3458 | - "__event_end" => op_event_end, | |
| 3459 | - "__wait_until" => op_wait_until, | |
| 3460 | - "__event_depth" => op_event_depth, | |
| 3461 | - "__als_get" => op_als_get, | |
| 3462 | - "__als_set" => op_als_set, | |
| 3463 | - "__util_type_flags" => op_util_type_flags, | |
| 3464 | - "__util_constructor_name" => op_util_constructor_name, | |
| 3465 | - "__util_proxy_details" => op_util_proxy_details, | |
| 3466 | - "__util_promise_details" => op_util_promise_details, | |
| 3467 | - "__util_preview_entries" => op_util_preview_entries, | |
| 3468 | - "__builtin_module" => op_builtin_module, | |
| 3469 | - "__zlib" => zlib::op_zlib, | |
| 3470 | - "__zlib_stream_new" => zlib::op_zlib_stream_new, | |
| 3471 | - "__zlib_stream_push" => zlib::op_zlib_stream_push, | |
| 3472 | - "__zlib_stream_end" => zlib::op_zlib_stream_end, | |
| 3473 | - "__zlib_stream_drop" => zlib::op_zlib_stream_drop, | |
| 3474 | - } | |
| 3475 | - #[cfg(all(test, celld_internal_tests))] | |
| 3476 | - ops! { scope, global, | |
| 3477 | - "__test_gc" => op_test_gc, | |
| 3478 | - "__loader_count" => op_loader_count, | |
| 3479 | - "__test_set_heap_limit_excessively_exceeded" => | |
| 3480 | - op_test_set_heap_limit_excessively_exceeded, | |
| 3481 | - "__test_force_heap_admission_refusal" => | |
| 3482 | - op_test_force_heap_admission_refusal, | |
| 3483 | - "__test_heap_share" => op_test_heap_share, | |
| 3484 | - "__sql_set_max_page_count_for_test" => | |
| 3485 | - storage_ops::op_sql_set_max_page_count_for_test, | |
| 3486 | - "__sql_set_write_fault_for_test" => storage_ops::op_sql_set_write_fault_for_test, | |
| 3487 | - "__sql_set_cache_size_for_test" => storage_ops::op_sql_set_cache_size_for_test, | |
| 3488 | - "__sql_set_interrupt_fault_for_test" => | |
| 3489 | - storage_ops::op_sql_set_interrupt_fault_for_test, | |
| 3490 | - "__sql_register_nomem_function_for_test" => | |
| 3491 | - storage_ops::op_sql_register_nomem_function_for_test, | |
| 3492 | - } | |
| 3493 | -} | |
| 3494 | - | |
| 3495 | -/// Create a JS promise for an async op `id` and return it to JS. | |
| 3496 | -fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> { | |
| 3497 | - let resolver = v8::PromiseResolver::new(scope).unwrap(); | |
| 3498 | - let promise = resolver.get_promise(scope); | |
| 3499 | - promise_store(scope, id, v8::Global::new(scope, resolver)); | |
| 3500 | - promise.into() | |
| 3501 | -} | |
| 3502 | - | |
| 3503 | -/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await | |
| 3504 | -/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON | |
| 3505 | -/// `{status, body, headers}` string the harness turns back into a Response. | |
| 3506 | -/// `__svc_rpc(script, entrypoint, method, argsSc)` -> Promise<Uint8Array>; | |
| 3507 | -/// arguments and result are V8 structured-clone bytes. | |
| 3508 | -fn op_svc_rpc( | |
| 3509 | - scope: &mut v8::PinScope, | |
| 3510 | - args: v8::FunctionCallbackArguments, | |
| 3511 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 3512 | -) { | |
| 3513 | - let script = args.get(0).to_rust_string_lossy(scope); | |
| 3514 | - let entrypoint = args.get(1).to_rust_string_lossy(scope); | |
| 3515 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 3516 | - let call_args = view_bytes(args.get(3)).unwrap_or_default(); | |
| 3517 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 3518 | - let gate = egress_gate_request(); | |
| 3519 | - let request = SvcRpcReq { | |
| 3520 | - script, | |
| 3521 | - entrypoint, | |
| 3522 | - method, | |
| 3523 | - args: call_args, | |
| 3524 | - reply: tx, | |
| 3525 | - }; | |
| 3526 | - let id = asyncrt::enqueue(async move { | |
| 3527 | - gated_channel_send(gate, &SVC_RPC_TX, request, "no service binding channel").await?; | |
| 3528 | - match rx.await { | |
| 3529 | - Ok(Ok(result)) => Ok(result), | |
| 3530 | - Ok(Err(error)) => Err(format!("{error}")), | |
| 3531 | - Err(error) => Err(format!("service dropped: {error}")), | |
| 3532 | - } | |
| 3533 | - }); | |
| 3534 | - rv.set(promise_for(scope, id)); | |
| 3535 | -} | |
| 3536 | - | |
| 3537 | -/// `__svc_call(script, url, method, body, headersJson)` -> Promise<json>. | |
| 3538 | -/// The service-binding equivalent of `__do_call`: no scope to resolve and no | |
| 3539 | -/// cancellation token, just a handoff to the target script's pool. | |
| 3540 | -fn op_svc_call( | |
| 3541 | - scope: &mut v8::PinScope, | |
| 3542 | - args: v8::FunctionCallbackArguments, | |
| 3543 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 3544 | -) { | |
| 3545 | - op_svc_call_impl(scope, args, &mut rv, false); | |
| 3546 | -} | |
| 3547 | - | |
| 3548 | -fn op_svc_call_cancellable( | |
| 3549 | - scope: &mut v8::PinScope, | |
| 3550 | - args: v8::FunctionCallbackArguments, | |
| 3551 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 3552 | -) { | |
| 3553 | - op_svc_call_impl(scope, args, &mut rv, true); | |
| 3554 | -} | |
| 3555 | - | |
| 3556 | -fn op_svc_call_impl( | |
| 3557 | - scope: &mut v8::PinScope, | |
| 3558 | - args: v8::FunctionCallbackArguments, | |
| 3559 | - rv: &mut v8::ReturnValue<v8::Value>, | |
| 3560 | - cancellable: bool, | |
| 3561 | -) { | |
| 3562 | - let script = args.get(0).to_rust_string_lossy(scope); | |
| 3563 | - let url = args.get(1).to_rust_string_lossy(scope); | |
| 3564 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 3565 | - let body = view_bytes(args.get(3)).unwrap_or_default(); | |
| 3566 | - let headers = | |
| 3567 | - serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default(); | |
| 3568 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 3569 | - // Shares the Durable Object cancel registry, so `__do_call_cancel` works | |
| 3570 | - // unchanged for a service call. | |
| 3571 | - let (request_id, cancel, cancel_guard) = if cancellable { | |
| 3572 | - let request_id = next_do_request_id(); | |
| 3573 | - let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel(); | |
| 3574 | - do_call_cancels() | |
| 3575 | - .lock() | |
| 3576 | - .unwrap() | |
| 3577 | - .insert(request_id, cancel_sender); | |
| 3578 | - ( | |
| 3579 | - Some(request_id), | |
| 3580 | - Some(cancel_receiver), | |
| 3581 | - Some(DoCallCancelGuard::new(request_id)), | |
| 3582 | - ) | |
| 3583 | - } else { | |
| 3584 | - (None, None, None) | |
| 3585 | - }; | |
| 3586 | - let gate = egress_gate_request(); | |
| 3587 | - let request = SvcCallReq { | |
| 3588 | - cancel, | |
| 3589 | - script, | |
| 3590 | - url, | |
| 3591 | - method, | |
| 3592 | - body, | |
| 3593 | - headers, | |
| 3594 | - reply: tx, | |
| 3595 | - }; | |
| 3596 | - let id = asyncrt::enqueue(async move { | |
| 3597 | - let mut cancel_guard = cancel_guard; | |
| 3598 | - gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?; | |
| 3599 | - let result = match rx.await { | |
| 3600 | - Ok(Ok(response)) => Ok(encode_http_response(response, true)), | |
| 3601 | - Ok(Err(error)) => Err(format!("{error}")), | |
| 3602 | - Err(error) => Err(format!("service dropped: {error}")), | |
| 3603 | - }; | |
| 3604 | - if let Some(cancel_guard) = cancel_guard.as_mut() { | |
| 3605 | - cancel_guard.disarm(); | |
| 3606 | - } | |
| 3607 | - result | |
| 3608 | - }); | |
| 3609 | - let promise = promise_for(scope, id); | |
| 3610 | - if let Some(request_id) = request_id { | |
| 3611 | - if let Some(object) = promise.to_object(scope) { | |
| 3612 | - let key = v8::String::new(scope, "__celldCancelId").unwrap(); | |
| 3613 | - let value = v8::String::new(scope, &request_id.to_string()).unwrap(); | |
| 3614 | - object.set(scope, key.into(), value.into()); | |
| 3615 | - } | |
| 3616 | - } | |
| 3617 | - rv.set(promise); | |
| 3618 | -} | |
| 3619 | - | |
| 3620 | -// --- Worker Loader: dynamic isolates for Code Mode --- | |
| 3621 | -// A running Worker creates a fresh isolate from code it supplies at runtime | |
| 3622 | -// and invokes it. The loaded isolate uses the same turn driver as every | |
| 3623 | -// stateless Worker, so an awaited operation holds no thread or isolate. | |
| 3624 | - | |
| 3625 | -// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total | |
| 3626 | -// module bytes, 1 MiB env. Messages match so the conformance cases pass. | |
| 3627 | -const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024; | |
| 3628 | -const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024; | |
| 3629 | - | |
| 3630 | -#[derive(Clone)] | |
| 3631 | -enum LoaderState { | |
| 3632 | - Loading, | |
| 3633 | - Ready(Arc<crate::pool::Slot>), | |
| 3634 | - Failed(Arc<str>), | |
| 3635 | -} | |
| 3636 | - | |
| 3637 | -type LoaderRegistry = HashMap<u64, tokio::sync::watch::Receiver<LoaderState>>; | |
| 3638 | -static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new(); | |
| 3639 | -static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1); | |
| 3640 | - | |
| 3641 | -fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> { | |
| 3642 | - LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new())) | |
| 3643 | -} | |
| 3644 | - | |
| 3645 | -fn loader_throw(scope: &mut v8::PinScope, message: &str) { | |
| 3646 | - let message = v8::String::new(scope, message).unwrap(); | |
| 3647 | - let exception = v8::Exception::error(scope, message); | |
| 3648 | - scope.throw_exception(exception); | |
| 3649 | -} | |
| 3650 | - | |
| 3651 | -async fn loaded_worker_slot( | |
| 3652 | - mut state: tokio::sync::watch::Receiver<LoaderState>, | |
| 3653 | -) -> Result<Arc<crate::pool::Slot>, String> { | |
| 3654 | - loop { | |
| 3655 | - match state.borrow().clone() { | |
| 3656 | - LoaderState::Ready(slot) => return Ok(slot), | |
| 3657 | - LoaderState::Failed(error) => return Err(error.to_string()), | |
| 3658 | - LoaderState::Loading => {} | |
| 3659 | - } | |
| 3660 | - state | |
| 3661 | - .changed() | |
| 3662 | - .await | |
| 3663 | - .map_err(|_| "worker loader: load task dropped".to_string())?; | |
| 3664 | - } | |
| 3665 | -} | |
| 3666 | - | |
| 3667 | -/// `__loader_load(codeJson)` -> stub id. Builds a WorkerConfig from the | |
| 3668 | -/// supplied modules and registers its asynchronous load state. Compilation | |
| 3669 | -/// runs on Tokio's blocking pool. Calls wait for that result and then use the | |
| 3670 | -/// normal stateless turn driver. | |
| 3671 | -fn op_loader_load( | |
| 3672 | - scope: &mut v8::PinScope, | |
| 3673 | - args: v8::FunctionCallbackArguments, | |
| 3674 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 3675 | -) { | |
| 3676 | - let code_json = args.get(0).to_rust_string_lossy(scope); | |
| 3677 | - let code: serde_json::Value = match serde_json::from_str(&code_json) { | |
| 3678 | - Ok(code) => code, | |
| 3679 | - Err(e) => return loader_throw(scope, &format!("worker loader: {e}")), | |
| 3680 | - }; | |
| 3681 | - let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else { | |
| 3682 | - return loader_throw(scope, "worker loader: missing mainModule"); | |
| 3683 | - }; | |
| 3684 | - let Some(src) = code | |
| 3685 | - .get("modules") | |
| 3686 | - .and_then(|m| m.get(main)) | |
| 3687 | - .and_then(|v| v.as_str()) | |
| 3688 | - .map(str::to_string) | |
| 3689 | - else { | |
| 3690 | - return loader_throw( | |
| 3691 | - scope, | |
| 3692 | - &format!("worker loader: module {main:?} missing or not a string"), | |
| 3693 | - ); | |
| 3694 | - }; | |
| 3695 | - // Every module other than the main one is a sibling the main module may | |
| 3696 | - // import. JS modules arrive in the JSON as strings; anything else there is | |
| 3697 | - // rejected — JSON.stringify would already have mangled it, and dropping it | |
| 3698 | - // silently leaves the loaded worker failing instantiation with an | |
| 3699 | - // unresolved specifier that never names the cause. Wasm modules arrive | |
| 3700 | - // out of band as the second argument, an array of `[name, Uint8Array]` | |
| 3701 | - // pairs, which keeps the blobs out of the JSON payload entirely. | |
| 3702 | - let mut modules: Vec<(String, ModuleSource)> = Vec::new(); | |
| 3703 | - if let Some(map) = code.get("modules").and_then(|m| m.as_object()) { | |
| 3704 | - for (name, value) in map.iter().filter(|(name, _)| name.as_str() != main) { | |
| 3705 | - let Some(source) = value.as_str() else { | |
| 3706 | - return loader_throw( | |
| 3707 | - scope, | |
| 3708 | - &format!("worker loader: module {name:?} must be a string or wasm bytes"), | |
| 3709 | - ); | |
| 3710 | - }; | |
| 3711 | - modules.push((name.clone(), ModuleSource::EsModule(source.to_string()))); | |
| 3712 | - } | |
| 3713 | - } | |
| 3714 | - let sideband = args.get(1); | |
| 3715 | - if !sideband.is_undefined() { | |
| 3716 | - let Ok(entries) = v8::Local::<v8::Array>::try_from(sideband) else { | |
| 3717 | - return loader_throw(scope, "worker loader: wasm modules must be an array"); | |
| 3718 | - }; | |
| 3719 | - for index in 0..entries.length() { | |
| 3720 | - let entry = entries | |
| 3721 | - .get_index(scope, index) | |
| 3722 | - .and_then(|entry| v8::Local::<v8::Array>::try_from(entry).ok()) | |
| 3723 | - .and_then(|pair| Some((pair.get_index(scope, 0)?, pair.get_index(scope, 1)?))) | |
| 3724 | - .filter(|(name, _)| name.is_string()) | |
| 3725 | - .and_then(|(name, value)| { | |
| 3726 | - let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?; | |
| 3727 | - Some((name.to_rust_string_lossy(scope), view)) | |
| 3728 | - }); | |
| 3729 | - let Some((name, view)) = entry else { | |
| 3730 | - return loader_throw(scope, "worker loader: malformed wasm module entry"); | |
| 3731 | - }; | |
| 3732 | - // A name carried by both the JSON map and the side-band would | |
| 3733 | - // silently shadow one module with the other in the registry; | |
| 3734 | - // refuse it the way a non-string JSON module is refused. | |
| 3735 | - if name == main || modules.iter().any(|(existing, _)| *existing == name) { | |
| 3736 | - return loader_throw( | |
| 3737 | - scope, | |
| 3738 | - &format!("worker loader: duplicate module name {name:?}"), | |
| 3739 | - ); | |
| 3740 | - } | |
| 3741 | - let mut bytes = vec![0u8; view.byte_length()]; | |
| 3742 | - view.copy_contents(&mut bytes); | |
| 3743 | - modules.push((name, ModuleSource::Wasm(bytes.into()))); | |
| 3744 | - } | |
| 3745 | - } | |
| 3746 | - // Total module bytes, checked before compiling anything (the oversized | |
| 3747 | - // module is never parsed) — the extra modules are not yet loaded but do | |
| 3748 | - // count against the ceiling, as upstream. | |
| 3749 | - let code_size: usize = src.len() | |
| 3750 | - + modules | |
| 3751 | - .iter() | |
| 3752 | - .map(|(_, source)| match source { | |
| 3753 | - ModuleSource::Text(source) | ModuleSource::EsModule(source) => source.len(), | |
| 3754 | - ModuleSource::Wasm(bytes) => bytes.len(), | |
| 3755 | - }) | |
| 3756 | - .sum::<usize>(); | |
| 3757 | - if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE { | |
| 3758 | - return loader_throw( | |
| 3759 | - scope, | |
| 3760 | - &format!( | |
| 3761 | - "Dynamic Worker code size ({code_size} bytes) exceeds the \ | |
| 3762 | - maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes." | |
| 3763 | - ), | |
| 3764 | - ); | |
| 3765 | - } | |
| 3766 | - // Plain JSON `env` values merge onto the loaded worker's env; capability | |
| 3767 | - // stubs are not yet supported and would fail to serialize upstream in JS. | |
| 3768 | - let loader_env = code | |
| 3769 | - .get("env") | |
| 3770 | - .filter(|v| !v.is_null()) | |
| 3771 | - .map(|v| v.to_string()); | |
| 3772 | - if let Some(env) = &loader_env { | |
| 3773 | - if env.len() > MAX_DYNAMIC_WORKER_ENV_SIZE { | |
| 3774 | - return loader_throw( | |
| 3775 | - scope, | |
| 3776 | - &format!( | |
| 3777 | - "Dynamic Worker env size ({} bytes) exceeds the maximum \ | |
| 3778 | - allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.", | |
| 3779 | - env.len() | |
| 3780 | - ), | |
| 3781 | - ); | |
| 3782 | - } | |
| 3783 | - } | |
| 3784 | - // globalOutbound: absent inherits the caller's authority, null denies | |
| 3785 | - // ambient egress, a Fetcher (broker) is not implemented yet. | |
| 3786 | - let egress = match code.get("globalOutbound") { | |
| 3787 | - None => actor_runtime_state(scope).egress, | |
| 3788 | - Some(v) if v.is_null() => EgressPolicy::Deny, | |
| 3789 | - Some(_) => { | |
| 3790 | - return loader_throw( | |
| 3791 | - scope, | |
| 3792 | - "worker loader: globalOutbound broker is not implemented yet", | |
| 3793 | - ); | |
| 3794 | - } | |
| 3795 | - }; | |
| 3796 | - // Bound live loaded workers so a runaway agent loop cannot exhaust | |
| 3797 | - // isolates. Evicted workers (dropped stubs) free their slot. | |
| 3798 | - let max = crate::env_vars::positive_or("CELLD_MAX_LOADED_WORKERS", 256) | |
| 3799 | - .expect("validated CELLD_MAX_LOADED_WORKERS"); | |
| 3800 | - if loader_registry().lock().unwrap().len() >= max { | |
| 3801 | - return loader_throw( | |
| 3802 | - scope, | |
| 3803 | - &format!("worker loader: too many loaded workers (limit {max})"), | |
| 3804 | - ); | |
| 3805 | - } | |
| 3806 | - // Honor the WorkerCode's declared compatibility (workerd worker_compat | |
| 3807 | - // reads snake_case keys); Code Mode workers keep RPC on regardless. | |
| 3808 | - let mut compat = crate::worker_compat(&serde_json::json!({ | |
| 3809 | - "compatibility_date": code.get("compatibilityDate"), | |
| 3810 | - "compatibility_flags": code.get("compatibilityFlags"), | |
| 3811 | - })); | |
| 3812 | - compat.js_rpc = true; | |
| 3813 | - let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed); | |
| 3814 | - let config = Arc::new( | |
| 3815 | - WorkerConfig::new(WorkerConfigOptions { | |
| 3816 | - src, | |
| 3817 | - script_name: format!("__loader:{id}"), | |
| 3818 | - do_classes: Vec::new(), | |
| 3819 | - bindings: Vec::new(), | |
| 3820 | - r2_bindings: Vec::new(), | |
| 3821 | - // A loaded worker reaches D1 only if its parent injects a stub; | |
| 3822 | - // ambient bindings are exactly what Code Mode withholds. | |
| 3823 | - d1_bindings: Vec::new(), | |
| 3824 | - ai_binding: None, | |
| 3825 | - vars: Vec::new(), | |
| 3826 | - node: String::new(), | |
| 3827 | - modules, | |
| 3828 | - compat, | |
| 3829 | - }) | |
| 3830 | - .with_egress(egress) | |
| 3831 | - .with_loader_env(loader_env), | |
| 3832 | - ); | |
| 3833 | - let handle = match tokio::runtime::Handle::try_current() { | |
| 3834 | - Ok(handle) => handle, | |
| 3835 | - Err(error) => return loader_throw(scope, &format!("worker loader: {error}")), | |
| 3836 | - }; | |
| 3837 | - let (loaded, state) = tokio::sync::watch::channel(LoaderState::Loading); | |
| 3838 | - loader_registry().lock().unwrap().insert(id, state); | |
| 3839 | - handle.spawn(async move { | |
| 3840 | - let state = | |
| 3841 | - match tokio::task::spawn_blocking(move || Worker::load_config(config, &[])).await { | |
| 3842 | - Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::standalone(worker)), | |
| 3843 | - Ok(Err(error)) => LoaderState::Failed(Arc::from(format!("{error}"))), | |
| 3844 | - Err(error) => LoaderState::Failed(Arc::from(format!( | |
| 3845 | - "worker loader: load task failed: {error}" | |
| 3846 | - ))), | |
| 3847 | - }; | |
| 3848 | - loaded.send_replace(state); | |
| 3849 | - }); | |
| 3850 | - rv.set(v8::Number::new(scope, id as f64).into()); | |
| 3851 | -} | |
| 3852 | - | |
| 3853 | -/// `__loader_fetch(id, url, method, body, headersJson)` -> Promise<json>. The | |
| 3854 | -/// loaded-worker analog of `__svc_call`: encodes the response the same way. | |
| 3855 | -fn op_loader_fetch( | |
| 3856 | - scope: &mut v8::PinScope, | |
| 3857 | - args: v8::FunctionCallbackArguments, | |
| 3858 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 3859 | -) { | |
| 3860 | - let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 3861 | - let url = args.get(1).to_rust_string_lossy(scope); | |
| 3862 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 3863 | - let body = view_bytes(args.get(3)).unwrap_or_default(); | |
| 3864 | - let headers = | |
| 3865 | - serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default(); | |
| 3866 | - let loaded = loader_registry().lock().unwrap().get(&id).cloned(); | |
| 3867 | - let async_id = asyncrt::enqueue(async move { | |
| 3868 | - let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 3869 | - let slot = loaded_worker_slot(state).await?; | |
| 3870 | - let (reply, receive) = tokio::sync::oneshot::channel(); | |
| 3871 | - let job = crate::WorkerJob::Fetch { | |
| 3872 | - queued_at: Instant::now(), | |
| 3873 | - url, | |
| 3874 | - method, | |
| 3875 | - body: body.into(), | |
| 3876 | - headers, | |
| 3877 | - request_id: None, | |
| 3878 | - reply, | |
| 3879 | - }; | |
| 3880 | - let driving = tokio::spawn(crate::runtime::drive(slot, job, None)); | |
| 3881 | - match receive.await { | |
| 3882 | - Ok(Ok(response)) => Ok(encode_http_response(response, false)), | |
| 3883 | - Ok(Err(error)) => Err(format!("{error}")), | |
| 3884 | - Err(_) => match driving.await { | |
| 3885 | - Err(error) => Err(format!("loaded worker task died: {error}")), | |
| 3886 | - Ok(()) => Err("loaded worker dropped response".to_string()), | |
| 3887 | - }, | |
| 3888 | - } | |
| 3889 | - }); | |
| 3890 | - rv.set(promise_for(scope, async_id)); | |
| 3891 | -} | |
| 3892 | - | |
| 3893 | -/// `__loader_rpc(id, entrypoint, method, argsSc)` -> Promise<Uint8Array>. The | |
| 3894 | -/// loaded-worker analog of `__svc_rpc`: a named-entrypoint method call whose | |
| 3895 | -/// args and result are V8 structured-clone bytes. | |
| 3896 | -fn op_loader_rpc( | |
| 3897 | - scope: &mut v8::PinScope, | |
| 3898 | - args: v8::FunctionCallbackArguments, | |
| 3899 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 3900 | -) { | |
| 3901 | - let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 3902 | - let entrypoint = args.get(1).to_rust_string_lossy(scope); | |
| 3903 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 3904 | - let call_args = view_bytes(args.get(3)).unwrap_or_default(); | |
| 3905 | - let loaded = loader_registry().lock().unwrap().get(&id).cloned(); | |
| 3906 | - let async_id = asyncrt::enqueue(async move { | |
| 3907 | - let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?; | |
| 3908 | - let slot = loaded_worker_slot(state).await?; | |
| 3909 | - let (reply, receive) = tokio::sync::oneshot::channel(); | |
| 3910 | - let job = crate::WorkerJob::Rpc { | |
| 3911 | - entrypoint, | |
| 3912 | - method, | |
| 3913 | - args: call_args, | |
| 3914 | - reply, | |
| 3915 | - }; | |
| 3916 | - let driving = tokio::spawn(crate::runtime::drive(slot, job, None)); | |
| 3917 | - match receive.await { | |
| 3918 | - Ok(Ok(result)) => Ok(result), | |
| 3919 | - Ok(Err(error)) => Err(format!("{error}")), | |
| 3920 | - Err(_) => match driving.await { | |
| 3921 | - Err(error) => Err(format!("loaded worker task died: {error}")), | |
| 3922 | - Ok(()) => Err("loaded worker dropped RPC result".to_string()), | |
| 3923 | - }, | |
| 3924 | - } | |
| 3925 | - }); | |
| 3926 | - rv.set(promise_for(scope, async_id)); | |
| 3927 | -} | |
| 3928 | - | |
| 3929 | -/// `__loader_drop(id)` — evict a loaded worker. Called from a | |
| 3930 | -/// FinalizationRegistry when its stub is GC'd. Removing the registry entry | |
| 3931 | -/// drops the isolate after any calls that already cloned its load state end. | |
| 3932 | -fn op_loader_drop( | |
| 3933 | - scope: &mut v8::PinScope, | |
| 3934 | - args: v8::FunctionCallbackArguments, | |
| 3935 | - _rv: v8::ReturnValue<v8::Value>, | |
| 3936 | -) { | |
| 3937 | - let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 3938 | - if let Some(state) = loader_registry().lock().unwrap().remove(&id) { | |
| 3939 | - // This op runs while the parent isolate is entered. The load state can | |
| 3940 | - // own the loaded isolate, and V8 forbids dropping one isolate while a | |
| 3941 | - // different isolate is entered on the same thread. Hand the final | |
| 3942 | - // reference to the host scheduler so destruction happens after this | |
| 3943 | - // turn has left V8. | |
| 3944 | - asyncrt::op_handle().spawn(async move { drop(state) }); | |
| 3945 | - } | |
| 3946 | -} | |
| 3947 | - | |
| 3948 | -/// `__writePosition(scope)` -> the cell's committed-write position (a number), | |
| 3949 | -/// or `null` when the scope has no open connection. The co-hosted DO fast path | |
| 3950 | -/// samples this around an inline `fetch` to tell a write from a read. | |
| 3951 | -fn op_write_position( | |
| 3952 | - scope: &mut v8::PinScope, | |
| 3953 | - args: v8::FunctionCallbackArguments, | |
| 3954 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 3955 | -) { | |
| 3956 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 3957 | - match storage::write_position(&cell) { | |
| 3958 | - Some(position) => rv.set(v8::Number::new(scope, position as f64).into()), | |
| 3959 | - None => rv.set(v8::null(scope).into()), | |
| 3960 | - } | |
| 3961 | -} | |
| 3962 | - | |
| 3963 | -/// `__gateWrite(scope, positionOrNull)` -> a promise that resolves once every | |
| 3964 | -/// write the response can reveal is durable. A null position identifies a | |
| 3965 | -/// read-only response, which trails any barrier already open for the cell. | |
| 3966 | -fn op_gate_write( | |
| 3967 | - scope: &mut v8::PinScope, | |
| 3968 | - args: v8::FunctionCallbackArguments, | |
| 3969 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 3970 | -) { | |
| 3971 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 3972 | - let value = args.get(1); | |
| 3973 | - let position = (!value.is_null_or_undefined()) | |
| 3974 | - .then(|| value.to_integer(scope).map(|n| n.value() as u64)) | |
| 3975 | - .flatten(); | |
| 3976 | - let read_only = position.is_none(); | |
| 3977 | - let (tx, receive) = tokio::sync::oneshot::channel(); | |
| 3978 | - let sent = GATE_TX | |
| 3979 | - .get() | |
| 3980 | - .map(|gate| { | |
| 3981 | - gate.send(GateReq { | |
| 3982 | - scope: cell, | |
| 3983 | - position, | |
| 3984 | - reply: tx, | |
| 3985 | - }) | |
| 3986 | - .is_ok() | |
| 3987 | - }) | |
| 3988 | - .unwrap_or(false); | |
| 3989 | - let id = asyncrt::enqueue(async move { | |
| 3990 | - if !sent { | |
| 3991 | - if read_only { | |
| 3992 | - return Ok(String::new()); | |
| 3993 | - } | |
| 3994 | - return Err("no output-gate channel".into()); | |
| 3995 | - } | |
| 3996 | - match receive.await { | |
| 3997 | - Ok(Ok(())) => Ok(String::new()), | |
| 3998 | - Ok(Err(error)) => Err(format!("{error:?}")), | |
| 3999 | - Err(_) => Err("output gate dropped".into()), | |
| 4000 | - } | |
| 4001 | - }); | |
| 4002 | - rv.set(promise_for(scope, id)); | |
| 4003 | -} | |
| 4004 | - | |
| 4005 | -fn op_do_call( | |
| 4006 | - scope: &mut v8::PinScope, | |
| 4007 | - args: v8::FunctionCallbackArguments, | |
| 4008 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4009 | -) { | |
| 4010 | - op_do_call_impl(scope, args, &mut rv, false); | |
| 4011 | -} | |
| 4012 | - | |
| 4013 | -fn op_do_call_cancellable( | |
| 4014 | - scope: &mut v8::PinScope, | |
| 4015 | - args: v8::FunctionCallbackArguments, | |
| 4016 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4017 | -) { | |
| 4018 | - op_do_call_impl(scope, args, &mut rv, true); | |
| 4019 | -} | |
| 4020 | - | |
| 4021 | -fn op_do_call_impl( | |
| 4022 | - scope: &mut v8::PinScope, | |
| 4023 | - args: v8::FunctionCallbackArguments, | |
| 4024 | - rv: &mut v8::ReturnValue<v8::Value>, | |
| 4025 | - cancellable: bool, | |
| 4026 | -) { | |
| 4027 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 4028 | - let name_value = args.get(1); | |
| 4029 | - let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope)); | |
| 4030 | - let url = args.get(2).to_rust_string_lossy(scope); | |
| 4031 | - let method = args.get(3).to_rust_string_lossy(scope); | |
| 4032 | - let body = view_bytes(args.get(4)).unwrap_or_default(); | |
| 4033 | - let headers = | |
| 4034 | - serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)).unwrap_or_default(); | |
| 4035 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 4036 | - // Taken here and nowhere later: this is the last point that still runs | |
| 4037 | - // in the order the script made the calls. | |
| 4038 | - let order = Some(enter_call_order(current_context(), &cell)); | |
| 4039 | - // Every host op needs an internal cancellation channel. A caller without | |
| 4040 | - // an AbortSignal cannot cancel from JavaScript, but its enclosing Worker | |
| 4041 | - // can still disappear and drop this op before routing completes. | |
| 4042 | - let request_id = next_do_request_id(); | |
| 4043 | - let (cancel_sender, cancel) = tokio::sync::oneshot::channel(); | |
| 4044 | - do_call_cancels() | |
| 4045 | - .lock() | |
| 4046 | - .unwrap() | |
| 4047 | - .insert(request_id, cancel_sender); | |
| 4048 | - let mut cancel_guard = DoCallCancelGuard::new(request_id); | |
| 4049 | - let gate = egress_gate_request(); | |
| 4050 | - let request = DoCallReq { | |
| 4051 | - request_id: Some(request_id), | |
| 4052 | - cancel: Some(cancel), | |
| 4053 | - deliver_abort_to_handler: cancellable, | |
| 4054 | - scope: cell, | |
| 4055 | - name, | |
| 4056 | - url, | |
| 4057 | - method, | |
| 4058 | - body, | |
| 4059 | - headers, | |
| 4060 | - reply: tx, | |
| 4061 | - order, | |
| 4062 | - parent: current_trace_ids(scope), | |
| 4063 | - }; | |
| 4064 | - let id = asyncrt::enqueue(async move { | |
| 4065 | - gated_channel_send(gate, &DO_CALL_TX, request, "no proxy channel").await?; | |
| 4066 | - let result = match rx.await { | |
| 4067 | - Ok(Ok(response)) => Ok(encode_http_response(response, true)), | |
| 4068 | - Ok(Err(e)) => Err(format!("{e}")), | |
| 4069 | - Err(e) => Err(format!("proxy dropped: {e}")), | |
| 4070 | - }; | |
| 4071 | - cancel_guard.disarm(); | |
| 4072 | - result | |
| 4073 | - }); | |
| 4074 | - let p = promise_for(scope, id); | |
| 4075 | - if cancellable { | |
| 4076 | - if let Some(promise) = p.to_object(scope) { | |
| 4077 | - let key = v8::String::new(scope, "__celldCancelId").unwrap(); | |
| 4078 | - let request_id = v8::String::new(scope, &request_id_string(request_id)).unwrap(); | |
| 4079 | - promise.set(scope, key.into(), request_id.into()); | |
| 4080 | - } | |
| 4081 | - } | |
| 4082 | - rv.set(p); | |
| 4083 | -} | |
| 4084 | - | |
| 4085 | -fn op_do_call_cancel( | |
| 4086 | - scope: &mut v8::PinScope, | |
| 4087 | - args: v8::FunctionCallbackArguments, | |
| 4088 | - _rv: v8::ReturnValue<v8::Value>, | |
| 4089 | -) { | |
| 4090 | - let request_id = args.get(0).to_rust_string_lossy(scope); | |
| 4091 | - let Some(request_id) = parse_request_id(&request_id) else { | |
| 4092 | - return; | |
| 4093 | - }; | |
| 4094 | - if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) { | |
| 4095 | - let _ = cancel.send(()); | |
| 4096 | - } | |
| 4097 | -} | |
| 4098 | - | |
| 4099 | -/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>; | |
| 4100 | -/// arguments and result are V8 structured-clone bytes. | |
| 4101 | -fn op_rpc_call( | |
| 4102 | - scope: &mut v8::PinScope, | |
| 4103 | - args: v8::FunctionCallbackArguments, | |
| 4104 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4105 | -) { | |
| 4106 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 4107 | - let name_value = args.get(1); | |
| 4108 | - let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope)); | |
| 4109 | - let method = args.get(2).to_rust_string_lossy(scope); | |
| 4110 | - let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default()); | |
| 4111 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 4112 | - let gate = egress_gate_request(); | |
| 4113 | - let request = RpcCallReq { | |
| 4114 | - scope: cell, | |
| 4115 | - name, | |
| 4116 | - method, | |
| 4117 | - args, | |
| 4118 | - reply: tx, | |
| 4119 | - }; | |
| 4120 | - let id = asyncrt::enqueue(async move { | |
| 4121 | - gated_channel_send(gate, &RPC_CALL_TX, request, "no RPC channel").await?; | |
| 4122 | - match rx.await { | |
| 4123 | - Ok(Ok(RpcData::V8(bytes))) => Ok(bytes), | |
| 4124 | - Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()), | |
| 4125 | - Ok(Err(e)) => Err(format!("{e}")), | |
| 4126 | - Err(e) => Err(format!("RPC proxy dropped: {e}")), | |
| 4127 | - } | |
| 4128 | - }); | |
| 4129 | - let p = promise_for(scope, id); | |
| 4130 | - rv.set(p); | |
| 4131 | -} | |
| 4132 | - | |
| 4133 | -/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON | |
| 4134 | -/// `{status, body, headers}` string. Streaming is a later layer. | |
| 4135 | -fn op_fetch( | |
| 4136 | - scope: &mut v8::PinScope, | |
| 4137 | - args: v8::FunctionCallbackArguments, | |
| 4138 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4139 | -) { | |
| 4140 | - // A loaded worker with globalOutbound: null has no ambient egress: it must | |
| 4141 | - // reach the world through `env` capabilities. Message matches workerd. | |
| 4142 | - if actor_runtime_state(scope).egress == EgressPolicy::Deny { | |
| 4143 | - return loader_throw( | |
| 4144 | - scope, | |
| 4145 | - "This worker is not permitted to access the internet via global \ | |
| 4146 | - functions like fetch(). It must use capabilities (such as \ | |
| 4147 | - bindings in 'env') to talk to the outside world.", | |
| 4148 | - ); | |
| 4149 | - } | |
| 4150 | - let method = args.get(0).to_rust_string_lossy(scope); | |
| 4151 | - let url = args.get(1).to_rust_string_lossy(scope); | |
| 4152 | - let b = args.get(2); | |
| 4153 | - let body: Option<Vec<u8>> = if b.is_undefined() || b.is_null() { | |
| 4154 | - None | |
| 4155 | - } else { | |
| 4156 | - serde_json::from_str(&b.to_rust_string_lossy(scope)).ok() | |
| 4157 | - }; | |
| 4158 | - let mut headers: Vec<(String, String)> = | |
| 4159 | - serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default(); | |
| 4160 | - let redirect = args.get(4).to_rust_string_lossy(scope); | |
| 4161 | - let client = if redirect == "manual" { | |
| 4162 | - HTTP_MANUAL.with(|client| client.clone()) | |
| 4163 | - } else { | |
| 4164 | - HTTP.with(|client| client.clone()) | |
| 4165 | - }; | |
| 4166 | - // The creating context, read here while JS is still running: the op | |
| 4167 | - // future resolves on whatever worker polls it, far from any CPED. | |
| 4168 | - let trace = current_trace_ids(scope); | |
| 4169 | - // The child's ids are minted before the request leaves so the | |
| 4170 | - // traceparent header carries them: whatever this fetch reaches can | |
| 4171 | - // join the trace celld is part of. | |
| 4172 | - let child = trace.as_ref().map(crate::telemetry::child_ids); | |
| 4173 | - if let Some(child) = child.as_ref() { | |
| 4174 | - if !headers | |
| 4175 | - .iter() | |
| 4176 | - .any(|(name, _)| name.eq_ignore_ascii_case("traceparent")) | |
| 4177 | - { | |
| 4178 | - headers.push(("traceparent".into(), crate::telemetry::traceparent(child))); | |
| 4179 | - } | |
| 4180 | - } | |
| 4181 | - let span_url = trace.as_ref().map(|_| url.clone()); | |
| 4182 | - // Whatever this request can reveal must be durable before it leaves: a | |
| 4183 | - // third party that has acted on a write celld then loses cannot be told to | |
| 4184 | - // un-act. That covers a write this handler made and a value it only read, | |
| 4185 | - // because the third party cannot tell the two apart. | |
| 4186 | - let gate = egress_gate_request(); | |
| 4187 | - let id = asyncrt::enqueue(async move { | |
| 4188 | - let span_started = trace.as_ref().map(|_| crate::telemetry::now_unix_us()); | |
| 4189 | - let mut span = trace.as_ref().zip(child).map(|(parent, child)| { | |
| 4190 | - let mut span = | |
| 4191 | - crate::telemetry::Span::new(child, "fetch", crate::telemetry::KIND_CLIENT); | |
| 4192 | - span.parent_span_id = Some(parent.span_id); | |
| 4193 | - span.parent_remote = Some(false); | |
| 4194 | - span.url = span_url; | |
| 4195 | - span | |
| 4196 | - }); | |
| 4197 | - let mut finish = |ok: bool, status: Option<u16>, error: Option<String>| { | |
| 4198 | - if let Some(mut span) = span.take() { | |
| 4199 | - span.start_unix_us = span_started.unwrap_or_default(); | |
| 4200 | - span.duration_us = crate::telemetry::now_unix_us() - span.start_unix_us; | |
| 4201 | - span.ok = ok; | |
| 4202 | - span.http_status = status; | |
| 4203 | - span.error = error; | |
| 4204 | - crate::telemetry::record(span); | |
| 4205 | - } | |
| 4206 | - }; | |
| 4207 | - await_egress_gate(gate).await.inspect_err(|error| { | |
| 4208 | - finish(false, None, Some(error.clone())); | |
| 4209 | - })?; | |
| 4210 | - let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET); | |
| 4211 | - // a timeout bounds a black-hole host: the future settles (Err) instead | |
| 4212 | - // of parking run_loop forever — the hang the Drop guard can't catch. | |
| 4213 | - let fetch_timeout = crate::env_vars::positive_or("CELLD_FETCH_TIMEOUT_S", 120) | |
| 4214 | - .expect("validated CELLD_FETCH_TIMEOUT_S"); | |
| 4215 | - let mut rb = client | |
| 4216 | - .request(m, &url) | |
| 4217 | - .timeout(std::time::Duration::from_secs(fetch_timeout)); | |
| 4218 | - for (name, value) in headers { | |
| 4219 | - rb = rb.header(name, value); | |
| 4220 | - } | |
| 4221 | - if let Some(b) = body { | |
| 4222 | - rb = rb.body(b); | |
| 4223 | - } | |
| 4224 | - match rb.send().await { | |
| 4225 | - Ok(resp) => { | |
| 4226 | - let status = resp.status().as_u16(); | |
| 4227 | - finish(true, Some(status), None); | |
| 4228 | - let headers = resp | |
| 4229 | - .headers() | |
| 4230 | - .iter() | |
| 4231 | - .map(|(name, value)| { | |
| 4232 | - ( | |
| 4233 | - name.as_str().to_string(), | |
| 4234 | - value.to_str().unwrap_or_default().to_string(), | |
| 4235 | - ) | |
| 4236 | - }) | |
| 4237 | - .collect::<Vec<_>>(); | |
| 4238 | - let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 4239 | - register_http_stream(stream_id, HttpStreamSource::Response(resp)); | |
| 4240 | - Ok(serde_json::json!({ | |
| 4241 | - "status": status, "streamId": stream_id, "headers": headers, | |
| 4242 | - }) | |
| 4243 | - .to_string()) | |
| 4244 | - } | |
| 4245 | - Err(e) => { | |
| 4246 | - finish(false, None, Some(format!("fetch: {e}"))); | |
| 4247 | - Err(format!("fetch: {e}")) | |
| 4248 | - } | |
| 4249 | - } | |
| 4250 | - }); | |
| 4251 | - let p = promise_for(scope, id); | |
| 4252 | - rv.set(p); | |
| 4253 | -} | |
| 4254 | - | |
| 4255 | -fn op_asset_fetch( | |
| 4256 | - scope: &mut v8::PinScope, | |
| 4257 | - args: v8::FunctionCallbackArguments, | |
| 4258 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4259 | -) { | |
| 4260 | - let script = args.get(0).to_rust_string_lossy(scope); | |
| 4261 | - let method = args.get(1).to_rust_string_lossy(scope); | |
| 4262 | - let url = args.get(2).to_rust_string_lossy(scope); | |
| 4263 | - let headers: Vec<(String, String)> = | |
| 4264 | - serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default(); | |
| 4265 | - let (tx, rx) = tokio::sync::oneshot::channel(); | |
| 4266 | - let sent = ASSET_CALL_TX.get().is_some_and(|sender| { | |
| 4267 | - sender | |
| 4268 | - .send(AssetCallReq { | |
| 4269 | - script, | |
| 4270 | - url, | |
| 4271 | - method, | |
| 4272 | - headers, | |
| 4273 | - reply: tx, | |
| 4274 | - }) | |
| 4275 | - .is_ok() | |
| 4276 | - }); | |
| 4277 | - let id = asyncrt::enqueue(async move { | |
| 4278 | - if !sent { | |
| 4279 | - return Err("no asset resolver channel".to_string()); | |
| 4280 | - } | |
| 4281 | - match rx.await { | |
| 4282 | - Ok(Ok(response)) => Ok(encode_http_response(response, false)), | |
| 4283 | - Ok(Err(error)) => Err(format!("asset fetch: {error}")), | |
| 4284 | - Err(error) => Err(format!("asset resolver dropped: {error}")), | |
| 4285 | - } | |
| 4286 | - }); | |
| 4287 | - rv.set(promise_for(scope, id)); | |
| 4288 | -} | |
| 4289 | - | |
| 4290 | -async fn next_http_stream_chunk(source: &mut HttpStreamSource) -> Result<Option<Vec<u8>>, String> { | |
| 4291 | - match source { | |
| 4292 | - HttpStreamSource::Response(response) => response | |
| 4293 | - .chunk() | |
| 4294 | - .await | |
| 4295 | - .map(|chunk| chunk.map(|bytes| bytes.to_vec())) | |
| 4296 | - .map_err(|error| format!("response stream: {error}")), | |
| 4297 | - HttpStreamSource::Receiver(receiver) => match receiver.recv().await { | |
| 4298 | - Some(Ok(bytes)) => Ok(Some(bytes)), | |
| 4299 | - Some(Err(error)) => Err(error), | |
| 4300 | - None => Ok(None), | |
| 4301 | - }, | |
| 4302 | - HttpStreamSource::Stream(stream) => stream.next().await.transpose(), | |
| 4303 | - } | |
| 4304 | -} | |
| 4305 | - | |
| 4306 | -/// Move a host response source into a directly-polled stream. No pump task is | |
| 4307 | -/// needed: the eventual HTTP or JS consumer supplies the backpressure. | |
| 4308 | -fn http_chunk_stream(source: HttpStreamSource) -> HttpChunkStream { | |
| 4309 | - match source { | |
| 4310 | - HttpStreamSource::Response(response) => Box::pin(response.bytes_stream().map(|chunk| { | |
| 4311 | - chunk | |
| 4312 | - .map(|bytes| bytes.to_vec()) | |
| 4313 | - .map_err(|error| format!("response stream: {error}")) | |
| 4314 | - })), | |
| 4315 | - HttpStreamSource::Receiver(receiver) => { | |
| 4316 | - Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver)) | |
| 4317 | - } | |
| 4318 | - HttpStreamSource::Stream(stream) => stream, | |
| 4319 | - } | |
| 4320 | -} | |
| 4321 | - | |
| 4322 | -/// Host-native tee for an outbound response. Both branches are represented by | |
| 4323 | -/// stream IDs, so one can be returned through Axum while JS independently | |
| 4324 | -/// scans the other for observability or usage accounting. | |
| 4325 | -fn tee_http_stream(mut source: HttpStreamSource) -> (u64, u64) { | |
| 4326 | - let (tx1, rx1) = tokio::sync::mpsc::channel(16); | |
| 4327 | - let (tx2, rx2) = tokio::sync::mpsc::channel(16); | |
| 4328 | - let id1 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 4329 | - let id2 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 4330 | - register_http_stream(id1, HttpStreamSource::Receiver(rx1)); | |
| 4331 | - register_http_stream(id2, HttpStreamSource::Receiver(rx2)); | |
| 4332 | - asyncrt::op_handle().spawn(async move { | |
| 4333 | - loop { | |
| 4334 | - match next_http_stream_chunk(&mut source).await { | |
| 4335 | - Ok(Some(bytes)) => { | |
| 4336 | - let first = tx1.send(Ok(bytes.clone())).await.is_ok(); | |
| 4337 | - let second = tx2.send(Ok(bytes)).await.is_ok(); | |
| 4338 | - if !first && !second { | |
| 4339 | - break; | |
| 4340 | - } | |
| 4341 | - } | |
| 4342 | - Ok(None) => break, | |
| 4343 | - Err(error) => { | |
| 4344 | - let _ = tx1.send(Err(error.clone())).await; | |
| 4345 | - let _ = tx2.send(Err(error)).await; | |
| 4346 | - break; | |
| 4347 | - } | |
| 4348 | - } | |
| 4349 | - } | |
| 4350 | - }); | |
| 4351 | - (id1, id2) | |
| 4352 | -} | |
| 4353 | - | |
| 4354 | -fn op_http_stream_read( | |
| 4355 | - scope: &mut v8::PinScope, | |
| 4356 | - args: v8::FunctionCallbackArguments, | |
| 4357 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4358 | -) { | |
| 4359 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 4360 | - let source = http_streams() | |
| 4361 | - .lock() | |
| 4362 | - .unwrap() | |
| 4363 | - .get_mut(&stream_id) | |
| 4364 | - .and_then(|stream| { | |
| 4365 | - stream | |
| 4366 | - .source | |
| 4367 | - .take() | |
| 4368 | - .map(|source| (source, stream.cancelled.subscribe())) | |
| 4369 | - }); | |
| 4370 | - let id = asyncrt::enqueue(async move { | |
| 4371 | - let Some((mut source, mut cancelled)) = source else { | |
| 4372 | - return Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())); | |
| 4373 | - }; | |
| 4374 | - let next = tokio::select! { | |
| 4375 | - result = next_http_stream_chunk(&mut source) => Some(result), | |
| 4376 | - _ = cancelled.changed() => None, | |
| 4377 | - }; | |
| 4378 | - match next { | |
| 4379 | - None => Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())), | |
| 4380 | - Some(Ok(Some(bytes))) => { | |
| 4381 | - if let Some(stream) = http_streams().lock().unwrap().get_mut(&stream_id) { | |
| 4382 | - stream.created = Instant::now(); | |
| 4383 | - stream.source = Some(source); | |
| 4384 | - } | |
| 4385 | - Ok(asyncrt::OpOut::Bytes(bytes)) | |
| 4386 | - } | |
| 4387 | - Some(Ok(None)) => { | |
| 4388 | - http_streams().lock().unwrap().remove(&stream_id); | |
| 4389 | - Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())) | |
| 4390 | - } | |
| 4391 | - Some(Err(error)) => { | |
| 4392 | - http_streams().lock().unwrap().remove(&stream_id); | |
| 4393 | - Err(error) | |
| 4394 | - } | |
| 4395 | - } | |
| 4396 | - }); | |
| 4397 | - rv.set(promise_for(scope, id)); | |
| 4398 | -} | |
| 4399 | - | |
| 4400 | -fn op_http_stream_tee( | |
| 4401 | - scope: &mut v8::PinScope, | |
| 4402 | - args: v8::FunctionCallbackArguments, | |
| 4403 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4404 | -) { | |
| 4405 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 4406 | - let source = http_streams() | |
| 4407 | - .lock() | |
| 4408 | - .unwrap() | |
| 4409 | - .remove(&stream_id) | |
| 4410 | - .and_then(|stream| stream.source); | |
| 4411 | - let Some(source) = source else { | |
| 4412 | - let message = v8::String::new(scope, "response stream is no longer available").unwrap(); | |
| 4413 | - let exception = v8::Exception::type_error(scope, message); | |
| 4414 | - scope.throw_exception(exception); | |
| 4415 | - return; | |
| 4416 | - }; | |
| 4417 | - let ids = tee_http_stream(source); | |
| 4418 | - let json = serde_json::to_string(&ids).unwrap(); | |
| 4419 | - rv.set(v8::String::new(scope, &json).unwrap().into()); | |
| 4420 | -} | |
| 4421 | - | |
| 4422 | -fn op_http_stream_cancel( | |
| 4423 | - scope: &mut v8::PinScope, | |
| 4424 | - args: v8::FunctionCallbackArguments, | |
| 4425 | - _rv: v8::ReturnValue<v8::Value>, | |
| 4426 | -) { | |
| 4427 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 4428 | - if let Some(stream) = http_streams().lock().unwrap().remove(&stream_id) { | |
| 4429 | - let _ = stream.cancelled.send(true); | |
| 4430 | - } | |
| 4431 | -} | |
| 4432 | - | |
| 4433 | -fn op_response_stream_create( | |
| 4434 | - scope: &mut v8::PinScope, | |
| 4435 | - _args: v8::FunctionCallbackArguments, | |
| 4436 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4437 | -) { | |
| 4438 | - let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 4439 | - let (writer, receiver) = tokio::sync::mpsc::channel(1); | |
| 4440 | - let (finished, _) = tokio::sync::watch::channel(false); | |
| 4441 | - let now = Instant::now(); | |
| 4442 | - register_http_stream(stream_id, HttpStreamSource::Receiver(receiver)); | |
| 4443 | - let mut writers = response_stream_writers().lock().unwrap(); | |
| 4444 | - writers.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60)); | |
| 4445 | - writers.insert( | |
| 4446 | - stream_id, | |
| 4447 | - ResponseStreamWriter { | |
| 4448 | - created: now, | |
| 4449 | - writer, | |
| 4450 | - finished, | |
| 4451 | - }, | |
| 4452 | - ); | |
| 4453 | - rv.set(v8::Number::new(scope, stream_id as f64).into()); | |
| 4454 | -} | |
| 4455 | - | |
| 4456 | -fn op_response_stream_write( | |
| 4457 | - scope: &mut v8::PinScope, | |
| 4458 | - args: v8::FunctionCallbackArguments, | |
| 4459 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4460 | -) { | |
| 4461 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 4462 | - let bytes = args | |
| 4463 | - .get(1) | |
| 4464 | - .try_cast::<v8::ArrayBufferView>() | |
| 4465 | - .ok() | |
| 4466 | - .map(|view| { | |
| 4467 | - let mut bytes = vec![0; view.byte_length()]; | |
| 4468 | - view.copy_contents(&mut bytes); | |
| 4469 | - bytes | |
| 4470 | - }); | |
| 4471 | - let writer = response_stream_writers() | |
| 4472 | - .lock() | |
| 4473 | - .unwrap() | |
| 4474 | - .get_mut(&stream_id) | |
| 4475 | - .map(|stream| { | |
| 4476 | - stream.created = Instant::now(); | |
| 4477 | - stream.writer.clone() | |
| 4478 | - }); | |
| 4479 | - let id = asyncrt::enqueue(async move { | |
| 4480 | - let Some(bytes) = bytes else { | |
| 4481 | - return Err("response stream chunks must be ArrayBuffer views".into()); | |
| 4482 | - }; | |
| 4483 | - let Some(writer) = writer else { | |
| 4484 | - return Err("response stream consumer canceled".into()); | |
| 4485 | - }; | |
| 4486 | - if writer.send(Ok(bytes)).await.is_err() { | |
| 4487 | - response_stream_writers().lock().unwrap().remove(&stream_id); | |
| 4488 | - return Err("response stream consumer canceled".into()); | |
| 4489 | - } | |
| 4490 | - Ok(String::new()) | |
| 4491 | - }); | |
| 4492 | - rv.set(promise_for(scope, id)); | |
| 4493 | -} | |
| 4494 | - | |
| 4495 | -fn op_response_stream_closed( | |
| 4496 | - scope: &mut v8::PinScope, | |
| 4497 | - args: v8::FunctionCallbackArguments, | |
| 4498 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4499 | -) { | |
| 4500 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 4501 | - let (writer, mut finished) = response_stream_writers() | |
| 4502 | - .lock() | |
| 4503 | - .unwrap() | |
| 4504 | - .get(&stream_id) | |
| 4505 | - .map(|stream| (stream.writer.clone(), stream.finished.subscribe())) | |
| 4506 | - .unzip(); | |
| 4507 | - let id = asyncrt::enqueue(async move { | |
| 4508 | - let cancelled = match (writer, finished.as_mut()) { | |
| 4509 | - (Some(writer), Some(finished)) => tokio::select! { | |
| 4510 | - biased; | |
| 4511 | - result = finished.changed() => result.is_err(), | |
| 4512 | - _ = writer.closed() => true, | |
| 4513 | - }, | |
| 4514 | - _ => false, | |
| 4515 | - }; | |
| 4516 | - Ok(String::from(if cancelled { | |
| 4517 | - "cancelled" | |
| 4518 | - } else { | |
| 4519 | - "finished" | |
| 4520 | - })) | |
| 4521 | - }); | |
| 4522 | - rv.set(promise_for(scope, id)); | |
| 4523 | -} | |
| 4524 | - | |
| 4525 | -fn op_response_stream_close( | |
| 4526 | - scope: &mut v8::PinScope, | |
| 4527 | - args: v8::FunctionCallbackArguments, | |
| 4528 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4529 | -) { | |
| 4530 | - let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 4531 | - let error = args.get(1).to_rust_string_lossy(scope); | |
| 4532 | - let stream = response_stream_writers().lock().unwrap().remove(&stream_id); | |
| 4533 | - let id = asyncrt::enqueue(async move { | |
| 4534 | - if let Some(stream) = stream { | |
| 4535 | - let _ = stream.finished.send(true); | |
| 4536 | - if !error.is_empty() { | |
| 4537 | - let _ = stream.writer.send(Err(error)).await; | |
| 4538 | - } | |
| 4539 | - } | |
| 4540 | - Ok(String::new()) | |
| 4541 | - }); | |
| 4542 | - rv.set(promise_for(scope, id)); | |
| 4543 | -} | |
| 4544 | - | |
| 4545 | -pub fn reqwest_response_stream(response: reqwest::Response) -> HttpChunkStream { | |
| 4546 | - http_chunk_stream(HttpStreamSource::Response(response)) | |
| 4547 | -} | |
| 4548 | - | |
| 4549 | -/// Hand a request body to the isolate as a stream rather than as bytes. | |
| 4550 | -/// The returned id names the stream for `__http_stream_read`, so the | |
| 4551 | -/// Worker pulls each chunk off the socket as it asks for it and the host | |
| 4552 | -/// never holds the whole body. | |
| 4553 | -pub fn register_body_stream(stream: HttpChunkStream) -> u64 { | |
| 4554 | - let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 4555 | - register_http_stream(stream_id, HttpStreamSource::Stream(stream)); | |
| 4556 | - stream_id | |
| 4557 | -} | |
| 4558 | - | |
| 4559 | -/// How an incoming request body reaches the isolate. | |
| 4560 | -/// | |
| 4561 | -/// A small body crosses as bytes. This costs one copy and no asynchronous | |
| 4562 | -/// operations, so a common request pays nothing for a stream that it does | |
| 4563 | -/// not need. A large body, or a body of unknown length, crosses as a | |
| 4564 | -/// stream id. The peak cost of that body is one chunk, not its length. | |
| 4565 | -pub enum RequestBody { | |
| 4566 | - Bytes(Vec<u8>), | |
| 4567 | - Stream(u64), | |
| 4568 | -} | |
| 4569 | - | |
| 4570 | -impl RequestBody { | |
| 4571 | - /// The bytes already in hand, for the paths that hold a whole body. | |
| 4572 | - pub fn bytes(&self) -> &[u8] { | |
| 4573 | - match self { | |
| 4574 | - Self::Bytes(bytes) => bytes, | |
| 4575 | - Self::Stream(_) => &[], | |
| 4576 | - } | |
| 4577 | - } | |
| 4578 | -} | |
| 4579 | - | |
| 4580 | -impl From<Vec<u8>> for RequestBody { | |
| 4581 | - fn from(bytes: Vec<u8>) -> Self { | |
| 4582 | - Self::Bytes(bytes) | |
| 4583 | - } | |
| 4584 | -} | |
| 4585 | - | |
| 4586 | -/// Timer op behind `setTimeout`: a promise resolving after `ms`. | |
| 4587 | -fn op_timer( | |
| 4588 | - scope: &mut v8::PinScope, | |
| 4589 | - args: v8::FunctionCallbackArguments, | |
| 4590 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4591 | -) { | |
| 4592 | - let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 4593 | - let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64; | |
| 4594 | - let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel(); | |
| 4595 | - timer_cancels().lock().unwrap().insert(timer_id, cancel_tx); | |
| 4596 | - let id = asyncrt::enqueue(async move { | |
| 4597 | - tokio::select! { | |
| 4598 | - _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {} | |
| 4599 | - _ = &mut cancel_rx => {} | |
| 4600 | - } | |
| 4601 | - timer_cancels().lock().unwrap().remove(&timer_id); | |
| 4602 | - Ok(String::new()) | |
| 4603 | - }); | |
| 4604 | - let p = promise_for(scope, id); | |
| 4605 | - rv.set(p); | |
| 4606 | -} | |
| 4607 | - | |
| 4608 | -/// `__gate_acquire(scope)` — take the cell's input gate for a | |
| 4609 | -/// `blockConcurrencyWhile`, waiting if another block holds it. | |
| 4610 | -/// | |
| 4611 | -/// Answers a promise of the event id, not the id itself. It was synchronous, | |
| 4612 | -/// and that was right while a cell's events came off one channel: only one | |
| 4613 | -/// ran at a time, a delivery point had already found the gate open, and | |
| 4614 | -/// yielding even one microtask reopened a window in which a nested delivery | |
| 4615 | -/// could wait on a gate nothing would release. Neither half holds now — | |
| 4616 | -/// events are independent tasks, several run at once, and nothing nests — | |
| 4617 | -/// so two blocks can meet and the second must queue. | |
| 4618 | -fn op_gate_acquire( | |
| 4619 | - scope: &mut v8::PinScope, | |
| 4620 | - args: v8::FunctionCallbackArguments, | |
| 4621 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4622 | -) { | |
| 4623 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 4624 | - let event = NEXT_GATE_EVENT.fetch_add(1, Ordering::Relaxed); | |
| 4625 | - // Taken under the gates lock so the test and the take are one step: a | |
| 4626 | - // release landing between them would leave this block queued behind a | |
| 4627 | - // gate that is already open. | |
| 4628 | - let taken = cell_gates() | |
| 4629 | - .lock() | |
| 4630 | - .unwrap() | |
| 4631 | - .entry(cell.clone()) | |
| 4632 | - .or_default() | |
| 4633 | - .acquire(event); | |
| 4634 | - if taken { | |
| 4635 | - let id = asyncrt::enqueue(async move { Ok(event.to_string()) }); | |
| 4636 | - rv.set(promise_for(scope, id)); | |
| 4637 | - return; | |
| 4638 | - } | |
| 4639 | - let id = asyncrt::enqueue(async move { | |
| 4640 | - loop { | |
| 4641 | - // Ask for a ticket first: `cell_gate_wait` tests and enqueues | |
| 4642 | - // under the gates lock, so a release landing between the two | |
| 4643 | - // cannot leave this waiter behind an open gate. | |
| 4644 | - let waiting = cell_gate_wait(&cell); | |
| 4645 | - let taken = cell_gates() | |
| 4646 | - .lock() | |
| 4647 | - .unwrap() | |
| 4648 | - .entry(cell.clone()) | |
| 4649 | - .or_default() | |
| 4650 | - .acquire(event); | |
| 4651 | - if taken { | |
| 4652 | - return Ok(event.to_string()); | |
| 4653 | - } | |
| 4654 | - match waiting { | |
| 4655 | - Some(open) => match open.await { | |
| 4656 | - Ok(Ok(())) => {} | |
| 4657 | - // The block ahead of this one failed and reset the cell, | |
| 4658 | - // so this block has nothing left to guard. | |
| 4659 | - Ok(Err(failure)) => return Err(failure), | |
| 4660 | - Err(_) => { | |
| 4661 | - return Err("cell stopped while waiting for its input gate".to_string()) | |
| 4662 | - } | |
| 4663 | - }, | |
| 4664 | - // The gate was open when we asked and shut before we took | |
| 4665 | - // it: another block won the race. Yield rather than spin — | |
| 4666 | - // this runs on a tokio worker, and a bare `continue` here | |
| 4667 | - // starved the runtime. | |
| 4668 | - None => tokio::task::yield_now().await, | |
| 4669 | - } | |
| 4670 | - } | |
| 4671 | - }); | |
| 4672 | - rv.set(promise_for(scope, id)); | |
| 4673 | -} | |
| 4674 | - | |
| 4675 | -/// `__gate_wait(scope)` — settle when the cell's input gate is open. | |
| 4676 | -/// | |
| 4677 | -/// The gate's other side. `op_gate_acquire` is for something that wants to | |
| 4678 | -/// *hold* the gate; this is for something that only has to arrive after it, | |
| 4679 | -/// which is every event the gate exists to hold back. A drive does this in | |
| 4680 | -/// Rust before it begins a turn; an RPC stub op does it here, because it is | |
| 4681 | -/// dispatched inside the isolate and never becomes a drive. | |
| 4682 | -/// | |
| 4683 | -/// Rejecting matters as much as resolving: a critical section that failed | |
| 4684 | -/// reset the cell, so what waited behind it is refused with the reason | |
| 4685 | -/// rather than run against state that no longer exists. | |
| 4686 | -fn op_gate_wait( | |
| 4687 | - scope: &mut v8::PinScope, | |
| 4688 | - args: v8::FunctionCallbackArguments, | |
| 4689 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4690 | -) { | |
| 4691 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 4692 | - let id = asyncrt::enqueue(async move { | |
| 4693 | - loop { | |
| 4694 | - match cell_gate_wait(&cell) { | |
| 4695 | - None => return Ok(String::new()), | |
| 4696 | - Some(open) => match open.await { | |
| 4697 | - Ok(Ok(())) => {} | |
| 4698 | - Ok(Err(failure)) => return Err(failure), | |
| 4699 | - Err(_) => { | |
| 4700 | - return Err("cell stopped while waiting for its input gate".to_string()) | |
| 4701 | - } | |
| 4702 | - }, | |
| 4703 | - } | |
| 4704 | - } | |
| 4705 | - }); | |
| 4706 | - rv.set(promise_for(scope, id)); | |
| 4707 | -} | |
| 4708 | - | |
| 4709 | -/// `__gate_release(scope, event)` — the block is over. The next delivery | |
| 4710 | -/// point to run takes whatever queued behind it. | |
| 4711 | -fn op_gate_release( | |
| 4712 | - scope: &mut v8::PinScope, | |
| 4713 | - args: v8::FunctionCallbackArguments, | |
| 4714 | - _rv: v8::ReturnValue<v8::Value>, | |
| 4715 | -) { | |
| 4716 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 4717 | - let event = args.get(1).number_value(scope).unwrap_or_default() as celld_logic::gate::EventId; | |
| 4718 | - // A third argument means the block failed and the actor was reset, so | |
| 4719 | - // what queued behind it is refused with that reason rather than | |
| 4720 | - // delivered to a cell whose state is gone. | |
| 4721 | - let failure = args.get(2); | |
| 4722 | - let outcome = if failure.is_null_or_undefined() { | |
| 4723 | - Ok(()) | |
| 4724 | - } else { | |
| 4725 | - Err(failure.to_rust_string_lossy(scope)) | |
| 4726 | - }; | |
| 4727 | - if let Some(gate) = cell_gates().lock().unwrap().get_mut(&cell) { | |
| 4728 | - gate.release(event); | |
| 4729 | - } | |
| 4730 | - wake_gate_waiters(&cell, outcome); | |
| 4731 | -} | |
| 4732 | - | |
| 4733 | -fn op_timer_alloc( | |
| 4734 | - scope: &mut v8::PinScope, | |
| 4735 | - _args: v8::FunctionCallbackArguments, | |
| 4736 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4737 | -) { | |
| 4738 | - let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64); | |
| 4739 | - rv.set(id.into()); | |
| 4740 | -} | |
| 4741 | - | |
| 4742 | -fn op_timer_cancel( | |
| 4743 | - scope: &mut v8::PinScope, | |
| 4744 | - args: v8::FunctionCallbackArguments, | |
| 4745 | - _rv: v8::ReturnValue<v8::Value>, | |
| 4746 | -) { | |
| 4747 | - let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64; | |
| 4748 | - if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) { | |
| 4749 | - let _ = cancel.send(()); | |
| 4750 | - } | |
| 4751 | -} | |
| 4752 | - | |
| 4753 | -fn durable_object_id_key(namespace_key: &str) -> [u8; 32] { | |
| 4754 | - DO_ID_KEYS.with(|keys| { | |
| 4755 | - if let Some(key) = keys.borrow().get(namespace_key) { | |
| 4756 | - return *key; | |
| 4757 | - } | |
| 4758 | - use sha2::Digest; | |
| 4759 | - let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into(); | |
| 4760 | - keys.borrow_mut().insert(namespace_key.to_string(), key); | |
| 4761 | - key | |
| 4762 | - }) | |
| 4763 | -} | |
| 4764 | - | |
| 4765 | -fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> { | |
| 4766 | - use hmac::Mac; | |
| 4767 | - let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key) | |
| 4768 | - .expect("SHA-256 accepts any HMAC key"); | |
| 4769 | - mac.update(input); | |
| 4770 | - mac | |
| 4771 | -} | |
| 4772 | - | |
| 4773 | -/// Ids already derived on this thread, keyed by namespace and name. | |
| 4774 | -/// | |
| 4775 | -/// `getByName` costs two HMAC-SHA256 rounds, and a profile of `/c/hello` | |
| 4776 | -/// found them among the largest terms the stateless path does not have — | |
| 4777 | -/// the same name resolving to the same id, recomputed on every request. | |
| 4778 | -/// | |
| 4779 | -/// Per thread and unsynchronised, which is sound because the derivation is | |
| 4780 | -/// a pure function of its inputs: a worker that has not seen a name pays | |
| 4781 | -/// for it once, and no answer can differ between threads. Bounded because | |
| 4782 | -/// names come from the application, and cleared wholesale at the cap rather | |
| 4783 | -/// than evicted one at a time — a cache this cheap to refill does not earn | |
| 4784 | -/// an LRU. | |
| 4785 | -const DO_ID_CACHE_MAX: usize = 4096; | |
| 4786 | - | |
| 4787 | -fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] { | |
| 4788 | - use hmac::Mac; | |
| 4789 | - | |
| 4790 | - thread_local! { | |
| 4791 | - static IDS: RefCell<HashMap<(String, String), [u8; 32]>> = | |
| 4792 | - RefCell::new(HashMap::new()); | |
| 4793 | - } | |
| 4794 | - let cached = IDS.with(|ids| { | |
| 4795 | - ids.borrow() | |
| 4796 | - .get(&(namespace_key.to_string(), name.to_string())) | |
| 4797 | - .copied() | |
| 4798 | - }); | |
| 4799 | - if let Some(id) = cached { | |
| 4800 | - return id; | |
| 4801 | - } | |
| 4802 | - | |
| 4803 | - let key = durable_object_id_key(namespace_key); | |
| 4804 | - let mut id = [0_u8; 32]; | |
| 4805 | - let digest = durable_object_id_hmac(&key, name.as_bytes()) | |
| 4806 | - .finalize() | |
| 4807 | - .into_bytes(); | |
| 4808 | - id[..16].copy_from_slice(&digest[..16]); | |
| 4809 | - let digest = durable_object_id_hmac(&key, &id[..16]) | |
| 4810 | - .finalize() | |
| 4811 | - .into_bytes(); | |
| 4812 | - id[16..].copy_from_slice(&digest[..16]); | |
| 4813 | - | |
| 4814 | - IDS.with(|ids| { | |
| 4815 | - let mut ids = ids.borrow_mut(); | |
| 4816 | - if ids.len() >= DO_ID_CACHE_MAX { | |
| 4817 | - ids.clear(); | |
| 4818 | - } | |
| 4819 | - ids.insert((namespace_key.to_string(), name.to_string()), id); | |
| 4820 | - }); | |
| 4821 | - id | |
| 4822 | -} | |
| 4823 | - | |
| 4824 | -/// The key a Durable Object namespace derives its IDs from. D1 uses one | |
| 4825 | -/// fleet-wide namespace because the database is a resource that several | |
| 4826 | -/// Workers can bind, and a Worker rename must not rename that database. | |
| 4827 | -const D1_NAMESPACE_KEY: &str = "cells:v1:d1:__D1Database"; | |
| 4828 | - | |
| 4829 | -pub(crate) fn namespace_key(script_name: &str, class_name: &str) -> String { | |
| 4830 | - if class_name == crate::deploy::D1_CLASS { | |
| 4831 | - D1_NAMESPACE_KEY.to_string() | |
| 4832 | - } else { | |
| 4833 | - format!("cells:v1:{}:{script_name}:{class_name}", script_name.len()) | |
| 4834 | - } | |
| 4835 | -} | |
| 4836 | - | |
| 4837 | -/// The cell scope a D1 database lives at, for a caller outside any isolate. | |
| 4838 | -/// `celld d1` addresses a database over the operator route, which takes a | |
| 4839 | -/// scope, so this derives what `getByName` derives in the harness, from the | |
| 4840 | -/// same key and the same HMAC. | |
| 4841 | -pub fn d1_cell_scope(database_identity: &str) -> String { | |
| 4842 | - let id = durable_object_id_for_name(D1_NAMESPACE_KEY, database_identity); | |
| 4843 | - format!("{}:{}", crate::deploy::D1_CLASS, durable_object_id_hex(&id)) | |
| 4844 | -} | |
| 4845 | - | |
| 4846 | -fn durable_object_id_hex(bytes: &[u8; 32]) -> String { | |
| 4847 | - const HEX: &[u8; 16] = b"0123456789abcdef"; | |
| 4848 | - let mut output = String::with_capacity(64); | |
| 4849 | - for byte in bytes { | |
| 4850 | - output.push(HEX[(byte >> 4) as usize] as char); | |
| 4851 | - output.push(HEX[(byte & 0x0f) as usize] as char); | |
| 4852 | - } | |
| 4853 | - output | |
| 4854 | -} | |
| 4855 | - | |
| 4856 | -fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> { | |
| 4857 | - if value.len() != 64 { | |
| 4858 | - return None; | |
| 4859 | - } | |
| 4860 | - let mut output = [0_u8; 32]; | |
| 4861 | - for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() { | |
| 4862 | - let nibble = |byte| match byte { | |
| 4863 | - b'0'..=b'9' => Some(byte - b'0'), | |
| 4864 | - b'a'..=b'f' => Some(byte - b'a' + 10), | |
| 4865 | - b'A'..=b'F' => Some(byte - b'A' + 10), | |
| 4866 | - _ => None, | |
| 4867 | - }; | |
| 4868 | - output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?; | |
| 4869 | - } | |
| 4870 | - Some(output) | |
| 4871 | -} | |
| 4872 | - | |
| 4873 | -fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) { | |
| 4874 | - let message = v8::String::new(scope, message).unwrap(); | |
| 4875 | - let exception = v8::Exception::type_error(scope, message); | |
| 4876 | - scope.throw_exception(exception); | |
| 4877 | -} | |
| 4878 | - | |
| 4879 | -fn register_actor_name( | |
| 4880 | - scope: &mut v8::PinScope, | |
| 4881 | - actor_scope: &str, | |
| 4882 | - name: Option<&str>, | |
| 4883 | -) -> Result<()> { | |
| 4884 | - let Some(name) = name else { | |
| 4885 | - return Ok(()); | |
| 4886 | - }; | |
| 4887 | - let context = scope.get_current_context(); | |
| 4888 | - let global = context.global(scope); | |
| 4889 | - let cell_key = v8::String::new(scope, "__cell").unwrap(); | |
| 4890 | - let cell = global | |
| 4891 | - .get(scope, cell_key.into()) | |
| 4892 | - .and_then(|value| value.to_object(scope)) | |
| 4893 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 4894 | - let names_key = v8::String::new(scope, "idNames").unwrap(); | |
| 4895 | - let names = cell | |
| 4896 | - .get(scope, names_key.into()) | |
| 4897 | - .and_then(|value| value.to_object(scope)) | |
| 4898 | - .ok_or_else(|| anyhow!("missing Durable Object name registry"))?; | |
| 4899 | - let actor_scope_key = v8::String::new(scope, actor_scope).unwrap(); | |
| 4900 | - if let Some(existing) = names.get(scope, actor_scope_key.into()) { | |
| 4901 | - if !existing.is_undefined() { | |
| 4902 | - if existing.to_rust_string_lossy(scope) == name { | |
| 4903 | - return Ok(()); | |
| 4904 | - } | |
| 4905 | - anyhow::bail!("actor name conflicts with active identity for {actor_scope}"); | |
| 4906 | - } | |
| 4907 | - } | |
| 4908 | - | |
| 4909 | - let (class_name, id) = actor_scope | |
| 4910 | - .split_once(':') | |
| 4911 | - .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?; | |
| 4912 | - let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap(); | |
| 4913 | - let namespace_keys = cell | |
| 4914 | - .get(scope, namespace_keys_key.into()) | |
| 4915 | - .and_then(|value| value.to_object(scope)) | |
| 4916 | - .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?; | |
| 4917 | - let class_name_key = v8::String::new(scope, class_name).unwrap(); | |
| 4918 | - let namespace_key = namespace_keys | |
| 4919 | - .get(scope, class_name_key.into()) | |
| 4920 | - .filter(|value| value.is_string()) | |
| 4921 | - .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))? | |
| 4922 | - .to_rust_string_lossy(scope); | |
| 4923 | - let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name)); | |
| 4924 | - if id != expected { | |
| 4925 | - anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}"); | |
| 4926 | - } | |
| 4927 | - storage::set_actor_name(actor_scope, name)?; | |
| 4928 | - | |
| 4929 | - let name_value = v8::String::new(scope, name).unwrap(); | |
| 4930 | - if !names | |
| 4931 | - .set(scope, actor_scope_key.into(), name_value.into()) | |
| 4932 | - .unwrap_or(false) | |
| 4933 | - { | |
| 4934 | - anyhow::bail!("could not register Durable Object name"); | |
| 4935 | - } | |
| 4936 | - Ok(()) | |
| 4937 | -} | |
| 4938 | - | |
| 4939 | -fn op_do_id( | |
| 4940 | - scope: &mut v8::PinScope, | |
| 4941 | - args: v8::FunctionCallbackArguments, | |
| 4942 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 4943 | -) { | |
| 4944 | - use hmac::Mac; | |
| 4945 | - | |
| 4946 | - let namespace_key = args.get(0).to_rust_string_lossy(scope); | |
| 4947 | - let operation = args.get(1).to_rust_string_lossy(scope); | |
| 4948 | - let input = args.get(2).to_rust_string_lossy(scope); | |
| 4949 | - let key = durable_object_id_key(&namespace_key); | |
| 4950 | - let mut id = [0_u8; 32]; | |
| 4951 | - | |
| 4952 | - match operation.as_str() { | |
| 4953 | - "name" => { | |
| 4954 | - id = durable_object_id_for_name(&namespace_key, &input); | |
| 4955 | - rv.set( | |
| 4956 | - v8::String::new(scope, &durable_object_id_hex(&id)) | |
| 4957 | - .unwrap() | |
| 4958 | - .into(), | |
| 4959 | - ); | |
| 4960 | - return; | |
| 4961 | - } | |
| 4962 | - "unique" => { | |
| 4963 | - if getrandom::fill(&mut id[..16]).is_err() { | |
| 4964 | - throw_durable_object_id_error(scope, "secure random generation failed"); | |
| 4965 | - return; | |
| 4966 | - } | |
| 4967 | - } | |
| 4968 | - "validate" => { | |
| 4969 | - let Some(decoded) = decode_durable_object_id(&input) else { | |
| 4970 | - throw_durable_object_id_error( | |
| 4971 | - scope, | |
| 4972 | - "Invalid Durable Object ID: must be 64 hex digits", | |
| 4973 | - ); | |
| 4974 | - return; | |
| 4975 | - }; | |
| 4976 | - if durable_object_id_hmac(&key, &decoded[..16]) | |
| 4977 | - .verify_truncated_left(&decoded[16..]) | |
| 4978 | - .is_err() | |
| 4979 | - { | |
| 4980 | - throw_durable_object_id_error( | |
| 4981 | - scope, | |
| 4982 | - "Durable Object ID is not valid for this namespace", | |
| 4983 | - ); | |
| 4984 | - return; | |
| 4985 | - } | |
| 4986 | - rv.set( | |
| 4987 | - v8::String::new(scope, &input.to_ascii_lowercase()) | |
| 4988 | - .unwrap() | |
| 4989 | - .into(), | |
| 4990 | - ); | |
| 4991 | - return; | |
| 4992 | - } | |
| 4993 | - _ => { | |
| 4994 | - throw_durable_object_id_error(scope, "unknown Durable Object ID operation"); | |
| 4995 | - return; | |
| 4996 | - } | |
| 4997 | - } | |
| 4998 | - | |
| 4999 | - let digest = durable_object_id_hmac(&key, &id[..16]) | |
| 5000 | - .finalize() | |
| 5001 | - .into_bytes(); | |
| 5002 | - id[16..].copy_from_slice(&digest[..16]); | |
| 5003 | - rv.set( | |
| 5004 | - v8::String::new(scope, &durable_object_id_hex(&id)) | |
| 5005 | - .unwrap() | |
| 5006 | - .into(), | |
| 5007 | - ); | |
| 5008 | -} | |
| 5009 | - | |
| 5010 | -fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> { | |
| 5011 | - let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?; | |
| 5012 | - let mut bytes = vec![0_u8; view.byte_length()]; | |
| 5013 | - view.copy_contents(&mut bytes); | |
| 5014 | - Some(bytes) | |
| 5015 | -} | |
| 5016 | - | |
| 5017 | -fn webcrypto_return_bytes( | |
| 5018 | - scope: &mut v8::PinScope, | |
| 5019 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5020 | - bytes: &[u8], | |
| 5021 | -) { | |
| 5022 | - let buffer = v8::ArrayBuffer::new(scope, bytes.len()); | |
| 5023 | - if !bytes.is_empty() { | |
| 5024 | - let store = buffer.get_backing_store(); | |
| 5025 | - let destination = unsafe { | |
| 5026 | - std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len()) | |
| 5027 | - }; | |
| 5028 | - destination.copy_from_slice(bytes); | |
| 5029 | - } | |
| 5030 | - let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap(); | |
| 5031 | - rv.set(view.into()); | |
| 5032 | -} | |
| 5033 | - | |
| 5034 | -mod crypto; | |
| 5035 | -mod zlib; | |
| 5036 | - | |
| 5037 | -fn op_actor_abort( | |
| 5038 | - scope: &mut v8::PinScope, | |
| 5039 | - args: v8::FunctionCallbackArguments, | |
| 5040 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5041 | -) { | |
| 5042 | - let cell = args.get(0).to_rust_string_lossy(scope); | |
| 5043 | - let reason = args.get(1).to_rust_string_lossy(scope); | |
| 5044 | - let state = actor_runtime_state(scope); | |
| 5045 | - state | |
| 5046 | - .pending_puts | |
| 5047 | - .lock() | |
| 5048 | - .expect("pending puts lock poisoned") | |
| 5049 | - .remove(&cell); | |
| 5050 | - *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination { | |
| 5051 | - error: format!("__CELLD_ACTOR_ABORT__:{reason}"), | |
| 5052 | - actor_scope: Some(cell), | |
| 5053 | - }); | |
| 5054 | - scope.terminate_execution(); | |
| 5055 | -} | |
| 5056 | - | |
| 5057 | -fn op_process_exit( | |
| 5058 | - scope: &mut v8::PinScope, | |
| 5059 | - args: v8::FunctionCallbackArguments, | |
| 5060 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5061 | -) { | |
| 5062 | - let code = args.get(0).integer_value(scope).unwrap_or(0); | |
| 5063 | - if current_context().depth() == 0 { | |
| 5064 | - tracing::warn!( | |
| 5065 | - code, | |
| 5066 | - "process.exit called without an active request; ignoring" | |
| 5067 | - ); | |
| 5068 | - return; | |
| 5069 | - } | |
| 5070 | - let actor_scope = args.get(1).to_rust_string_lossy(scope); | |
| 5071 | - let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope); | |
| 5072 | - let state = actor_runtime_state(scope); | |
| 5073 | - if let Some(actor_scope) = actor_scope.as_deref() { | |
| 5074 | - state | |
| 5075 | - .pending_puts | |
| 5076 | - .lock() | |
| 5077 | - .expect("pending puts lock poisoned") | |
| 5078 | - .remove(actor_scope); | |
| 5079 | - } | |
| 5080 | - *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination { | |
| 5081 | - error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."), | |
| 5082 | - actor_scope, | |
| 5083 | - }); | |
| 5084 | - scope.terminate_execution(); | |
| 5085 | -} | |
| 5086 | - | |
| 5087 | -fn op_log( | |
| 5088 | - scope: &mut v8::PinScope, | |
| 5089 | - args: v8::FunctionCallbackArguments, | |
| 5090 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5091 | -) { | |
| 5092 | - let msg: Vec<String> = (0..args.length()) | |
| 5093 | - .map(|i| args.get(i).to_rust_string_lossy(scope)) | |
| 5094 | - .collect(); | |
| 5095 | - let body = msg.join(" "); | |
| 5096 | - // Correlated by CPED, so a continuation logging after an await — or | |
| 5097 | - // another entry's continuation running in this turn's checkpoint — | |
| 5098 | - // lands on the trace that owns it, not on whoever holds the isolate. | |
| 5099 | - if crate::telemetry::active() { | |
| 5100 | - let ids = current_trace_ids(scope); | |
| 5101 | - crate::telemetry::record_log(crate::telemetry::Log { | |
| 5102 | - trace_id: ids.as_ref().map(|ids| ids.trace_id), | |
| 5103 | - span_id: ids.as_ref().map(|ids| ids.span_id), | |
| 5104 | - time_unix_us: crate::telemetry::now_unix_us(), | |
| 5105 | - body: body.clone(), | |
| 5106 | - }); | |
| 5107 | - } | |
| 5108 | - tracing::info!(target: "cell_console", "{}", body); | |
| 5109 | -} | |
| 5110 | -fn op_heap_limit_excessively_exceeded( | |
| 5111 | - scope: &mut v8::PinScope, | |
| 5112 | - _args: v8::FunctionCallbackArguments, | |
| 5113 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5114 | -) { | |
| 5115 | - let exceeded = scope | |
| 5116 | - .get_slot::<Arc<HeapLimitState>>() | |
| 5117 | - .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed)); | |
| 5118 | - rv.set(v8::Boolean::new(scope, exceeded).into()); | |
| 5119 | -} | |
| 5120 | -/// Whether this isolate is too close to its heap limit to retain more state. | |
| 5121 | -fn op_heap_over_admission_share( | |
| 5122 | - scope: &mut v8::PinScope, | |
| 5123 | - _args: v8::FunctionCallbackArguments, | |
| 5124 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5125 | -) { | |
| 5126 | - let state = scope.get_slot::<Arc<HeapLimitState>>().cloned(); | |
| 5127 | - let over = match state { | |
| 5128 | - // A condemned isolate admits nothing, whatever the heap now reads. | |
| 5129 | - Some(state) | |
| 5130 | - if state.excessively_exceeded.load(Ordering::Relaxed) | |
| 5131 | - || admission_refusal_forced(&state) => | |
| 5132 | - { | |
| 5133 | - true | |
| 5134 | - } | |
| 5135 | - Some(state) => heap_share(scope, state.limit) >= HEAP_ADMISSION_SHARE, | |
| 5136 | - None => false, | |
| 5137 | - }; | |
| 5138 | - rv.set(v8::Boolean::new(scope, over).into()); | |
| 5139 | -} | |
| 5140 | -#[cfg(all(test, celld_internal_tests))] | |
| 5141 | -fn op_test_set_heap_limit_excessively_exceeded( | |
| 5142 | - scope: &mut v8::PinScope, | |
| 5143 | - args: v8::FunctionCallbackArguments, | |
| 5144 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5145 | -) { | |
| 5146 | - if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() { | |
| 5147 | - state | |
| 5148 | - .excessively_exceeded | |
| 5149 | - .store(args.get(0).boolean_value(scope), Ordering::Relaxed); | |
| 5150 | - } | |
| 5151 | -} | |
| 5152 | -#[cfg(all(test, celld_internal_tests))] | |
| 5153 | -fn op_test_force_heap_admission_refusal( | |
| 5154 | - scope: &mut v8::PinScope, | |
| 5155 | - args: v8::FunctionCallbackArguments, | |
| 5156 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5157 | -) { | |
| 5158 | - if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() { | |
| 5159 | - state | |
| 5160 | - .forced_admission_refusal | |
| 5161 | - .store(args.get(0).boolean_value(scope), Ordering::Relaxed); | |
| 5162 | - } | |
| 5163 | -} | |
| 5164 | -#[cfg(all(test, celld_internal_tests))] | |
| 5165 | -fn op_test_gc( | |
| 5166 | - scope: &mut v8::PinScope, | |
| 5167 | - _args: v8::FunctionCallbackArguments, | |
| 5168 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5169 | -) { | |
| 5170 | - scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full); | |
| 5171 | -} | |
| 5172 | -mod storage_ops; | |
| 5173 | -use storage_ops::{actor_runtime_state, throw_storage_error}; | |
| 5174 | - | |
| 5175 | -/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href} | |
| 5176 | -/// Backed by the WHATWG-conformant `url` crate. | |
| 5177 | -fn op_url_parse( | |
| 5178 | - scope: &mut v8::PinScope, | |
| 5179 | - args: v8::FunctionCallbackArguments, | |
| 5180 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5181 | -) { | |
| 5182 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 5183 | - let base = args.get(1); | |
| 5184 | - let parsed = if base.is_undefined() { | |
| 5185 | - url::Url::parse(&input) | |
| 5186 | - } else { | |
| 5187 | - url::Url::options() | |
| 5188 | - .base_url( | |
| 5189 | - url::Url::parse(&base.to_rust_string_lossy(scope)) | |
| 5190 | - .ok() | |
| 5191 | - .as_ref(), | |
| 5192 | - ) | |
| 5193 | - .parse(&input) | |
| 5194 | - }; | |
| 5195 | - let u = match parsed { | |
| 5196 | - Ok(u) => u, | |
| 5197 | - Err(e) => { | |
| 5198 | - let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap(); | |
| 5199 | - let exc = v8::Exception::type_error(scope, msg); | |
| 5200 | - scope.throw_exception(exc); | |
| 5201 | - return; | |
| 5202 | - } | |
| 5203 | - }; | |
| 5204 | - let o = v8::Object::new(scope); | |
| 5205 | - let set = |k: &str, v: &str| { | |
| 5206 | - let key = v8::String::new(scope, k).unwrap(); | |
| 5207 | - let val = v8::String::new(scope, v).unwrap(); | |
| 5208 | - o.set(scope, key.into(), val.into()); | |
| 5209 | - }; | |
| 5210 | - set("protocol", u.scheme()); | |
| 5211 | - set("username", u.username()); | |
| 5212 | - set("password", u.password().unwrap_or("")); | |
| 5213 | - set("host", u.host_str().unwrap_or("")); | |
| 5214 | - set("port", &u.port().map(|p| p.to_string()).unwrap_or_default()); | |
| 5215 | - set("pathname", u.path()); | |
| 5216 | - set("search", u.query().unwrap_or("")); | |
| 5217 | - set("hash", u.fragment().unwrap_or("")); | |
| 5218 | - set("href", u.as_str()); | |
| 5219 | - rv.set(o.into()); | |
| 5220 | -} | |
| 5221 | - | |
| 5222 | -// URLPattern host seam, split like Deno's: pattern parsing and match-input | |
| 5223 | -// canonicalization run in Rust via the `urlpattern` crate; per-match regex | |
| 5224 | -// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the | |
| 5225 | -// boundary — both ops run at construct/match-canonicalize time only. | |
| 5226 | - | |
| 5227 | -/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a | |
| 5228 | -/// pattern string or an init object of string components. Returns | |
| 5229 | -/// per-component `{ patternString, regexpString, groupNameList }` plus | |
| 5230 | -/// `hasRegexpGroups`. Throws TypeError on an invalid pattern. | |
| 5231 | -fn op_urlpattern_parse( | |
| 5232 | - scope: &mut v8::PinScope, | |
| 5233 | - args: v8::FunctionCallbackArguments, | |
| 5234 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5235 | -) { | |
| 5236 | - use urlpattern::quirks; | |
| 5237 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 5238 | - let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap(); | |
| 5239 | - let base = args.get(1); | |
| 5240 | - let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope)); | |
| 5241 | - let options = urlpattern::UrlPatternOptions { | |
| 5242 | - ignore_case: args.get(2).boolean_value(scope), | |
| 5243 | - }; | |
| 5244 | - let pattern = quirks::process_construct_pattern_input(input, base.as_deref()) | |
| 5245 | - .and_then(|init| quirks::parse_pattern(init, options)); | |
| 5246 | - let p = match pattern { | |
| 5247 | - Ok(p) => p, | |
| 5248 | - Err(e) => { | |
| 5249 | - let msg = v8::String::new(scope, &e.to_string()).unwrap(); | |
| 5250 | - let exc = v8::Exception::type_error(scope, msg); | |
| 5251 | - scope.throw_exception(exc); | |
| 5252 | - return; | |
| 5253 | - } | |
| 5254 | - }; | |
| 5255 | - let component = |c: &quirks::UrlPatternComponent| { | |
| 5256 | - serde_json::json!({ | |
| 5257 | - "patternString": c.pattern_string, | |
| 5258 | - "regexpString": c.regexp_string, | |
| 5259 | - "groupNameList": c.group_name_list, | |
| 5260 | - }) | |
| 5261 | - }; | |
| 5262 | - let out = serde_json::json!({ | |
| 5263 | - "protocol": component(&p.protocol), | |
| 5264 | - "username": component(&p.username), | |
| 5265 | - "password": component(&p.password), | |
| 5266 | - "hostname": component(&p.hostname), | |
| 5267 | - "port": component(&p.port), | |
| 5268 | - "pathname": component(&p.pathname), | |
| 5269 | - "search": component(&p.search), | |
| 5270 | - "hash": component(&p.hash), | |
| 5271 | - "hasRegexpGroups": p.has_regexp_groups, | |
| 5272 | - }); | |
| 5273 | - rv.set(v8::String::new(scope, &out.to_string()).unwrap().into()); | |
| 5274 | -} | |
| 5275 | - | |
| 5276 | -/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in | |
| 5277 | -/// component order (protocol..hash), or `null` when the input does not parse | |
| 5278 | -/// as a URL. Throws TypeError for an init combined with a baseURL argument. | |
| 5279 | -fn op_urlpattern_match_input( | |
| 5280 | - scope: &mut v8::PinScope, | |
| 5281 | - args: v8::FunctionCallbackArguments, | |
| 5282 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5283 | -) { | |
| 5284 | - use urlpattern::quirks; | |
| 5285 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 5286 | - let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap(); | |
| 5287 | - let base = args.get(1); | |
| 5288 | - let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope)); | |
| 5289 | - let null = v8::null(scope).into(); | |
| 5290 | - let m = match quirks::process_match_input(input, base.as_deref()) { | |
| 5291 | - Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) { | |
| 5292 | - Some(m) => m, | |
| 5293 | - None => return rv.set(null), | |
| 5294 | - }, | |
| 5295 | - Ok(None) => return rv.set(null), | |
| 5296 | - Err(e) => { | |
| 5297 | - let msg = v8::String::new(scope, &e.to_string()).unwrap(); | |
| 5298 | - let exc = v8::Exception::type_error(scope, msg); | |
| 5299 | - scope.throw_exception(exc); | |
| 5300 | - return; | |
| 5301 | - } | |
| 5302 | - }; | |
| 5303 | - let out = serde_json::json!([ | |
| 5304 | - m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash, | |
| 5305 | - ]); | |
| 5306 | - rv.set(v8::String::new(scope, &out.to_string()).unwrap().into()); | |
| 5307 | -} | |
| 5308 | - | |
| 5309 | -fn op_atob( | |
| 5310 | - scope: &mut v8::PinScope, | |
| 5311 | - args: v8::FunctionCallbackArguments, | |
| 5312 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5313 | -) { | |
| 5314 | - use base64::Engine; | |
| 5315 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 5316 | - let cleaned: String = input.chars().filter(|c| !c.is_whitespace()).collect(); | |
| 5317 | - match base64::engine::general_purpose::STANDARD.decode(cleaned) { | |
| 5318 | - Ok(bytes) => { | |
| 5319 | - // atob returns a binary string (latin1) | |
| 5320 | - let s: String = bytes.iter().map(|&b| b as char).collect(); | |
| 5321 | - rv.set(v8::String::new(scope, &s).unwrap().into()); | |
| 5322 | - } | |
| 5323 | - Err(_) => { | |
| 5324 | - let msg = v8::String::new(scope, "Invalid base64").unwrap(); | |
| 5325 | - let exc = v8::Exception::error(scope, msg); | |
| 5326 | - scope.throw_exception(exc); | |
| 5327 | - } | |
| 5328 | - } | |
| 5329 | -} | |
| 5330 | - | |
| 5331 | -// node:util introspection seam: V8-level queries that JS cannot perform, | |
| 5332 | -// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy | |
| 5333 | -// node:async_hooks prelude calls these. The value is V8's | |
| 5334 | -// continuation-preserved embedder data — the primitive Workerd's | |
| 5335 | -// AsyncContextFrame rides — which V8 itself captures and restores | |
| 5336 | -// around every promise reaction. No promise hooks are installed, and an | |
| 5337 | -// isolate that never touches AsyncLocalStorage never sets the value, so | |
| 5338 | -// a bundle that does not import async_hooks pays nothing per promise. | |
| 5339 | - | |
| 5340 | -/// The per-request context: everything a request owns while it is in flight. | |
| 5341 | -/// | |
| 5342 | -/// Modelled on workerd's `IoContext`. The host owns it, not JS: a request's | |
| 5343 | -/// event frames and the `waitUntil` promises inside them live here, and JS | |
| 5344 | -/// reaches them only through ops that ask for the *current* context. That | |
| 5345 | -/// inversion is the point. While an isolate serves one request at a time, | |
| 5346 | -/// JS-side per-request state is indistinguishable from isolate-side state, | |
| 5347 | -/// and the two silently diverge the moment requests interleave — one | |
| 5348 | -/// request's `__endEvent` popping another's event, its `waitUntil` work | |
| 5349 | -/// attributed to a request that never asked for it. | |
| 5350 | -/// | |
| 5351 | -/// `current()` is a thread-local the host installs for the duration of a | |
| 5352 | -/// turn and restores on the way out, exactly as `threadLocalRequest` is set | |
| 5353 | -/// in `IoContext::runInContextScope` and restored by `SuppressIoContextScope`. | |
| 5354 | -/// An op that needs a context and finds none is a bug in the host, not in | |
| 5355 | -/// the script, so it says so rather than inventing one. | |
| 5356 | -/// | |
| 5357 | -/// **It is `Send + Sync`, and that is load-bearing.** Under D1 a request is | |
| 5358 | -/// a tokio task that suspends between turns and can resume on any worker, so | |
| 5359 | -/// the context it carries has to cross threads with it. `Rc` and `RefCell` | |
| 5360 | -/// would forbid that, and the alternative — parking every live context in a | |
| 5361 | -/// map inside the isolate, keyed by request id — rebuilds the very | |
| 5362 | -/// demultiplexing table (`idmap`) that deleting the pump exists to remove. | |
| 5363 | -/// So the interiors are `Mutex` instead. The locks are uncontended by | |
| 5364 | -/// construction, because only the isolate's holder can reach a context, and | |
| 5365 | -/// they are taken about twice per request. | |
| 5366 | -pub struct IoContext { | |
| 5367 | - /// This caller's delivery order for each cell it has called. See | |
| 5368 | - /// `CallOrder` — it is here rather than in a process-wide map because | |
| 5369 | - /// nothing outside this caller ever reads it. | |
| 5370 | - call_chains: Mutex<CallChains>, | |
| 5371 | - /// Event frames, innermost last. A frame collects the `waitUntil` | |
| 5372 | - /// promises registered while it is the innermost one. | |
| 5373 | - /// | |
| 5374 | - /// Nesting is per-request and strictly LIFO — a service-binding | |
| 5375 | - /// dispatch, an RPC entry, or a DO construction pushes its own frame so | |
| 5376 | - /// its `waitUntil` binds to that dispatch, matching workerd. | |
| 5377 | - events: Mutex<Vec<Vec<v8::Global<v8::Promise>>>>, | |
| 5378 | - /// Isolate-polled sockets opened by each nested run loop of this | |
| 5379 | - /// request, innermost last. `asyncrt` aborts a region's pending ops when | |
| 5380 | - /// it exits; these are host-side resources abort cannot reach, so the | |
| 5381 | - /// region closes them itself. | |
| 5382 | - sockets: Mutex<Vec<Vec<u64>>>, | |
| 5383 | - /// Sockets opened before any run loop exists. A handler runs | |
| 5384 | - /// synchronously to its first await before its loop is entered, so a | |
| 5385 | - /// socket built at the top of a handler has no frame yet; the loop | |
| 5386 | - /// adopts these when it starts. | |
| 5387 | - pending_sockets: Mutex<Vec<u64>>, | |
| 5388 | - /// Output-gate capture. While a `webSocketMessage` runs, the frames it | |
| 5389 | - /// sends are collected here instead of reaching the wire, so the shell | |
| 5390 | - /// can hold them until the message's write is durable. A stack, so a | |
| 5391 | - /// nested dispatch keeps its frames apart from the outer one's. | |
| 5392 | - /// | |
| 5393 | - /// On the event and not on the thread, because an event outlives the | |
| 5394 | - /// turn that began it: capture starts in one turn and is taken in a | |
| 5395 | - /// later one, which tokio may run on a different worker. | |
| 5396 | - ws_capture: Mutex<Vec<Vec<(u64, WsOut)>>>, | |
| 5397 | - /// Which cell an event belongs to, and the committed-write position it | |
| 5398 | - /// started at, innermost last. An outbound effect raised during the | |
| 5399 | - /// event consults this: if the handler has advanced the position, the | |
| 5400 | - /// effect waits for the output gate before it leaves the process. | |
| 5401 | - /// | |
| 5402 | - /// Empty for stateless Worker code, which owns no cell and gates | |
| 5403 | - /// nothing. | |
| 5404 | - egress: Mutex<Vec<(String, u64)>>, | |
| 5405 | -} | |
| 5406 | - | |
| 5407 | -impl IoContext { | |
| 5408 | - fn new() -> Arc<Self> { | |
| 5409 | - Arc::new(Self { | |
| 5410 | - call_chains: Mutex::new(CallChains::default()), | |
| 5411 | - events: Mutex::new(Vec::new()), | |
| 5412 | - sockets: Mutex::new(Vec::new()), | |
| 5413 | - pending_sockets: Mutex::new(Vec::new()), | |
| 5414 | - ws_capture: Mutex::new(Vec::new()), | |
| 5415 | - egress: Mutex::new(Vec::new()), | |
| 5416 | - }) | |
| 5417 | - } | |
| 5418 | - | |
| 5419 | - fn begin_event(&self) { | |
| 5420 | - self.events.lock().unwrap().push(Vec::new()); | |
| 5421 | - } | |
| 5422 | - | |
| 5423 | - /// Pop the innermost frame and hand back what it collected. `None` when | |
| 5424 | - /// there is no frame, which is a script calling `waitUntil` outside any | |
| 5425 | - /// event; the harness turns that into workerd's global-scope error. | |
| 5426 | - fn end_event(&self) -> Option<Vec<v8::Global<v8::Promise>>> { | |
| 5427 | - self.events.lock().unwrap().pop() | |
| 5428 | - } | |
| 5429 | - | |
| 5430 | - fn register_wait_until(&self, promise: v8::Global<v8::Promise>) { | |
| 5431 | - if let Some(frame) = self.events.lock().unwrap().last_mut() { | |
| 5432 | - frame.push(promise); | |
| 5433 | - } | |
| 5434 | - } | |
| 5435 | - | |
| 5436 | - fn depth(&self) -> usize { | |
| 5437 | - self.events.lock().unwrap().len() | |
| 5438 | - } | |
| 5439 | -} | |
| 5440 | - | |
| 5441 | -/// What `OwnedIsolate::into_shared` demands of us: every slot value on a | |
| 5442 | -/// shared isolate is reachable, and droppable, from whichever thread holds | |
| 5443 | -/// the lock. The type system cannot check it at the call site, so it is | |
| 5444 | -/// checked here instead. | |
| 5445 | -const _: fn() = || { | |
| 5446 | - fn assert_send_sync<T: Send + Sync>() {} | |
| 5447 | - assert_send_sync::<HeapLimitState>(); | |
| 5448 | - assert_send_sync::<ActorRuntimeState>(); | |
| 5449 | - assert_send_sync::<ModuleRegistry>(); | |
| 5450 | -}; | |
| 5451 | - | |
| 5452 | -/// A request must be able to carry its own context across a suspension. A | |
| 5453 | -/// compile-time check, because losing it would surface as an unrelated | |
| 5454 | -/// `Send` error wherever the request task is spawned. | |
| 5455 | -const _: fn() = || { | |
| 5456 | - fn assert_send_sync<T: Send + Sync>() {} | |
| 5457 | - assert_send_sync::<Arc<IoContext>>(); | |
| 5458 | -}; | |
| 5459 | - | |
| 5460 | -thread_local! { | |
| 5461 | - /// The request whose turn is running on this thread, or none between | |
| 5462 | - /// turns. Never set by JS. | |
| 5463 | - static CURRENT: RefCell<Option<Arc<IoContext>>> = | |
| 5464 | - const { RefCell::new(None) }; | |
| 5465 | -} | |
| 5466 | - | |
| 5467 | -/// Install `context` for the duration of a turn, restoring whatever was | |
| 5468 | -/// current when the guard drops. | |
| 5469 | -/// | |
| 5470 | -/// Restoring rather than clearing is what makes nested host dispatch safe: a | |
| 5471 | -/// service binding runs a second handler inside the first one's turn, and the | |
| 5472 | -/// outer request must still be current when it returns. | |
| 5473 | -pub struct CurrentGuard(Option<Arc<IoContext>>); | |
| 5474 | - | |
| 5475 | -impl CurrentGuard { | |
| 5476 | - pub fn enter(context: Arc<IoContext>) -> Self { | |
| 5477 | - CurrentGuard(CURRENT.with(|current| current.borrow_mut().replace(context))) | |
| 5478 | - } | |
| 5479 | -} | |
| 5480 | - | |
| 5481 | -impl Drop for CurrentGuard { | |
| 5482 | - fn drop(&mut self) { | |
| 5483 | - CURRENT.with(|current| *current.borrow_mut() = self.0.take()); | |
| 5484 | - } | |
| 5485 | -} | |
| 5486 | - | |
| 5487 | -/// The context this turn belongs to. | |
| 5488 | -/// | |
| 5489 | -/// A thread that has not had one installed gets a default: every path that | |
| 5490 | -/// runs JS without an explicit request context — a cell isolate, which the | |
| 5491 | -/// DO contract already serializes, an RPC entry, a DO constructor — keeps | |
| 5492 | -/// exactly the semantics it had when the stack lived in JS, one per isolate. | |
| 5493 | -/// Isolation is a property of *installing* a context, so it arrives with the | |
| 5494 | -/// paths that need it rather than being retrofitted to every caller at once. | |
| 5495 | -fn current_context() -> Arc<IoContext> { | |
| 5496 | - CURRENT.with(|current| { | |
| 5497 | - let mut current = current.borrow_mut(); | |
| 5498 | - current.get_or_insert_with(IoContext::new).clone() | |
| 5499 | - }) | |
| 5500 | -} | |
| 5501 | - | |
| 5502 | -fn op_event_begin( | |
| 5503 | - scope: &mut v8::PinScope, | |
| 5504 | - _args: v8::FunctionCallbackArguments, | |
| 5505 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5506 | -) { | |
| 5507 | - let _ = scope; | |
| 5508 | - current_context().begin_event(); | |
| 5509 | -} | |
| 5510 | - | |
| 5511 | -/// Pop the innermost event and return the aggregate of its `waitUntil` | |
| 5512 | -/// promises, or null when it collected none. The aggregate is built here | |
| 5513 | -/// rather than in JS because the promises live here: the host holds them for | |
| 5514 | -/// the request, and the request is what the frame belongs to. | |
| 5515 | -fn op_event_end<'s>( | |
| 5516 | - scope: &mut v8::PinScope<'s, '_>, | |
| 5517 | - _args: v8::FunctionCallbackArguments, | |
| 5518 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5519 | -) { | |
| 5520 | - let Some(frame) = current_context().end_event() else { | |
| 5521 | - rv.set_null(); | |
| 5522 | - return; | |
| 5523 | - }; | |
| 5524 | - if frame.is_empty() { | |
| 5525 | - rv.set_null(); | |
| 5526 | - return; | |
| 5527 | - } | |
| 5528 | - let promises: Vec<v8::Local<v8::Value>> = frame | |
| 5529 | - .iter() | |
| 5530 | - .map(|promise| v8::Local::new(scope, promise).into()) | |
| 5531 | - .collect(); | |
| 5532 | - let array = v8::Array::new_with_elements(scope, &promises); | |
| 5533 | - match all_settled(scope, array.into()) { | |
| 5534 | - Some(aggregate) => rv.set(aggregate), | |
| 5535 | - None => rv.set_null(), | |
| 5536 | - } | |
| 5537 | -} | |
| 5538 | - | |
| 5539 | -fn op_wait_until<'s>( | |
| 5540 | - scope: &mut v8::PinScope<'s, '_>, | |
| 5541 | - args: v8::FunctionCallbackArguments<'s>, | |
| 5542 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5543 | -) { | |
| 5544 | - let value = args.get(0); | |
| 5545 | - let promise = match value.try_cast::<v8::Promise>() { | |
| 5546 | - Ok(promise) => promise, | |
| 5547 | - Err(_) => match resolved_promise(scope, value) { | |
| 5548 | - Ok(promise) => promise, | |
| 5549 | - Err(_) => return, | |
| 5550 | - }, | |
| 5551 | - }; | |
| 5552 | - current_context().register_wait_until(v8::Global::new(scope, promise)); | |
| 5553 | -} | |
| 5554 | - | |
| 5555 | -/// How many events are open on the current request. The harness uses it for | |
| 5556 | -/// workerd's global-scope error, which fires when `waitUntil` is imported and | |
| 5557 | -/// called with no event in progress. | |
| 5558 | -fn op_event_depth( | |
| 5559 | - scope: &mut v8::PinScope, | |
| 5560 | - _args: v8::FunctionCallbackArguments, | |
| 5561 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5562 | -) { | |
| 5563 | - let depth = current_context().depth(); | |
| 5564 | - rv.set(v8::Integer::new(scope, depth as i32).into()); | |
| 5565 | -} | |
| 5566 | - | |
| 5567 | -/// `Promise.allSettled(values)`, from the context's own realm. | |
| 5568 | -fn all_settled<'s>( | |
| 5569 | - scope: &mut v8::PinScope<'s, '_>, | |
| 5570 | - values: v8::Local<'s, v8::Value>, | |
| 5571 | -) -> Option<v8::Local<'s, v8::Value>> { | |
| 5572 | - let global = scope.get_current_context().global(scope); | |
| 5573 | - let key = v8::String::new(scope, "Promise").unwrap(); | |
| 5574 | - let promise_ctor: v8::Local<v8::Object> = global.get(scope, key.into())?.try_into().ok()?; | |
| 5575 | - let key = v8::String::new(scope, "allSettled").unwrap(); | |
| 5576 | - let all_settled: v8::Local<v8::Function> = | |
| 5577 | - promise_ctor.get(scope, key.into())?.try_into().ok()?; | |
| 5578 | - all_settled.call(scope, promise_ctor.into(), &[values]) | |
| 5579 | -} | |
| 5580 | - | |
| 5581 | -fn op_als_get( | |
| 5582 | - scope: &mut v8::PinScope, | |
| 5583 | - _args: v8::FunctionCallbackArguments, | |
| 5584 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5585 | -) { | |
| 5586 | - rv.set(cped_frame(scope)); | |
| 5587 | -} | |
| 5588 | - | |
| 5589 | -fn op_als_set( | |
| 5590 | - scope: &mut v8::PinScope, | |
| 5591 | - args: v8::FunctionCallbackArguments, | |
| 5592 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5593 | -) { | |
| 5594 | - let trace = cped_trace(scope); | |
| 5595 | - set_cped(scope, args.get(0), trace); | |
| 5596 | -} | |
| 5597 | - | |
| 5598 | -// node:util prelude calls these; registration is the sole per-isolate cost. | |
| 5599 | - | |
| 5600 | -/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js. | |
| 5601 | -fn op_util_type_flags( | |
| 5602 | - _scope: &mut v8::PinScope, | |
| 5603 | - args: v8::FunctionCallbackArguments, | |
| 5604 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5605 | -) { | |
| 5606 | - let v = args.get(0); | |
| 5607 | - let checks: [bool; 27] = [ | |
| 5608 | - v.is_external(), | |
| 5609 | - v.is_date(), | |
| 5610 | - v.is_arguments_object(), | |
| 5611 | - v.is_big_int_object(), | |
| 5612 | - v.is_boolean_object(), | |
| 5613 | - v.is_number_object(), | |
| 5614 | - v.is_string_object(), | |
| 5615 | - v.is_symbol_object(), | |
| 5616 | - v.is_native_error(), | |
| 5617 | - v.is_reg_exp(), | |
| 5618 | - v.is_async_function(), | |
| 5619 | - v.is_generator_function(), | |
| 5620 | - v.is_generator_object(), | |
| 5621 | - v.is_promise(), | |
| 5622 | - v.is_map(), | |
| 5623 | - v.is_set(), | |
| 5624 | - v.is_map_iterator(), | |
| 5625 | - v.is_set_iterator(), | |
| 5626 | - v.is_weak_map(), | |
| 5627 | - v.is_weak_set(), | |
| 5628 | - v.is_array_buffer(), | |
| 5629 | - v.is_data_view(), | |
| 5630 | - v.is_shared_array_buffer(), | |
| 5631 | - v.is_proxy(), | |
| 5632 | - v.is_module_namespace_object(), | |
| 5633 | - v.is_typed_array(), | |
| 5634 | - v.is_array_buffer_view(), | |
| 5635 | - ]; | |
| 5636 | - let mut flags: u32 = 0; | |
| 5637 | - for (i, hit) in checks.iter().enumerate() { | |
| 5638 | - if *hit { | |
| 5639 | - flags |= 1 << i; | |
| 5640 | - } | |
| 5641 | - } | |
| 5642 | - rv.set_uint32(flags); | |
| 5643 | -} | |
| 5644 | - | |
| 5645 | -fn op_util_constructor_name( | |
| 5646 | - _scope: &mut v8::PinScope, | |
| 5647 | - args: v8::FunctionCallbackArguments, | |
| 5648 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5649 | -) { | |
| 5650 | - let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else { | |
| 5651 | - return; // undefined | |
| 5652 | - }; | |
| 5653 | - rv.set(obj.get_constructor_name().into()); | |
| 5654 | -} | |
| 5655 | - | |
| 5656 | -/// `[target, handler]` for a proxy, undefined otherwise. | |
| 5657 | -fn op_util_proxy_details( | |
| 5658 | - scope: &mut v8::PinScope, | |
| 5659 | - args: v8::FunctionCallbackArguments, | |
| 5660 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5661 | -) { | |
| 5662 | - let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else { | |
| 5663 | - return; | |
| 5664 | - }; | |
| 5665 | - let target = proxy.get_target(scope); | |
| 5666 | - let handler = proxy.get_handler(scope); | |
| 5667 | - rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into()); | |
| 5668 | -} | |
| 5669 | - | |
| 5670 | -/// `[state]` for a pending promise, `[state, result]` otherwise, | |
| 5671 | -/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected. | |
| 5672 | -fn op_util_promise_details( | |
| 5673 | - scope: &mut v8::PinScope, | |
| 5674 | - args: v8::FunctionCallbackArguments, | |
| 5675 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5676 | -) { | |
| 5677 | - let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else { | |
| 5678 | - return; | |
| 5679 | - }; | |
| 5680 | - let state = match promise.state() { | |
| 5681 | - v8::PromiseState::Pending => 0, | |
| 5682 | - v8::PromiseState::Fulfilled => 1, | |
| 5683 | - v8::PromiseState::Rejected => 2, | |
| 5684 | - }; | |
| 5685 | - let pending = state == 0; | |
| 5686 | - let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into(); | |
| 5687 | - let elements = if pending { | |
| 5688 | - vec![state] | |
| 5689 | - } else { | |
| 5690 | - vec![state, promise.result(scope)] | |
| 5691 | - }; | |
| 5692 | - rv.set(v8::Array::new_with_elements(scope, &elements).into()); | |
| 5693 | -} | |
| 5694 | - | |
| 5695 | -/// `[entries, isKeyValue]` for collections and their iterators (V8's | |
| 5696 | -/// PreviewEntries), undefined when V8 has no preview. | |
| 5697 | -fn op_util_preview_entries( | |
| 5698 | - scope: &mut v8::PinScope, | |
| 5699 | - args: v8::FunctionCallbackArguments, | |
| 5700 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5701 | -) { | |
| 5702 | - let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else { | |
| 5703 | - return; | |
| 5704 | - }; | |
| 5705 | - let (entries, is_key_value) = obj.preview_entries(scope); | |
| 5706 | - let Some(entries) = entries else { return }; | |
| 5707 | - let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into(); | |
| 5708 | - rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into()); | |
| 5709 | -} | |
| 5710 | - | |
| 5711 | -fn op_alarm_set( | |
| 5712 | - scope: &mut v8::PinScope, | |
| 5713 | - args: v8::FunctionCallbackArguments, | |
| 5714 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5715 | -) { | |
| 5716 | - let s = args.get(0).to_rust_string_lossy(scope); | |
| 5717 | - let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64; | |
| 5718 | - match storage::set_alarm(&s, at) { | |
| 5719 | - Err(error) => throw_storage_error(scope, "setAlarm", error), | |
| 5720 | - // Committed immediately: register the wake-entry PUT against the | |
| 5721 | - // cell's output gate. Inside an explicit transaction (`Ok(None)`) | |
| 5722 | - // the gate registers at that transaction's commit instead. | |
| 5723 | - Ok(Some(committed)) if committed >= 0 => spawn_arm_gate(&s, committed), | |
| 5724 | - Ok(_) => {} | |
| 5725 | - } | |
| 5726 | -} | |
| 5727 | -fn op_alarm_get( | |
| 5728 | - scope: &mut v8::PinScope, | |
| 5729 | - args: v8::FunctionCallbackArguments, | |
| 5730 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5731 | -) { | |
| 5732 | - let s = args.get(0).to_rust_string_lossy(scope); | |
| 5733 | - match storage::get_alarm(&s) { | |
| 5734 | - Some(at) => rv.set(v8::Number::new(scope, at as f64).into()), | |
| 5735 | - None => rv.set(v8::null(scope).into()), | |
| 5736 | - } | |
| 5737 | -} | |
| 5738 | -fn op_alarm_delete( | |
| 5739 | - scope: &mut v8::PinScope, | |
| 5740 | - args: v8::FunctionCallbackArguments, | |
| 5741 | - _rv: v8::ReturnValue<v8::Value>, | |
| 5742 | -) { | |
| 5743 | - let s = args.get(0).to_rust_string_lossy(scope); | |
| 5744 | - if let Err(error) = storage::delete_alarm(&s) { | |
| 5745 | - throw_storage_error(scope, "deleteAlarm", error); | |
| 5746 | - } | |
| 5747 | -} | |
| 5748 | - | |
| 5749 | -/// The reserved cron cell's whole schedule decision, in one call so the policy | |
| 5750 | -/// has one home in `celld_logic::cron` rather than a JavaScript copy that can | |
| 5751 | -/// drift from it. | |
| 5752 | -/// | |
| 5753 | -/// `firedMs` is the occurrence being handled, or negative when the cell is | |
| 5754 | -/// only arming. Returns `{ matching, armAt, armIsRetry }`: which expressions | |
| 5755 | -/// the occurrence belongs to, by index into the list passed in, when to arm | |
| 5756 | -/// next — `null` when the schedule is exhausted and the cell should retire — | |
| 5757 | -/// and whether that deadline is the failure backoff rather than the next | |
| 5758 | -/// occurrence. | |
| 5759 | -fn op_cron_plan( | |
| 5760 | - scope: &mut v8::PinScope, | |
| 5761 | - args: v8::FunctionCallbackArguments, | |
| 5762 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5763 | -) { | |
| 5764 | - let Ok(list) = v8::Local::<v8::Array>::try_from(args.get(0)) else { | |
| 5765 | - return; | |
| 5766 | - }; | |
| 5767 | - let mut crons = Vec::with_capacity(list.length() as usize); | |
| 5768 | - // Where each parsed expression sits in the list the caller passed. A | |
| 5769 | - // malformed expression is already refused by `celld deploy`, but the | |
| 5770 | - // control plane checks only the field count, so one can still arrive here. | |
| 5771 | - // Skipping it keeps one bad entry from silencing a script's other crons, | |
| 5772 | - // and this map is what keeps the skip from renumbering them: the caller | |
| 5773 | - // reports `controller.cron` by index, so a shifted index names the wrong | |
| 5774 | - // expression for every entry after the bad one. | |
| 5775 | - let mut positions = Vec::with_capacity(list.length() as usize); | |
| 5776 | - for index in 0..list.length() { | |
| 5777 | - let Some(value) = list.get_index(scope, index) else { | |
| 5778 | - continue; | |
| 5779 | - }; | |
| 5780 | - if let Ok(cron) = celld_logic::cron::parse(&value.to_rust_string_lossy(scope)) { | |
| 5781 | - crons.push(cron); | |
| 5782 | - positions.push(index as usize); | |
| 5783 | - } | |
| 5784 | - } | |
| 5785 | - let fired_ms = args.get(1).number_value(scope).unwrap_or(-1.0) as i64; | |
| 5786 | - let now_ms = args.get(2).number_value(scope).unwrap_or(0.0) as i64; | |
| 5787 | - let retry = args.get(3).number_value(scope).unwrap_or(0.0) as i64; | |
| 5788 | - let failed = args.get(4).boolean_value(scope); | |
| 5789 | - | |
| 5790 | - let matching = if fired_ms >= 0 { | |
| 5791 | - celld_logic::cron::matching(&crons, fired_ms) | |
| 5792 | - } else { | |
| 5793 | - Vec::new() | |
| 5794 | - }; | |
| 5795 | - let next = celld_logic::cron::next_across(&crons, now_ms); | |
| 5796 | - // The retry backoff is `alarm::alarm_retry`'s, not a second schedule: | |
| 5797 | - // a cron that fails behaves like any other failing alarm, except that | |
| 5798 | - // `cron_rearm` never lets the backoff outlast the next occurrence. | |
| 5799 | - let retry_at = failed | |
| 5800 | - .then(|| celld_logic::alarm::alarm_retry(now_ms, retry, retry, true)) | |
| 5801 | - .flatten(); | |
| 5802 | - let arm_at = celld_logic::cron::cron_rearm(next, retry_at); | |
| 5803 | - // Which of the two the deadline belongs to. `cron_rearm` takes the earlier | |
| 5804 | - // and gives a tie to the occurrence, so `armAt` alone cannot say — and the | |
| 5805 | - // caller has to know, because a retry owes the expressions of the | |
| 5806 | - // occurrence that failed, while a deadline that is an occurrence owes the | |
| 5807 | - // expressions that match it. | |
| 5808 | - let arm_is_retry = match (arm_at, next) { | |
| 5809 | - (Some(at), Some(occurrence)) => at < occurrence, | |
| 5810 | - (Some(_), None) => true, | |
| 5811 | - (None, _) => false, | |
| 5812 | - }; | |
| 5813 | - | |
| 5814 | - let indices = v8::Array::new(scope, matching.len() as i32); | |
| 5815 | - for (slot, index) in matching.iter().enumerate() { | |
| 5816 | - let value = v8::Number::new(scope, positions[*index] as f64); | |
| 5817 | - indices.set_index(scope, slot as u32, value.into()); | |
| 5818 | - } | |
| 5819 | - let result = v8::Object::new(scope); | |
| 5820 | - let key = v8::String::new(scope, "matching").unwrap(); | |
| 5821 | - result.set(scope, key.into(), indices.into()); | |
| 5822 | - let key = v8::String::new(scope, "armAt").unwrap(); | |
| 5823 | - let value: v8::Local<v8::Value> = match arm_at { | |
| 5824 | - Some(at) => v8::Number::new(scope, at as f64).into(), | |
| 5825 | - None => v8::null(scope).into(), | |
| 5826 | - }; | |
| 5827 | - result.set(scope, key.into(), value); | |
| 5828 | - let key = v8::String::new(scope, "armIsRetry").unwrap(); | |
| 5829 | - let value = v8::Boolean::new(scope, arm_is_retry); | |
| 5830 | - result.set(scope, key.into(), value.into()); | |
| 5831 | - rv.set(result.into()); | |
| 5832 | -} | |
| 5833 | - | |
| 5834 | -fn op_btoa( | |
| 5835 | - scope: &mut v8::PinScope, | |
| 5836 | - args: v8::FunctionCallbackArguments, | |
| 5837 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5838 | -) { | |
| 5839 | - use base64::Engine; | |
| 5840 | - let input = args.get(0).to_rust_string_lossy(scope); | |
| 5841 | - let bytes: Vec<u8> = input.chars().map(|c| c as u8).collect(); | |
| 5842 | - let s = base64::engine::general_purpose::STANDARD.encode(bytes); | |
| 5843 | - rv.set(v8::String::new(scope, &s).unwrap().into()); | |
| 5844 | -} | |
| 5845 | - | |
| 5846 | -// ---- WHATWG text decoders (encoding_rs) ---- | |
| 5847 | -// | |
| 5848 | -// These ops back every TextDecoder decode. src/js/text_encoding.js | |
| 5849 | -// resolves the label and owns the decoder's lifetime, and encoding_rs | |
| 5850 | -// does the decoding — for utf-8 and utf-16 as much as for every other | |
| 5851 | -// WHATWG label (windows-1252, Big5, GBK/GB18030, ISO-2022-JP, | |
| 5852 | -// x-user-defined, …). Previous utf-8 and utf-16 JS decoders were slower | |
| 5853 | -// than these ops at every measured size. | |
| 5854 | -// Streaming decoders live in a per-isolate table keyed by id; JS frees | |
| 5855 | -// one on the final decode (last=true), on a fatal error (encoding_rs | |
| 5856 | -// poisons an errored decoder), or via FinalizationRegistry when a | |
| 5857 | -// mid-stream decoder is abandoned. Ids are never reused, so a late | |
| 5858 | -// finalizer free of an already-closed id is a no-op. | |
| 5859 | - | |
| 5860 | -/// Live streaming decoders for one isolate, keyed by an id JS holds across | |
| 5861 | -/// awaits. | |
| 5862 | -/// | |
| 5863 | -/// An isolate slot rather than a process-wide `Mutex<HashMap<..>>` like | |
| 5864 | -/// [`zlib_streams`]. The reason that one is process-wide holds here too — a | |
| 5865 | -/// `TextDecoder` in streaming mode outlives the turn that made it, and the | |
| 5866 | -/// next turn can run on a different tokio worker — but it argues against a | |
| 5867 | -/// *thread-local*, not against this. A `TextDecoder` is a JS object, so it | |
| 5868 | -/// never leaves the isolate that made it, and every op that touches its | |
| 5869 | -/// decoder runs under that isolate's `v8::Locker`. The lock the embedder | |
| 5870 | -/// already holds is what makes the access exclusive, which `&mut Isolate` | |
| 5871 | -/// on the slot then proves. A second lock inside it buys nothing. | |
| 5872 | -/// | |
| 5873 | -/// This removes a ceiling rather than a measured regression, and the | |
| 5874 | -/// difference matters. In isolation the pattern does collapse: replayed on | |
| 5875 | -/// its own — remove, decode outside the lock, insert — 256-byte chunks | |
| 5876 | -/// peaked at two threads and then went *backwards*, 8 threads serving | |
| 5877 | -/// 0.46x what 1 thread served against 6.7x for the same decoding with no | |
| 5878 | -/// table. But celld end to end shows no difference between the two, at any | |
| 5879 | -/// concurrency this hardware can drive, because a chunk costs about 42us | |
| 5880 | -/// of stream and turn machinery around a lock held for about 100ns. So the | |
| 5881 | -/// mutex was not what any cell was waiting on. It was a process-wide | |
| 5882 | -/// serialisation point on a path that every stream now takes, and it went | |
| 5883 | -/// because it does not need to exist, not because it was costing anything | |
| 5884 | -/// yet. | |
| 5885 | -/// | |
| 5886 | -/// Dropping the isolate drops the table, so a decoder abandoned by a cell | |
| 5887 | -/// that goes away needs no finalizer to run. | |
| 5888 | -#[derive(Default)] | |
| 5889 | -struct TextDecoders(HashMap<u64, encoding_rs::Decoder>); | |
| 5890 | - | |
| 5891 | -static TEXT_DECODER_NEXT: AtomicU64 = AtomicU64::new(1); | |
| 5892 | - | |
| 5893 | -/// The calling isolate's decoder table, created on first use. | |
| 5894 | -fn text_decoders<'a>(scope: &'a mut v8::PinScope) -> &'a mut HashMap<u64, encoding_rs::Decoder> { | |
| 5895 | - if scope.get_slot::<TextDecoders>().is_none() { | |
| 5896 | - scope.set_slot(TextDecoders::default()); | |
| 5897 | - } | |
| 5898 | - &mut scope.get_slot_mut::<TextDecoders>().expect("just set").0 | |
| 5899 | -} | |
| 5900 | - | |
| 5901 | -/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined | |
| 5902 | -/// for unknown labels and the replacement encoding (RangeError in JS). | |
| 5903 | -fn op_text_decoder_label( | |
| 5904 | - scope: &mut v8::PinScope, | |
| 5905 | - args: v8::FunctionCallbackArguments, | |
| 5906 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5907 | -) { | |
| 5908 | - let label = args.get(0).to_rust_string_lossy(scope); | |
| 5909 | - if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) { | |
| 5910 | - let name = enc.name().to_ascii_lowercase(); | |
| 5911 | - rv.set(v8::String::new(scope, &name).unwrap().into()); | |
| 5912 | - } | |
| 5913 | -} | |
| 5914 | - | |
| 5915 | -/// `$$textDecoderNew(name, ignoreBOM)` -> id. | |
| 5916 | -fn op_text_decoder_new( | |
| 5917 | - scope: &mut v8::PinScope, | |
| 5918 | - args: v8::FunctionCallbackArguments, | |
| 5919 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5920 | -) { | |
| 5921 | - let name = args.get(0).to_rust_string_lossy(scope); | |
| 5922 | - let ignore_bom = args.get(1).boolean_value(scope); | |
| 5923 | - let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label"); | |
| 5924 | - let dec = if ignore_bom { | |
| 5925 | - enc.new_decoder_without_bom_handling() | |
| 5926 | - } else { | |
| 5927 | - enc.new_decoder_with_bom_removal() | |
| 5928 | - }; | |
| 5929 | - let id = TEXT_DECODER_NEXT.fetch_add(1, Ordering::Relaxed); | |
| 5930 | - text_decoders(scope).insert(id, dec); | |
| 5931 | - rv.set(v8::Number::new(scope, id as f64).into()); | |
| 5932 | -} | |
| 5933 | - | |
| 5934 | -/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the | |
| 5935 | -/// decoder when `last` is true or on a fatal malformed sequence | |
| 5936 | -/// (TypeError). | |
| 5937 | -fn op_text_decoder_decode( | |
| 5938 | - scope: &mut v8::PinScope, | |
| 5939 | - args: v8::FunctionCallbackArguments, | |
| 5940 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5941 | -) { | |
| 5942 | - let id = args.get(0).integer_value(scope).unwrap_or(0) as u64; | |
| 5943 | - let bytes = view_bytes(args.get(1)).unwrap_or_default(); | |
| 5944 | - let fatal = args.get(2).boolean_value(scope); | |
| 5945 | - let last = args.get(3).boolean_value(scope); | |
| 5946 | - // Per spec an empty streaming chunk is a no-op, but encoding_rs | |
| 5947 | - // 0.8 flushes a pending multibyte lead when fed an empty non-last | |
| 5948 | - // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead | |
| 5949 | - // of あ). Skip the decoder entirely. | |
| 5950 | - if bytes.is_empty() && !last { | |
| 5951 | - rv.set(v8::String::empty(scope).into()); | |
| 5952 | - return; | |
| 5953 | - } | |
| 5954 | - let mut dec = text_decoders(scope) | |
| 5955 | - .remove(&id) | |
| 5956 | - .expect("JS holds the only live id"); | |
| 5957 | - let Ok(out) = run_decoder(&mut dec, &bytes, fatal, last) else { | |
| 5958 | - throw_invalid_encoded_data(scope); | |
| 5959 | - return; | |
| 5960 | - }; | |
| 5961 | - if !last { | |
| 5962 | - text_decoders(scope).insert(id, dec); | |
| 5963 | - } | |
| 5964 | - rv.set(v8::String::new(scope, &out).unwrap().into()); | |
| 5965 | -} | |
| 5966 | - | |
| 5967 | -/// `$$textDecoderDecodeOnce(name, view, fatal, ignoreBOM)` -> string, for | |
| 5968 | -/// a complete buffer. | |
| 5969 | -/// | |
| 5970 | -/// The whole decode is one call, so the decoder never outlives it and | |
| 5971 | -/// never reaches [`text_decoders`]. That saves an insert and a remove, | |
| 5972 | -/// and it keeps every non-streaming decode on the node off a table that | |
| 5973 | -/// is one mutex for the whole process — which is most decodes, because | |
| 5974 | -/// `request.text()` and `response.text()` are not streams. A stream | |
| 5975 | -/// still takes that lock twice per chunk, which is a cost per chunk | |
| 5976 | -/// rather than per byte, and it has not been measured under load; | |
| 5977 | -/// sharding the table is the answer if it ever shows. | |
| 5978 | -fn op_text_decoder_decode_once( | |
| 5979 | - scope: &mut v8::PinScope, | |
| 5980 | - args: v8::FunctionCallbackArguments, | |
| 5981 | - mut rv: v8::ReturnValue<v8::Value>, | |
| 5982 | -) { | |
| 5983 | - let name = args.get(0).to_rust_string_lossy(scope); | |
| 5984 | - let bytes = view_bytes(args.get(1)).unwrap_or_default(); | |
| 5985 | - let fatal = args.get(2).boolean_value(scope); | |
| 5986 | - let ignore_bom = args.get(3).boolean_value(scope); | |
| 5987 | - let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label"); | |
| 5988 | - let mut dec = if ignore_bom { | |
| 5989 | - enc.new_decoder_without_bom_handling() | |
| 5990 | - } else { | |
| 5991 | - enc.new_decoder_with_bom_removal() | |
| 5992 | - }; | |
| 5993 | - match run_decoder(&mut dec, &bytes, fatal, true) { | |
| 5994 | - Ok(out) => rv.set(v8::String::new(scope, &out).unwrap().into()), | |
| 5995 | - Err(()) => throw_invalid_encoded_data(scope), | |
| 5996 | - } | |
| 5997 | -} | |
| 5998 | - | |
| 5999 | -/// Feeds `bytes` to `dec` and answers the text. `Err` means `fatal` was | |
| 6000 | -/// set and the input was malformed. | |
| 6001 | -fn run_decoder( | |
| 6002 | - dec: &mut encoding_rs::Decoder, | |
| 6003 | - bytes: &[u8], | |
| 6004 | - fatal: bool, | |
| 6005 | - last: bool, | |
| 6006 | -) -> Result<String, ()> { | |
| 6007 | - let mut out = String::new(); | |
| 6008 | - if fatal { | |
| 6009 | - let cap = dec | |
| 6010 | - .max_utf8_buffer_length_without_replacement(bytes.len()) | |
| 6011 | - .unwrap(); | |
| 6012 | - out.reserve(cap); | |
| 6013 | - if !matches!( | |
| 6014 | - dec.decode_to_string_without_replacement(bytes, &mut out, last), | |
| 6015 | - (encoding_rs::DecoderResult::InputEmpty, _), | |
| 6016 | - ) { | |
| 6017 | - return Err(()); | |
| 6018 | - } | |
| 6019 | - } else { | |
| 6020 | - let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap(); | |
| 6021 | - out.reserve(cap); | |
| 6022 | - let _ = dec.decode_to_string(bytes, &mut out, last); | |
| 6023 | - } | |
| 6024 | - Ok(out) | |
| 6025 | -} | |
| 6026 | - | |
| 6027 | -fn throw_invalid_encoded_data(scope: &mut v8::PinScope) { | |
| 6028 | - let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap(); | |
| 6029 | - let exc = v8::Exception::type_error(scope, msg); | |
| 6030 | - scope.throw_exception(exc); | |
| 6031 | -} | |
| 6032 | - | |
| 6033 | -/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder | |
| 6034 | -/// abandoned mid-stream. | |
| 6035 | -fn op_text_decoder_free( | |
| 6036 | - scope: &mut v8::PinScope, | |
| 6037 | - args: v8::FunctionCallbackArguments, | |
| 6038 | - _rv: v8::ReturnValue<v8::Value>, | |
| 6039 | -) { | |
| 6040 | - let id = args.get(0).integer_value(scope).unwrap_or(0) as u64; | |
| 6041 | - text_decoders(scope).remove(&id); | |
| 6042 | -} | |
| 6043 | - | |
| 6044 | -// ---- the JS harness: Web API + the DO object model ---- | |
| 6045 | - | |
| 6046 | -mod bootstrap; | |
| 6047 | -mod modules; | |
| 6048 | -use bootstrap::{ | |
| 6049 | - adopt_cell, begin_event_context, build_env, end_event_context, harness_env, | |
| 6050 | - inject_compatibility_flags, inject_crons, inject_namespace_keys, inject_routing, | |
| 6051 | - inject_storage_compatibility, install_harness, install_prelude, populate_cf_exports, | |
| 6052 | - register_class, register_entrypoints, | |
| 6053 | -}; | |
| 6054 | -use modules::{ | |
| 6055 | - compile_module, host_import_module_dynamically, install_lazy_globals, op_builtin_module, | |
| 6056 | - register_loader_modules, register_stubs, register_wasm_modules, resolve_external, | |
| 6057 | - ModuleRegistry, | |
| 6058 | -}; | |
| 6059 | -/// Like `make_request`, but marks the request as incoming. Its signal is | |
| 6060 | -/// registered only if the handler actually suspends, preserving the | |
| 6061 | -/// synchronous request path. | |
| 6062 | -fn make_incoming_request<'s>( | |
| 6063 | - tc: &mut v8::PinScope<'s, '_>, | |
| 6064 | - url: &str, | |
| 6065 | - method: &str, | |
| 6066 | - body: &RequestBody, | |
| 6067 | - headers: &[(String, String)], | |
| 6068 | -) -> Result<v8::Local<'s, v8::Value>> { | |
| 6069 | - let global = tc.get_current_context().global(tc); | |
| 6070 | - let key = v8::String::new(tc, "__makeIncomingRequest").unwrap(); | |
| 6071 | - let f: v8::Local<v8::Function> = global | |
| 6072 | - .get(tc, key.into()) | |
| 6073 | - .ok_or_else(|| anyhow!("no __makeIncomingRequest"))? | |
| 6074 | - .try_into() | |
| 6075 | - .map_err(|_| anyhow!("not fn"))?; | |
| 6076 | - let url = v8::String::new(tc, url).unwrap(); | |
| 6077 | - let method = v8::String::new(tc, method).unwrap(); | |
| 6078 | - let headers = v8::String::new( | |
| 6079 | - tc, | |
| 6080 | - &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()), | |
| 6081 | - ) | |
| 6082 | - .unwrap(); | |
| 6083 | - // A streamed body passes its id, and the harness builds the body | |
| 6084 | - // stream around that id. A held body passes the bytes. | |
| 6085 | - let (body, stream_id) = match body { | |
| 6086 | - RequestBody::Bytes(bytes) => (bytes_value(tc, bytes.clone()), v8::undefined(tc).into()), | |
| 6087 | - RequestBody::Stream(id) => ( | |
| 6088 | - v8::undefined(tc).into(), | |
| 6089 | - v8::Number::new(tc, *id as f64).into(), | |
| 6090 | - ), | |
| 6091 | - }; | |
| 6092 | - let recv = v8::undefined(tc).into(); | |
| 6093 | - f.call( | |
| 6094 | - tc, | |
| 6095 | - recv, | |
| 6096 | - &[url.into(), method.into(), body, headers.into(), stream_id], | |
| 6097 | - ) | |
| 6098 | - .ok_or_else(|| anyhow!("__makeIncomingRequest threw")) | |
| 6099 | -} | |
| 6100 | - | |
| 6101 | -fn register_incoming_request( | |
| 6102 | - tc: &mut v8::PinScope, | |
| 6103 | - request_id: RequestId, | |
| 6104 | - request: v8::Local<v8::Value>, | |
| 6105 | -) -> Result<()> { | |
| 6106 | - let global = tc.get_current_context().global(tc); | |
| 6107 | - let key = v8::String::new(tc, "__registerIncomingRequest").unwrap(); | |
| 6108 | - let function: v8::Local<v8::Function> = global | |
| 6109 | - .get(tc, key.into()) | |
| 6110 | - .ok_or_else(|| anyhow!("no __registerIncomingRequest"))? | |
| 6111 | - .try_into() | |
| 6112 | - .map_err(|_| anyhow!("__registerIncomingRequest is not a function"))?; | |
| 6113 | - let id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 6114 | - let recv = v8::undefined(tc).into(); | |
| 6115 | - function | |
| 6116 | - .call(tc, recv, &[id.into(), request]) | |
| 6117 | - .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?; | |
| 6118 | - Ok(()) | |
| 6119 | -} | |
| 6120 | - | |
| 6121 | -fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) { | |
| 6122 | - let global = tc.get_current_context().global(tc); | |
| 6123 | - let key = v8::String::new(tc, "__finishIncomingRequest").unwrap(); | |
| 6124 | - let Some(value) = global.get(tc, key.into()) else { | |
| 6125 | - return; | |
| 6126 | - }; | |
| 6127 | - let Ok(function) = value.try_cast::<v8::Function>() else { | |
| 6128 | - return; | |
| 6129 | - }; | |
| 6130 | - let id = v8::String::new(tc, &request_id_string(request_id)).unwrap(); | |
| 6131 | - let recv = v8::undefined(tc).into(); | |
| 6132 | - let _ = function.call(tc, recv, &[id.into()]); | |
| 6133 | -} | |
| 6134 | - | |
| 6135 | -fn make_request<'s>( | |
| 6136 | - tc: &mut v8::PinScope<'s, '_>, | |
| 6137 | - url: &str, | |
| 6138 | - method: &str, | |
| 6139 | - body: &[u8], | |
| 6140 | - headers: &[(String, String)], | |
| 6141 | -) -> Result<v8::Local<'s, v8::Value>> { | |
| 6142 | - let g = tc.get_current_context().global(tc); | |
| 6143 | - let k = v8::String::new(tc, "__makeRequest").unwrap(); | |
| 6144 | - let f: v8::Local<v8::Function> = g.get(tc, k.into()).unwrap().try_into().unwrap(); | |
| 6145 | - let u = v8::String::new(tc, url).unwrap(); | |
| 6146 | - let m = v8::String::new(tc, method).unwrap(); | |
| 6147 | - let b = bytes_value(tc, body.to_vec()); | |
| 6148 | - let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap(); | |
| 6149 | - let recv = v8::undefined(tc).into(); | |
| 6150 | - f.call(tc, recv, &[u.into(), m.into(), b, h.into()]) | |
| 6151 | - .ok_or_else(|| anyhow!("makeRequest threw")) | |
| 6152 | -} | |
| 6153 | - | |
| 6154 | -fn read_response(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> Result<HttpResponse> { | |
| 6155 | - let ctx = scope.get_current_context(); | |
| 6156 | - let global = ctx.global(scope); | |
| 6157 | - let key = v8::String::new(scope, "__readResponse").unwrap(); | |
| 6158 | - let f: v8::Local<v8::Function> = global | |
| 6159 | - .get(scope, key.into()) | |
| 6160 | - .ok_or_else(|| anyhow!("no __readResponse"))? | |
| 6161 | - .try_into() | |
| 6162 | - .map_err(|_| anyhow!("not fn"))?; | |
| 6163 | - let recv = v8::undefined(scope).into(); | |
| 6164 | - let out = f | |
| 6165 | - .call(scope, recv, &[ret]) | |
| 6166 | - .ok_or_else(|| anyhow!("readResponse threw"))?; | |
| 6167 | - // The harness response reader is synchronous. Keeping this assertion at | |
| 6168 | - // the native boundary prevents a future harness change from quietly | |
| 6169 | - // reintroducing a nested async runtime while an isolate is entered. | |
| 6170 | - if out.is_promise() { | |
| 6171 | - return Err(anyhow!("__readResponse returned a promise")); | |
| 6172 | - } | |
| 6173 | - let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?; | |
| 6174 | - let sk = v8::String::new(scope, "status").unwrap(); | |
| 6175 | - let bk = v8::String::new(scope, "bodyBytes").unwrap(); | |
| 6176 | - let tk = v8::String::new(scope, "bodyStreamId").unwrap(); | |
| 6177 | - let hk = v8::String::new(scope, "headersJson").unwrap(); | |
| 6178 | - let wk = v8::String::new(scope, "wsTargetJson").unwrap(); | |
| 6179 | - let status = out | |
| 6180 | - .get(scope, sk.into()) | |
| 6181 | - .and_then(|v| v.uint32_value(scope)) | |
| 6182 | - .unwrap_or(200) as u16; | |
| 6183 | - // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON | |
| 6184 | - // number array (which was ~4x the bytes to serialize + parse per response). | |
| 6185 | - let body = out | |
| 6186 | - .get(scope, bk.into()) | |
| 6187 | - .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok()) | |
| 6188 | - .map(|view| { | |
| 6189 | - let mut buf = vec![0u8; view.byte_length()]; | |
| 6190 | - view.copy_contents(&mut buf); | |
| 6191 | - buf | |
| 6192 | - }) | |
| 6193 | - .unwrap_or_default(); | |
| 6194 | - let stream_id = out | |
| 6195 | - .get(scope, tk.into()) | |
| 6196 | - .and_then(|value| value.integer_value(scope)) | |
| 6197 | - .unwrap_or(0) | |
| 6198 | - .max(0) as u64; | |
| 6199 | - let stream = if stream_id == 0 { | |
| 6200 | - None | |
| 6201 | - } else { | |
| 6202 | - http_streams() | |
| 6203 | - .lock() | |
| 6204 | - .unwrap() | |
| 6205 | - .remove(&stream_id) | |
| 6206 | - .and_then(|stream| stream.source) | |
| 6207 | - .map(http_chunk_stream) | |
| 6208 | - }; | |
| 6209 | - if stream_id != 0 && stream.is_none() { | |
| 6210 | - return Err(anyhow!( | |
| 6211 | - "response stream {stream_id} is no longer available" | |
| 6212 | - )); | |
| 6213 | - } | |
| 6214 | - let headers = out | |
| 6215 | - .get(scope, hk.into()) | |
| 6216 | - .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok()) | |
| 6217 | - .unwrap_or_default(); | |
| 6218 | - let ws_json = out | |
| 6219 | - .get(scope, wk.into()) | |
| 6220 | - .map(|v| v.to_rust_string_lossy(scope)) | |
| 6221 | - .unwrap_or_else(|| "null".into()); | |
| 6222 | - let ws = serde_json::from_str(&ws_json).ok(); | |
| 6223 | - if status == 101 { | |
| 6224 | - tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response"); | |
| 6225 | - } | |
| 6226 | - Ok(HttpResponse { | |
| 6227 | - status, | |
| 6228 | - body, | |
| 6229 | - stream, | |
| 6230 | - headers, | |
| 6231 | - ws, | |
| 6232 | - write_position: None, | |
| 6233 | - }) | |
| 6234 | -} | |
| 6235 | - | |
| 6236 | -#[cfg(all(test, celld_internal_tests))] | |
| 6237 | -fn init_engine_for_tests() { | |
| 6238 | - static INIT: std::sync::Once = std::sync::Once::new(); | |
| 6239 | - INIT.call_once(|| { | |
| 6240 | - v8::V8::set_flags_from_string("--expose-gc"); | |
| 6241 | - Engine::init(); | |
| 6242 | - }); | |
| 6243 | -} | |
| 6244 | - | |
| 6245 | -#[cfg(all(test, celld_internal_tests))] | |
| 6246 | -include!(env!("CELLD_INTERNAL_JS_OBSERVERS")); | |
| 6247 | - | |
| 6248 | -/// Externally injected Web-platform tests. | |
| 6249 | -#[cfg(all(test, celld_internal_tests))] | |
| 6250 | -pub(crate) mod conformance_runtime_tests { | |
| 6251 | - include!(env!("CELLD_CONFORMANCE_JS_RUNTIME_TESTS")); | |
| 6252 | -} | |
| 6253 | - | |
| 6254 | -#[cfg(all(test, celld_internal_tests))] | |
| 6255 | -mod conformance_web_platform_tests { | |
| 6256 | - include!(env!("CELLD_CONFORMANCE_WEB_PLATFORM_TESTS")); | |
| 6257 | -} | |
| 6258 | - | |
| 6259 | -#[cfg(all(test, celld_internal_tests))] | |
| 6260 | -mod call_order_private { | |
| 6261 | - include!(env!("CELLD_CONFORMANCE_CALL_ORDER_TESTS")); | |
| 6262 | -} | |
| 3 | +// The raw V8 adapter and its child modules remain outside the Actor execution | |
| 4 | +// domain. The Actor-reachable wake and WebSocket state is injected through | |
| 5 | +// HostServices. | |
| 6 | +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] | |
| 7 | + | |
| 8 | +//! The JS engine: rusty_v8 directly. One isolate per cell. | |
| 9 | +//! | |
| 10 | +//! This slice runs actual Durable Objects: the worker's default-export `fetch` | |
| 11 | +//! receives an `env` whose bindings are DO namespaces; `env.NS.get(id).fetch()` | |
| 12 | +//! instantiates the exported DO class (once per id) with a `state` whose | |
| 13 | +//! `storage` is backed by the cell's SQLite (crate::storage). DO storage is | |
| 14 | +//! async in JS, synchronous underneath — the ops are sync Rust, wrapped in | |
| 15 | +//! `async` by the JS harness. | |
| 16 | +use crate::asyncrt; | |
| 17 | +use crate::storage; | |
| 18 | +use anyhow::{anyhow, Context as _, Result}; | |
| 19 | +use base64::Engine as _; | |
| 20 | +use futures_util::StreamExt as _; | |
| 21 | +use std::cell::RefCell; | |
| 22 | +use std::collections::{HashMap, HashSet}; | |
| 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, | |
| 9042 | + }) | |
| 9043 | +} | |
| 9044 | + | |
| 9045 | +#[cfg(celld_internal_tests)] | |
| 9046 | +#[doc(hidden)] | |
| 9047 | +pub fn init_engine_for_tests() { | |
| 9048 | + Engine::init(); | |
| 9049 | +} | |
| 9050 | + | |
| 9051 | +#[cfg(celld_internal_tests)] | |
| 9052 | +include!(env!("CELLD_INTERNAL_JS_OBSERVERS")); |
modifiedcrates/celld/js/bootstrap.rs+999−491View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/crypto.js+381−397View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/crypto.rs+1168−1042View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/harness.js+9844−5234View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/headers.js+322−148View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/modules.rs+600−570View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_buffer.js+62−38View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_events.js+1−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_util.js+1−1View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/r2_ops.rs+1286−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/storage_ops.rs+277−175View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/v8_strings.rs+65−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/websocket.rs+1152−995View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/kv_cli.rs+775−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/lib.rs+517−237View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/local_store.rs+557−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ltx_repl.rs+3494−1919View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/machine.rs+123−137View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main.rs+4936−3233View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/cli.rs+383−316View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/main/peer_tunnel.rs+691−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/websocket.rs+971−1117View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/memory.rs+196−97View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/node_log.rs+4925−2938View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/operator_cell.rs+251−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/otlp.rs+0−137View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ownership_store.rs+592−505View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/peer_auth.rs+362−345View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/peer_probe.rs+127−127View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/pool.rs+649−419View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/protocol.rs+330−108View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/queue_cli.rs+221−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/replication.rs+402−388View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/runtime.rs+3419−2193View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/startup.rs+0−6View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/storage.rs+3822−3778View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/telemetry.rs+1003−1254View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/wake.rs+312−350View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ws_client.rs+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/Cargo.toml+5−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/drain.rs+154−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/http.rs+227−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/isolate.rs+7−5View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/kv.rs+280−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/lib.rs+5487−4680View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/log_evict.rs+347−207View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/log_tier.rs+94−53View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/output_gate.rs+286−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/pressure.rs+218−169View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/queue.rs+365−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/schedule.rs+2−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/sqlite.rs+1−1View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/sweep.rs+12−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/types.rs+912−753View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/wake.rs+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/Cargo.toml+29−29View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/README.md+59−76View file
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/reference/litestream-go/testdata/wal-reader/frame-checksum-mismatch/wal+0−0
Binary file not shown.
deletedcrates/ltx/reference/litestream-go/testdata/wal-reader/frame-salts/wal+0−0
Binary file not shown.
deletedcrates/ltx/reference/litestream-go/testdata/wal-reader/ok/wal+0−0
Binary file not shown.
deletedcrates/ltx/reference/litestream-go/testdata/wal-reader/salt-mismatch/wal+0−0
Binary file not shown.
deletedcrates/ltx/scripts/capture-golden.sh+0−74
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/scripts/db_equal.sh+0−72
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/bundle.rs+123−181View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/file.rs+0−36View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/mod.rs+63−171View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/object_store.rs+887−1083View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/compaction_level.rs+0−57View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/compactor.rs+0−240View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/db.rs+2131−2288View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/host.rs+321−317View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/lib.rs+399−389View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/ltx.rs+562−799View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/lz4_block.rs+8−59View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica.rs+1002−1336View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica_compactor.rs+46−195View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica_url.rs+0−278View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/wal.rs+547−843View file
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/differential_xtool.rs+0−585
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/faults_inject.rs+0−441
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/fixtures/golden/.gitkeep+0−1
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/fixtures/golden/MANIFEST.md+0−38
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000001-0000000000000001.ltx+0−0
Binary file not shown.
deletedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000002-0000000000000002.ltx+0−0
Binary file not shown.
deletedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000003-0000000000000003.ltx+0−0
Binary file not shown.
deletedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000004-0000000000000004.ltx+0−0
Binary file not shown.
deletedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000005-0000000000000005.ltx+0−0
Binary file not shown.
deletedcrates/ltx/tests/fixtures/golden/replica/ltx/0/0000000000000006-0000000000000006.ltx+0−0
Binary file not shown.
deletedcrates/ltx/tests/fixtures/golden/sample.wal+0−0
Binary file not shown.
deletedcrates/ltx/tests/fuzz_bundle.rs+0−218
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/fuzz_parsers.rs+0−539
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/integration_file.rs+0−315
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/integration_resilience.rs+0−449
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/integration_s3.rs+0−397
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/litestream_helpers.rs+0−525
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/property_roundtrip.rs+0−243
Diff not rendered to keep this page fast. View the file
modifieddocs/README.md+705−391View file
Diff not rendered to keep this page fast. View the file
modifieddocs/cloudflare-compat.md+334−373View file
Diff not rendered to keep this page fast. View the file
deleteddocs/fencing.md+0−231
Diff not rendered to keep this page fast. View the file
addeddocs/guarantees.md+228−0View file
Diff not rendered to keep this page fast. View the file
addeddocs/library-api.md+60−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/limitations.md+46−53View file
Diff not rendered to keep this page fast. View the file
modifieddocs/security.md+150−126View file
Diff not rendered to keep this page fast. View the file
modifieddocs/telemetry.md+4−4View file
Diff not rendered to keep this page fast. View the file
modifieddocs/testing.md+73−63View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/README.md+33−18View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/alarm/index.js+29−21View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/alarm/wrangler.jsonc+3−1View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/async/index.js+17−29View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/async/wrangler.jsonc+4−2View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/body/index.js+21−21View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/counter/index.js+16−13View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/counter/wrangler.jsonc+3−1View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/cron/index.js+6−44View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/cron/wrangler.jsonc+1−6View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/d1/index.js+36−55View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/d1/wrangler.jsonc+0−4View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/hello/index.js+4−2View file
Diff not rendered to keep this page fast. View the file
addedexamples/kv/index.js+21−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/kv/wrangler.jsonc+11−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/r2/index.js+33−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/r2/wrangler.jsonc+8−0View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/router/index.js+18−20View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/router/wrangler.jsonc+3−1View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/rpc/index.js+21−134View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/rpc/wrangler.jsonc+4−2View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/vectordb/index.js+37−24View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/vectordb/wrangler.jsonc+5−3View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/wasm/Cargo.toml+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/wasm/README.md+21−22View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/wasm/src/lib.rs+0−2View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/wasm/wrangler.jsonc+6−5View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/webapi/index.js+12−10View file
Diff not rendered to keep this page fast. View the file
addedexamples/workflow/index.js+36−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/workflow/wrangler.jsonc+12−0View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/wsclient/index.js+23−35View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/wsecho/index.js+24−27View file
Diff not rendered to keep this page fast. View the file