v0.5.0
Upgrading from v0.4.1 requires stopping the whole fleet first. Highlights: - Support for Containers and the Cloudflare Sandbox SDK. - Support for worker_loaders in wrangler.json. Loaded Workers can receive service bindings and use a custom outbound fetch handler. - Service bindings now support fetch() on named entrypoints across Workers. - RPC support for default service bindings and nested properties. AbortSignal can pass through RPC calls on the same node. - Choose how long to keep completed Workflow runs, or delete them manually. - Support for .dev.vars in celld dev, with automatic reloads. - Support for WASM files in prebuilt deployments. - Lower memory use per cell and faster KV prefix listings. - Fixes for nested transactions, facet rollback, and unfinished SQL writes. - More reliable alarm delivery and background work after a response. - Database recovery fixes, with lower memory use during recovery and compaction. - Internal host functions are no longer exposed to application code. - Configure telemetry with CELLD_OTEL: 1 for the bucket, or an OTLP collector URL. Issues fixed: - #177: Pass service bindings to loaded Workers. - #192: Isolate host state between loaded Workers. - #193: Recover cells after their owner freezes. - #194, #195, #196, #197: Fix Base64 and argument handling. - #198, #199: Fix database compaction and restore failures. - #200: Resume async work when another request wakes it. - #201: Recognize minified imports for Node.js builtins. - #203: Fix duplicate WebSocket Close frames. Co-authored-by: Bartek Iwańczuk <[email protected]> Co-authored-by: Nathan Whitaker <[email protected]> Co-authored-by: Yusuke Tanaka <[email protected]> Co-authored-by: Andrew Joslin <[email protected]>
Ryan Dahl authored signed1 parent 10cb130commit 12d5b6333fe52717325addcfe1e99e9fd4f77bcdBrowse files
122 files changed+55306−59387
Files (122)
- .gitignore+3−0
- Cargo.lock+2−1
- README.md+9−0
- crates/celld/Cargo.toml+1−1
- crates/celld/actor.rs+187−91
- crates/celld/actor/local_request.rs+119−0
- crates/celld/asyncrt.rs+63−6
- crates/celld/bucket.rs+5−1
- crates/celld/container.rs+1588−0
- crates/celld/control_plane.rs+12−75
- crates/celld/deploy.rs+489−30
- crates/celld/dev.rs+36−1
- crates/celld/docker.rs+267−0
- crates/celld/env_vars.rs+196−47
- crates/celld/fleet.rs+67−60
- crates/celld/generation.rs+8−8
- crates/celld/js.rs+0−0
- crates/celld/js/atob_btoa.js+53−28
- crates/celld/js/bootstrap.rs+341−201
- crates/celld/js/byte_streams.js+2−2
- crates/celld/js/cache.js+2−2
- crates/celld/js/compression_streams.js+2−2
- crates/celld/js/container.rs+325−0
- crates/celld/js/crypto.js+2−14
- crates/celld/js/event_source.js+1−1
- crates/celld/js/harness.js+12178−11166
- crates/celld/js/headers.js+12−12
- crates/celld/js/html_rewriter.js+1−1
- crates/celld/js/identity_transform_stream.js+5−5
- crates/celld/js/message_channel.js+1−1
- crates/celld/js/modules.rs+348−165
- crates/celld/js/node_assert.js+3−3
- crates/celld/js/node_async_hooks.js+5−5
- crates/celld/js/node_buffer.js+5−5
- crates/celld/js/node_crypto.js+12−16
- crates/celld/js/node_diagnostics_channel.js+1−1
- crates/celld/js/node_events.js+2−2
- crates/celld/js/node_os.js+2−2
- crates/celld/js/node_path.js+2−2
- crates/celld/js/node_stream.js+5−5
- crates/celld/js/node_test.js+2−2
- crates/celld/js/node_timers.js+1−1
- crates/celld/js/node_util.js+11−11
- crates/celld/js/r2_ops.rs+33−2
- crates/celld/js/set_immediate.js+1−1
- crates/celld/js/sockets.js+3−3
- crates/celld/js/storage_ops.rs+163−20
- crates/celld/js/streams.js+7−7
- crates/celld/js/tcp.rs+29−8
- crates/celld/js/text_encoding.js+6−6
- crates/celld/js/url.js+5−5
- crates/celld/js/url_pattern.js+2−2
- crates/celld/js/url_search_params.js+5−5
- crates/celld/js/v8_strings.rs+14−2
- crates/celld/js/websocket.rs+28−10
- crates/celld/js/writable_stream.js+9−9
- crates/celld/lib.rs+44−2
- crates/celld/ltx_repl.rs+328−174
- crates/celld/main.rs+5469−5566
- crates/celld/main/cli.rs+1−31
- crates/celld/main/peer_tunnel.rs+60−32
- crates/celld/main/websocket.rs+78−83
- crates/celld/node_log.rs+5924−5711
- crates/celld/node_log/recovery_progress.rs+8−1
- crates/celld/ownership_store.rs+1194−1104
- crates/celld/pool.rs+602−633
- crates/celld/protocol.rs+43−27
- crates/celld/queue_batching.rs+43−0
- crates/celld/replication.rs+46−0
- crates/celld/runtime.rs+4143−3984
- crates/celld/storage.rs+4548−4140
- crates/celld/storage/wake_record.rs+105−0
- crates/celld/telemetry.rs+863−872
- crates/celld/wake.rs+657−420
- crates/celld/wake_format.rs+194−0
- crates/celld/ws_client.rs+6−3
- crates/logic/lib.rs+6538−6178
- crates/logic/output_gate.rs+347−349
- crates/logic/pressure.rs+35−21
- crates/logic/rebalance.rs+10−5
- crates/logic/schedule.rs+92−0
- crates/logic/types.rs+1052−994
- crates/logic/wake.rs+277−491
- crates/ltx/Cargo.toml+1−0
- crates/ltx/src/client/bundle.rs+136−75
- crates/ltx/src/client/file.rs+58−0
- crates/ltx/src/client/mod.rs+109−76
- crates/ltx/src/client/object_store.rs+459−393
- crates/ltx/src/compactor.rs+57−29
- crates/ltx/src/db.rs+2266−2188
- crates/ltx/src/host.rs+77−61
- crates/ltx/src/replica_compactor.rs+436−222
- docs/README.md+945−858
- docs/cloudflare-compat.md+472−494
- docs/guarantees.md+325−211
- docs/security.md+6−0
- docs/telemetry.md+140−126
- docs/wasm.md+23−0
- examples/README.md+5−0
- examples/container/Dockerfile+6−0
- examples/container/README.md+36−0
- examples/container/index.js+39−0
- examples/container/package.json+8−0
- examples/container/server.py+32−0
- examples/container/wrangler.jsonc+17−0
- examples/facets/README.md+21−0
- examples/facets/index.js+45−0
- examples/facets/wrangler.jsonc+10−0
- examples/opencode/README.md+1−1
- examples/opencode/package-lock.json+0−8679
- examples/opencode/package.json+0−3
- examples/pi/.gitignore+0−1
- examples/pi/README.md+27−26
- examples/pi/index.js+50−52
- examples/pi/package-lock.json+0−3011
- examples/pi/package.json+0−3
- examples/pi/wrangler.jsonc+2−1
- examples/sandbox/Dockerfile+5−0
- examples/sandbox/README.md+32−0
- examples/sandbox/index.js+46−0
- examples/sandbox/package.json+8−0
- examples/sandbox/wrangler.jsonc+18−0
modified.gitignore+3−0View file
| @@ -1,3 +1,6 @@ | ||
| 1 | 1 | .DS_Store |
| 2 | 2 | .celld/ |
| 3 | 3 | /target/ |
| 4 | +.dev.vars | |
| 5 | +node_modules/ | |
| 6 | +package-lock.json |
modifiedCargo.lock+2−1View file
| @@ -285,7 +285,7 @@ | ||
| 285 | 285 | |
| 286 | 286 | [[package]] |
| 287 | 287 | name = "celld" |
| 288 | -version = "0.4.1" | |
| 288 | +version = "0.5.0" | |
| 289 | 289 | dependencies = [ |
| 290 | 290 | "aes", |
| 291 | 291 | "aes-gcm", |
| @@ -376,6 +376,7 @@ | ||
| 376 | 376 | "object_store", |
| 377 | 377 | "percent-encoding", |
| 378 | 378 | "rusqlite", |
| 379 | + "tempfile", | |
| 379 | 380 | "thiserror 2.0.19", |
| 380 | 381 | "tokio", |
| 381 | 382 | "tracing", |
modifiedREADME.md+9−0View file
| @@ -54,6 +54,8 @@ | ||
| 54 | 54 | | Workflows: durable steps, sleeps, events, pause and restart | [`workflow`](examples/workflow) | |
| 55 | 55 | | Cron Triggers: one run for each occurrence across the fleet | [`cron`](examples/cron) | |
| 56 | 56 | | Static assets: asset-only or with a Worker, `_headers`, `_redirects` | [docs](docs/cloudflare-compat.md#static-assets) | |
| 57 | +| Containers (experimental): a Durable Object that supervises a container, `@cloudflare/containers` | [`container`](examples/container) | | |
| 58 | +| Sandboxes: the Cloudflare Sandbox SDK, `@cloudflare/sandbox`, on a container per sandbox | [`sandbox`](examples/sandbox) | | |
| 57 | 59 | |
| 58 | 60 | A product that needs the Cloudflare network, a GPU, or a browser farm is out |
| 59 | 61 | of scope. The [Cloudflare compatibility](docs/cloudflare-compat.md) page |
| @@ -217,6 +219,13 @@ | ||
| 217 | 219 | bucket leases; there is no account or join service. Run `celld --help` for |
| 218 | 220 | the complete command line. |
| 219 | 221 | |
| 222 | +An upgrade from v0.4.1 preserves the existing bucket and node data directories. | |
| 223 | +Stop all old nodes, then start the new binaries with the same configuration. | |
| 224 | +Startup upgrades the wake format automatically before a node serves traffic. | |
| 225 | +Mixed versions cannot share a serving fleet. | |
| 226 | +The [wake format contract](docs/guarantees.md#start-a-fleet-with-this-format) | |
| 227 | +describes the startup checks and the boundary for existing fleet data. | |
| 228 | + | |
| 220 | 229 | Peer HTTP and the operator API use the internal listener. Put every |
| 221 | 230 | advertised address on a trusted private network or an encrypted overlay such |
| 222 | 231 | as WireGuard or Tailscale, and do not publish the internal port. celld |
modifiedcrates/celld/Cargo.toml+1−1View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [package] |
| 2 | 2 | name = "celld" |
| 3 | -version = "0.4.1" | |
| 3 | +version = "0.5.0" | |
| 4 | 4 | edition = "2021" |
| 5 | 5 | rust-version = "1.94.1" |
| 6 | 6 | license = "Apache-2.0" |
modifiedcrates/celld/actor.rs+187−91View file
| @@ -26,9 +26,14 @@ | ||
| 26 | 26 | use tokio::sync::{mpsc, oneshot, watch, Mutex}; |
| 27 | 27 | use tokio_util::time::{delay_queue, DelayQueue}; |
| 28 | 28 | |
| 29 | +mod local_request; | |
| 29 | 30 | mod production; |
| 31 | +pub use local_request::{LocalRequest, LocalRequestCompletion, LocalRequestFailure}; | |
| 30 | 32 | |
| 31 | 33 | const DEFAULT_OPERATION_DEADLINE_MS: u64 = 15_000; |
| 34 | +/// How long a graceful handoff keeps refreshing an uncovered alarm's wake | |
| 35 | +/// entry before it gives up and lets the drain deadline decide. | |
| 36 | +const HANDOFF_ALARM_COVERAGE_MS: u64 = 5_000; | |
| 32 | 37 | |
| 33 | 38 | /// The shell's deadline for one actor operation. Queue leases include this |
| 34 | 39 | /// exact budget for their settlement call, so the actor and broker must read |
| @@ -164,7 +169,7 @@ | ||
| 164 | 169 | } |
| 165 | 170 | |
| 166 | 171 | impl Ownership { |
| 167 | - async fn read_owner(&self, cell: &str) -> Result<Option<OwnerRecord>, Failure> { | |
| 172 | + pub(crate) async fn read_owner(&self, cell: &str) -> Result<Option<OwnerRecord>, Failure> { | |
| 168 | 173 | match self { |
| 169 | 174 | Self::Memory(memory) => Ok(memory.lock().await.owners.get(cell).cloned()), |
| 170 | 175 | Self::Bucket(bucket) => bucket.read_owner(cell).await.map_err(|error| { |
| @@ -421,7 +426,7 @@ | ||
| 421 | 426 | // request's completion costs the serial core one message, not two — the |
| 422 | 427 | // hot path for every routed DO call. |
| 423 | 428 | cell: String, |
| 424 | - alarm_at_ms: Option<i64>, | |
| 429 | + alarm: celld_logic::wake::AlarmSnapshot, | |
| 425 | 430 | alarm_covered: bool, |
| 426 | 431 | }, |
| 427 | 432 | /// An outbound effect is ready to leave on `channel`. A write opens a |
| @@ -459,9 +464,12 @@ | ||
| 459 | 464 | }, |
| 460 | 465 | AlarmObserved { |
| 461 | 466 | cell: String, |
| 462 | - at_ms: Option<i64>, | |
| 467 | + alarm: celld_logic::wake::AlarmSnapshot, | |
| 463 | 468 | covered: bool, |
| 464 | 469 | }, |
| 470 | + MaintainWake { | |
| 471 | + cell: String, | |
| 472 | + }, | |
| 465 | 473 | WakeHint { |
| 466 | 474 | cell: String, |
| 467 | 475 | entry_ms: i64, |
| @@ -886,7 +894,7 @@ | ||
| 886 | 894 | pub struct ActivityGuard { |
| 887 | 895 | tx: mpsc::UnboundedSender<Message>, |
| 888 | 896 | request: u64, |
| 889 | - runtime: Option<RuntimeManager>, | |
| 897 | + host: Option<CellHost>, | |
| 890 | 898 | cell: String, |
| 891 | 899 | drain_pins: DrainPinRegistry, |
| 892 | 900 | cancellation: watch::Receiver<bool>, |
| @@ -950,20 +958,25 @@ | ||
| 950 | 958 | // report cannot carry an alarm older than one the reporter already |
| 951 | 959 | // sent — a stale fold arriving later would unarm the core and |
| 952 | 960 | // delete the wake entry (`alarm_reporter` documents the ordering). |
| 953 | - let send = |tx: &mpsc::UnboundedSender<Message>, at_ms, covered| { | |
| 961 | + // The cache also retains the source revision: this notification can | |
| 962 | + // still wait in the mailbox while an admitted handler arms the cell. | |
| 963 | + let send = |tx: &mpsc::UnboundedSender<Message>, alarm, covered| { | |
| 954 | 964 | let _ = tx.send(Message::ActivityFinished { |
| 955 | 965 | request: self.request, |
| 956 | 966 | cell: self.cell.clone(), |
| 957 | - alarm_at_ms: at_ms, | |
| 967 | + alarm, | |
| 958 | 968 | alarm_covered: covered, |
| 959 | 969 | }); |
| 960 | 970 | }; |
| 961 | - match &self.runtime { | |
| 962 | - Some(runtime) => runtime.with_alarm(&self.cell, |at_ms| { | |
| 963 | - let covered = runtime.alarm_covered(&self.cell, at_ms); | |
| 964 | - send(&self.tx, at_ms, covered); | |
| 971 | + match &self.host { | |
| 972 | + Some(host) => host.with_alarm(&self.cell, |alarm, covered| { | |
| 973 | + send(&self.tx, alarm, covered); | |
| 965 | 974 | }), |
| 966 | - None => send(&self.tx, None, false), | |
| 975 | + None => send( | |
| 976 | + &self.tx, | |
| 977 | + celld_logic::wake::AlarmSnapshot::without_wake(None), | |
| 978 | + false, | |
| 979 | + ), | |
| 967 | 980 | } |
| 968 | 981 | } |
| 969 | 982 | } |
| @@ -1103,6 +1116,21 @@ | ||
| 1103 | 1116 | Fut: std::future::Future<Output = anyhow::Result<()>>, |
| 1104 | 1117 | { |
| 1105 | 1118 | while let Err(error) = release().await { |
| 1119 | + // An abandoned eviction is the one failure that must not be retried. | |
| 1120 | + // The cell is resident at its own epoch with a request waiting on it, | |
| 1121 | + // and a retry would take the cell the abandonment just gave back. | |
| 1122 | + // `RuntimeStopFailed` is the same ending a stop that ran out of time | |
| 1123 | + // reports, and the core answers both by starting the cell in place. | |
| 1124 | + if let Some(abandoned) = error.downcast_ref::<crate::replication::EvictionAbandoned>() { | |
| 1125 | + tracing::info!( | |
| 1126 | + event, | |
| 1127 | + %cell, | |
| 1128 | + epoch, | |
| 1129 | + reason = %abandoned, | |
| 1130 | + "a request reached the cell before the eviction took it; restarting it in place" | |
| 1131 | + ); | |
| 1132 | + return CompletedEffect::plain(Event::RuntimeStopFailed { op }); | |
| 1133 | + } | |
| 1106 | 1134 | if deadline_mono_ms.is_some_and(|deadline| crate::asyncrt::mono_ms() >= deadline) { |
| 1107 | 1135 | tracing::warn!( |
| 1108 | 1136 | event, |
| @@ -1200,6 +1228,8 @@ | ||
| 1200 | 1228 | pub struct AppHandle { |
| 1201 | 1229 | pub tx: mpsc::UnboundedSender<Message>, |
| 1202 | 1230 | pub runtime: Option<RuntimeManager>, |
| 1231 | + #[cfg(all(test, celld_internal_tests))] | |
| 1232 | + pub(crate) scripted_activity_host: Option<crate::conformance_sim_cell_host::SimCellHost>, | |
| 1203 | 1233 | /// Asks the pointer watcher to adopt the current deployment now. Sending |
| 1204 | 1234 | /// fails on a node with no pointer to watch, such as a local-script node. |
| 1205 | 1235 | pub reload: crate::generation::ReloadSender, |
| @@ -1207,11 +1237,6 @@ | ||
| 1207 | 1237 | pub peer_auth: Arc<PeerAuth>, |
| 1208 | 1238 | pub advertise: String, |
| 1209 | 1239 | pub websockets: mpsc::UnboundedSender<WebSocketFuture>, |
| 1210 | - /// Whether the RPO=0 output gate is armed: hold a local write's response | |
| 1211 | - /// until its cell is proven durable. On by default; set `CELLD_OUTPUT_GATE=0` | |
| 1212 | - /// to acknowledge writes without proving them durable. The core and its DST | |
| 1213 | - /// are unconditional. | |
| 1214 | - pub output_gate: bool, | |
| 1215 | 1240 | /// Concurrent outbound WebSockets one cell may hold, for the refusal |
| 1216 | 1241 | /// message; the core enforces it. |
| 1217 | 1242 | pub max_outbound_websockets: usize, |
| @@ -1470,10 +1495,13 @@ | ||
| 1470 | 1495 | origin: &'static str, |
| 1471 | 1496 | ) -> ActivityGuard { |
| 1472 | 1497 | let cancellation = self.drain_pins.begin(request, request_id, origin); |
| 1498 | + let host = self.runtime.clone().map(CellHost::V8); | |
| 1499 | + #[cfg(all(test, celld_internal_tests))] | |
| 1500 | + let host = host.or_else(|| self.scripted_activity_host.clone().map(CellHost::Scripted)); | |
| 1473 | 1501 | ActivityGuard { |
| 1474 | 1502 | tx: self.tx.clone(), |
| 1475 | 1503 | request, |
| 1476 | - runtime: self.runtime.clone(), | |
| 1504 | + host, | |
| 1477 | 1505 | cell, |
| 1478 | 1506 | drain_pins: self.drain_pins.clone(), |
| 1479 | 1507 | cancellation, |
| @@ -1600,8 +1628,9 @@ | ||
| 1600 | 1628 | .context("core stopped while opening WebSocket")?; |
| 1601 | 1629 | anyhow::ensure!( |
| 1602 | 1630 | held, |
| 1603 | - "outbound WebSocket refused: a cell may hold at most {}, and a node \ | |
| 1604 | - may pin at most {}% of its residency ceiling", | |
| 1631 | + "outbound WebSocket refused: the cell is leaving this node, or a cell \ | |
| 1632 | + may hold at most {} and a node may pin at most {}% of its residency \ | |
| 1633 | + ceiling", | |
| 1605 | 1634 | self.max_outbound_websockets, |
| 1606 | 1635 | celld_logic::pressure::MAX_OUTBOUND_PIN_PERCENT, |
| 1607 | 1636 | ); |
| @@ -1837,8 +1866,14 @@ | ||
| 1837 | 1866 | pub ownership: Ownership, |
| 1838 | 1867 | peer_http: reqwest::Client, |
| 1839 | 1868 | peer_auth: Arc<PeerAuth>, |
| 1840 | - paced_handoff: bool, | |
| 1841 | 1869 | operation_deadline_ms: u64, |
| 1870 | + /// The abandon signal of every eviction stop now in flight, by its op. | |
| 1871 | + /// | |
| 1872 | + /// Only a bounded eviction has an entry, because only a bounded eviction | |
| 1873 | + /// can be given back. The entry is removed when the stop reports either | |
| 1874 | + /// ending, so a late `AbandonEvictionStop` for a finished op finds | |
| 1875 | + /// nothing and does nothing. | |
| 1876 | + eviction_abandons: BTreeMap<OpId, Arc<crate::replication::EvictionAbandon>>, | |
| 1842 | 1877 | handoff_directory: Arc<Mutex<HandoffDirectory>>, |
| 1843 | 1878 | host: Option<CellHost>, |
| 1844 | 1879 | drain_pins: DrainPinRegistry, |
| @@ -2001,8 +2036,7 @@ | ||
| 2001 | 2036 | && !peer.addr.is_empty() |
| 2002 | 2037 | && peer.peer_protocol == peer_auth::PROTOCOL_VERSION |
| 2003 | 2038 | && peer.sampled_ms != 0 |
| 2004 | - && !peer.pressured | |
| 2005 | - && peer.memory_headroom != Some(false) | |
| 2039 | + && peer.reports_adoption_capacity() | |
| 2006 | 2040 | && peer.paced_handoff |
| 2007 | 2041 | }) |
| 2008 | 2042 | .collect(); |
| @@ -2064,6 +2098,8 @@ | ||
| 2064 | 2098 | pub struct AdmissionLimits { |
| 2065 | 2099 | pub resident: usize, |
| 2066 | 2100 | pub activations: usize, |
| 2101 | + // Private worlds vary admission pressure; production fixes this in the core config. | |
| 2102 | + #[cfg(all(test, celld_internal_tests))] | |
| 2067 | 2103 | pub evictions: usize, |
| 2068 | 2104 | pub releases: usize, |
| 2069 | 2105 | /// The ownership share this node publishes for rebalancing. |
| @@ -2094,7 +2130,6 @@ | ||
| 2094 | 2130 | pub ownership: Option<Ownership>, |
| 2095 | 2131 | pub peer_http: reqwest::Client, |
| 2096 | 2132 | pub peer_auth: Arc<PeerAuth>, |
| 2097 | - pub paced_handoff: bool, | |
| 2098 | 2133 | } |
| 2099 | 2134 | |
| 2100 | 2135 | struct ActorHostServices { |
| @@ -2103,10 +2138,31 @@ | ||
| 2103 | 2138 | ownership: Option<Ownership>, |
| 2104 | 2139 | peer_http: reqwest::Client, |
| 2105 | 2140 | peer_auth: Arc<PeerAuth>, |
| 2106 | - paced_handoff: bool, | |
| 2107 | 2141 | } |
| 2108 | 2142 | |
| 2109 | 2143 | impl Actor { |
| 2144 | + fn schedule_wake_maintenance(&self, cell: String, alarm: celld_logic::wake::AlarmSnapshot) { | |
| 2145 | + let Some(host) = self.host.clone() else { | |
| 2146 | + return; | |
| 2147 | + }; | |
| 2148 | + let ownership = self.ownership.clone(); | |
| 2149 | + let node = self.state.node().to_string(); | |
| 2150 | + let deadline = std::time::Duration::from_millis(self.operation_deadline_ms); | |
| 2151 | + crate::asyncrt::spawn(async move { | |
| 2152 | + match crate::asyncrt::timeout( | |
| 2153 | + deadline, | |
| 2154 | + crate::js::maintain_wake_entry(&cell, alarm, &host, &ownership, &node), | |
| 2155 | + ) | |
| 2156 | + .await | |
| 2157 | + { | |
| 2158 | + Ok(Ok(())) => {} | |
| 2159 | + Ok(Err(error)) => tracing::warn!(%cell, %error, "wake maintenance deferred"), | |
| 2160 | + Err(_) => tracing::warn!(%cell, "wake maintenance timed out; a later scan retries"), | |
| 2161 | + } | |
| 2162 | + }) | |
| 2163 | + .detach(); | |
| 2164 | + } | |
| 2165 | + | |
| 2110 | 2166 | pub async fn from_environment( |
| 2111 | 2167 | limits: AdmissionLimits, |
| 2112 | 2168 | fail_publish_once: bool, |
| @@ -2127,7 +2183,6 @@ | ||
| 2127 | 2183 | ownership, |
| 2128 | 2184 | peer_http: reqwest::Client::new(), |
| 2129 | 2185 | peer_auth, |
| 2130 | - paced_handoff: false, | |
| 2131 | 2186 | }, |
| 2132 | 2187 | identity, |
| 2133 | 2188 | resume_generation, |
| @@ -2149,7 +2204,6 @@ | ||
| 2149 | 2204 | ownership, |
| 2150 | 2205 | peer_http, |
| 2151 | 2206 | peer_auth, |
| 2152 | - paced_handoff, | |
| 2153 | 2207 | } = services; |
| 2154 | 2208 | Self::from_environment_with_cell_host( |
| 2155 | 2209 | limits, |
| @@ -2161,7 +2215,6 @@ | ||
| 2161 | 2215 | ownership, |
| 2162 | 2216 | peer_http, |
| 2163 | 2217 | peer_auth, |
| 2164 | - paced_handoff, | |
| 2165 | 2218 | }, |
| 2166 | 2219 | identity, |
| 2167 | 2220 | resume_generation, |
| @@ -2190,7 +2243,6 @@ | ||
| 2190 | 2243 | ownership, |
| 2191 | 2244 | peer_http: reqwest::Client::new(), |
| 2192 | 2245 | peer_auth, |
| 2193 | - paced_handoff: false, | |
| 2194 | 2246 | }, |
| 2195 | 2247 | identity, |
| 2196 | 2248 | resume_generation, |
| @@ -2267,7 +2319,6 @@ | ||
| 2267 | 2319 | ownership, |
| 2268 | 2320 | peer_http, |
| 2269 | 2321 | peer_auth, |
| 2270 | - paced_handoff, | |
| 2271 | 2322 | } = services; |
| 2272 | 2323 | let ActorIdentity { |
| 2273 | 2324 | node, |
| @@ -2320,6 +2371,10 @@ | ||
| 2320 | 2371 | Config { |
| 2321 | 2372 | max_resident: limits.resident, |
| 2322 | 2373 | max_activations: limits.activations, |
| 2374 | + // Each eviction proves durability, so bound background bucket I/O. | |
| 2375 | + #[cfg(not(all(test, celld_internal_tests)))] | |
| 2376 | + max_evictions: 4, | |
| 2377 | + #[cfg(all(test, celld_internal_tests))] | |
| 2323 | 2378 | max_evictions: limits.evictions, |
| 2324 | 2379 | max_releases: limits.releases, |
| 2325 | 2380 | alarm_resident_ms: crate::wake::resident_ms().max(0) as u64, |
| @@ -2355,8 +2410,8 @@ | ||
| 2355 | 2410 | ownership, |
| 2356 | 2411 | peer_http, |
| 2357 | 2412 | peer_auth, |
| 2358 | - paced_handoff, | |
| 2359 | 2413 | operation_deadline_ms, |
| 2414 | + eviction_abandons: BTreeMap::new(), | |
| 2360 | 2415 | handoff_directory: Arc::new(Mutex::new(HandoffDirectory::default())), |
| 2361 | 2416 | host, |
| 2362 | 2417 | drain_pins, |
| @@ -2570,6 +2625,9 @@ | ||
| 2570 | 2625 | in_use_bytes: metrics.in_use_bytes, |
| 2571 | 2626 | cgroup_working_set_bytes: metrics.cgroup_working_set_bytes, |
| 2572 | 2627 | cgroup_current_bytes: metrics.cgroup_current_bytes, |
| 2628 | + // Containers run in sibling cgroups, so the sample above | |
| 2629 | + // omits their memory; add what they reserve on this node. | |
| 2630 | + container_reserved_bytes: crate::container::reserved_memory_bytes(), | |
| 2573 | 2631 | }; |
| 2574 | 2632 | let now_mono_ms = crate::asyncrt::mono_ms(); |
| 2575 | 2633 | self.drive(Event::LoadSampled { load, now_mono_ms }, out); |
| @@ -2710,7 +2768,7 @@ | ||
| 2710 | 2768 | Message::ActivityFinished { |
| 2711 | 2769 | request, |
| 2712 | 2770 | cell, |
| 2713 | - alarm_at_ms, | |
| 2771 | + alarm, | |
| 2714 | 2772 | alarm_covered, |
| 2715 | 2773 | } => { |
| 2716 | 2774 | // Folded from the old AlarmObserved-then-ActivityFinished pair the |
| @@ -2724,7 +2782,7 @@ | ||
| 2724 | 2782 | self.drive( |
| 2725 | 2783 | Event::AlarmObserved { |
| 2726 | 2784 | cell, |
| 2727 | - at_ms: alarm_at_ms, | |
| 2785 | + alarm, | |
| 2728 | 2786 | covered: alarm_covered, |
| 2729 | 2787 | now_ms: now_ms(), |
| 2730 | 2788 | now_mono_ms: crate::asyncrt::mono_ms(), |
| @@ -2770,7 +2828,7 @@ | ||
| 2770 | 2828 | } |
| 2771 | 2829 | Message::AlarmObserved { |
| 2772 | 2830 | cell, |
| 2773 | - at_ms, | |
| 2831 | + alarm, | |
| 2774 | 2832 | covered, |
| 2775 | 2833 | } => { |
| 2776 | 2834 | let retired_durability = match self.state.phase(&cell) { |
| @@ -2780,7 +2838,7 @@ | ||
| 2780 | 2838 | self.drive( |
| 2781 | 2839 | Event::AlarmObserved { |
| 2782 | 2840 | cell, |
| 2783 | - at_ms, | |
| 2841 | + alarm, | |
| 2784 | 2842 | covered, |
| 2785 | 2843 | now_ms: now_ms(), |
| 2786 | 2844 | now_mono_ms: crate::asyncrt::mono_ms(), |
| @@ -2804,6 +2862,12 @@ | ||
| 2804 | 2862 | out, |
| 2805 | 2863 | ); |
| 2806 | 2864 | } |
| 2865 | + Message::MaintainWake { cell } => { | |
| 2866 | + if let Some(host) = &self.host { | |
| 2867 | + let alarm = host.with_alarm(&cell, |alarm, _| alarm); | |
| 2868 | + self.schedule_wake_maintenance(cell, alarm); | |
| 2869 | + } | |
| 2870 | + } | |
| 2807 | 2871 | Message::WakeHint { .. } if self.preserving => {} |
| 2808 | 2872 | Message::WakeHint { |
| 2809 | 2873 | cell, |
| @@ -3010,6 +3074,12 @@ | ||
| 3010 | 3074 | Event::RuntimeStopped { op } | Event::RuntimeStopFailed { op } => Some(*op), |
| 3011 | 3075 | _ => None, |
| 3012 | 3076 | }; |
| 3077 | + // The stop has an ending, so its signal can no longer change | |
| 3078 | + // anything. Dropping it here keeps the map the size of the stops | |
| 3079 | + // actually in flight. | |
| 3080 | + if let Some(op) = stopped { | |
| 3081 | + self.eviction_abandons.remove(&op); | |
| 3082 | + } | |
| 3013 | 3083 | let effects = apply_core_event(&mut self.state, event); |
| 3014 | 3084 | if let Some(op) = durability { |
| 3015 | 3085 | if let Some((_, waiters)) = self.durability_waiters.remove(&op) { |
| @@ -3333,47 +3403,9 @@ | ||
| 3333 | 3403 | ) |
| 3334 | 3404 | })); |
| 3335 | 3405 | } |
| 3336 | - Effect::AdoptWakeEntry { cell, entry_ms } => { | |
| 3337 | - crate::js::adopt_wake_entry(&cell, entry_ms); | |
| 3406 | + Effect::ReconcileWakeEntry { cell, alarm } => { | |
| 3407 | + self.schedule_wake_maintenance(cell, alarm); | |
| 3338 | 3408 | } |
| 3339 | - Effect::ReconcileWakeEntry { | |
| 3340 | - cell, | |
| 3341 | - next_alarm_ms, | |
| 3342 | - } => { | |
| 3343 | - if self.host.is_some() { | |
| 3344 | - // An ARMED alarm must always be reconcilable, tracked or | |
| 3345 | - // not: belief can be lost while the alarm stands (a | |
| 3346 | - // failed arm-time PUT, an entry retired under a racing | |
| 3347 | - // arm), and skipping here would mean it is never | |
| 3348 | - // re-asserted — entryless until the alarm fires or the | |
| 3349 | - // cell moves. Gating the CONSUME side on tracking is | |
| 3350 | - // what keeps alarm-less cells op-quiescent: untracked | |
| 3351 | - // with no alarm, there is nothing to delete. | |
| 3352 | - if next_alarm_ms >= 0 || crate::js::wake_entry_tracked(&cell) { | |
| 3353 | - // On the host runtime: this arm runs on the core | |
| 3354 | - // thread, and a bare spawn would schedule the S3 | |
| 3355 | - // round trip there too. | |
| 3356 | - crate::asyncrt::spawn(async move { | |
| 3357 | - // A consume-delete only ever follows a firing, and | |
| 3358 | - // the core orders it from the far side of the | |
| 3359 | - // output gate: `alarm_finished` gates the | |
| 3360 | - // consuming commit, and only a proven | |
| 3361 | - // DurableReached — with an ownership read behind a | |
| 3362 | - // bucket proof — lets the alarm settle | |
| 3363 | - // into this reconcile. So by the time this delete | |
| 3364 | - // is ordered, the proof already happened, and | |
| 3365 | - // nothing here decides anything. The old | |
| 3366 | - // sync_refused probe asked the same question a | |
| 3367 | - // second way and was wrong more often: it refused | |
| 3368 | - // for any database the replicator never | |
| 3369 | - // registered, leaving the entry to outlive its | |
| 3370 | - // alarm forever. | |
| 3371 | - crate::js::reconcile_wake_entry(&cell, next_alarm_ms, true).await; | |
| 3372 | - }) | |
| 3373 | - .detach(); | |
| 3374 | - } | |
| 3375 | - } | |
| 3376 | - } | |
| 3377 | 3409 | Effect::ReleaseOwner { op, cell, epoch } => { |
| 3378 | 3410 | if self.handoff_timings.contains_key(&cell) { |
| 3379 | 3411 | self.handoff_phase_ops.insert( |
| @@ -3398,9 +3430,8 @@ | ||
| 3398 | 3430 | rebalance, |
| 3399 | 3431 | } => { |
| 3400 | 3432 | // The in-memory adapter is one process, so it has no successor |
| 3401 | - // to acknowledge a handoff. The feature switch is an escape | |
| 3402 | - // hatch for mixed operational use, not the production default. | |
| 3403 | - if !self.paced_handoff || matches!(&self.ownership, Ownership::Memory(_)) { | |
| 3433 | + // to acknowledge a handoff. | |
| 3434 | + if matches!(&self.ownership, Ownership::Memory(_)) { | |
| 3404 | 3435 | immediate.push_back(Event::SuccessorAdopted { |
| 3405 | 3436 | op, |
| 3406 | 3437 | result: Err(Failure::Definite), |
| @@ -3565,33 +3596,60 @@ | ||
| 3565 | 3596 | // entry PUT before telling the core this cell can leave. |
| 3566 | 3597 | if let Some(runtime) = self.host.clone() { |
| 3567 | 3598 | match runtime.alarm_observation(&cell) { |
| 3568 | - Some((Some(at_ms), false)) => { | |
| 3599 | + Some((mut alarm, false)) if alarm.at_ms().is_some() => { | |
| 3600 | + let at_ms = alarm.at_ms().unwrap(); | |
| 3569 | 3601 | out.effects.push(Box::pin(async move { |
| 3570 | 3602 | let started = crate::asyncrt::mono_ms(); |
| 3571 | - let (observed, covered) = runtime | |
| 3572 | - .refresh_handoff_alarm_coverage(&cell, at_ms) | |
| 3573 | - .await | |
| 3574 | - .unwrap_or((Some(at_ms), false)); | |
| 3603 | + // One refresh is not enough for an object | |
| 3604 | + // that re-arms its alarm continuously (the | |
| 3605 | + // `@cloudflare/containers` class does, every | |
| 3606 | + // second on the Sandbox SDK): a completed | |
| 3607 | + // PUT can cover the previous installation | |
| 3608 | + // while the latest remains uncovered. A | |
| 3609 | + // single attempt could hold the cell for | |
| 3610 | + // the whole drain window. Keep refreshing | |
| 3611 | + // the latest snapshot until it is covered. | |
| 3612 | + let mut attempts = 0u32; | |
| 3613 | + let (observed, covered) = loop { | |
| 3614 | + attempts += 1; | |
| 3615 | + let (observed, covered) = runtime | |
| 3616 | + .refresh_handoff_alarm_coverage(&cell, alarm) | |
| 3617 | + .await | |
| 3618 | + .unwrap_or((alarm, false)); | |
| 3619 | + let settled = covered || observed.at_ms().is_none(); | |
| 3620 | + if settled | |
| 3621 | + || crate::asyncrt::mono_ms().saturating_sub(started) | |
| 3622 | + >= HANDOFF_ALARM_COVERAGE_MS | |
| 3623 | + { | |
| 3624 | + break (observed, covered); | |
| 3625 | + } | |
| 3626 | + crate::asyncrt::sleep(std::time::Duration::from_millis(100)) | |
| 3627 | + .await; | |
| 3628 | + alarm = runtime | |
| 3629 | + .alarm_observation(&cell) | |
| 3630 | + .map_or(alarm, |(alarm, _)| alarm); | |
| 3631 | + }; | |
| 3575 | 3632 | tracing::info!( |
| 3576 | 3633 | event = "handoff_alarm_coverage", |
| 3577 | 3634 | %cell, |
| 3578 | 3635 | at_ms, |
| 3579 | 3636 | covered, |
| 3637 | + attempts, | |
| 3580 | 3638 | elapsed_ms = crate::asyncrt::mono_ms().saturating_sub(started), |
| 3581 | 3639 | "refreshed alarm coverage for graceful handoff" |
| 3582 | 3640 | ); |
| 3583 | 3641 | CompletedEffect::plain(Event::AlarmObserved { |
| 3584 | 3642 | cell, |
| 3585 | - at_ms: observed, | |
| 3643 | + alarm: observed, | |
| 3586 | 3644 | covered, |
| 3587 | 3645 | now_ms: now_ms(), |
| 3588 | 3646 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 3589 | 3647 | }) |
| 3590 | 3648 | })); |
| 3591 | 3649 | } |
| 3592 | - Some((at_ms, covered)) => immediate.push_back(Event::AlarmObserved { | |
| 3650 | + Some((alarm, covered)) => immediate.push_back(Event::AlarmObserved { | |
| 3593 | 3651 | cell, |
| 3594 | - at_ms, | |
| 3652 | + alarm, | |
| 3595 | 3653 | covered, |
| 3596 | 3654 | now_ms: now_ms(), |
| 3597 | 3655 | now_mono_ms: crate::asyncrt::mono_ms(), |
| @@ -3718,7 +3776,12 @@ | ||
| 3718 | 3776 | } |
| 3719 | 3777 | immediate.push_back(Event::Published { op, result }); |
| 3720 | 3778 | } |
| 3721 | - Effect::EnsureDurable { op, cell, epoch } => { | |
| 3779 | + Effect::EnsureDurable { | |
| 3780 | + op, | |
| 3781 | + cell, | |
| 3782 | + epoch, | |
| 3783 | + revocable, | |
| 3784 | + } => { | |
| 3722 | 3785 | if let Some(timing) = self.handoff_timings.get_mut(&cell) { |
| 3723 | 3786 | if timing.quiesce_us.is_none() { |
| 3724 | 3787 | timing.quiesce_us = Some(mono_elapsed_us(timing.nominated_mono_ms)); |
| @@ -3742,7 +3805,8 @@ | ||
| 3742 | 3805 | // renew and fence timers. Polling the proof inline can |
| 3743 | 3806 | // therefore turn a graceful handoff into a self-fence. |
| 3744 | 3807 | let task = crate::asyncrt::spawn(async move { |
| 3745 | - let result = runtime.ensure_durable(&cell, epoch).await.map_err(|error| { | |
| 3808 | + let proved = runtime.ensure_durable(&cell, epoch, revocable).await; | |
| 3809 | + let result = proved.map_err(|error| { | |
| 3746 | 3810 | eprintln!( |
| 3747 | 3811 | "celld durability proof failed for {cell} epoch {epoch}: {error:#}" |
| 3748 | 3812 | ); |
| @@ -3858,6 +3922,8 @@ | ||
| 3858 | 3922 | | Channel::WsSelf |
| 3859 | 3923 | | Channel::Service |
| 3860 | 3924 | | Channel::CellRpc |
| 3925 | + | Channel::R2 | |
| 3926 | + | Channel::Tcp | |
| 3861 | 3927 | | Channel::Queue |
| 3862 | 3928 | | Channel::Sync => { |
| 3863 | 3929 | if let Some(reply) = self.gated_responses.remove(&held) { |
| @@ -3919,9 +3985,19 @@ | ||
| 3919 | 3985 | // authority, so it makes the closed image a proved local |
| 3920 | 3986 | // base. A fence can only close in place, and a reset must |
| 3921 | 3987 | // discard the database that failed its durability proof. |
| 3988 | + // Only a bounded eviction gets a signal. A drain or a | |
| 3989 | + // fence has nowhere to put the cell back, so an abandon | |
| 3990 | + // request could change nothing, and the core does not send | |
| 3991 | + // one for either. | |
| 3992 | + let abandon = (evicting && bounded).then(|| { | |
| 3993 | + let signal = Arc::new(crate::replication::EvictionAbandon::default()); | |
| 3994 | + self.eviction_abandons.insert(op, signal.clone()); | |
| 3995 | + signal | |
| 3996 | + }); | |
| 3922 | 3997 | let stop_mode = match cause { |
| 3923 | 3998 | StopCause::Evict { rebalance } => crate::runtime::StopMode::Evict { |
| 3924 | 3999 | preserve_local: !rebalance, |
| 4000 | + abandon, | |
| 3925 | 4001 | }, |
| 3926 | 4002 | StopCause::Cleanup => crate::runtime::StopMode::Rebase, |
| 3927 | 4003 | StopCause::Fence => crate::runtime::StopMode::CloseInPlace, |
| @@ -3956,6 +4032,7 @@ | ||
| 3956 | 4032 | move || { |
| 3957 | 4033 | let runtime = runtime.clone(); |
| 3958 | 4034 | let cell = released.clone(); |
| 4035 | + let stop_mode = stop_mode.clone(); | |
| 3959 | 4036 | async move { runtime.stop_cell(&cell, epoch, stop_mode).await } |
| 3960 | 4037 | }, |
| 3961 | 4038 | )); |
| @@ -3967,6 +4044,20 @@ | ||
| 3967 | 4044 | } |
| 3968 | 4045 | } |
| 3969 | 4046 | } |
| 4047 | + Effect::AbandonEvictionStop { op, cell } => { | |
| 4048 | + // The stop may already have passed the point where it can | |
| 4049 | + // stop, or may already have finished. Either way this only | |
| 4050 | + // sets a bit that `LtxRepl::evict` reads at the points where | |
| 4051 | + // it can still act on it. | |
| 4052 | + if let Some(signal) = self.eviction_abandons.get(&op) { | |
| 4053 | + signal.request(); | |
| 4054 | + tracing::info!( | |
| 4055 | + event = "eviction_abandon_requested", | |
| 4056 | + %cell, | |
| 4057 | + "a request reached a cell whose eviction is stopping it" | |
| 4058 | + ); | |
| 4059 | + } | |
| 4060 | + } | |
| 3970 | 4061 | Effect::FireAlarm { |
| 3971 | 4062 | op, |
| 3972 | 4063 | cell, |
| @@ -4009,7 +4100,11 @@ | ||
| 4009 | 4100 | epoch, |
| 4010 | 4101 | now_ms: now_ms(), |
| 4011 | 4102 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 4012 | - result: Ok((None, true, None)), | |
| 4103 | + result: Ok(( | |
| 4104 | + celld_logic::wake::AlarmSnapshot::without_wake(None), | |
| 4105 | + true, | |
| 4106 | + None, | |
| 4107 | + )), | |
| 4013 | 4108 | }); |
| 4014 | 4109 | } |
| 4015 | 4110 | } |
| @@ -4068,8 +4163,8 @@ | ||
| 4068 | 4163 | // the core it is gone, so the cell is not left believing it |
| 4069 | 4164 | // has a socket the node already closed. |
| 4070 | 4165 | eprintln!( |
| 4071 | - "celld refused an outbound WebSocket for {cell}: the node's \ | |
| 4072 | - outbound pin budget is spent" | |
| 4166 | + "celld refused an outbound WebSocket for {cell}: the cell is \ | |
| 4167 | + leaving this node or the node's outbound pin budget is spent" | |
| 4073 | 4168 | ); |
| 4074 | 4169 | crate::js::ws_unregister(websocket); |
| 4075 | 4170 | immediate.push_back(Event::WebSocketClosed { cell, websocket }); |
| @@ -4148,7 +4243,7 @@ | ||
| 4148 | 4243 | .collect::<Vec<_>>() |
| 4149 | 4244 | .join(","); |
| 4150 | 4245 | format!( |
| 4151 | - "{{\"ownership\":{:?},\"owned_cells\":{},\"occupied\":{},\"quiescing\":{},\"evicting\":{},\"releasing\":{},\"adopting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"handed_off\":{},\"handoff_failed\":{},\"rebalanced\":{},\"rebalance_failed\":{},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"cgroup_working_set_bytes\":{},\"cgroup_current_bytes\":{},\"node_load\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}", | |
| 4246 | + "{{\"ownership\":{:?},\"owned_cells\":{},\"occupied\":{},\"quiescing\":{},\"evicting\":{},\"releasing\":{},\"adopting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"handed_off\":{},\"handoff_failed\":{},\"rebalanced\":{},\"rebalance_failed\":{},\"remote_route_refreshes\":{},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"cgroup_working_set_bytes\":{},\"cgroup_current_bytes\":{},\"node_load\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}", | |
| 4152 | 4247 | self.ownership.name(), |
| 4153 | 4248 | self.state.owned_cells(), |
| 4154 | 4249 | self.state.occupied(), |
| @@ -4165,6 +4260,7 @@ | ||
| 4165 | 4260 | activity.handoff_failed, |
| 4166 | 4261 | activity.rebalanced, |
| 4167 | 4262 | activity.rebalance_failed, |
| 4263 | + activity.remote_route_refreshes, | |
| 4168 | 4264 | self.state |
| 4169 | 4265 | .shed_reason() |
| 4170 | 4266 | .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")), |
addedcrates/celld/actor/local_request.rs+119−0View file
| @@ -1,0 +1,119 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +use super::{ActivityGuard, AppHandle}; | |
| 4 | +use crate::js::{answer_ticket, GatedAnswer, RequestId}; | |
| 5 | +use celld_logic::RequestError; | |
| 6 | +use std::future::Future; | |
| 7 | + | |
| 8 | +/// A locally routed request and its activity lifetime. | |
| 9 | +pub struct LocalRequest<'a> { | |
| 10 | + app: &'a AppHandle, | |
| 11 | + activity: ActivityGuard, | |
| 12 | + #[cfg(all(test, celld_internal_tests))] | |
| 13 | + omit_read_position_for_tooth: bool, | |
| 14 | + #[cfg(all(test, celld_internal_tests))] | |
| 15 | + mutation_position_for_tooth: Option<Option<u64>>, | |
| 16 | +} | |
| 17 | + | |
| 18 | +/// A handler failure or a rejected output, with the original failure retained. | |
| 19 | +#[derive(Debug)] | |
| 20 | +pub enum LocalRequestFailure { | |
| 21 | + Handler(anyhow::Error), | |
| 22 | + OutputGate { | |
| 23 | + verdict: RequestError, | |
| 24 | + handler: Option<anyhow::Error>, | |
| 25 | + }, | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// A gated result and the activity that must follow its response body. | |
| 29 | +pub struct LocalRequestCompletion<T> { | |
| 30 | + pub result: Result<T, LocalRequestFailure>, | |
| 31 | + pub activity: ActivityGuard, | |
| 32 | +} | |
| 33 | + | |
| 34 | +impl AppHandle { | |
| 35 | + /// Bind a locally admitted request to its handler and response lifetime. | |
| 36 | + pub fn local_request( | |
| 37 | + &self, | |
| 38 | + request: u64, | |
| 39 | + cell: String, | |
| 40 | + request_id: Option<RequestId>, | |
| 41 | + origin: &'static str, | |
| 42 | + ) -> LocalRequest<'_> { | |
| 43 | + LocalRequest { | |
| 44 | + app: self, | |
| 45 | + activity: self.activity_for(request, cell, request_id, origin), | |
| 46 | + #[cfg(all(test, celld_internal_tests))] | |
| 47 | + omit_read_position_for_tooth: false, | |
| 48 | + #[cfg(all(test, celld_internal_tests))] | |
| 49 | + mutation_position_for_tooth: None, | |
| 50 | + } | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +impl LocalRequest<'_> { | |
| 55 | + // Reproduce the old read ticket at the request boundary. Keep the handler's | |
| 56 | + // original sample so the omitted position remains detectable. | |
| 57 | + #[cfg(all(test, celld_internal_tests))] | |
| 58 | + pub(crate) fn without_read_position_for_tooth(mut self) -> Self { | |
| 59 | + self.omit_read_position_for_tooth = true; | |
| 60 | + self | |
| 61 | + } | |
| 62 | + | |
| 63 | + // Damage only the production ticket after the handler has returned its | |
| 64 | + // actual SQLite sample. Rewriting both would conceal the missing proof. | |
| 65 | + #[cfg(all(test, celld_internal_tests))] | |
| 66 | + pub(crate) fn with_mutation_position_for_tooth(mut self, position: Option<u64>) -> Self { | |
| 67 | + self.mutation_position_for_tooth = Some(position); | |
| 68 | + self | |
| 69 | + } | |
| 70 | + | |
| 71 | + /// Execute a handler and hold its answer until its output ticket resolves. | |
| 72 | + pub async fn run<T: GatedAnswer>( | |
| 73 | + self, | |
| 74 | + handler: impl Future<Output = anyhow::Result<T>>, | |
| 75 | + ) -> LocalRequestCompletion<T> { | |
| 76 | + let result = handler.await; | |
| 77 | + // A failed handler can reveal a committed or observed position too. | |
| 78 | + // Gating successes alone lets its error escape before that position is | |
| 79 | + // durable and leaves later read-only requests without a barrier. | |
| 80 | + let ticket = answer_ticket(&result); | |
| 81 | + #[cfg(all(test, celld_internal_tests))] | |
| 82 | + let ticket = ticket.map(|mut ticket| { | |
| 83 | + if self.omit_read_position_for_tooth && ticket.position.is_none() { | |
| 84 | + ticket.observed = None; | |
| 85 | + } | |
| 86 | + if let (Some(_), Some(position)) = (ticket.position, self.mutation_position_for_tooth) { | |
| 87 | + ticket.position = position; | |
| 88 | + } | |
| 89 | + ticket | |
| 90 | + }); | |
| 91 | + let result = match ticket { | |
| 92 | + Some(ticket) => { | |
| 93 | + self.activity.set_phase("output_gate", false, false); | |
| 94 | + if let Some(position) = ticket.position { | |
| 95 | + self.activity.gate_started(position); | |
| 96 | + } | |
| 97 | + // The activity owns the request used by the gate. Accepting | |
| 98 | + // another request here could acknowledge a different write or | |
| 99 | + // release this cell while its answer still waits for proof. | |
| 100 | + let gated = self.app.gate_output(self.activity.request, ticket).await; | |
| 101 | + self.activity.gate_finished(gated.is_ok()); | |
| 102 | + match gated { | |
| 103 | + Ok(()) => result.map_err(LocalRequestFailure::Handler), | |
| 104 | + Err(verdict) => Err(LocalRequestFailure::OutputGate { | |
| 105 | + verdict, | |
| 106 | + handler: result.err(), | |
| 107 | + }), | |
| 108 | + } | |
| 109 | + } | |
| 110 | + None => result.map_err(LocalRequestFailure::Handler), | |
| 111 | + }; | |
| 112 | + // A streaming answer still pins the cell. Returning only its value | |
| 113 | + // would drop the guard before the response-body owner can retain it. | |
| 114 | + LocalRequestCompletion { | |
| 115 | + result, | |
| 116 | + activity: self.activity, | |
| 117 | + } | |
| 118 | + } | |
| 119 | +} |
modifiedcrates/celld/asyncrt.rs+63−6View file
| @@ -29,7 +29,7 @@ | ||
| 29 | 29 | static SELECT_STATE: OnceLock<AtomicU64> = OnceLock::new(); |
| 30 | 30 | |
| 31 | 31 | thread_local! { |
| 32 | - static SPAWNS: RefCell<Vec<(u64, OpFuture, OpLifetime)>> = const { RefCell::new(Vec::new()) }; | |
| 32 | + static SPAWNS: RefCell<Vec<Spawn>> = const { RefCell::new(Vec::new()) }; | |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | 35 | struct ProductionDomain { |
| @@ -454,12 +454,24 @@ | ||
| 454 | 454 | |
| 455 | 455 | pub type OpFuture = Pin<Box<dyn Future<Output = Result<OpOut, String>> + Send>>; |
| 456 | 456 | |
| 457 | -#[derive(Clone, Copy)] | |
| 458 | -enum OpLifetime { | |
| 457 | +#[derive(Clone, Copy, PartialEq, Eq)] | |
| 458 | +pub enum OpLifetime { | |
| 459 | 459 | Handler, |
| 460 | 460 | IoContext, |
| 461 | + Unrefed, | |
| 461 | 462 | } |
| 462 | 463 | |
| 464 | +/// One enqueued operation, waiting for a driver to take it. | |
| 465 | +struct Spawn { | |
| 466 | + id: u64, | |
| 467 | + future: OpFuture, | |
| 468 | + lifetime: OpLifetime, | |
| 469 | + /// The `IoContext` of the continuation that enqueued it, when the op layer | |
| 470 | + /// could read one. `None` for work with no event behind it, which the | |
| 471 | + /// running turn owns as it always has. | |
| 472 | + owner: Option<u64>, | |
| 473 | +} | |
| 474 | + | |
| 463 | 475 | fn enqueue_with_lifetime<T: Into<OpOut>>( |
| 464 | 476 | future: impl Future<Output = Result<T, String>> + Send + 'static, |
| 465 | 477 | lifetime: OpLifetime, |
| @@ -468,10 +480,44 @@ | ||
| 468 | 480 | .next_async_op |
| 469 | 481 | .fetch_add(1, Ordering::Relaxed); |
| 470 | 482 | let future: OpFuture = Box::pin(async move { future.await.map(Into::into) }); |
| 471 | - SPAWNS.with(|spawns| spawns.borrow_mut().push((id, future, lifetime))); | |
| 483 | + SPAWNS.with(|spawns| { | |
| 484 | + spawns.borrow_mut().push(Spawn { | |
| 485 | + id, | |
| 486 | + future, | |
| 487 | + lifetime, | |
| 488 | + owner: None, | |
| 489 | + }) | |
| 490 | + }); | |
| 472 | 491 | id |
| 473 | 492 | } |
| 474 | 493 | |
| 494 | +/// How many operations wait for the driver to take them. | |
| 495 | +/// | |
| 496 | +/// The op layer reads this before and after one JavaScript op call, so it can | |
| 497 | +/// name the event that enqueued an operation without paying for that lookup on | |
| 498 | +/// every call that enqueues nothing. | |
| 499 | +pub fn spawn_count() -> usize { | |
| 500 | + SPAWNS.with(|spawns| spawns.borrow().len()) | |
| 501 | +} | |
| 502 | + | |
| 503 | +/// Name the event that enqueued every operation added since `from`. | |
| 504 | +/// | |
| 505 | +/// An operation belongs to its continuation's driver (its origin unless a | |
| 506 | +/// critical section installs another driver), not necessarily the running | |
| 507 | +/// turn: V8 runs a foreign continuation during another event's microtask | |
| 508 | +/// checkpoint. Without this the running turn adopts the operation and cancels | |
| 509 | +/// it when it retires, and the event that is really waiting never settles. | |
| 510 | +pub fn attribute_spawns(from: usize, owner: u64) { | |
| 511 | + SPAWNS.with(|spawns| { | |
| 512 | + for spawn in spawns.borrow_mut().iter_mut().skip(from) { | |
| 513 | + // A native callback can invoke JS that enqueues under a nested | |
| 514 | + // continuation context. Its inner wrapper already named the | |
| 515 | + // driver; the outer wrapper must not overwrite that attribution. | |
| 516 | + spawn.owner.get_or_insert(owner); | |
| 517 | + } | |
| 518 | + }); | |
| 519 | +} | |
| 520 | + | |
| 475 | 521 | /// Register an asynchronous operation. The request driver polls the operation. |
| 476 | 522 | pub fn enqueue<T: Into<OpOut>>( |
| 477 | 523 | future: impl Future<Output = Result<T, String>> + Send + 'static, |
| @@ -486,12 +532,23 @@ | ||
| 486 | 532 | enqueue_with_lifetime(future, OpLifetime::IoContext) |
| 487 | 533 | } |
| 488 | 534 | |
| 489 | -pub fn drain_spawns() -> Vec<(u64, OpFuture, bool)> { | |
| 535 | +/// Register an operation that runs with its event but cannot keep it alive. | |
| 536 | +/// | |
| 537 | +/// A listener needs turns while the handler or `waitUntil` work is live, but | |
| 538 | +/// an idle listener is not pending application work. The request driver drops | |
| 539 | +/// this operation when no referenced work remains. | |
| 540 | +pub(crate) fn enqueue_unrefed<T: Into<OpOut>>( | |
| 541 | + future: impl Future<Output = Result<T, String>> + Send + 'static, | |
| 542 | +) -> u64 { | |
| 543 | + enqueue_with_lifetime(future, OpLifetime::Unrefed) | |
| 544 | +} | |
| 545 | + | |
| 546 | +pub fn drain_spawns() -> Vec<(u64, OpFuture, OpLifetime, Option<u64>)> { | |
| 490 | 547 | SPAWNS.with(|spawns| { |
| 491 | 548 | spawns |
| 492 | 549 | .borrow_mut() |
| 493 | 550 | .drain(..) |
| 494 | - .map(|(id, future, lifetime)| (id, future, matches!(lifetime, OpLifetime::IoContext))) | |
| 551 | + .map(|spawn| (spawn.id, spawn.future, spawn.lifetime, spawn.owner)) | |
| 495 | 552 | .collect() |
| 496 | 553 | }) |
| 497 | 554 | } |
modifiedcrates/celld/bucket.rs+5−1View file
| @@ -1055,7 +1055,11 @@ | ||
| 1055 | 1055 | ) -> anyhow::Result<ObjectPage> { |
| 1056 | 1056 | // `PaginatedListStore` does not append the separator that |
| 1057 | 1057 | // `ObjectStore::list` appends to a path-segment prefix. |
| 1058 | - let path = self.key(&format!("{}/", prefix.trim_end_matches('/'))); | |
| 1058 | + let path = if prefix.is_empty() { | |
| 1059 | + self.key("") | |
| 1060 | + } else { | |
| 1061 | + self.key(&format!("{}/", prefix.trim_end_matches('/'))) | |
| 1062 | + }; | |
| 1059 | 1063 | let mut result = self |
| 1060 | 1064 | .paginated |
| 1061 | 1065 | .list_paginated( |
addedcrates/celld/container.rs+1588−0View file
| @@ -1,0 +1,1588 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! Containers attached to Durable Objects: the engine side of | |
| 4 | +//! `ctx.container`. | |
| 5 | +//! | |
| 6 | +//! A cell of a class named in the deployment's `containers` config owns at | |
| 7 | +//! most one container, named after the cell, on the node that owns the | |
| 8 | +//! cell. The Durable Object supervises it through the ops in | |
| 9 | +//! `js/container.rs`; this module performs the effects against the | |
| 10 | +//! container engine, which is the Docker Engine API on a unix socket | |
| 11 | +//! (Podman serves the same API). | |
| 12 | +//! | |
| 13 | +//! The container is bound to the cell's ownership on this node, not to its | |
| 14 | +//! residency: an idle eviction leaves it running under an inactivity timer | |
| 15 | +//! and the next activation of the same cell reconnects to it by name, which | |
| 16 | +//! is what Cloudflare does and what the `@cloudflare/containers` class's | |
| 17 | +//! `sleepAfter` alarm relies on. Every other stop destroys it. The | |
| 18 | +//! container's disk is ephemeral on Cloudflare too, so a takeover that | |
| 19 | +//! starts fresh is conformant. | |
| 20 | +//! | |
| 21 | +//! Images travel through the bucket. `celld deploy` saves the image the | |
| 22 | +//! config names as a tar at `deploy/images/<id>.tar`, and a node loads it | |
| 23 | +//! into its engine the first time a cell of that class starts, so a node | |
| 24 | +//! never talks to a registry. | |
| 25 | + | |
| 26 | +use crate::asyncrt; | |
| 27 | +use crate::docker::{frame_header, Docker, Stream}; | |
| 28 | +use anyhow::{anyhow, Context}; | |
| 29 | +use bytes::Bytes; | |
| 30 | +use serde_json::{json, Value}; | |
| 31 | +use std::collections::HashMap; | |
| 32 | +use std::path::PathBuf; | |
| 33 | +use std::sync::atomic::{AtomicU64, Ordering}; | |
| 34 | +use std::sync::{Arc, Mutex, OnceLock, RwLock}; | |
| 35 | +use std::time::Duration; | |
| 36 | +use tokio::io::{AsyncReadExt, AsyncWriteExt}; | |
| 37 | +use tokio::sync::{mpsc, watch}; | |
| 38 | + | |
| 39 | +/// One `containers[]` entry of a deployment, as the node sees it. | |
| 40 | +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] | |
| 41 | +pub struct ContainerSpec { | |
| 42 | + pub class_name: String, | |
| 43 | + /// The image reference the engine starts, `celld-image:<content key>`, | |
| 44 | + /// so two deployments of one image share one tar and one load. | |
| 45 | + pub image: String, | |
| 46 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 47 | + pub instance_type: Option<String>, | |
| 48 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 49 | + pub max_instances: Option<u64>, | |
| 50 | + /// The OCI runtime this class runs under, such as `runsc` (gVisor) for | |
| 51 | + /// untrusted code. Overrides the node's `CELLD_CONTAINER_RUNTIME` for | |
| 52 | + /// this class; `None` takes the node default. A node whose daemon does | |
| 53 | + /// not have the runtime fails every start of the class, so the class | |
| 54 | + /// runs only where its isolation is available. celld extends the | |
| 55 | + /// Cloudflare config here, which has no per-class runtime. | |
| 56 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 57 | + pub runtime: Option<String>, | |
| 58 | +} | |
| 59 | + | |
| 60 | +/// The reference every engine holds an image under, from its content key. | |
| 61 | +/// The key hashes the layer digests and the image config, so an engine | |
| 62 | +/// that rebuilds identical content under a new id still resolves it. | |
| 63 | +pub fn image_reference(key: &str) -> String { | |
| 64 | + format!("celld-image:{key}") | |
| 65 | +} | |
| 66 | + | |
| 67 | +/// The bucket key of one saved image, from its reference. | |
| 68 | +pub fn image_key(image: &str) -> String { | |
| 69 | + format!( | |
| 70 | + "deploy/images/{}.tar", | |
| 71 | + image.trim_start_matches("celld-image:") | |
| 72 | + ) | |
| 73 | +} | |
| 74 | + | |
| 75 | +/// The resources an instance type reserves. Cloudflare's published table; | |
| 76 | +/// a name outside it is refused at deploy. | |
| 77 | +pub fn instance_resources(instance_type: &str) -> Option<(f64, u64)> { | |
| 78 | + let gib = 1024 * 1024 * 1024; | |
| 79 | + Some(match instance_type { | |
| 80 | + "lite" | "dev" => (1.0 / 16.0, 256 * 1024 * 1024), | |
| 81 | + "basic" => (0.25, gib), | |
| 82 | + "standard-1" | "standard" => (0.5, 4 * gib), | |
| 83 | + "standard-2" => (1.0, 6 * gib), | |
| 84 | + "standard-3" => (2.0, 8 * gib), | |
| 85 | + "standard-4" => (4.0, 12 * gib), | |
| 86 | + _ => return None, | |
| 87 | + }) | |
| 88 | +} | |
| 89 | + | |
| 90 | +/// The instance type of a class that declares none, as on Cloudflare. | |
| 91 | +const DEFAULT_INSTANCE_TYPE: &str = "dev"; | |
| 92 | + | |
| 93 | +/// The resolvers a container gets when it runs under a non-default runtime | |
| 94 | +/// and the operator set none. gVisor's network stack does not reach | |
| 95 | +/// Docker's embedded resolver at `127.0.0.11`, so a container under it | |
| 96 | +/// cannot resolve a hostname though it reaches the Internet by address; a | |
| 97 | +/// public resolver, which the fence permits, restores name resolution. | |
| 98 | +/// `CELLD_CONTAINER_DNS` overrides this. | |
| 99 | +const DEFAULT_CONTAINER_DNS: &[&str] = &["1.1.1.1", "1.0.0.1"]; | |
| 100 | + | |
| 101 | +/// The memory a container of this instance type reserves on the node. A | |
| 102 | +/// class that declares none gets the default type, as `create_and_start` | |
| 103 | +/// does. An unknown name is refused at deploy, so a running container | |
| 104 | +/// always maps; this returns 0 for a name that somehow does not, which | |
| 105 | +/// undercounts rather than blocks a sample. | |
| 106 | +pub fn instance_memory_bytes(instance_type: Option<&str>) -> u64 { | |
| 107 | + instance_resources(instance_type.unwrap_or(DEFAULT_INSTANCE_TYPE)) | |
| 108 | + .map(|(_, memory)| memory) | |
| 109 | + .unwrap_or(0) | |
| 110 | +} | |
| 111 | + | |
| 112 | +/// The memory this node commits to its running containers, for the node's | |
| 113 | +/// capacity accounting. Zero when no engine has connected. See | |
| 114 | +/// `celld_logic::pressure::Load::container_reserved_bytes` for why the node | |
| 115 | +/// counts the cap rather than the container's live usage. | |
| 116 | +pub fn reserved_memory_bytes() -> u64 { | |
| 117 | + engine_if_ready().map_or(0, |engine| engine.reserved_memory_bytes()) | |
| 118 | +} | |
| 119 | + | |
| 120 | +/// This node's running containers per class, published in the node lease so | |
| 121 | +/// peers can sum a class's instances across the fleet for `max_instances`. | |
| 122 | +/// Empty when no engine has connected. | |
| 123 | +pub fn running_instances_by_class() -> std::collections::BTreeMap<String, u64> { | |
| 124 | + engine_if_ready().map_or_else(Default::default, |engine| { | |
| 125 | + engine.running_instances_by_class() | |
| 126 | + }) | |
| 127 | +} | |
| 128 | +/// Processes one container can hold. Cloudflare publishes no number; this | |
| 129 | +/// is room for a build tool's process tree and far short of a fork bomb. | |
| 130 | +const PIDS_LIMIT: u64 = 1024; | |
| 131 | +/// The host interfaces of the two bridges, named so the fence can address | |
| 132 | +/// them; Docker's default `br-<id>` changes with every recreation. | |
| 133 | +const OPEN_BRIDGE: &str = "celld0"; | |
| 134 | +const INTERNAL_BRIDGE: &str = "celld1"; | |
| 135 | +const BRIDGE_NAME_OPTION: &str = "com.docker.network.bridge.name"; | |
| 136 | +/// The fence, installed on the node from a one-shot privileged container of | |
| 137 | +/// the `celld-fence` image: a container may reach the Internet and nothing | |
| 138 | +/// of the node's own. Hooks before Docker's own chains (priority filter - | |
| 139 | +/// 10) so a verdict here is final. Input: no new connection from a bridge | |
| 140 | +/// to the node itself, which is where the internal listener and the public | |
| 141 | +/// listener bind; replies to connections the node opened still pass. | |
| 142 | +/// Forward: nothing to the private ranges, where the fleet, the VPC, and | |
| 143 | +/// the metadata service live. Rules on the host side of the bridge cover | |
| 144 | +/// every runtime, gVisor included, and no process inside a container can | |
| 145 | +/// see them, let alone remove them. | |
| 146 | +const FENCE_RULES: &str = r#"table inet celld | |
| 147 | +delete table inet celld | |
| 148 | +table inet celld { | |
| 149 | + chain input { | |
| 150 | + type filter hook input priority -10; policy accept; | |
| 151 | + iifname { "celld0", "celld1" } ct state established,related accept | |
| 152 | + iifname { "celld0", "celld1" } reject | |
| 153 | + } | |
| 154 | + chain forward { | |
| 155 | + type filter hook forward priority -10; policy accept; | |
| 156 | + iifname { "celld0", "celld1" } ip daddr { 169.254.0.0/16, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 } reject | |
| 157 | + iifname { "celld0", "celld1" } ip6 daddr { fe80::/10, fc00::/7 } reject | |
| 158 | + } | |
| 159 | +} | |
| 160 | +"#; | |
| 161 | + | |
| 162 | +/// Docker's bridge option that forbids traffic between two containers on | |
| 163 | +/// the same bridge. The node still reaches every container, because it | |
| 164 | +/// speaks from the host side of the bridge. | |
| 165 | +const ICC_OPTION: &str = "com.docker.network.bridge.enable_icc"; | |
| 166 | + | |
| 167 | +/// How a cell stop treats its container. | |
| 168 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 169 | +pub enum Release { | |
| 170 | + /// An idle eviction: keep the container under its inactivity timer. | |
| 171 | + Keep, | |
| 172 | + /// Ownership leaves this node, or the cell is reset: destroy it. | |
| 173 | + Destroy, | |
| 174 | +} | |
| 175 | + | |
| 176 | +/// The default inactivity window after an idle eviction when the object | |
| 177 | +/// never set one. The `@cloudflare/containers` alarm wakes the object well | |
| 178 | +/// inside this to enforce `sleepAfter`, so this is the backstop for an | |
| 179 | +/// object that never wakes, not the policy. | |
| 180 | +const DEFAULT_INACTIVITY: Duration = Duration::from_secs(10 * 60); | |
| 181 | + | |
| 182 | +/// Environment every container sees. The values mirror workerd's local | |
| 183 | +/// engine: applications read the names, never the values. | |
| 184 | +const DEFAULT_ENV: &[&str] = &[ | |
| 185 | + "CLOUDFLARE_COUNTRY_A2=XX", | |
| 186 | + "CLOUDFLARE_DEPLOYMENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", | |
| 187 | + "CLOUDFLARE_LOCATION=loc01", | |
| 188 | + "CLOUDFLARE_REGION=REGN", | |
| 189 | + "CLOUDFLARE_APPLICATION_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", | |
| 190 | +]; | |
| 191 | + | |
| 192 | +pub struct StartParams { | |
| 193 | + pub entrypoint: Option<Vec<String>>, | |
| 194 | + pub env: Vec<(String, String)>, | |
| 195 | + pub enable_internet: bool, | |
| 196 | + pub labels: Vec<(String, String)>, | |
| 197 | +} | |
| 198 | + | |
| 199 | +#[derive(Default)] | |
| 200 | +struct CellState { | |
| 201 | + running: bool, | |
| 202 | + /// Where the node dials the container: the bridge address on Linux, | |
| 203 | + /// the published loopback ports elsewhere. | |
| 204 | + address: Address, | |
| 205 | + inactivity: Option<Duration>, | |
| 206 | + /// The pending destroy after an idle eviction. Dropping it cancels. | |
| 207 | + sweeper: Option<asyncrt::TaskHandle<()>>, | |
| 208 | + /// Bumped per start so a wait from a previous run cannot report for | |
| 209 | + /// this one. | |
| 210 | + run: u64, | |
| 211 | +} | |
| 212 | + | |
| 213 | +#[derive(Clone, Debug, Default)] | |
| 214 | +enum Address { | |
| 215 | + #[default] | |
| 216 | + None, | |
| 217 | + Ip(String), | |
| 218 | + Published(HashMap<u16, u16>), | |
| 219 | +} | |
| 220 | + | |
| 221 | +pub struct CellContainer { | |
| 222 | + scope: String, | |
| 223 | + name: String, | |
| 224 | + spec: Arc<ContainerSpec>, | |
| 225 | + state: Mutex<CellState>, | |
| 226 | + /// Processes `exec()` started in this container. An object drops one | |
| 227 | + /// after `output()`; the rest go with the container. | |
| 228 | + processes: Mutex<Vec<u64>>, | |
| 229 | + /// The exit of the current run, `None` while it runs. `Some(Err)` is | |
| 230 | + /// an engine failure the wait could not attribute to the process. | |
| 231 | + /// Written with `send_replace`: a plain `send` discards the value | |
| 232 | + /// while nobody subscribes, and `monitor()` usually subscribes late. | |
| 233 | + exit: watch::Sender<Option<(u64, Result<i64, String>)>>, | |
| 234 | +} | |
| 235 | + | |
| 236 | +impl CellContainer { | |
| 237 | + pub fn running(&self) -> bool { | |
| 238 | + self.state.lock().unwrap().running | |
| 239 | + } | |
| 240 | + | |
| 241 | + /// `host:port` for `getTcpPort(port)`. | |
| 242 | + pub fn address(&self, port: u16) -> Result<String, String> { | |
| 243 | + let state = self.state.lock().unwrap(); | |
| 244 | + if !state.running { | |
| 245 | + return Err("the container is not running".to_string()); | |
| 246 | + } | |
| 247 | + match &state.address { | |
| 248 | + Address::Ip(ip) => Ok(format!("{ip}:{port}")), | |
| 249 | + Address::Published(ports) => ports | |
| 250 | + .get(&port) | |
| 251 | + .map(|host| format!("127.0.0.1:{host}")) | |
| 252 | + .ok_or_else(|| { | |
| 253 | + format!( | |
| 254 | + "The container is not listening on port {port}: on this platform a port \ | |
| 255 | + must be declared with EXPOSE in the image" | |
| 256 | + ) | |
| 257 | + }), | |
| 258 | + Address::None => Err(format!("The container is not listening on port {port}")), | |
| 259 | + } | |
| 260 | + } | |
| 261 | + | |
| 262 | + pub fn set_inactivity(&self, duration: Duration) { | |
| 263 | + self.state.lock().unwrap().inactivity = Some(duration); | |
| 264 | + } | |
| 265 | + | |
| 266 | + /// Open the next run, synchronously, before the start is even queued. | |
| 267 | + /// The object's `start()` returns at once and its `monitor()` follows | |
| 268 | + /// immediately, so the run they both mean must exist before either | |
| 269 | + /// effect runs, or the monitor would find the previous run's exit and | |
| 270 | + /// report the new container dead on arrival. | |
| 271 | + pub fn begin_run(&self) -> u64 { | |
| 272 | + let mut state = self.state.lock().unwrap(); | |
| 273 | + state.run += 1; | |
| 274 | + state.running = true; | |
| 275 | + state.address = Address::None; | |
| 276 | + let run = state.run; | |
| 277 | + drop(state); | |
| 278 | + self.exit.send_replace(None); | |
| 279 | + run | |
| 280 | + } | |
| 281 | + | |
| 282 | + /// The run `monitor()` waits on: the newest one. | |
| 283 | + pub fn current_run(&self) -> u64 { | |
| 284 | + self.state.lock().unwrap().run | |
| 285 | + } | |
| 286 | +} | |
| 287 | + | |
| 288 | +pub struct ContainerEngine { | |
| 289 | + /// See `Config::runtime`. | |
| 290 | + runtime: Option<String>, | |
| 291 | + /// See `Config::dns`. | |
| 292 | + dns: Vec<String>, | |
| 293 | + /// The absolute path of the container resolv.conf this engine wrote and | |
| 294 | + /// bind-mounts; `None` when it could not be written. | |
| 295 | + resolv_conf: Option<PathBuf>, | |
| 296 | + docker: Docker, | |
| 297 | + node: String, | |
| 298 | + bucket: Option<crate::bucket::Bucket>, | |
| 299 | + /// Per-image load lock, so two cells of one class starting together | |
| 300 | + /// load the tar once. | |
| 301 | + images: Mutex<HashMap<String, Arc<tokio::sync::Mutex<bool>>>>, | |
| 302 | + cells: Mutex<HashMap<String, Arc<CellContainer>>>, | |
| 303 | + networks: tokio::sync::Mutex<Option<(String, String)>>, | |
| 304 | + /// Whether this process has installed the fence on the node's bridges. | |
| 305 | + fenced: tokio::sync::Mutex<bool>, | |
| 306 | +} | |
| 307 | + | |
| 308 | +/// What the runtime told this module about the node: set once at start. | |
| 309 | +struct Config { | |
| 310 | + node: String, | |
| 311 | + bucket: Option<crate::bucket::Bucket>, | |
| 312 | + /// `CELLD_CONTAINER_RUNTIME`: the OCI runtime every container starts | |
| 313 | + /// under, such as `runsc` (gVisor) or `kata` (a VM). `None` is the | |
| 314 | + /// daemon's default, which is `runc` unless the operator changed it. A | |
| 315 | + /// class can override it, see `ContainerSpec::runtime`. | |
| 316 | + runtime: Option<String>, | |
| 317 | + /// `CELLD_CONTAINER_DNS`: the resolvers a container gets, overriding | |
| 318 | + /// `DEFAULT_CONTAINER_DNS`. Empty takes the default when a runtime is in | |
| 319 | + /// use and the daemon's otherwise. | |
| 320 | + dns: Vec<String>, | |
| 321 | + /// The node's state directory. celld writes the container resolv.conf | |
| 322 | + /// here and bind-mounts it, so the path must be the same on the host as | |
| 323 | + /// celld sees it; a self-hosted node runs celld as a host process, and | |
| 324 | + /// the lab mounts the directory one-to-one. | |
| 325 | + data_dir: PathBuf, | |
| 326 | +} | |
| 327 | + | |
| 328 | +static CONFIG: RwLock<Option<Config>> = RwLock::new(None); | |
| 329 | +/// The deployment's container classes. Replaced on every generation swap; | |
| 330 | +/// a running container keeps the spec it started with. | |
| 331 | +static SPECS: RwLock<Vec<Arc<ContainerSpec>>> = RwLock::new(Vec::new()); | |
| 332 | +/// The deployment's `celld-fence` image; see `Manifest::fence_image`. | |
| 333 | +static FENCE_IMAGE: RwLock<Option<String>> = RwLock::new(None); | |
| 334 | +/// The engine, connected on first use. A node whose deployment declares no | |
| 335 | +/// container class never opens the socket. | |
| 336 | +static ENGINE: tokio::sync::OnceCell<Arc<ContainerEngine>> = tokio::sync::OnceCell::const_new(); | |
| 337 | + | |
| 338 | +pub fn configure(node: String, bucket: Option<crate::bucket::Bucket>, data_dir: PathBuf) { | |
| 339 | + let runtime = std::env::var("CELLD_CONTAINER_RUNTIME") | |
| 340 | + .ok() | |
| 341 | + .filter(|runtime| !runtime.is_empty()); | |
| 342 | + let dns = std::env::var("CELLD_CONTAINER_DNS") | |
| 343 | + .unwrap_or_default() | |
| 344 | + .split(',') | |
| 345 | + .map(|resolver| resolver.trim().to_string()) | |
| 346 | + .filter(|resolver| !resolver.is_empty()) | |
| 347 | + .collect(); | |
| 348 | + *CONFIG.write().unwrap() = Some(Config { | |
| 349 | + node, | |
| 350 | + bucket, | |
| 351 | + runtime, | |
| 352 | + dns, | |
| 353 | + data_dir, | |
| 354 | + }); | |
| 355 | +} | |
| 356 | + | |
| 357 | +pub fn install_specs(specs: Vec<ContainerSpec>, fence_image: Option<String>) { | |
| 358 | + *SPECS.write().unwrap() = specs.into_iter().map(Arc::new).collect(); | |
| 359 | + *FENCE_IMAGE.write().unwrap() = fence_image; | |
| 360 | +} | |
| 361 | + | |
| 362 | +pub fn spec(class: &str) -> Option<Arc<ContainerSpec>> { | |
| 363 | + SPECS | |
| 364 | + .read() | |
| 365 | + .unwrap() | |
| 366 | + .iter() | |
| 367 | + .find(|spec| spec.class_name == class) | |
| 368 | + .cloned() | |
| 369 | +} | |
| 370 | + | |
| 371 | +/// The engine, connecting on the first call. A failure is returned rather | |
| 372 | +/// than cached, so a daemon that comes up later is found by the next call. | |
| 373 | +pub async fn engine() -> anyhow::Result<Arc<ContainerEngine>> { | |
| 374 | + ENGINE | |
| 375 | + .get_or_try_init(|| async { | |
| 376 | + let (node, bucket, runtime, dns, data_dir) = { | |
| 377 | + let config = CONFIG.read().unwrap(); | |
| 378 | + let config = config.as_ref().ok_or_else(|| { | |
| 379 | + anyhow!("the container engine is not configured on this node") | |
| 380 | + })?; | |
| 381 | + ( | |
| 382 | + config.node.clone(), | |
| 383 | + config.bucket.clone(), | |
| 384 | + config.runtime.clone(), | |
| 385 | + config.dns.clone(), | |
| 386 | + config.data_dir.clone(), | |
| 387 | + ) | |
| 388 | + }; | |
| 389 | + let docker = Docker::discover().ok_or_else(|| { | |
| 390 | + anyhow!( | |
| 391 | + "no container engine: set DOCKER_HOST to a unix socket, or run a Docker or \ | |
| 392 | + Podman daemon on this node" | |
| 393 | + ) | |
| 394 | + })?; | |
| 395 | + Ok(Arc::new( | |
| 396 | + ContainerEngine::connect(docker, node, bucket, runtime, dns, data_dir).await?, | |
| 397 | + )) | |
| 398 | + }) | |
| 399 | + .await | |
| 400 | + .cloned() | |
| 401 | +} | |
| 402 | + | |
| 403 | +/// The engine only if a previous call connected it. | |
| 404 | +pub fn engine_if_ready() -> Option<Arc<ContainerEngine>> { | |
| 405 | + ENGINE.get().cloned() | |
| 406 | +} | |
| 407 | + | |
| 408 | +/// Destroy every container of this node at process exit. A preserve | |
| 409 | +/// shutdown (`celld dev` on Ctrl-C) keeps its cells resident and stops | |
| 410 | +/// none of them, and a handoff cut by the deadline leaves cells behind | |
| 411 | +/// too; without this their containers ran on until the next start of the | |
| 412 | +/// same node reaped them, invisible to the object that owned them. | |
| 413 | +pub async fn shutdown() { | |
| 414 | + let Some(engine) = engine_if_ready() else { | |
| 415 | + return; | |
| 416 | + }; | |
| 417 | + if let Err(error) = engine.reap().await { | |
| 418 | + tracing::warn!( | |
| 419 | + event = "container_shutdown_reap_failed", | |
| 420 | + error = %format!("{error:#}"), | |
| 421 | + "containers of this node may still be running" | |
| 422 | + ); | |
| 423 | + } | |
| 424 | +} | |
| 425 | + | |
| 426 | +/// Connect and load every image of the installed specs, ahead of the | |
| 427 | +/// first cell that needs one. Failures are logged: a node without an | |
| 428 | +/// engine still serves every other class, and the container class fails | |
| 429 | +/// at its first `start()` with the same message. | |
| 430 | +pub async fn prewarm() { | |
| 431 | + let engine = match engine().await { | |
| 432 | + Ok(engine) => engine, | |
| 433 | + Err(error) => { | |
| 434 | + tracing::warn!(error = %format!("{error:#}"), "containers are unavailable on this node"); | |
| 435 | + return; | |
| 436 | + } | |
| 437 | + }; | |
| 438 | + if let Err(error) = engine.ensure_fence().await { | |
| 439 | + tracing::warn!( | |
| 440 | + error = %format!("{error:#}"), | |
| 441 | + "the container bridges are not fenced; no container starts on this node" | |
| 442 | + ); | |
| 443 | + } | |
| 444 | + let specs = SPECS.read().unwrap().clone(); | |
| 445 | + for spec in specs { | |
| 446 | + if let Err(error) = engine.ensure_image(&spec.image).await { | |
| 447 | + tracing::warn!( | |
| 448 | + class = %spec.class_name, | |
| 449 | + image = %spec.image, | |
| 450 | + error = %format!("{error:#}"), | |
| 451 | + "container image is unavailable" | |
| 452 | + ); | |
| 453 | + } | |
| 454 | + } | |
| 455 | +} | |
| 456 | + | |
| 457 | +impl ContainerEngine { | |
| 458 | + /// Connect to the engine and reap every container a previous process | |
| 459 | + /// of this node left behind. A restarted node cannot know which of its | |
| 460 | + /// containers still belong to cells it will own again, and a container | |
| 461 | + /// whose object has lost track of it is a leak, so a restart starts | |
| 462 | + /// clean. The next `start()` of each object creates a fresh one. | |
| 463 | + pub async fn connect( | |
| 464 | + docker: Docker, | |
| 465 | + node: String, | |
| 466 | + bucket: Option<crate::bucket::Bucket>, | |
| 467 | + runtime: Option<String>, | |
| 468 | + dns: Vec<String>, | |
| 469 | + data_dir: PathBuf, | |
| 470 | + ) -> anyhow::Result<Self> { | |
| 471 | + // Write the resolv.conf once, to bind into every container that runs | |
| 472 | + // under a non-default runtime. gVisor cannot reach Docker's embedded | |
| 473 | + // resolver, so a bind-mounted file with a public resolver, which the | |
| 474 | + // fence permits, is the only resolv.conf the container can use. | |
| 475 | + let resolvers: Vec<String> = if dns.is_empty() { | |
| 476 | + DEFAULT_CONTAINER_DNS | |
| 477 | + .iter() | |
| 478 | + .map(|r| r.to_string()) | |
| 479 | + .collect() | |
| 480 | + } else { | |
| 481 | + dns.clone() | |
| 482 | + }; | |
| 483 | + let resolv_conf = { | |
| 484 | + let path = data_dir.join("container-resolv.conf"); | |
| 485 | + let body: String = resolvers | |
| 486 | + .iter() | |
| 487 | + .map(|resolver| format!("nameserver {resolver}\n")) | |
| 488 | + .collect(); | |
| 489 | + let fs = asyncrt::fs(); | |
| 490 | + match fs | |
| 491 | + .create_dir_all(&data_dir) | |
| 492 | + .and_then(|()| fs.write(&path, body.as_bytes())) | |
| 493 | + { | |
| 494 | + Ok(()) => Some(path), | |
| 495 | + Err(error) => { | |
| 496 | + tracing::warn!(event = "container_resolv_write_failed", %error); | |
| 497 | + None | |
| 498 | + } | |
| 499 | + } | |
| 500 | + }; | |
| 501 | + let engine = Self { | |
| 502 | + docker, | |
| 503 | + node, | |
| 504 | + bucket, | |
| 505 | + runtime, | |
| 506 | + dns, | |
| 507 | + resolv_conf, | |
| 508 | + images: Mutex::new(HashMap::new()), | |
| 509 | + cells: Mutex::new(HashMap::new()), | |
| 510 | + networks: tokio::sync::Mutex::new(None), | |
| 511 | + fenced: tokio::sync::Mutex::new(false), | |
| 512 | + }; | |
| 513 | + engine.reap().await?; | |
| 514 | + Ok(engine) | |
| 515 | + } | |
| 516 | + | |
| 517 | + pub fn socket(&self) -> &std::path::Path { | |
| 518 | + self.docker.socket() | |
| 519 | + } | |
| 520 | + | |
| 521 | + async fn reap(&self) -> anyhow::Result<()> { | |
| 522 | + let filters = json!({ "label": [format!("celld.node={}", self.node)] }).to_string(); | |
| 523 | + let reply = self | |
| 524 | + .docker | |
| 525 | + .expect( | |
| 526 | + "GET", | |
| 527 | + &format!( | |
| 528 | + "/containers/json?all=true&filters={}", | |
| 529 | + percent_encoding::utf8_percent_encode( | |
| 530 | + &filters, | |
| 531 | + percent_encoding::NON_ALPHANUMERIC | |
| 532 | + ) | |
| 533 | + ), | |
| 534 | + None, | |
| 535 | + "list containers", | |
| 536 | + ) | |
| 537 | + .await?; | |
| 538 | + let list = reply.json()?; | |
| 539 | + for entry in list.as_array().into_iter().flatten() { | |
| 540 | + if let Some(id) = entry.get("Id").and_then(Value::as_str) { | |
| 541 | + let _ = self | |
| 542 | + .docker | |
| 543 | + .call("DELETE", &format!("/containers/{id}?force=true"), None) | |
| 544 | + .await; | |
| 545 | + } | |
| 546 | + } | |
| 547 | + Ok(()) | |
| 548 | + } | |
| 549 | + | |
| 550 | + /// Make the class's image present in the engine, loading it from the | |
| 551 | + /// bucket when it is not. Idempotent and serialized per image. | |
| 552 | + pub async fn ensure_image(&self, image: &str) -> anyhow::Result<()> { | |
| 553 | + let lock = self | |
| 554 | + .images | |
| 555 | + .lock() | |
| 556 | + .unwrap() | |
| 557 | + .entry(image.to_string()) | |
| 558 | + .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(false))) | |
| 559 | + .clone(); | |
| 560 | + let mut loaded = lock.lock().await; | |
| 561 | + if *loaded { | |
| 562 | + return Ok(()); | |
| 563 | + } | |
| 564 | + let reply = self | |
| 565 | + .docker | |
| 566 | + .call("GET", &format!("/images/{image}/json"), None) | |
| 567 | + .await?; | |
| 568 | + if reply.status.is_success() { | |
| 569 | + tracing::info!(image, "container image present in the engine"); | |
| 570 | + *loaded = true; | |
| 571 | + return Ok(()); | |
| 572 | + } | |
| 573 | + let bucket = self | |
| 574 | + .bucket | |
| 575 | + .as_ref() | |
| 576 | + .ok_or_else(|| anyhow!("image {image} is not present in the container engine"))?; | |
| 577 | + let key = image_key(image); | |
| 578 | + let (tar, _) = bucket.get(&key).await?.ok_or_else(|| { | |
| 579 | + anyhow!("image {image} is not in the bucket at {key}; run `celld deploy`") | |
| 580 | + })?; | |
| 581 | + let bytes = tar.len(); | |
| 582 | + let reply = self | |
| 583 | + .docker | |
| 584 | + .post_octets("/images/load?quiet=true", tar, "load image") | |
| 585 | + .await?; | |
| 586 | + tracing::info!( | |
| 587 | + image, | |
| 588 | + bytes, | |
| 589 | + answer = %String::from_utf8_lossy(&reply.body).trim_end(), | |
| 590 | + "container image loaded from the bucket" | |
| 591 | + ); | |
| 592 | + *loaded = true; | |
| 593 | + Ok(()) | |
| 594 | + } | |
| 595 | + | |
| 596 | + /// The two bridges every container joins: one with egress, one | |
| 597 | + /// without. Docker implements an internal network by omitting the | |
| 598 | + /// masquerade rule and the default route; the node still reaches the | |
| 599 | + /// bridge address, which is all ingress needs. | |
| 600 | + async fn networks(&self) -> anyhow::Result<(String, String)> { | |
| 601 | + let mut guard = self.networks.lock().await; | |
| 602 | + if let Some(names) = guard.as_ref() { | |
| 603 | + return Ok(names.clone()); | |
| 604 | + } | |
| 605 | + for (name, internal) in [("celld", false), ("celld-internal", true)] { | |
| 606 | + // A bridge keeps the options it was created with, so one from | |
| 607 | + // before containers were isolated from each other is replaced. | |
| 608 | + // The replacement fails while a container is attached, which a | |
| 609 | + // node start after its reap never has; a failure keeps the old | |
| 610 | + // bridge and says so rather than refusing every container. | |
| 611 | + let current = self | |
| 612 | + .docker | |
| 613 | + .call("GET", &format!("/networks/{name}"), None) | |
| 614 | + .await?; | |
| 615 | + if current.status.is_success() { | |
| 616 | + let bridge = if internal { | |
| 617 | + INTERNAL_BRIDGE | |
| 618 | + } else { | |
| 619 | + OPEN_BRIDGE | |
| 620 | + }; | |
| 621 | + let current_options = current | |
| 622 | + .json() | |
| 623 | + .ok() | |
| 624 | + .and_then(|network| network.get("Options").cloned()) | |
| 625 | + .unwrap_or(Value::Null); | |
| 626 | + let option = |key: &str| current_options.get(key).and_then(Value::as_str); | |
| 627 | + if option(ICC_OPTION) == Some("false") && option(BRIDGE_NAME_OPTION) == Some(bridge) | |
| 628 | + { | |
| 629 | + continue; | |
| 630 | + } | |
| 631 | + let removed = self | |
| 632 | + .docker | |
| 633 | + .call("DELETE", &format!("/networks/{name}"), None) | |
| 634 | + .await?; | |
| 635 | + if !removed.status.is_success() { | |
| 636 | + tracing::warn!( | |
| 637 | + network = name, | |
| 638 | + error = %removed.message(), | |
| 639 | + "the container bridge predates container isolation and is in use; \ | |
| 640 | + containers on it can reach each other until the node restarts idle" | |
| 641 | + ); | |
| 642 | + continue; | |
| 643 | + } | |
| 644 | + } | |
| 645 | + let reply = self | |
| 646 | + .docker | |
| 647 | + .call( | |
| 648 | + "POST", | |
| 649 | + "/networks/create", | |
| 650 | + Some(json!({ | |
| 651 | + "Name": name, | |
| 652 | + "Driver": "bridge", | |
| 653 | + "Internal": internal, | |
| 654 | + "Options": { | |
| 655 | + ICC_OPTION: "false", | |
| 656 | + BRIDGE_NAME_OPTION: if internal { INTERNAL_BRIDGE } else { OPEN_BRIDGE }, | |
| 657 | + }, | |
| 658 | + })), | |
| 659 | + ) | |
| 660 | + .await?; | |
| 661 | + // 409: it exists, which is the steady state. | |
| 662 | + if !reply.status.is_success() && reply.status.as_u16() != 409 { | |
| 663 | + return Err(anyhow!( | |
| 664 | + "create network {name} failed with [{}] {}", | |
| 665 | + reply.status.as_u16(), | |
| 666 | + reply.message() | |
| 667 | + )); | |
| 668 | + } | |
| 669 | + } | |
| 670 | + let names = ("celld".to_string(), "celld-internal".to_string()); | |
| 671 | + *guard = Some(names.clone()); | |
| 672 | + Ok(names) | |
| 673 | + } | |
| 674 | + | |
| 675 | + /// Install the fence on the node's bridges, once per process. Every | |
| 676 | + /// container start waits on this and fails when it fails: a node that | |
| 677 | + /// cannot fence its bridges runs no container, because an unfenced | |
| 678 | + /// container can reach the node's internal listener and the cloud's | |
| 679 | + /// metadata service. The rules live in the kernel and outlive this | |
| 680 | + /// process; a restart re-applies them, which is idempotent. | |
| 681 | + pub async fn ensure_fence(&self) -> anyhow::Result<()> { | |
| 682 | + let mut fenced = self.fenced.lock().await; | |
| 683 | + if *fenced { | |
| 684 | + return Ok(()); | |
| 685 | + } | |
| 686 | + let image = FENCE_IMAGE.read().unwrap().clone().ok_or_else(|| { | |
| 687 | + anyhow!( | |
| 688 | + "this deployment has no fence image; deploy it again with this celld, which \ | |
| 689 | + saves the celld-fence image beside the container images" | |
| 690 | + ) | |
| 691 | + })?; | |
| 692 | + self.ensure_image(&image).await?; | |
| 693 | + self.networks().await?; | |
| 694 | + let body = json!({ | |
| 695 | + "Image": image, | |
| 696 | + "Env": [format!("CELLD_NFT={FENCE_RULES}")], | |
| 697 | + "Cmd": ["sh", "-c", "printf '%s' \"$CELLD_NFT\" | nft -f -"], | |
| 698 | + "Labels": { "celld.node": self.node, "celld.fence": "1" }, | |
| 699 | + "HostConfig": { "NetworkMode": "host", "CapAdd": ["NET_ADMIN"] }, | |
| 700 | + }); | |
| 701 | + let created = self | |
| 702 | + .docker | |
| 703 | + .expect( | |
| 704 | + "POST", | |
| 705 | + "/containers/create", | |
| 706 | + Some(body), | |
| 707 | + "create fence container", | |
| 708 | + ) | |
| 709 | + .await? | |
| 710 | + .json()?; | |
| 711 | + let id = created | |
| 712 | + .get("Id") | |
| 713 | + .and_then(Value::as_str) | |
| 714 | + .ok_or_else(|| anyhow!("create fence container answered without an id"))? | |
| 715 | + .to_string(); | |
| 716 | + let outcome = async { | |
| 717 | + self.docker | |
| 718 | + .expect( | |
| 719 | + "POST", | |
| 720 | + &format!("/containers/{id}/start"), | |
| 721 | + None, | |
| 722 | + "start fence container", | |
| 723 | + ) | |
| 724 | + .await?; | |
| 725 | + let waited = self | |
| 726 | + .docker | |
| 727 | + .expect( | |
| 728 | + "POST", | |
| 729 | + &format!("/containers/{id}/wait"), | |
| 730 | + None, | |
| 731 | + "wait fence container", | |
| 732 | + ) | |
| 733 | + .await? | |
| 734 | + .json()?; | |
| 735 | + let code = waited | |
| 736 | + .get("StatusCode") | |
| 737 | + .and_then(Value::as_i64) | |
| 738 | + .unwrap_or(-1); | |
| 739 | + if code != 0 { | |
| 740 | + let logs = self.logs(&id).await.unwrap_or_default(); | |
| 741 | + return Err(anyhow!( | |
| 742 | + "the fence container exited with {code}: {}", | |
| 743 | + logs.trim() | |
| 744 | + )); | |
| 745 | + } | |
| 746 | + Ok(()) | |
| 747 | + } | |
| 748 | + .await; | |
| 749 | + let _ = self | |
| 750 | + .docker | |
| 751 | + .call("DELETE", &format!("/containers/{id}?force=true"), None) | |
| 752 | + .await; | |
| 753 | + outcome.context("fence the container bridges")?; | |
| 754 | + tracing::info!( | |
| 755 | + event = "container_bridges_fenced", | |
| 756 | + bridges = format!("{OPEN_BRIDGE},{INTERNAL_BRIDGE}"), | |
| 757 | + "containers can reach the Internet and nothing of the node's own" | |
| 758 | + ); | |
| 759 | + *fenced = true; | |
| 760 | + Ok(()) | |
| 761 | + } | |
| 762 | + | |
| 763 | + /// Both output streams of a stopped container, for an error message. | |
| 764 | + async fn logs(&self, id: &str) -> anyhow::Result<String> { | |
| 765 | + let reply = self | |
| 766 | + .docker | |
| 767 | + .expect( | |
| 768 | + "GET", | |
| 769 | + &format!("/containers/{id}/logs?stdout=true&stderr=true"), | |
| 770 | + None, | |
| 771 | + "container logs", | |
| 772 | + ) | |
| 773 | + .await?; | |
| 774 | + let mut text = Vec::new(); | |
| 775 | + let mut rest: &[u8] = &reply.body; | |
| 776 | + while rest.len() >= 8 { | |
| 777 | + let (_, length) = frame_header(rest[..8].try_into().unwrap()); | |
| 778 | + let end = (8 + length).min(rest.len()); | |
| 779 | + text.extend_from_slice(&rest[8..end]); | |
| 780 | + rest = &rest[end..]; | |
| 781 | + } | |
| 782 | + Ok(String::from_utf8_lossy(&text).into_owned()) | |
| 783 | + } | |
| 784 | + | |
| 785 | + /// The cell's container handle, adopting a container a previous | |
| 786 | + /// activation on this node left running. Called at cell start for a | |
| 787 | + /// class with a spec; the object's `running` reads the answer. | |
| 788 | + pub async fn attach(&self, scope: &str, class: &str) -> anyhow::Result<Arc<CellContainer>> { | |
| 789 | + let spec = spec(class).ok_or_else(|| anyhow!("class {class} has no container"))?; | |
| 790 | + let cell = { | |
| 791 | + let mut cells = self.cells.lock().unwrap(); | |
| 792 | + let cell = cells.entry(scope.to_string()).or_insert_with(|| { | |
| 793 | + Arc::new(CellContainer { | |
| 794 | + scope: scope.to_string(), | |
| 795 | + name: container_name(&self.node, scope), | |
| 796 | + spec, | |
| 797 | + state: Mutex::new(CellState::default()), | |
| 798 | + processes: Mutex::new(Vec::new()), | |
| 799 | + exit: watch::channel(None).0, | |
| 800 | + }) | |
| 801 | + }); | |
| 802 | + // A returning cell cancels the destroy its eviction armed. | |
| 803 | + cell.state.lock().unwrap().sweeper = None; | |
| 804 | + cell.clone() | |
| 805 | + }; | |
| 806 | + let running = self.inspect_running(&cell).await?; | |
| 807 | + // A container this handle did not start, left running by an | |
| 808 | + // earlier owner of the name: give it a run so `monitor()` has an | |
| 809 | + // exit to wait for. The run opens before the address lands, because | |
| 810 | + // opening one clears it. | |
| 811 | + let adopted = running.is_some() && !cell.running(); | |
| 812 | + if adopted { | |
| 813 | + let run = cell.begin_run(); | |
| 814 | + self.watch_exit(&cell, run); | |
| 815 | + } | |
| 816 | + let mut state = cell.state.lock().unwrap(); | |
| 817 | + state.running = running.is_some(); | |
| 818 | + state.address = running.unwrap_or_default(); | |
| 819 | + drop(state); | |
| 820 | + Ok(cell) | |
| 821 | + } | |
| 822 | + | |
| 823 | + /// The cell's handle, if the cell started on this node. | |
| 824 | + pub fn cell(&self, scope: &str) -> Option<Arc<CellContainer>> { | |
| 825 | + self.cells.lock().unwrap().get(scope).cloned() | |
| 826 | + } | |
| 827 | + | |
| 828 | + /// The memory the node's running containers reserve, summed over their | |
| 829 | + /// instance-type caps. A cell whose container is not running reserves | |
| 830 | + /// nothing: a stopped container holds no memory, and an idle eviction | |
| 831 | + /// stops it before the sample would count it. | |
| 832 | + pub fn reserved_memory_bytes(&self) -> u64 { | |
| 833 | + self.cells | |
| 834 | + .lock() | |
| 835 | + .unwrap() | |
| 836 | + .values() | |
| 837 | + .filter(|cell| cell.running()) | |
| 838 | + .map(|cell| instance_memory_bytes(cell.spec.instance_type.as_deref())) | |
| 839 | + .sum() | |
| 840 | + } | |
| 841 | + | |
| 842 | + /// This node's running containers per class. | |
| 843 | + fn running_instances_by_class(&self) -> std::collections::BTreeMap<String, u64> { | |
| 844 | + let mut counts = std::collections::BTreeMap::new(); | |
| 845 | + for cell in self.cells.lock().unwrap().values() { | |
| 846 | + if cell.running() { | |
| 847 | + *counts.entry(cell.spec.class_name.clone()).or_insert(0) += 1; | |
| 848 | + } | |
| 849 | + } | |
| 850 | + counts | |
| 851 | + } | |
| 852 | + | |
| 853 | + /// Refuse a start that would put the class over its fleet-wide | |
| 854 | + /// `max_instances`. The fleet count is this node's own running | |
| 855 | + /// containers of the class, read live, plus every peer's count from the | |
| 856 | + /// shared capacity sample; `begin_run` already marked the starting cell | |
| 857 | + /// running, so the live count includes it. A class with no | |
| 858 | + /// `max_instances`, or a node with no bucket to read the sample from as | |
| 859 | + /// under `celld dev`, has no fleet ceiling. See | |
| 860 | + /// [`crate::ownership_store::fleet_class_instances`] for the staleness | |
| 861 | + /// the sample admits. | |
| 862 | + async fn enforce_instance_ceiling(&self, cell: &CellContainer) -> anyhow::Result<()> { | |
| 863 | + let Some(max) = cell.spec.max_instances else { | |
| 864 | + return Ok(()); | |
| 865 | + }; | |
| 866 | + let class = &cell.spec.class_name; | |
| 867 | + let here = self | |
| 868 | + .cells | |
| 869 | + .lock() | |
| 870 | + .unwrap() | |
| 871 | + .values() | |
| 872 | + .filter(|other| other.running() && other.spec.class_name == *class) | |
| 873 | + .count() as u64; | |
| 874 | + let elsewhere = match &self.bucket { | |
| 875 | + Some(bucket) => { | |
| 876 | + crate::ownership_store::fleet_class_instances(bucket, class, &self.node).await | |
| 877 | + } | |
| 878 | + None => 0, | |
| 879 | + }; | |
| 880 | + anyhow::ensure!( | |
| 881 | + here + elsewhere <= max, | |
| 882 | + "container class {class} is at its max_instances limit of {max}: \ | |
| 883 | + {here} on this node and {elsewhere} on other nodes", | |
| 884 | + ); | |
| 885 | + Ok(()) | |
| 886 | + } | |
| 887 | + | |
| 888 | + async fn inspect_running(&self, cell: &CellContainer) -> anyhow::Result<Option<Address>> { | |
| 889 | + let reply = self | |
| 890 | + .docker | |
| 891 | + .call("GET", &format!("/containers/{}/json", cell.name), None) | |
| 892 | + .await?; | |
| 893 | + if reply.status.as_u16() == 404 { | |
| 894 | + return Ok(None); | |
| 895 | + } | |
| 896 | + if !reply.status.is_success() { | |
| 897 | + return Err(anyhow!( | |
| 898 | + "inspect container failed with [{}] {}", | |
| 899 | + reply.status.as_u16(), | |
| 900 | + reply.message() | |
| 901 | + )); | |
| 902 | + } | |
| 903 | + let info = reply.json()?; | |
| 904 | + let running = info | |
| 905 | + .pointer("/State/Running") | |
| 906 | + .and_then(Value::as_bool) | |
| 907 | + .unwrap_or(false); | |
| 908 | + Ok(running.then(|| address_of(&info))) | |
| 909 | + } | |
| 910 | + | |
| 911 | + /// Start the cell's container. The object's `start()` returns before | |
| 912 | + /// this completes, as on Cloudflare; a failure surfaces through | |
| 913 | + /// `monitor()`. | |
| 914 | + /// Start the cell's container for the run `begin_run` opened. The | |
| 915 | + /// object's `start()` returns before this completes, as on Cloudflare; | |
| 916 | + /// a failure surfaces through `monitor()`. | |
| 917 | + pub async fn start( | |
| 918 | + &self, | |
| 919 | + cell: &Arc<CellContainer>, | |
| 920 | + run: u64, | |
| 921 | + params: StartParams, | |
| 922 | + ) -> anyhow::Result<()> { | |
| 923 | + let started = self.create_and_start(cell, params).await; | |
| 924 | + let address = match started { | |
| 925 | + Ok(address) => address, | |
| 926 | + Err(error) => { | |
| 927 | + // `start()` is fire-and-forget for the object, and its | |
| 928 | + // `monitor()` sees this error only if it was already | |
| 929 | + // waiting; say it here too, or a start that fails fast | |
| 930 | + // leaves no trace anywhere. | |
| 931 | + tracing::warn!( | |
| 932 | + event = "container_start_failed", | |
| 933 | + cell = %cell.scope, | |
| 934 | + error = %format!("{error:#}"), | |
| 935 | + "the container did not start" | |
| 936 | + ); | |
| 937 | + let mut state = cell.state.lock().unwrap(); | |
| 938 | + state.running = false; | |
| 939 | + drop(state); | |
| 940 | + cell.exit | |
| 941 | + .send_replace(Some((run, Err(format!("{error:#}"))))); | |
| 942 | + return Err(error); | |
| 943 | + } | |
| 944 | + }; | |
| 945 | + { | |
| 946 | + let mut state = cell.state.lock().unwrap(); | |
| 947 | + state.running = true; | |
| 948 | + state.address = address; | |
| 949 | + } | |
| 950 | + self.watch_exit(cell, run); | |
| 951 | + Ok(()) | |
| 952 | + } | |
| 953 | + | |
| 954 | + /// Wait for the container's root process to end and publish the exit | |
| 955 | + /// for `run`; a later run's start has already replaced the state. | |
| 956 | + fn watch_exit(&self, cell: &Arc<CellContainer>, run: u64) { | |
| 957 | + let docker = self.docker.clone(); | |
| 958 | + let cell_ = cell.clone(); | |
| 959 | + asyncrt::spawn(async move { | |
| 960 | + let result = docker | |
| 961 | + .call("POST", &format!("/containers/{}/wait", cell_.name), None) | |
| 962 | + .await | |
| 963 | + .and_then(|reply| { | |
| 964 | + if !reply.status.is_success() { | |
| 965 | + return Err(anyhow!( | |
| 966 | + "wait failed with [{}] {}", | |
| 967 | + reply.status.as_u16(), | |
| 968 | + reply.message() | |
| 969 | + )); | |
| 970 | + } | |
| 971 | + reply | |
| 972 | + .json()? | |
| 973 | + .get("StatusCode") | |
| 974 | + .and_then(Value::as_i64) | |
| 975 | + .ok_or_else(|| anyhow!("wait answered without a status code")) | |
| 976 | + }) | |
| 977 | + .map_err(|error| format!("{error:#}")); | |
| 978 | + let mut state = cell_.state.lock().unwrap(); | |
| 979 | + if state.run == run { | |
| 980 | + state.running = false; | |
| 981 | + state.address = Address::None; | |
| 982 | + } | |
| 983 | + drop(state); | |
| 984 | + cell_.exit.send_replace(Some((run, result))); | |
| 985 | + }) | |
| 986 | + .detach(); | |
| 987 | + } | |
| 988 | + | |
| 989 | + async fn create_and_start( | |
| 990 | + &self, | |
| 991 | + cell: &CellContainer, | |
| 992 | + params: StartParams, | |
| 993 | + ) -> anyhow::Result<Address> { | |
| 994 | + self.ensure_fence().await?; | |
| 995 | + self.enforce_instance_ceiling(cell).await?; | |
| 996 | + self.ensure_image(&cell.spec.image).await?; | |
| 997 | + let (open, internal) = self.networks().await?; | |
| 998 | + // A previous run's container may still be named: the wait task | |
| 999 | + // observed its exit but nothing removed it, or a restart adopted a | |
| 1000 | + // stopped one. The name is the cell's, so it is ours to remove. | |
| 1001 | + let _ = self | |
| 1002 | + .docker | |
| 1003 | + .call( | |
| 1004 | + "DELETE", | |
| 1005 | + &format!("/containers/{}?force=true", cell.name), | |
| 1006 | + None, | |
| 1007 | + ) | |
| 1008 | + .await; | |
| 1009 | + let mut env: Vec<String> = DEFAULT_ENV.iter().map(|entry| entry.to_string()).collect(); | |
| 1010 | + env.push(format!("CLOUDFLARE_DURABLE_OBJECT_ID={}", cell.scope)); | |
| 1011 | + env.extend( | |
| 1012 | + params | |
| 1013 | + .env | |
| 1014 | + .iter() | |
| 1015 | + .map(|(name, value)| format!("{name}={value}")), | |
| 1016 | + ); | |
| 1017 | + let mut labels = serde_json::Map::new(); | |
| 1018 | + labels.insert("celld.node".into(), json!(self.node)); | |
| 1019 | + labels.insert("celld.cell".into(), json!(cell.scope)); | |
| 1020 | + labels.insert("celld.class".into(), json!(cell.spec.class_name)); | |
| 1021 | + for (name, value) in ¶ms.labels { | |
| 1022 | + labels.insert(format!("celld.user.{name}"), json!(value)); | |
| 1023 | + } | |
| 1024 | + // Off Linux the node reaches a container only through published | |
| 1025 | + // ports, and Docker publishes nothing on an internal network, so | |
| 1026 | + // `enableInternet: false` would make the container unreachable. | |
| 1027 | + // Development there keeps egress; the compat page says so. | |
| 1028 | + let offline = !params.enable_internet && cfg!(target_os = "linux"); | |
| 1029 | + if !params.enable_internet && !offline { | |
| 1030 | + tracing::warn!( | |
| 1031 | + cell = %cell.scope, | |
| 1032 | + "enableInternet: false is not enforced on this platform; the container keeps egress" | |
| 1033 | + ); | |
| 1034 | + } | |
| 1035 | + // A container is a tenant's process tree, not the operator's: no | |
| 1036 | + // capability, no privilege gain through setuid binaries, the | |
| 1037 | + // daemon's seccomp profile, and a process ceiling. What a class | |
| 1038 | + // legitimately needs beyond this is a config question for later, | |
| 1039 | + // not a default. The kernel boundary itself is the runtime's. | |
| 1040 | + let mut host_config = json!({ | |
| 1041 | + "NetworkMode": if offline { &internal } else { &open }, | |
| 1042 | + "PublishAllPorts": !cfg!(target_os = "linux"), | |
| 1043 | + "CapDrop": ["ALL"], | |
| 1044 | + "SecurityOpt": ["no-new-privileges"], | |
| 1045 | + "PidsLimit": PIDS_LIMIT, | |
| 1046 | + // An init as PID 1 reaps orphaned children. Without it a process | |
| 1047 | + // whose parent exits becomes a zombie the container holds until | |
| 1048 | + // it stops, and enough of them exhaust the PID ceiling; a fleet | |
| 1049 | + // fork bomb left exactly these behind. | |
| 1050 | + "Init": true, | |
| 1051 | + }); | |
| 1052 | + // A class can name its own runtime, else the node default. A class | |
| 1053 | + // that needs isolation names `runsc`, and the node's daemon must | |
| 1054 | + // have it or the start fails, so the class runs only where its | |
| 1055 | + // isolation is real. | |
| 1056 | + let runtime = cell | |
| 1057 | + .spec | |
| 1058 | + .runtime | |
| 1059 | + .as_deref() | |
| 1060 | + .or(self.runtime.as_deref()) | |
| 1061 | + .filter(|runtime| !runtime.is_empty()); | |
| 1062 | + if let Some(runtime) = runtime { | |
| 1063 | + host_config["Runtime"] = json!(runtime); | |
| 1064 | + } | |
| 1065 | + // A container under a non-default runtime gets an explicit resolver | |
| 1066 | + // through a bind-mounted resolv.conf: gVisor cannot reach Docker's | |
| 1067 | + // embedded resolver at `127.0.0.11`, and on a user bridge Docker | |
| 1068 | + // keeps that address in resolv.conf whatever `--dns` says, so the | |
| 1069 | + // file itself must name a reachable resolver. An operator who set | |
| 1070 | + // `CELLD_CONTAINER_DNS` gets it for every container. | |
| 1071 | + let wants_resolver = runtime.is_some() || !self.dns.is_empty(); | |
| 1072 | + if wants_resolver { | |
| 1073 | + if let Some(resolv) = &self.resolv_conf { | |
| 1074 | + let bind = format!("{}:/etc/resolv.conf:ro", resolv.display()); | |
| 1075 | + host_config["Binds"] = json!([bind]); | |
| 1076 | + } | |
| 1077 | + } | |
| 1078 | + // Every container has a limit: a class without an instance type | |
| 1079 | + // gets Cloudflare's default type rather than the node. | |
| 1080 | + let instance_type = cell | |
| 1081 | + .spec | |
| 1082 | + .instance_type | |
| 1083 | + .as_deref() | |
| 1084 | + .unwrap_or(DEFAULT_INSTANCE_TYPE); | |
| 1085 | + let (vcpu, memory) = | |
| 1086 | + instance_resources(instance_type).expect("the deploy refused this instance type"); | |
| 1087 | + host_config["NanoCpus"] = json!((vcpu * 1e9) as u64); | |
| 1088 | + host_config["Memory"] = json!(memory); | |
| 1089 | + host_config["MemorySwap"] = json!(memory); | |
| 1090 | + let mut body = json!({ | |
| 1091 | + "Image": cell.spec.image, | |
| 1092 | + "Env": env, | |
| 1093 | + "Labels": labels, | |
| 1094 | + "HostConfig": host_config, | |
| 1095 | + }); | |
| 1096 | + if let Some(entrypoint) = params.entrypoint { | |
| 1097 | + body["Cmd"] = json!(entrypoint); | |
| 1098 | + } | |
| 1099 | + // The daemon can answer 409 for a name whose previous container is | |
| 1100 | + // still being removed, so a fresh start after `destroy()` retries | |
| 1101 | + // briefly, as workerd's engine does. | |
| 1102 | + let mut reply = self | |
| 1103 | + .docker | |
| 1104 | + .call( | |
| 1105 | + "POST", | |
| 1106 | + &format!("/containers/create?name={}", cell.name), | |
| 1107 | + Some(body.clone()), | |
| 1108 | + ) | |
| 1109 | + .await?; | |
| 1110 | + for _ in 0..20 { | |
| 1111 | + if reply.status.as_u16() != 409 { | |
| 1112 | + break; | |
| 1113 | + } | |
| 1114 | + asyncrt::sleep(Duration::from_millis(100)).await; | |
| 1115 | + let _ = self | |
| 1116 | + .docker | |
| 1117 | + .call( | |
| 1118 | + "DELETE", | |
| 1119 | + &format!("/containers/{}?force=true", cell.name), | |
| 1120 | + None, | |
| 1121 | + ) | |
| 1122 | + .await; | |
| 1123 | + reply = self | |
| 1124 | + .docker | |
| 1125 | + .call( | |
| 1126 | + "POST", | |
| 1127 | + &format!("/containers/create?name={}", cell.name), | |
| 1128 | + Some(body.clone()), | |
| 1129 | + ) | |
| 1130 | + .await?; | |
| 1131 | + } | |
| 1132 | + if reply.status.as_u16() == 404 { | |
| 1133 | + return Err(anyhow!("No such image available named {}", cell.spec.image)); | |
| 1134 | + } | |
| 1135 | + if !reply.status.is_success() { | |
| 1136 | + return Err(anyhow!( | |
| 1137 | + "Create container failed with [{}] {}", | |
| 1138 | + reply.status.as_u16(), | |
| 1139 | + reply.message() | |
| 1140 | + )); | |
| 1141 | + } | |
| 1142 | + self.docker | |
| 1143 | + .expect( | |
| 1144 | + "POST", | |
| 1145 | + &format!("/containers/{}/start", cell.name), | |
| 1146 | + None, | |
| 1147 | + "start container", | |
| 1148 | + ) | |
| 1149 | + .await?; | |
| 1150 | + let info = self | |
| 1151 | + .docker | |
| 1152 | + .expect( | |
| 1153 | + "GET", | |
| 1154 | + &format!("/containers/{}/json", cell.name), | |
| 1155 | + None, | |
| 1156 | + "inspect container", | |
| 1157 | + ) | |
| 1158 | + .await? | |
| 1159 | + .json()?; | |
| 1160 | + Ok(address_of(&info)) | |
| 1161 | + } | |
| 1162 | + | |
| 1163 | + /// Wait for the current run to end. `Ok(code)` is the root process's | |
| 1164 | + /// exit code; a destroyed container reports 137. | |
| 1165 | + pub async fn monitor(&self, cell: &Arc<CellContainer>, run: u64) -> Result<i64, String> { | |
| 1166 | + let mut receiver = cell.exit.subscribe(); | |
| 1167 | + loop { | |
| 1168 | + if let Some((ended, result)) = receiver.borrow_and_update().clone() { | |
| 1169 | + if ended >= run { | |
| 1170 | + return result; | |
| 1171 | + } | |
| 1172 | + } | |
| 1173 | + if receiver.changed().await.is_err() { | |
| 1174 | + return Err("the container engine went away".to_string()); | |
| 1175 | + } | |
| 1176 | + } | |
| 1177 | + } | |
| 1178 | + | |
| 1179 | + pub async fn destroy(&self, cell: &Arc<CellContainer>) -> anyhow::Result<()> { | |
| 1180 | + // Kill first so the wait task reports 137 before the removal makes | |
| 1181 | + // the name disappear under it. | |
| 1182 | + let _ = self | |
| 1183 | + .docker | |
| 1184 | + .call( | |
| 1185 | + "POST", | |
| 1186 | + &format!("/containers/{}/kill?signal=SIGKILL", cell.name), | |
| 1187 | + None, | |
| 1188 | + ) | |
| 1189 | + .await; | |
| 1190 | + let _ = self | |
| 1191 | + .docker | |
| 1192 | + .call( | |
| 1193 | + "DELETE", | |
| 1194 | + &format!("/containers/{}?force=true", cell.name), | |
| 1195 | + None, | |
| 1196 | + ) | |
| 1197 | + .await; | |
| 1198 | + let mut state = cell.state.lock().unwrap(); | |
| 1199 | + state.running = false; | |
| 1200 | + state.address = Address::None; | |
| 1201 | + Ok(()) | |
| 1202 | + } | |
| 1203 | + | |
| 1204 | + pub async fn signal(&self, cell: &Arc<CellContainer>, signal: u32) -> anyhow::Result<()> { | |
| 1205 | + self.docker | |
| 1206 | + .expect( | |
| 1207 | + "POST", | |
| 1208 | + &format!("/containers/{}/kill?signal={signal}", cell.name), | |
| 1209 | + None, | |
| 1210 | + "signal container", | |
| 1211 | + ) | |
| 1212 | + .await?; | |
| 1213 | + Ok(()) | |
| 1214 | + } | |
| 1215 | + | |
| 1216 | + /// The cell left this node's runtime. An idle eviction keeps the | |
| 1217 | + /// container for its inactivity window; anything else destroys it, and | |
| 1218 | + /// the stop waits for that: a drain ends the process right after its | |
| 1219 | + /// last stop, and a destroy left to a detached task did not always get | |
| 1220 | + /// its two daemon calls in before the exit. | |
| 1221 | + pub async fn release(self: &Arc<Self>, scope: &str, release: Release) { | |
| 1222 | + let Some(cell) = self.cell(scope) else { | |
| 1223 | + return; | |
| 1224 | + }; | |
| 1225 | + match release { | |
| 1226 | + Release::Keep => { | |
| 1227 | + let window = cell | |
| 1228 | + .state | |
| 1229 | + .lock() | |
| 1230 | + .unwrap() | |
| 1231 | + .inactivity | |
| 1232 | + .unwrap_or(DEFAULT_INACTIVITY); | |
| 1233 | + let engine = self.clone(); | |
| 1234 | + let cell_ = cell.clone(); | |
| 1235 | + let sweeper = asyncrt::spawn(async move { | |
| 1236 | + asyncrt::sleep(window).await; | |
| 1237 | + engine.forget(&cell_).await; | |
| 1238 | + }); | |
| 1239 | + cell.state.lock().unwrap().sweeper = Some(sweeper); | |
| 1240 | + } | |
| 1241 | + Release::Destroy => self.forget(&cell).await, | |
| 1242 | + } | |
| 1243 | + } | |
| 1244 | + | |
| 1245 | + async fn forget(&self, cell: &Arc<CellContainer>) { | |
| 1246 | + let _ = self.destroy(cell).await; | |
| 1247 | + for id in cell.processes.lock().unwrap().drain(..) { | |
| 1248 | + drop_process(id); | |
| 1249 | + } | |
| 1250 | + let mut cells = self.cells.lock().unwrap(); | |
| 1251 | + if cells | |
| 1252 | + .get(&cell.scope) | |
| 1253 | + .is_some_and(|current| Arc::ptr_eq(current, cell)) | |
| 1254 | + { | |
| 1255 | + cells.remove(&cell.scope); | |
| 1256 | + } | |
| 1257 | + } | |
| 1258 | + | |
| 1259 | + pub async fn exec( | |
| 1260 | + &self, | |
| 1261 | + cell: &Arc<CellContainer>, | |
| 1262 | + params: ExecParams, | |
| 1263 | + ) -> anyhow::Result<Arc<ExecProcess>> { | |
| 1264 | + if !cell.running() { | |
| 1265 | + return Err(anyhow!("exec() requires a running container.")); | |
| 1266 | + } | |
| 1267 | + let mut body = json!({ | |
| 1268 | + "AttachStdin": true, | |
| 1269 | + "AttachStdout": true, | |
| 1270 | + "AttachStderr": true, | |
| 1271 | + "Tty": false, | |
| 1272 | + "Cmd": params.cmd, | |
| 1273 | + }); | |
| 1274 | + if !params.env.is_empty() { | |
| 1275 | + body["Env"] = json!(params | |
| 1276 | + .env | |
| 1277 | + .iter() | |
| 1278 | + .map(|(name, value)| format!("{name}={value}")) | |
| 1279 | + .collect::<Vec<_>>()); | |
| 1280 | + } | |
| 1281 | + if let Some(cwd) = ¶ms.cwd { | |
| 1282 | + body["WorkingDir"] = json!(cwd); | |
| 1283 | + } | |
| 1284 | + if let Some(user) = ¶ms.user { | |
| 1285 | + body["User"] = json!(user); | |
| 1286 | + } | |
| 1287 | + let created = self | |
| 1288 | + .docker | |
| 1289 | + .expect( | |
| 1290 | + "POST", | |
| 1291 | + &format!("/containers/{}/exec", cell.name), | |
| 1292 | + Some(body), | |
| 1293 | + "create exec", | |
| 1294 | + ) | |
| 1295 | + .await? | |
| 1296 | + .json()?; | |
| 1297 | + let exec_id = created | |
| 1298 | + .get("Id") | |
| 1299 | + .and_then(Value::as_str) | |
| 1300 | + .ok_or_else(|| anyhow!("exec create answered without an id"))? | |
| 1301 | + .to_string(); | |
| 1302 | + let stream = self | |
| 1303 | + .docker | |
| 1304 | + .hijack( | |
| 1305 | + &format!("/exec/{exec_id}/start"), | |
| 1306 | + json!({ "Detach": false, "Tty": false }), | |
| 1307 | + ) | |
| 1308 | + .await?; | |
| 1309 | + // Docker reports `Running: false` with no pid before it has spawned | |
| 1310 | + // the process, and a finished exec keeps its pid, so a pid of zero | |
| 1311 | + // is the one answer that means "not yet": retry it briefly, as | |
| 1312 | + // workerd does. Breaking on `Running: false` here lost the pid of a | |
| 1313 | + // short command whenever the inspect landed in that window. | |
| 1314 | + let mut pid = 0; | |
| 1315 | + for _ in 0..20 { | |
| 1316 | + let info = self | |
| 1317 | + .docker | |
| 1318 | + .expect( | |
| 1319 | + "GET", | |
| 1320 | + &format!("/exec/{exec_id}/json"), | |
| 1321 | + None, | |
| 1322 | + "inspect exec", | |
| 1323 | + ) | |
| 1324 | + .await? | |
| 1325 | + .json()?; | |
| 1326 | + pid = info.get("Pid").and_then(Value::as_i64).unwrap_or(0); | |
| 1327 | + if pid != 0 { | |
| 1328 | + break; | |
| 1329 | + } | |
| 1330 | + asyncrt::sleep(Duration::from_millis(50)).await; | |
| 1331 | + } | |
| 1332 | + let (read, write) = tokio::io::split(stream); | |
| 1333 | + let (stdout_tx, stdout_rx) = mpsc::channel(16); | |
| 1334 | + let (stderr_tx, stderr_rx) = mpsc::channel(16); | |
| 1335 | + let combined = params.combined; | |
| 1336 | + let ended = watch::channel(false).0; | |
| 1337 | + let ended_ = ended.clone(); | |
| 1338 | + asyncrt::spawn(async move { | |
| 1339 | + demux(read, stdout_tx, stderr_tx, combined).await; | |
| 1340 | + ended_.send_replace(true); | |
| 1341 | + }) | |
| 1342 | + .detach(); | |
| 1343 | + let process = Arc::new(ExecProcess { | |
| 1344 | + id: next_exec_id(), | |
| 1345 | + exec_id, | |
| 1346 | + container: cell.name.clone(), | |
| 1347 | + pid, | |
| 1348 | + docker: self.docker.clone(), | |
| 1349 | + stdin: tokio::sync::Mutex::new(Some(write)), | |
| 1350 | + stdout: tokio::sync::Mutex::new(stdout_rx), | |
| 1351 | + stderr: tokio::sync::Mutex::new(stderr_rx), | |
| 1352 | + ended, | |
| 1353 | + exit_code: tokio::sync::Mutex::new(None), | |
| 1354 | + }); | |
| 1355 | + processes() | |
| 1356 | + .lock() | |
| 1357 | + .unwrap() | |
| 1358 | + .insert(process.id, process.clone()); | |
| 1359 | + cell.processes.lock().unwrap().push(process.id); | |
| 1360 | + Ok(process) | |
| 1361 | + } | |
| 1362 | +} | |
| 1363 | + | |
| 1364 | +pub struct ExecParams { | |
| 1365 | + pub cmd: Vec<String>, | |
| 1366 | + pub env: Vec<(String, String)>, | |
| 1367 | + pub cwd: Option<String>, | |
| 1368 | + pub user: Option<String>, | |
| 1369 | + /// stderr folded into stdout. | |
| 1370 | + pub combined: bool, | |
| 1371 | +} | |
| 1372 | + | |
| 1373 | +type WriteHalf = tokio::io::WriteHalf<Box<dyn Stream>>; | |
| 1374 | + | |
| 1375 | +pub struct ExecProcess { | |
| 1376 | + pub id: u64, | |
| 1377 | + exec_id: String, | |
| 1378 | + container: String, | |
| 1379 | + pub pid: i64, | |
| 1380 | + docker: Docker, | |
| 1381 | + stdin: tokio::sync::Mutex<Option<WriteHalf>>, | |
| 1382 | + stdout: tokio::sync::Mutex<mpsc::Receiver<Bytes>>, | |
| 1383 | + stderr: tokio::sync::Mutex<mpsc::Receiver<Bytes>>, | |
| 1384 | + /// True once the hijacked stream reached EOF, which the daemon sends | |
| 1385 | + /// when the process exits. | |
| 1386 | + ended: watch::Sender<bool>, | |
| 1387 | + exit_code: tokio::sync::Mutex<Option<i64>>, | |
| 1388 | +} | |
| 1389 | + | |
| 1390 | +fn processes() -> &'static Mutex<HashMap<u64, Arc<ExecProcess>>> { | |
| 1391 | + static PROCESSES: OnceLock<Mutex<HashMap<u64, Arc<ExecProcess>>>> = OnceLock::new(); | |
| 1392 | + PROCESSES.get_or_init(Default::default) | |
| 1393 | +} | |
| 1394 | + | |
| 1395 | +fn next_exec_id() -> u64 { | |
| 1396 | + static NEXT: AtomicU64 = AtomicU64::new(1); | |
| 1397 | + NEXT.fetch_add(1, Ordering::Relaxed) | |
| 1398 | +} | |
| 1399 | + | |
| 1400 | +pub fn process(id: u64) -> Option<Arc<ExecProcess>> { | |
| 1401 | + processes().lock().unwrap().get(&id).cloned() | |
| 1402 | +} | |
| 1403 | + | |
| 1404 | +pub fn drop_process(id: u64) { | |
| 1405 | + processes().lock().unwrap().remove(&id); | |
| 1406 | +} | |
| 1407 | + | |
| 1408 | +impl ExecProcess { | |
| 1409 | + /// One chunk of stdout (`1`) or stderr (`2`); empty at end of stream. | |
| 1410 | + pub async fn read(&self, which: u8) -> Bytes { | |
| 1411 | + let mut receiver = match which { | |
| 1412 | + 1 => self.stdout.lock().await, | |
| 1413 | + _ => self.stderr.lock().await, | |
| 1414 | + }; | |
| 1415 | + receiver.recv().await.unwrap_or_default() | |
| 1416 | + } | |
| 1417 | + | |
| 1418 | + pub async fn write(&self, bytes: &[u8]) -> Result<(), String> { | |
| 1419 | + let mut guard = self.stdin.lock().await; | |
| 1420 | + let stdin = guard.as_mut().ok_or("stdin is closed")?; | |
| 1421 | + stdin | |
| 1422 | + .write_all(bytes) | |
| 1423 | + .await | |
| 1424 | + .map_err(|error| format!("stdin write failed: {error}"))?; | |
| 1425 | + stdin | |
| 1426 | + .flush() | |
| 1427 | + .await | |
| 1428 | + .map_err(|error| format!("stdin flush failed: {error}")) | |
| 1429 | + } | |
| 1430 | + | |
| 1431 | + /// End stdin. Half-closing the hijacked connection is how the daemon | |
| 1432 | + /// learns the process's stdin reached EOF. | |
| 1433 | + pub async fn close_stdin(&self) { | |
| 1434 | + if let Some(mut stdin) = self.stdin.lock().await.take() { | |
| 1435 | + let _ = stdin.shutdown().await; | |
| 1436 | + } | |
| 1437 | + } | |
| 1438 | + | |
| 1439 | + pub async fn wait(&self) -> anyhow::Result<i64> { | |
| 1440 | + let mut exit = self.exit_code.lock().await; | |
| 1441 | + if let Some(code) = *exit { | |
| 1442 | + return Ok(code); | |
| 1443 | + } | |
| 1444 | + let mut ended = self.ended.subscribe(); | |
| 1445 | + while !*ended.borrow_and_update() { | |
| 1446 | + if ended.changed().await.is_err() { | |
| 1447 | + break; | |
| 1448 | + } | |
| 1449 | + } | |
| 1450 | + // The stream closes when the process exits, but the daemon records | |
| 1451 | + // the exit code a moment later. | |
| 1452 | + let mut code = None; | |
| 1453 | + for _ in 0..40 { | |
| 1454 | + let info = self | |
| 1455 | + .docker | |
| 1456 | + .expect( | |
| 1457 | + "GET", | |
| 1458 | + &format!("/exec/{}/json", self.exec_id), | |
| 1459 | + None, | |
| 1460 | + "inspect exec", | |
| 1461 | + ) | |
| 1462 | + .await? | |
| 1463 | + .json()?; | |
| 1464 | + if !info | |
| 1465 | + .get("Running") | |
| 1466 | + .and_then(Value::as_bool) | |
| 1467 | + .unwrap_or(false) | |
| 1468 | + { | |
| 1469 | + code = info.get("ExitCode").and_then(Value::as_i64); | |
| 1470 | + break; | |
| 1471 | + } | |
| 1472 | + asyncrt::sleep(Duration::from_millis(50)).await; | |
| 1473 | + } | |
| 1474 | + let code = code.ok_or_else(|| anyhow!("the process did not report an exit code"))?; | |
| 1475 | + *exit = Some(code); | |
| 1476 | + Ok(code) | |
| 1477 | + } | |
| 1478 | + | |
| 1479 | + /// The Engine API has no exec kill, so the signal is delivered by a | |
| 1480 | + /// second exec of `kill`, as workerd does. | |
| 1481 | + pub async fn kill(&self, signal: u32) -> anyhow::Result<()> { | |
| 1482 | + let body = json!({ | |
| 1483 | + "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, | |
| 1484 | + "Cmd": ["kill", format!("-{signal}"), self.pid.to_string()], | |
| 1485 | + }); | |
| 1486 | + let created = self | |
| 1487 | + .docker | |
| 1488 | + .expect( | |
| 1489 | + "POST", | |
| 1490 | + &format!("/containers/{}/exec", self.container), | |
| 1491 | + Some(body), | |
| 1492 | + "create exec", | |
| 1493 | + ) | |
| 1494 | + .await? | |
| 1495 | + .json()?; | |
| 1496 | + let id = created | |
| 1497 | + .get("Id") | |
| 1498 | + .and_then(Value::as_str) | |
| 1499 | + .ok_or_else(|| anyhow!("exec create answered without an id"))?; | |
| 1500 | + self.docker | |
| 1501 | + .expect( | |
| 1502 | + "POST", | |
| 1503 | + &format!("/exec/{id}/start"), | |
| 1504 | + Some(json!({ "Detach": true })), | |
| 1505 | + "start exec", | |
| 1506 | + ) | |
| 1507 | + .await?; | |
| 1508 | + Ok(()) | |
| 1509 | + } | |
| 1510 | +} | |
| 1511 | + | |
| 1512 | +/// Split Docker's multiplexed stream into stdout and stderr chunks until | |
| 1513 | +/// the daemon closes it. | |
| 1514 | +async fn demux( | |
| 1515 | + mut read: tokio::io::ReadHalf<Box<dyn Stream>>, | |
| 1516 | + stdout: mpsc::Sender<Bytes>, | |
| 1517 | + stderr: mpsc::Sender<Bytes>, | |
| 1518 | + combined: bool, | |
| 1519 | +) { | |
| 1520 | + let mut header = [0u8; 8]; | |
| 1521 | + loop { | |
| 1522 | + if read.read_exact(&mut header).await.is_err() { | |
| 1523 | + return; | |
| 1524 | + } | |
| 1525 | + let (stream, length) = frame_header(&header); | |
| 1526 | + let mut payload = vec![0u8; length]; | |
| 1527 | + if read.read_exact(&mut payload).await.is_err() { | |
| 1528 | + return; | |
| 1529 | + } | |
| 1530 | + let target = if stream == 2 && !combined { | |
| 1531 | + &stderr | |
| 1532 | + } else { | |
| 1533 | + &stdout | |
| 1534 | + }; | |
| 1535 | + if target.send(Bytes::from(payload)).await.is_err() { | |
| 1536 | + // The reader went away; keep draining so the process is not | |
| 1537 | + // blocked on a full pipe. | |
| 1538 | + continue; | |
| 1539 | + } | |
| 1540 | + } | |
| 1541 | +} | |
| 1542 | + | |
| 1543 | +fn address_of(info: &Value) -> Address { | |
| 1544 | + if cfg!(target_os = "linux") { | |
| 1545 | + let ip = info | |
| 1546 | + .pointer("/NetworkSettings/Networks") | |
| 1547 | + .and_then(Value::as_object) | |
| 1548 | + .and_then(|networks| networks.values().next()) | |
| 1549 | + .and_then(|network| network.get("IPAddress")) | |
| 1550 | + .and_then(Value::as_str) | |
| 1551 | + .filter(|ip| !ip.is_empty()); | |
| 1552 | + return ip.map_or(Address::None, |ip| Address::Ip(ip.to_string())); | |
| 1553 | + } | |
| 1554 | + let mut ports = HashMap::new(); | |
| 1555 | + if let Some(map) = info | |
| 1556 | + .pointer("/NetworkSettings/Ports") | |
| 1557 | + .and_then(Value::as_object) | |
| 1558 | + { | |
| 1559 | + for (key, bindings) in map { | |
| 1560 | + let Some(port) = key | |
| 1561 | + .strip_suffix("/tcp") | |
| 1562 | + .and_then(|port| port.parse::<u16>().ok()) | |
| 1563 | + else { | |
| 1564 | + continue; | |
| 1565 | + }; | |
| 1566 | + let host = bindings | |
| 1567 | + .as_array() | |
| 1568 | + .into_iter() | |
| 1569 | + .flatten() | |
| 1570 | + .find_map(|binding| binding.get("HostPort")?.as_str()?.parse::<u16>().ok()); | |
| 1571 | + if let Some(host) = host { | |
| 1572 | + ports.insert(port, host); | |
| 1573 | + } | |
| 1574 | + } | |
| 1575 | + } | |
| 1576 | + Address::Published(ports) | |
| 1577 | +} | |
| 1578 | + | |
| 1579 | +/// A Docker name from a node and a cell scope: the scope's characters are | |
| 1580 | +/// not all legal, so the name is a hash and the scope rides in a label. | |
| 1581 | +/// The node is part of it because two nodes can share one engine in a | |
| 1582 | +/// development or test setup, and a name from the scope alone let one | |
| 1583 | +/// node adopt, or reap, the other's container for the same object. | |
| 1584 | +fn container_name(node: &str, scope: &str) -> String { | |
| 1585 | + use sha2::Digest; | |
| 1586 | + let digest = sha2::Sha256::digest(format!("{node}\n{scope}").as_bytes()); | |
| 1587 | + format!("celld-{:x}", digest)[..30].to_string() | |
| 1588 | +} |
modifiedcrates/celld/control_plane.rs+12−75View file
| @@ -35,26 +35,8 @@ | ||
| 35 | 35 | const MAX_MANAGED_MODULES: usize = 64; |
| 36 | 36 | const MAX_MANAGED_MODULE_BYTES: usize = 25 * 1024 * 1024; |
| 37 | 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 | -fn restart_on_deployment_enabled() -> bool { | |
| 43 | - crate::env_vars::flag("CELLD_CLOUD_RESTART_ON_DEPLOY", false) | |
| 44 | - .expect("validated CELLD_CLOUD_RESTART_ON_DEPLOY") | |
| 45 | -} | |
| 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 | - | |
| 56 | 38 | #[cfg(unix)] |
| 57 | -fn restart_process(trigger: &'static str) -> ! { | |
| 39 | +fn restart_with_rotated_credentials() -> ! { | |
| 58 | 40 | use std::os::unix::process::CommandExt; |
| 59 | 41 | use std::process::Command; |
| 60 | 42 | |
| @@ -63,7 +45,7 @@ | ||
| 63 | 45 | Err(error) => { |
| 64 | 46 | warn!( |
| 65 | 47 | event = "control_plane_restart_exec_failed", |
| 66 | - trigger, | |
| 48 | + trigger = "credential_rotation", | |
| 67 | 49 | %error, |
| 68 | 50 | "could not locate celld for process reload; exiting for an external supervisor" |
| 69 | 51 | ); |
| @@ -75,7 +57,7 @@ | ||
| 75 | 57 | Err(error) => { |
| 76 | 58 | warn!( |
| 77 | 59 | event = "control_plane_restart_exec_failed", |
| 78 | - trigger, | |
| 60 | + trigger = "credential_rotation", | |
| 79 | 61 | %error, |
| 80 | 62 | "could not preserve process probe identity; exiting for an external supervisor" |
| 81 | 63 | ); |
| @@ -92,7 +74,7 @@ | ||
| 92 | 74 | let error = command.exec(); |
| 93 | 75 | warn!( |
| 94 | 76 | event = "control_plane_restart_exec_failed", |
| 95 | - trigger, | |
| 77 | + trigger = "credential_rotation", | |
| 96 | 78 | %error, |
| 97 | 79 | "could not re-exec celld for process reload; exiting for an external supervisor" |
| 98 | 80 | ); |
| @@ -100,14 +82,10 @@ | ||
| 100 | 82 | } |
| 101 | 83 | |
| 102 | 84 | #[cfg(not(unix))] |
| 103 | -fn restart_process(_trigger: &'static str) -> ! { | |
| 85 | +fn restart_with_rotated_credentials() -> ! { | |
| 104 | 86 | std::process::exit(75); |
| 105 | 87 | } |
| 106 | 88 | |
| 107 | -fn restart_for_deployment() -> ! { | |
| 108 | - restart_process("deployment") | |
| 109 | -} | |
| 110 | - | |
| 111 | 89 | static REEXEC_NODE_SESSION_ID: OnceLock<String> = OnceLock::new(); |
| 112 | 90 | |
| 113 | 91 | pub fn install_reexec_node_session_id(node: &str) -> anyhow::Result<()> { |
| @@ -175,13 +153,12 @@ | ||
| 175 | 153 | fresh one, or run `celld credentials refresh` if a rotation is pending" |
| 176 | 154 | ), |
| 177 | 155 | // No remedy on this node: the store lacks a required operation, so a |
| 178 | - // restart repeats the refusal. Name the two exits an operator has. | |
| 156 | + // restart repeats the refusal. The operator needs a compatible store. | |
| 179 | 157 | ManagedRuntimeState::StorageContractViolated => warn!( |
| 180 | 158 | event = "managed_runtime_state", |
| 181 | 159 | managed_state, |
| 182 | 160 | "the fleet bucket does not support a storage operation celld requires, \ |
| 183 | - so serving cannot start; move the fleet to a compatible store, or set \ | |
| 184 | - CELLD_STORAGE_PROBE=0 to start without this test" | |
| 161 | + so serving cannot start; move the fleet to a compatible store" | |
| 185 | 162 | ), |
| 186 | 163 | } |
| 187 | 164 | } |
| @@ -853,7 +830,7 @@ | ||
| 853 | 830 | credential_version, |
| 854 | 831 | "managed credential changed; restarting celld to rebuild every credentialed adapter" |
| 855 | 832 | ); |
| 856 | - restart_process("credential_rotation") | |
| 833 | + restart_with_rotated_credentials() | |
| 857 | 834 | } |
| 858 | 835 | |
| 859 | 836 | /// Watch the durable installation record for the lifetime of the advisory |
| @@ -940,8 +917,6 @@ | ||
| 940 | 917 | crate::env_vars::with_default("CELLD_PRESENCE_HEARTBEAT_MS", 30_000) |
| 941 | 918 | .expect("validated CELLD_PRESENCE_HEARTBEAT_MS"), |
| 942 | 919 | ); |
| 943 | - let shadow_presence = crate::env_vars::flag("CELLD_PRESENCE_SHADOW", false) | |
| 944 | - .expect("validated CELLD_PRESENCE_SHADOW"); | |
| 945 | 920 | pump_presence( |
| 946 | 921 | socket, |
| 947 | 922 | heartbeat_period, |
| @@ -949,11 +924,6 @@ | ||
| 949 | 924 | let snapshot = (runtime.snapshot)() |
| 950 | 925 | .await |
| 951 | 926 | .context("celld core stopped before presence snapshot")?; |
| 952 | - let lease_shadow = if shadow_presence { | |
| 953 | - Some(lease_shadow_observation(runtime).await) | |
| 954 | - } else { | |
| 955 | - None | |
| 956 | - }; | |
| 957 | 927 | let mut cells = snapshot |
| 958 | 928 | .cells |
| 959 | 929 | .iter() |
| @@ -972,7 +942,7 @@ | ||
| 972 | 942 | let cells_truncated = |
| 973 | 943 | cells.len() < snapshot.cells.len() || cells.len() > MAX_PRESENCE_CELLS; |
| 974 | 944 | cells.truncate(MAX_PRESENCE_CELLS); |
| 975 | - let mut message = serde_json::json!({ | |
| 945 | + let message = serde_json::json!({ | |
| 976 | 946 | "serving": snapshot.serving, |
| 977 | 947 | "owned_cells": snapshot.owned_cells(), |
| 978 | 948 | "cells": cells, |
| @@ -987,9 +957,6 @@ | ||
| 987 | 957 | "handoff_failed": snapshot.activity.handoff_failed, |
| 988 | 958 | }, |
| 989 | 959 | }); |
| 990 | - if let Some(observation) = lease_shadow { | |
| 991 | - message["lease_shadow"] = observation; | |
| 992 | - } | |
| 993 | 960 | Ok(message.to_string()) |
| 994 | 961 | }, |
| 995 | 962 | move |text| async move { |
| @@ -1013,10 +980,10 @@ | ||
| 1013 | 980 | .await? |
| 1014 | 981 | .is_some() |
| 1015 | 982 | { |
| 1016 | - adopt_or_restart(&runtime.reload); | |
| 983 | + crate::generation::nudge(&runtime.reload); | |
| 1017 | 984 | } |
| 1018 | 985 | } |
| 1019 | - Some("deployment_current") => adopt_or_restart(&runtime.reload), | |
| 986 | + Some("deployment_current") => crate::generation::nudge(&runtime.reload), | |
| 1020 | 987 | _ => {} |
| 1021 | 988 | } |
| 1022 | 989 | Ok(None) |
| @@ -1132,36 +1099,6 @@ | ||
| 1132 | 1099 | } |
| 1133 | 1100 | } |
| 1134 | 1101 | |
| 1135 | -/// Independently observe bucket truth for rollout comparison. This is an | |
| 1136 | -/// off-by-default management diagnostic: it never feeds the lease record back | |
| 1137 | -/// into the core or changes whether the node serves. | |
| 1138 | -async fn lease_shadow_observation(runtime: &PresenceRuntime) -> serde_json::Value { | |
| 1139 | - let checked_at_ms = crate::ownership_store::now_ms(); | |
| 1140 | - match crate::ownership_store::load_node_lease(&runtime.s3, &runtime.node_session_id).await { | |
| 1141 | - Ok(Some(record)) => serde_json::json!({ | |
| 1142 | - "bucket_status": if record.expires_ms > checked_at_ms { "live" } else { "expired" }, | |
| 1143 | - "node": record.node, | |
| 1144 | - "advertise": record.addr, | |
| 1145 | - "expires_ms": record.expires_ms, | |
| 1146 | - "checked_at_ms": checked_at_ms, | |
| 1147 | - }), | |
| 1148 | - Ok(None) => serde_json::json!({ | |
| 1149 | - "bucket_status": "missing", | |
| 1150 | - "node": null, | |
| 1151 | - "advertise": null, | |
| 1152 | - "expires_ms": null, | |
| 1153 | - "checked_at_ms": checked_at_ms, | |
| 1154 | - }), | |
| 1155 | - Err(_) => serde_json::json!({ | |
| 1156 | - "bucket_status": "unavailable", | |
| 1157 | - "node": null, | |
| 1158 | - "advertise": null, | |
| 1159 | - "expires_ms": null, | |
| 1160 | - "checked_at_ms": checked_at_ms, | |
| 1161 | - }), | |
| 1162 | - } | |
| 1163 | -} | |
| 1164 | - | |
| 1165 | 1102 | /// How long a read-only exploration can spend in object storage. |
| 1166 | 1103 | /// |
| 1167 | 1104 | /// A person waits for this answer in the Managed Control Plane, and the |
| @@ -1638,7 +1575,7 @@ | ||
| 1638 | 1575 | script_name = %applied.script_name, |
| 1639 | 1576 | "deployment applied to the fleet bucket; adopting it" |
| 1640 | 1577 | ); |
| 1641 | - adopt_or_restart(&reload); | |
| 1578 | + crate::generation::nudge(&reload); | |
| 1642 | 1579 | } |
| 1643 | 1580 | Ok(None) => { |
| 1644 | 1581 | if consecutive_failures > 0 { |
modifiedcrates/celld/deploy.rs+489−30View file
| @@ -12,13 +12,14 @@ | ||
| 12 | 12 | //! Cloudflare-shaped API. Config keys are an allowlist: anything we do not |
| 13 | 13 | //! model is refused, never silently dropped. |
| 14 | 14 | use crate::bucket::Bucket; |
| 15 | +use crate::container::ContainerSpec; | |
| 15 | 16 | use crate::note; |
| 16 | 17 | use crate::protocol::{ |
| 17 | 18 | asset_blob_key, AssetConfig, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest, |
| 18 | 19 | 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, | |
| 20 | + Rollout, RunWorkerFirst, FEATURE_ASSETS_V1, FEATURE_CONTAINERS_V1, FEATURE_CRON_V1, | |
| 21 | + FEATURE_D1_V1, FEATURE_KV_V1, FEATURE_QUEUES_V1, FEATURE_R2_V1, FEATURE_SQLITE_VEC_V1, | |
| 22 | + FEATURE_WASM_V1, FEATURE_WORKFLOWS_V1, QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION, | |
| 22 | 23 | }; |
| 23 | 24 | use anyhow::{anyhow, bail, Context}; |
| 24 | 25 | use flate2::write::GzEncoder; |
| @@ -52,6 +53,8 @@ | ||
| 52 | 53 | "queues", |
| 53 | 54 | "workflows", |
| 54 | 55 | "r2_buckets", |
| 56 | + "worker_loaders", | |
| 57 | + "containers", | |
| 55 | 58 | "no_bundle", |
| 56 | 59 | ]; |
| 57 | 60 | |
| @@ -194,6 +197,14 @@ | ||
| 194 | 197 | pub region: Option<String>, |
| 195 | 198 | pub dry_run: bool, |
| 196 | 199 | pub json: bool, |
| 200 | + /// Worker variables that override the `vars` of the config. `celld dev` | |
| 201 | + /// reads them from `.dev.vars`; `celld deploy` supplies none, so a local | |
| 202 | + /// credential cannot reach a fleet. | |
| 203 | + pub vars: BTreeMap<String, String>, | |
| 204 | + /// Keep container images in the local engine instead of saving them to | |
| 205 | + /// the bucket. `celld dev` runs its node on the same engine that built | |
| 206 | + /// them; a fleet needs the tar. | |
| 207 | + pub local_images: bool, | |
| 197 | 208 | } |
| 198 | 209 | |
| 199 | 210 | pub fn print_help() { |
| @@ -227,7 +238,9 @@ | ||
| 227 | 238 | endpoint: None, |
| 228 | 239 | region: None, |
| 229 | 240 | dry_run: false, |
| 241 | + local_images: false, | |
| 230 | 242 | json: false, |
| 243 | + vars: BTreeMap::new(), | |
| 231 | 244 | }; |
| 232 | 245 | let mut arguments = arguments.into_iter(); |
| 233 | 246 | while let Some(argument) = arguments.next() { |
| @@ -281,8 +294,25 @@ | ||
| 281 | 294 | queue_consumers: Vec<QueueConsumerConfig>, |
| 282 | 295 | has_queues: bool, |
| 283 | 296 | has_r2: bool, |
| 297 | + containers: Vec<ContainerDecl>, | |
| 284 | 298 | } |
| 285 | 299 | |
| 300 | +/// One `containers[]` entry as written, before its image is resolved. | |
| 301 | +#[derive(Clone, Debug, serde::Serialize)] | |
| 302 | +struct ContainerDecl { | |
| 303 | + class_name: String, | |
| 304 | + /// A Dockerfile path relative to the project, or an image reference. | |
| 305 | + image: String, | |
| 306 | + #[serde(skip_serializing_if = "Option::is_none")] | |
| 307 | + name: Option<String>, | |
| 308 | + #[serde(skip_serializing_if = "Option::is_none")] | |
| 309 | + instance_type: Option<String>, | |
| 310 | + #[serde(skip_serializing_if = "Option::is_none")] | |
| 311 | + max_instances: Option<u64>, | |
| 312 | + #[serde(skip_serializing_if = "Option::is_none")] | |
| 313 | + runtime: Option<String>, | |
| 314 | +} | |
| 315 | + | |
| 286 | 316 | struct ProjectAssets { |
| 287 | 317 | directory: PathBuf, |
| 288 | 318 | config: AssetConfig, |
| @@ -305,6 +335,13 @@ | ||
| 305 | 335 | pub modules: Vec<(String, Vec<u8>)>, |
| 306 | 336 | pub assets: Option<BuiltAssets>, |
| 307 | 337 | pub bundled_in: Duration, |
| 338 | + /// The resolved image ids of `containers[]`, in config order. | |
| 339 | + pub images: Vec<String>, | |
| 340 | + /// Save each image to the bucket. `celld dev` leaves them in the local | |
| 341 | + /// engine, which is where the node loads them from. | |
| 342 | + /// See `Manifest::fence_image`; saved beside `images`, reported apart. | |
| 343 | + pub fence_image: Option<String>, | |
| 344 | + pub upload_images: bool, | |
| 308 | 345 | } |
| 309 | 346 | |
| 310 | 347 | impl Built { |
| @@ -331,6 +368,9 @@ | ||
| 331 | 368 | assets.blobs.len(), |
| 332 | 369 | ); |
| 333 | 370 | } |
| 371 | + if !self.images.is_empty() { | |
| 372 | + note!("Containers: {} image(s)", self.images.len()); | |
| 373 | + } | |
| 334 | 374 | let bindings = self.bindings(); |
| 335 | 375 | if bindings.is_empty() { |
| 336 | 376 | note!("Your Worker has no bindings."); |
| @@ -413,6 +453,10 @@ | ||
| 413 | 453 | let bucket = binding.get("bucket_name").and_then(Value::as_str)?; |
| 414 | 454 | Some((format!("env.{name} (R2)"), bucket.to_string())) |
| 415 | 455 | } |
| 456 | + Some("worker_loader") => Some(( | |
| 457 | + format!("env.{name} (Worker Loader)"), | |
| 458 | + "Dynamic Workers".to_string(), | |
| 459 | + )), | |
| 416 | 460 | Some("plain_text") => Some(( |
| 417 | 461 | format!("env.{name} (Text)"), |
| 418 | 462 | "Environment Variable".to_string(), |
| @@ -447,7 +491,42 @@ | ||
| 447 | 491 | .filter(|path| !path.as_os_str().is_empty()) |
| 448 | 492 | .map(Path::to_path_buf) |
| 449 | 493 | .unwrap_or_else(|| PathBuf::from(".")); |
| 450 | - let project = read_project(&config_path, &root)?; | |
| 494 | + let mut project = read_project(&config_path, &root, &options.vars)?; | |
| 495 | + // Resolve every image before the version is computed: the id is part of | |
| 496 | + // the deployment's identity, so a rebuilt image is a new deployment. | |
| 497 | + // A fleet deploy builds for the platform the nodes run, which Wrangler | |
| 498 | + // also fixes at linux/amd64; a machine that builds for itself, as | |
| 499 | + // `celld dev` does, passes none. | |
| 500 | + let platform = (!options.local_images).then(|| { | |
| 501 | + std::env::var("CELLD_CONTAINER_PLATFORM").unwrap_or_else(|_| "linux/amd64".to_string()) | |
| 502 | + }); | |
| 503 | + let images = project | |
| 504 | + .containers | |
| 505 | + .iter() | |
| 506 | + .map(|decl| resolve_image(&root, &decl.image, platform.as_deref())) | |
| 507 | + .collect::<anyhow::Result<Vec<_>>>()?; | |
| 508 | + let container_specs: Vec<ContainerSpec> = project | |
| 509 | + .containers | |
| 510 | + .iter() | |
| 511 | + .zip(&images) | |
| 512 | + .map(|(decl, image)| ContainerSpec { | |
| 513 | + class_name: decl.class_name.clone(), | |
| 514 | + image: image.clone(), | |
| 515 | + instance_type: decl.instance_type.clone(), | |
| 516 | + max_instances: decl.max_instances, | |
| 517 | + runtime: decl.runtime.clone(), | |
| 518 | + }) | |
| 519 | + .collect(); | |
| 520 | + if !container_specs.is_empty() { | |
| 521 | + project.metadata["containers"] = json!(container_specs); | |
| 522 | + } | |
| 523 | + // The fence image rides with every deployment that has containers: a | |
| 524 | + // node runs it once, privileged, to fence its bridges before the first | |
| 525 | + // container starts. Built like an app image, keyed by content, so every | |
| 526 | + // deployment made by one celld shares one tar. | |
| 527 | + let fence_image = (!container_specs.is_empty()) | |
| 528 | + .then(|| resolve_fence_image(platform.as_deref())) | |
| 529 | + .transpose()?; | |
| 451 | 530 | let started = Instant::now(); |
| 452 | 531 | let built_assets = project.assets.as_ref().map(build_assets).transpose()?; |
| 453 | 532 | let bundle = project |
| @@ -456,16 +535,20 @@ | ||
| 456 | 535 | .map(|entry| { |
| 457 | 536 | if project.no_bundle { |
| 458 | 537 | // Already bundled by the caller's toolchain. Read it as it is; |
| 459 | - // running esbuild over a Vite build is what corrupts it. A | |
| 460 | - // pre-bundled entry carries no sibling wasm: esbuild's copy | |
| 461 | - // loader is what would have produced them. | |
| 538 | + // running esbuild over a Vite build is what corrupts it. | |
| 462 | 539 | let path = root.join(entry); |
| 463 | - std::fs::read(&path) | |
| 464 | - .with_context(|| format!("read entry point {}", path.display())) | |
| 465 | - .map(|bundle| BundleOutput { | |
| 466 | - bundle, | |
| 467 | - wasm: Vec::new(), | |
| 468 | - }) | |
| 540 | + let bundle = std::fs::read(&path) | |
| 541 | + .with_context(|| format!("read entry point {}", path.display()))?; | |
| 542 | + let mut wasm = Vec::new(); | |
| 543 | + collect_unbundled_wasm( | |
| 544 | + path.parent().context("entry has no directory")?, | |
| 545 | + "", | |
| 546 | + &path, | |
| 547 | + &mut wasm, | |
| 548 | + )?; | |
| 549 | + // Directory iteration order must not change deployment identity. | |
| 550 | + wasm.sort_by(|a, b| a.0.cmp(&b.0)); | |
| 551 | + Ok(BundleOutput { bundle, wasm }) | |
| 469 | 552 | } else { |
| 470 | 553 | run_esbuild(&root, entry) |
| 471 | 554 | } |
| @@ -473,8 +556,7 @@ | ||
| 473 | 556 | .transpose()?; |
| 474 | 557 | let bundled_in = started.elapsed(); |
| 475 | 558 | |
| 476 | - // esbuild emits one JS module plus a copy of every wasm file the bundle | |
| 477 | - // imports; the copies ship as sibling modules. | |
| 559 | + // Both build paths emit one JS module and its sibling wasm modules. | |
| 478 | 560 | let module_name = "index.js".to_string(); |
| 479 | 561 | let (mut modules, wasm_modules) = match bundle { |
| 480 | 562 | Some(output) => (vec![(module_name.clone(), output.bundle)], output.wasm), |
| @@ -521,6 +603,8 @@ | ||
| 521 | 603 | .collect(), |
| 522 | 604 | assets: asset_reference, |
| 523 | 605 | crons: project.crons.clone(), |
| 606 | + containers: container_specs.clone(), | |
| 607 | + fence_image: fence_image.clone(), | |
| 524 | 608 | queue_consumers: project.queue_consumers, |
| 525 | 609 | // Each capability the manifest depends on is named here, so a node |
| 526 | 610 | // that predates it rejects the deployment up front instead of |
| @@ -533,6 +617,9 @@ | ||
| 533 | 617 | if !project.crons.is_empty() { |
| 534 | 618 | features.push(FEATURE_CRON_V1.to_string()); |
| 535 | 619 | } |
| 620 | + if !container_specs.is_empty() { | |
| 621 | + features.push(FEATURE_CONTAINERS_V1.to_string()); | |
| 622 | + } | |
| 536 | 623 | if uses_d1 { |
| 537 | 624 | features.push(FEATURE_D1_V1.to_string()); |
| 538 | 625 | } |
| @@ -566,15 +653,146 @@ | ||
| 566 | 653 | modules, |
| 567 | 654 | assets: built_assets, |
| 568 | 655 | bundled_in, |
| 656 | + images, | |
| 657 | + fence_image, | |
| 658 | + upload_images: !options.local_images, | |
| 569 | 659 | }) |
| 570 | 660 | } |
| 571 | 661 | |
| 662 | +/// Whether `image` names a Dockerfile in the project rather than an image | |
| 663 | +/// reference: the file exists. Wrangler draws the same line. | |
| 664 | +fn is_dockerfile(root: &Path, image: &str) -> bool { | |
| 665 | + std::fs::symlink_metadata(root.join(image)).is_ok_and(|metadata| metadata.is_file()) | |
| 666 | +} | |
| 667 | + | |
| 668 | +fn engine_cli() -> String { | |
| 669 | + std::env::var("CELLD_DOCKER").unwrap_or_else(|_| "docker".to_string()) | |
| 670 | +} | |
| 671 | + | |
| 672 | +fn run_engine(args: &[&str], what: &str) -> anyhow::Result<String> { | |
| 673 | + let output = Command::new(engine_cli()) | |
| 674 | + .args(args) | |
| 675 | + .stdin(std::process::Stdio::null()) | |
| 676 | + .output() | |
| 677 | + .with_context(|| { | |
| 678 | + format!( | |
| 679 | + "{what}: run `{}`; is a Docker or Podman CLI on PATH?", | |
| 680 | + engine_cli() | |
| 681 | + ) | |
| 682 | + })?; | |
| 683 | + if !output.status.success() { | |
| 684 | + bail!( | |
| 685 | + "{what} failed:\n{}", | |
| 686 | + String::from_utf8_lossy(&output.stderr).trim_end() | |
| 687 | + ); | |
| 688 | + } | |
| 689 | + Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()) | |
| 690 | +} | |
| 691 | + | |
| 692 | +/// The fleet reference of the image a `containers[].image` names: build | |
| 693 | +/// the Dockerfile, or pull the reference, then tag the result by its | |
| 694 | +/// content. A platform pins the build and the pull to the nodes' | |
| 695 | +/// architecture; without one the engine's own is used, and a reference the | |
| 696 | +/// engine already holds is not pulled again. | |
| 697 | +/// | |
| 698 | +/// The engine's own image id is not the identity. Docker's containerd | |
| 699 | +/// image store mints a new id for every build of identical content, so an | |
| 700 | +/// id would make each deploy a new deployment version and a new tar in the | |
| 701 | +/// bucket. The layer digests and the image config are stable across such | |
| 702 | +/// builds, so their hash names the image everywhere: in the manifest, in | |
| 703 | +/// the bucket key, and as the tag every engine holds it under. | |
| 704 | +fn resolve_image(root: &Path, image: &str, platform: Option<&str>) -> anyhow::Result<String> { | |
| 705 | + let platform_args = platform | |
| 706 | + .map(|platform| vec!["--platform", platform]) | |
| 707 | + .unwrap_or_default(); | |
| 708 | + let id = if is_dockerfile(root, image) { | |
| 709 | + let path = root.join(image); | |
| 710 | + let context = path | |
| 711 | + .parent() | |
| 712 | + .filter(|parent| !parent.as_os_str().is_empty()) | |
| 713 | + .map(Path::to_path_buf) | |
| 714 | + .unwrap_or_else(|| root.to_path_buf()); | |
| 715 | + let path = path.display().to_string(); | |
| 716 | + let context = context.display().to_string(); | |
| 717 | + let mut args = vec!["build", "-q"]; | |
| 718 | + args.extend(&platform_args); | |
| 719 | + args.extend(["-f", &path, &context]); | |
| 720 | + run_engine(&args, "build container image")? | |
| 721 | + } else { | |
| 722 | + let inspect = ["image", "inspect", "--format", "{{.Id}}", image]; | |
| 723 | + let held = platform.is_none() && run_engine(&inspect, "inspect container image").is_ok(); | |
| 724 | + if !held { | |
| 725 | + let mut args = vec!["pull"]; | |
| 726 | + args.extend(&platform_args); | |
| 727 | + args.push(image); | |
| 728 | + run_engine(&args, "pull container image")?; | |
| 729 | + } | |
| 730 | + run_engine(&inspect, "inspect container image")? | |
| 731 | + }; | |
| 732 | + let content = run_engine( | |
| 733 | + &[ | |
| 734 | + "image", | |
| 735 | + "inspect", | |
| 736 | + "--format", | |
| 737 | + "{{json .RootFS.Layers}}{{json .Config}}", | |
| 738 | + &id, | |
| 739 | + ], | |
| 740 | + "inspect container image", | |
| 741 | + )?; | |
| 742 | + let reference = crate::container::image_reference(&format!("{:x}", Sha256::digest(&content))); | |
| 743 | + run_engine(&["tag", &id, &reference], "tag container image")?; | |
| 744 | + Ok(reference) | |
| 745 | +} | |
| 746 | + | |
| 747 | +/// The image the node fences its bridges with: `nft` and nothing else. | |
| 748 | +/// Pinned so the content key, and with it the tar in the bucket, is | |
| 749 | +/// stable across deployments. | |
| 750 | +const FENCE_DOCKERFILE: &str = "FROM alpine:3.20\nRUN apk add --no-cache nftables\n"; | |
| 751 | + | |
| 752 | +/// Build the fence image for `platform` and tag it by content, as | |
| 753 | +/// `resolve_image` does for an application image. | |
| 754 | +fn resolve_fence_image(platform: Option<&str>) -> anyhow::Result<String> { | |
| 755 | + let context = tempfile::tempdir().context("fence image build context")?; | |
| 756 | + std::fs::write(context.path().join("Dockerfile"), FENCE_DOCKERFILE) | |
| 757 | + .context("write fence Dockerfile")?; | |
| 758 | + resolve_image(context.path(), "Dockerfile", platform).context("build the celld-fence image") | |
| 759 | +} | |
| 760 | + | |
| 761 | +/// Save the image to the bucket under its content key unless it is there. | |
| 762 | +/// Saving by the reference writes the tag into the tar, so a node's load | |
| 763 | +/// holds the image under the same name. | |
| 764 | +async fn ensure_image_tar(bucket: &Bucket, image: &str) -> anyhow::Result<()> { | |
| 765 | + let key = crate::container::image_key(image); | |
| 766 | + if bucket.head(&key).await?.is_some() { | |
| 767 | + return Ok(()); | |
| 768 | + } | |
| 769 | + let output = Command::new(engine_cli()) | |
| 770 | + .args(["save", image]) | |
| 771 | + .stdin(std::process::Stdio::null()) | |
| 772 | + .output() | |
| 773 | + .context("save container image")?; | |
| 774 | + if !output.status.success() { | |
| 775 | + bail!( | |
| 776 | + "save container image failed:\n{}", | |
| 777 | + String::from_utf8_lossy(&output.stderr).trim_end() | |
| 778 | + ); | |
| 779 | + } | |
| 780 | + bucket.put(&key, output.stdout).await | |
| 781 | +} | |
| 782 | + | |
| 572 | 783 | pub async fn write(bucket: &Bucket, built: &Built) -> anyhow::Result<()> { |
| 573 | 784 | // Read every attachment before uploading immutable deployment objects. |
| 574 | 785 | // A competing consumer is a deploy refusal, so it must not leave a new |
| 575 | 786 | // version in the bucket that an operator can mistake for a published one. |
| 576 | 787 | let queue_attachments = prepare_queue_attachments(bucket, &built.manifest).await?; |
| 577 | 788 | |
| 789 | + // Images are fleet-wide and content-addressed like asset bodies, and | |
| 790 | + // they are what a node loads before a container class can start. | |
| 791 | + if built.upload_images { | |
| 792 | + for image in built.images.iter().chain(&built.fence_image) { | |
| 793 | + ensure_image_tar(bucket, image).await?; | |
| 794 | + } | |
| 795 | + } | |
| 578 | 796 | // Asset bodies are fleet-wide and content-addressed. Finish every body |
| 579 | 797 | // before publishing the deployment-local index or manifest so a reader |
| 580 | 798 | // can never observe a pointer whose assets are incomplete. |
| @@ -968,7 +1186,11 @@ | ||
| 968 | 1186 | ) |
| 969 | 1187 | } |
| 970 | 1188 | |
| 971 | -fn read_project(path: &Path, root: &Path) -> anyhow::Result<Project> { | |
| 1189 | +fn read_project( | |
| 1190 | + path: &Path, | |
| 1191 | + root: &Path, | |
| 1192 | + overrides: &BTreeMap<String, String>, | |
| 1193 | +) -> anyhow::Result<Project> { | |
| 972 | 1194 | let source = |
| 973 | 1195 | std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?; |
| 974 | 1196 | let config: Value = serde_json::from_str(&strip_jsonc(&source)) |
| @@ -1491,32 +1713,85 @@ | ||
| 1491 | 1713 | "bucket_name": bucket_name, |
| 1492 | 1714 | })); |
| 1493 | 1715 | } |
| 1494 | - let vars = match object.get("vars") { | |
| 1495 | - None => None, | |
| 1496 | - Some(Value::Object(vars)) => Some(vars), | |
| 1497 | - Some(_) => bail!("config `vars` must be an object"), | |
| 1716 | + // `worker_loaders` is how a Dynamic Workers project asks for a Worker | |
| 1717 | + // Loader. workerd declares the loaders in a `List(Binding)`, so a config | |
| 1718 | + // can name more than one, and each one holds its own cache of the Workers | |
| 1719 | + // it loaded. Two loaders are therefore two cache namespaces and not a | |
| 1720 | + // duplicate of one namespace, so celld binds every entry. The shared | |
| 1721 | + // binding-name check below refuses two entries that carry the same name. | |
| 1722 | + let worker_loaders = match object.get("worker_loaders") { | |
| 1723 | + None => &[][..], | |
| 1724 | + Some(Value::Array(loaders)) => loaders.as_slice(), | |
| 1725 | + Some(_) => bail!("config `worker_loaders` must be an array"), | |
| 1498 | 1726 | }; |
| 1499 | - let mut var_count = 0_usize; | |
| 1500 | - for (name, value) in vars.into_iter().flatten() { | |
| 1727 | + for loader in worker_loaders { | |
| 1728 | + let Value::Object(loader) = loader else { | |
| 1729 | + bail!("worker loader must be an object with a `binding` name"); | |
| 1730 | + }; | |
| 1731 | + let binding = match loader.get("binding") { | |
| 1732 | + None => bail!("worker loader has no `binding` name"), | |
| 1733 | + Some(Value::String(binding)) => binding.as_str(), | |
| 1734 | + Some(_) => bail!("worker loader `binding` must be a string"), | |
| 1735 | + }; | |
| 1736 | + if !valid_binding(binding) { | |
| 1737 | + bail!("invalid worker loader binding name: {binding:?}"); | |
| 1738 | + } | |
| 1739 | + // Cloudflare carries the per-loader Dynamic Workers options inside the | |
| 1740 | + // entry: `limits`, `tails`, and `allowExperimental`. celld honours none | |
| 1741 | + // of them, so accepting the key would deploy the project clean and drop | |
| 1742 | + // the option the author asked for. This follows the r2 `jurisdiction` | |
| 1743 | + // refusal above, and it is the config half of the gaps #836 tracks. | |
| 1744 | + for key in loader.keys() { | |
| 1745 | + if key != "binding" { | |
| 1746 | + bail!("worker loader {binding} sets `{key}`, which celld does not have"); | |
| 1747 | + } | |
| 1748 | + } | |
| 1749 | + bindings.push(json!({ | |
| 1750 | + "type": "worker_loader", | |
| 1751 | + "name": binding, | |
| 1752 | + })); | |
| 1753 | + } | |
| 1754 | + let mut vars = BTreeMap::new(); | |
| 1755 | + match object.get("vars") { | |
| 1756 | + None => {} | |
| 1757 | + Some(Value::Object(object)) => { | |
| 1758 | + for (name, value) in object { | |
| 1759 | + let value = value | |
| 1760 | + .as_str() | |
| 1761 | + .ok_or_else(|| anyhow!("var binding {name} must be a string"))?; | |
| 1762 | + vars.insert(name.as_str(), value); | |
| 1763 | + } | |
| 1764 | + } | |
| 1765 | + Some(_) => bail!("config `vars` must be an object"), | |
| 1766 | + } | |
| 1767 | + // An asset-only project has no Worker to hand a variable to, so a | |
| 1768 | + // `.dev.vars` beside it is residue, not a binding the guard below | |
| 1769 | + // should refuse in the config's name. | |
| 1770 | + let declared_vars = !vars.is_empty(); | |
| 1771 | + if main.is_some() { | |
| 1772 | + vars.extend( | |
| 1773 | + overrides | |
| 1774 | + .iter() | |
| 1775 | + .map(|(name, value)| (name.as_str(), value.as_str())), | |
| 1776 | + ); | |
| 1777 | + } | |
| 1778 | + for (name, value) in &vars { | |
| 1501 | 1779 | if !valid_binding(name) { |
| 1502 | 1780 | bail!("invalid var binding name: {name:?}"); |
| 1503 | 1781 | } |
| 1504 | - let value = value | |
| 1505 | - .as_str() | |
| 1506 | - .ok_or_else(|| anyhow!("var binding {name} must be a string"))?; | |
| 1507 | 1782 | bindings.push(json!({ |
| 1508 | 1783 | "type": "plain_text", |
| 1509 | 1784 | "name": name, |
| 1510 | 1785 | "text": value, |
| 1511 | 1786 | })); |
| 1512 | - var_count += 1; | |
| 1513 | 1787 | } |
| 1514 | 1788 | if main.is_none() |
| 1515 | 1789 | && (!do_classes.is_empty() |
| 1516 | 1790 | || !sqlite_classes.is_empty() |
| 1517 | 1791 | || service_count > 0 |
| 1518 | - || var_count > 0 | |
| 1519 | - || !r2_binding_names.is_empty()) | |
| 1792 | + || declared_vars | |
| 1793 | + || !r2_binding_names.is_empty() | |
| 1794 | + || !worker_loaders.is_empty()) | |
| 1520 | 1795 | { |
| 1521 | 1796 | bail!("an asset-only project cannot declare Worker bindings"); |
| 1522 | 1797 | } |
| @@ -1570,6 +1845,7 @@ | ||
| 1570 | 1845 | ); |
| 1571 | 1846 | } |
| 1572 | 1847 | |
| 1848 | + let containers = read_containers(object, &do_classes, &sqlite_classes)?; | |
| 1573 | 1849 | Ok(Project { |
| 1574 | 1850 | script_name, |
| 1575 | 1851 | no_bundle, |
| @@ -1584,9 +1860,122 @@ | ||
| 1584 | 1860 | has_queues: !queue_producers.is_empty() || !queue_consumers.is_empty(), |
| 1585 | 1861 | queue_consumers, |
| 1586 | 1862 | has_r2: !r2_buckets.is_empty(), |
| 1863 | + containers, | |
| 1587 | 1864 | }) |
| 1588 | 1865 | } |
| 1589 | 1866 | |
| 1867 | +/// The config's `containers[]`. Each entry attaches a container to one | |
| 1868 | +/// SQLite-backed Durable Object class of this Worker, which is what | |
| 1869 | +/// Cloudflare requires too. | |
| 1870 | +fn read_containers( | |
| 1871 | + object: &Map<String, Value>, | |
| 1872 | + do_classes: &[String], | |
| 1873 | + sqlite_classes: &[String], | |
| 1874 | +) -> anyhow::Result<Vec<ContainerDecl>> { | |
| 1875 | + let Some(value) = object.get("containers") else { | |
| 1876 | + return Ok(Vec::new()); | |
| 1877 | + }; | |
| 1878 | + let entries = value | |
| 1879 | + .as_array() | |
| 1880 | + .ok_or_else(|| anyhow!("config `containers` must be an array"))?; | |
| 1881 | + let mut declared: Vec<ContainerDecl> = Vec::new(); | |
| 1882 | + for (index, entry) in entries.iter().enumerate() { | |
| 1883 | + let entry = entry | |
| 1884 | + .as_object() | |
| 1885 | + .ok_or_else(|| anyhow!("config `containers[{index}]` must be an object"))?; | |
| 1886 | + if let Some(key) = entry.keys().find(|key| { | |
| 1887 | + !matches!( | |
| 1888 | + key.as_str(), | |
| 1889 | + "class_name" | "image" | "name" | "instance_type" | "max_instances" | "runtime" | |
| 1890 | + ) | |
| 1891 | + }) { | |
| 1892 | + bail!("config `containers[{index}]` declares `{key}`, which celld does not model"); | |
| 1893 | + } | |
| 1894 | + let class_name = entry | |
| 1895 | + .get("class_name") | |
| 1896 | + .and_then(Value::as_str) | |
| 1897 | + .filter(|class| !class.is_empty()) | |
| 1898 | + .ok_or_else(|| anyhow!("config `containers[{index}].class_name` must be a string"))?; | |
| 1899 | + if !do_classes.iter().any(|class| class == class_name) { | |
| 1900 | + bail!( | |
| 1901 | + "config `containers[{index}].class_name` {class_name:?} is not a Durable Object \ | |
| 1902 | + class of this Worker; declare it in `durable_objects.bindings`" | |
| 1903 | + ); | |
| 1904 | + } | |
| 1905 | + if !sqlite_classes.iter().any(|class| class == class_name) { | |
| 1906 | + bail!( | |
| 1907 | + "config `containers[{index}].class_name` {class_name:?} must be SQLite-backed; \ | |
| 1908 | + add it to `migrations[].new_sqlite_classes`" | |
| 1909 | + ); | |
| 1910 | + } | |
| 1911 | + if declared.iter().any(|decl| decl.class_name == class_name) { | |
| 1912 | + bail!("config `containers` names class {class_name:?} twice"); | |
| 1913 | + } | |
| 1914 | + let image = entry | |
| 1915 | + .get("image") | |
| 1916 | + .and_then(Value::as_str) | |
| 1917 | + .filter(|image| !image.is_empty()) | |
| 1918 | + .ok_or_else(|| anyhow!("config `containers[{index}].image` must be a string"))?; | |
| 1919 | + let name = entry | |
| 1920 | + .get("name") | |
| 1921 | + .map(|value| { | |
| 1922 | + value | |
| 1923 | + .as_str() | |
| 1924 | + .map(str::to_string) | |
| 1925 | + .ok_or_else(|| anyhow!("config `containers[{index}].name` must be a string")) | |
| 1926 | + }) | |
| 1927 | + .transpose()?; | |
| 1928 | + let instance_type = entry | |
| 1929 | + .get("instance_type") | |
| 1930 | + .map(|value| { | |
| 1931 | + let name = value.as_str().ok_or_else(|| { | |
| 1932 | + anyhow!("config `containers[{index}].instance_type` must be a string") | |
| 1933 | + })?; | |
| 1934 | + if crate::container::instance_resources(name).is_none() { | |
| 1935 | + bail!( | |
| 1936 | + "config `containers[{index}].instance_type` {name:?} is not an instance type" | |
| 1937 | + ); | |
| 1938 | + } | |
| 1939 | + Ok(name.to_string()) | |
| 1940 | + }) | |
| 1941 | + .transpose()?; | |
| 1942 | + let max_instances = entry | |
| 1943 | + .get("max_instances") | |
| 1944 | + .map(|value| { | |
| 1945 | + value.as_u64().ok_or_else(|| { | |
| 1946 | + anyhow!( | |
| 1947 | + "config `containers[{index}].max_instances` must be a non-negative integer" | |
| 1948 | + ) | |
| 1949 | + }) | |
| 1950 | + }) | |
| 1951 | + .transpose()?; | |
| 1952 | + let runtime = entry | |
| 1953 | + .get("runtime") | |
| 1954 | + .map(|value| { | |
| 1955 | + value | |
| 1956 | + .as_str() | |
| 1957 | + .filter(|runtime| !runtime.is_empty()) | |
| 1958 | + .map(str::to_string) | |
| 1959 | + .ok_or_else(|| { | |
| 1960 | + anyhow!( | |
| 1961 | + "config `containers[{index}].runtime` must be a non-empty string, \ | |
| 1962 | + the name of an OCI runtime the node's daemon has, such as `runsc`" | |
| 1963 | + ) | |
| 1964 | + }) | |
| 1965 | + }) | |
| 1966 | + .transpose()?; | |
| 1967 | + declared.push(ContainerDecl { | |
| 1968 | + class_name: class_name.to_string(), | |
| 1969 | + image: image.to_string(), | |
| 1970 | + name, | |
| 1971 | + instance_type, | |
| 1972 | + max_instances, | |
| 1973 | + runtime, | |
| 1974 | + }); | |
| 1975 | + } | |
| 1976 | + Ok(declared) | |
| 1977 | +} | |
| 1978 | + | |
| 1590 | 1979 | fn reject_queue_keys(value: &Value, accepted: &[&str], kind: &str) -> anyhow::Result<()> { |
| 1591 | 1980 | let object = value |
| 1592 | 1981 | .as_object() |
| @@ -2150,13 +2539,78 @@ | ||
| 2150 | 2539 | }) |
| 2151 | 2540 | } |
| 2152 | 2541 | |
| 2153 | -/// esbuild's outputs: the bundled entry module, and the wasm files its | |
| 2154 | -/// imports were resolved to (each under the name the rewritten import uses). | |
| 2542 | +/// The entry module and wasm files, keyed by their deployed module names. | |
| 2155 | 2543 | struct BundleOutput { |
| 2156 | 2544 | bundle: Vec<u8>, |
| 2157 | 2545 | wasm: Vec<(String, Vec<u8>)>, |
| 2158 | 2546 | } |
| 2159 | 2547 | |
| 2548 | +/// Wrangler's default unbundled WASM rule discovers `**/*.wasm` and | |
| 2549 | +/// `**/*.wasm?module` below the entry directory. Discover files rather than | |
| 2550 | +/// parsing JavaScript or running esbuild: the caller's toolchain owns the | |
| 2551 | +/// source and its import spellings. | |
| 2552 | +fn collect_unbundled_wasm( | |
| 2553 | + directory: &Path, | |
| 2554 | + relative: &str, | |
| 2555 | + entry_path: &Path, | |
| 2556 | + wasm: &mut Vec<(String, Vec<u8>)>, | |
| 2557 | +) -> anyhow::Result<()> { | |
| 2558 | + for entry in std::fs::read_dir(directory) | |
| 2559 | + .with_context(|| format!("read wasm directory {}", directory.display()))? | |
| 2560 | + { | |
| 2561 | + let entry = entry?; | |
| 2562 | + let file_type = entry.file_type()?; | |
| 2563 | + let path = entry.path(); | |
| 2564 | + // The entry already occupies the main-module slot. If it has a WASM | |
| 2565 | + // suffix, collecting it again creates two modules from one file. | |
| 2566 | + if path == entry_path { | |
| 2567 | + continue; | |
| 2568 | + } | |
| 2569 | + let is_wasm = path | |
| 2570 | + .extension() | |
| 2571 | + .is_some_and(|extension| extension == "wasm") | |
| 2572 | + || path | |
| 2573 | + .file_name() | |
| 2574 | + .and_then(|name| name.to_str()) | |
| 2575 | + .is_some_and(|name| name.ends_with(".wasm?module")); | |
| 2576 | + // Never follow directory symlinks or read special files. Unrelated | |
| 2577 | + // files do not participate in module discovery. | |
| 2578 | + if !file_type.is_dir() && !is_wasm { | |
| 2579 | + continue; | |
| 2580 | + } | |
| 2581 | + let name = entry.file_name().into_string().map_err(|_| { | |
| 2582 | + anyhow!( | |
| 2583 | + "wasm path contains a non-UTF-8 name under {}", | |
| 2584 | + directory.display() | |
| 2585 | + ) | |
| 2586 | + })?; | |
| 2587 | + // Wrangler excludes its state tree. The other exclusions prevent a | |
| 2588 | + // project-root entry from turning repository or celld state into an | |
| 2589 | + // application module when celld performs the same recursive scan. | |
| 2590 | + if file_type.is_dir() && matches!(name.as_str(), ".git" | ".celld" | ".wrangler") { | |
| 2591 | + continue; | |
| 2592 | + } | |
| 2593 | + if name.contains(['\\', '\0']) { | |
| 2594 | + bail!("invalid wasm path component: {name:?}"); | |
| 2595 | + } | |
| 2596 | + let name = if relative.is_empty() { | |
| 2597 | + name | |
| 2598 | + } else { | |
| 2599 | + format!("{relative}/{name}") | |
| 2600 | + }; | |
| 2601 | + if file_type.is_dir() { | |
| 2602 | + collect_unbundled_wasm(&path, &name, entry_path, wasm)?; | |
| 2603 | + } else if file_type.is_file() { | |
| 2604 | + let bytes = std::fs::read(&path) | |
| 2605 | + .with_context(|| format!("read wasm module {}", path.display()))?; | |
| 2606 | + wasm.push((name, bytes)); | |
| 2607 | + } else { | |
| 2608 | + bail!("wasm module {} is not a regular file", path.display()); | |
| 2609 | + } | |
| 2610 | + } | |
| 2611 | + Ok(()) | |
| 2612 | +} | |
| 2613 | + | |
| 2160 | 2614 | fn run_esbuild(root: &Path, entry: &str) -> anyhow::Result<BundleOutput> { |
| 2161 | 2615 | // node: builtins stay external. Wrangler polyfills them with unenv; celld |
| 2162 | 2616 | // implements the workerd `nodejs_compat` subset itself, so the runtime |
| @@ -2301,3 +2755,8 @@ | ||
| 2301 | 2755 | } |
| 2302 | 2756 | out |
| 2303 | 2757 | } |
| 2758 | + | |
| 2759 | +#[cfg(all(test, celld_internal_tests))] | |
| 2760 | +mod deploy_contract { | |
| 2761 | + include!(env!("CELLD_INTERNAL_DEPLOY_TESTS")); | |
| 2762 | +} |
modifiedcrates/celld/dev.rs+36−1View file
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | use notify::{RecursiveMode, Watcher as _}; |
| 14 | 14 | use nu_ansi_term::{Color, Style}; |
| 15 | 15 | use sha2::{Digest as _, Sha256}; |
| 16 | +use std::collections::BTreeMap; | |
| 16 | 17 | use std::io::IsTerminal as _; |
| 17 | 18 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; |
| 18 | 19 | use std::path::{Path, PathBuf}; |
| @@ -338,6 +339,8 @@ | ||
| 338 | 339 | that state across a restart. A configuration change does not migrate the\n\ |
| 339 | 340 | state, so a cell can keep a value that the new configuration rejects. Use\n\ |
| 340 | 341 | --clean to start from an empty local state.\n\n\ |
| 342 | +A .dev.vars file beside the config supplies Worker variables in dotenv form,\n\ | |
| 343 | +as for wrangler dev. Its entries override the vars of the config.\n\n\ | |
| 341 | 344 | OPTIONS:\n --host IP Worker listener host (default: 127.0.0.1)\n --port PORT Worker listener port (default: {DEFAULT_PORT})\n --clean Delete PROJECT/.celld/dev before the server starts\n --logs Show the node warning and information logs\n --no-watch Do not rebuild when a project file changes\n --watch-ignore PATTERN Ignore a project-relative glob; repeat as needed\n -h, --help Show this help" |
| 342 | 345 | ), |
| 343 | 346 | ) |
| @@ -478,6 +481,36 @@ | ||
| 478 | 481 | Ok(Store { database }) |
| 479 | 482 | } |
| 480 | 483 | |
| 484 | +/// The Worker variables of `.dev.vars` beside the config, in the dotenv form | |
| 485 | +/// `wrangler dev` reads. They override the `vars` of the config. Only | |
| 486 | +/// `celld dev` reads the file, so a local credential cannot reach a fleet. | |
| 487 | +#[allow(clippy::disallowed_methods)] // The project is on the operator's host filesystem. | |
| 488 | +fn read_dev_vars(config: &Path) -> anyhow::Result<BTreeMap<String, String>> { | |
| 489 | + let path = config.with_file_name(".dev.vars"); | |
| 490 | + if !path.exists() { | |
| 491 | + return Ok(BTreeMap::new()); | |
| 492 | + } | |
| 493 | + let contents = | |
| 494 | + std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?; | |
| 495 | + Ok(contents | |
| 496 | + .lines() | |
| 497 | + .map(str::trim) | |
| 498 | + .filter(|line| !line.is_empty() && !line.starts_with('#')) | |
| 499 | + .filter_map(|line| line.split_once('=')) | |
| 500 | + .map(|(name, value)| (name.trim(), value.trim())) | |
| 501 | + .filter(|(name, _)| !name.is_empty()) | |
| 502 | + .map(|(name, value)| { | |
| 503 | + // One matched pair of quotes comes off; a lone quote is part of | |
| 504 | + // the value, as in dotenv, so a secret that ends in one survives. | |
| 505 | + let value = ['"', '\''] | |
| 506 | + .into_iter() | |
| 507 | + .find_map(|quote| value.strip_prefix(quote)?.strip_suffix(quote)) | |
| 508 | + .unwrap_or(value); | |
| 509 | + (name.to_string(), value.to_string()) | |
| 510 | + }) | |
| 511 | + .collect()) | |
| 512 | +} | |
| 513 | + | |
| 481 | 514 | async fn deploy_project(config: &Path, store: &Store, logs: bool) -> anyhow::Result<()> { |
| 482 | 515 | let bucket = open_local_bucket(&store.database)?; |
| 483 | 516 | let built = deploy::build(&deploy::Options { |
| @@ -487,10 +520,13 @@ | ||
| 487 | 520 | region: None, |
| 488 | 521 | dry_run: false, |
| 489 | 522 | json: false, |
| 523 | + vars: read_dev_vars(config)?, | |
| 524 | + local_images: true, | |
| 490 | 525 | })?; |
| 491 | 526 | if logs { |
| 492 | 527 | built.report(); |
| 493 | 528 | } |
| 529 | + crate::wake_format::ensure_ready(&bucket).await?; | |
| 494 | 530 | deploy::write(&bucket, &built).await |
| 495 | 531 | } |
| 496 | 532 | |
| @@ -597,7 +633,6 @@ | ||
| 597 | 633 | "CELLD_BUCKET", |
| 598 | 634 | "CELLD_CLOUD", |
| 599 | 635 | "CELLD_INTERNAL_ADDR", |
| 600 | - "CELLD_STORAGE_PROBE", | |
| 601 | 636 | "CELLD_TEST_BUCKET", |
| 602 | 637 | "CELLD_TRUST_FORWARDED_HEADERS", |
| 603 | 638 | "CELLD_UNSAFE_PUBLIC_ADVERTISE", |
addedcrates/celld/docker.rs+267−0View file
| @@ -1,0 +1,267 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! A minimal Docker Engine API client over the daemon's unix socket. | |
| 4 | +//! | |
| 5 | +//! One HTTP/1.1 connection per call: the daemon is local, the calls are | |
| 6 | +//! rare (a container starts once), and a pooled client would have to be | |
| 7 | +//! taught about hijacked exec streams and long-polled waits anyway. Podman | |
| 8 | +//! serves the same API on its own socket, so nothing here names Docker | |
| 9 | +//! beyond the default socket path. | |
| 10 | + | |
| 11 | +use anyhow::{anyhow, Context}; | |
| 12 | +use bytes::Bytes; | |
| 13 | +use http_body_util::{BodyExt, Full}; | |
| 14 | +use hyper::body::Incoming; | |
| 15 | +use hyper::header::{CONNECTION, CONTENT_TYPE, HOST, UPGRADE}; | |
| 16 | +use hyper::{Request, Response, StatusCode}; | |
| 17 | +use hyper_util::rt::TokioIo; | |
| 18 | +use std::path::{Path, PathBuf}; | |
| 19 | +use tokio::io::{AsyncRead, AsyncWrite}; | |
| 20 | +use tokio::net::UnixStream; | |
| 21 | + | |
| 22 | +/// Unversioned paths: the daemon answers with its newest API, and every | |
| 23 | +/// call here uses fields that have been stable since API 1.24. A pinned | |
| 24 | +/// version is refused by a daemon whose minimum moved past it, which Docker | |
| 25 | +/// 29 did for 1.41. | |
| 26 | +const API: &str = ""; | |
| 27 | + | |
| 28 | +#[derive(Clone, Debug)] | |
| 29 | +pub struct Docker { | |
| 30 | + socket: PathBuf, | |
| 31 | +} | |
| 32 | + | |
| 33 | +/// A raw bidirectional stream the daemon hijacked for an exec or attach. | |
| 34 | +pub trait Stream: AsyncRead + AsyncWrite + Send + Unpin {} | |
| 35 | +impl<T: AsyncRead + AsyncWrite + Send + Unpin> Stream for T {} | |
| 36 | + | |
| 37 | +pub struct Reply { | |
| 38 | + pub status: StatusCode, | |
| 39 | + pub body: Bytes, | |
| 40 | +} | |
| 41 | + | |
| 42 | +impl Reply { | |
| 43 | + pub fn json(&self) -> anyhow::Result<serde_json::Value> { | |
| 44 | + serde_json::from_slice(&self.body).context("decode Docker response") | |
| 45 | + } | |
| 46 | + | |
| 47 | + /// The daemon's `message` field, or the raw body. | |
| 48 | + pub fn message(&self) -> String { | |
| 49 | + self.json() | |
| 50 | + .ok() | |
| 51 | + .and_then(|value| value.get("message")?.as_str().map(str::to_string)) | |
| 52 | + .unwrap_or_else(|| String::from_utf8_lossy(&self.body).into_owned()) | |
| 53 | + } | |
| 54 | +} | |
| 55 | + | |
| 56 | +impl Docker { | |
| 57 | + pub fn new(socket: impl Into<PathBuf>) -> Self { | |
| 58 | + Self { | |
| 59 | + socket: socket.into(), | |
| 60 | + } | |
| 61 | + } | |
| 62 | + | |
| 63 | + /// The daemon socket: `DOCKER_HOST` when it names a unix socket, else | |
| 64 | + /// the first of the well-known paths that exists. Docker Desktop and | |
| 65 | + /// OrbStack put theirs under the home directory; Linux under `/var/run`. | |
| 66 | + pub fn discover() -> Option<Self> { | |
| 67 | + if let Ok(host) = std::env::var("DOCKER_HOST") { | |
| 68 | + let path = host.strip_prefix("unix://")?; | |
| 69 | + return Some(Self::new(path)); | |
| 70 | + } | |
| 71 | + let home = std::env::var_os("HOME").map(PathBuf::from); | |
| 72 | + let candidates = [ | |
| 73 | + Some(PathBuf::from("/var/run/docker.sock")), | |
| 74 | + home.as_ref() | |
| 75 | + .map(|home| home.join(".orbstack/run/docker.sock")), | |
| 76 | + home.as_ref() | |
| 77 | + .map(|home| home.join(".docker/run/docker.sock")), | |
| 78 | + Some(PathBuf::from("/run/podman/podman.sock")), | |
| 79 | + ]; | |
| 80 | + // A connect, not a stat: the socket is a daemon's, not node | |
| 81 | + // storage, and a stale socket file without a daemon behind it must | |
| 82 | + // not win over the next candidate. | |
| 83 | + candidates | |
| 84 | + .into_iter() | |
| 85 | + .flatten() | |
| 86 | + .find(|path| std::os::unix::net::UnixStream::connect(path).is_ok()) | |
| 87 | + .map(Self::new) | |
| 88 | + } | |
| 89 | + | |
| 90 | + pub fn socket(&self) -> &Path { | |
| 91 | + &self.socket | |
| 92 | + } | |
| 93 | + | |
| 94 | + async fn connect(&self) -> anyhow::Result<UnixStream> { | |
| 95 | + UnixStream::connect(&self.socket).await.with_context(|| { | |
| 96 | + format!( | |
| 97 | + "connect to the container engine at {}", | |
| 98 | + self.socket.display() | |
| 99 | + ) | |
| 100 | + }) | |
| 101 | + } | |
| 102 | + | |
| 103 | + fn request( | |
| 104 | + &self, | |
| 105 | + method: &str, | |
| 106 | + path: &str, | |
| 107 | + body: Bytes, | |
| 108 | + ) -> anyhow::Result<Request<Full<Bytes>>> { | |
| 109 | + Request::builder() | |
| 110 | + .method(method) | |
| 111 | + .uri(format!("{API}{path}")) | |
| 112 | + .header(HOST, "docker") | |
| 113 | + .header(CONTENT_TYPE, "application/json") | |
| 114 | + .body(Full::new(body)) | |
| 115 | + .context("build Docker request") | |
| 116 | + } | |
| 117 | + | |
| 118 | + async fn send( | |
| 119 | + &self, | |
| 120 | + request: Request<Full<Bytes>>, | |
| 121 | + ) -> anyhow::Result<( | |
| 122 | + Response<Incoming>, | |
| 123 | + hyper::client::conn::http1::SendRequest<Full<Bytes>>, | |
| 124 | + )> { | |
| 125 | + let stream = self.connect().await?; | |
| 126 | + let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) | |
| 127 | + .await | |
| 128 | + .context("HTTP handshake with the container engine")?; | |
| 129 | + drive(connection); | |
| 130 | + let response = sender | |
| 131 | + .send_request(request) | |
| 132 | + .await | |
| 133 | + .context("send request to the container engine")?; | |
| 134 | + Ok((response, sender)) | |
| 135 | + } | |
| 136 | + | |
| 137 | + /// One call, whole body. A long-polled `wait` is fine here: the body | |
| 138 | + /// arrives only when the container exits. | |
| 139 | + pub async fn call( | |
| 140 | + &self, | |
| 141 | + method: &str, | |
| 142 | + path: &str, | |
| 143 | + body: Option<serde_json::Value>, | |
| 144 | + ) -> anyhow::Result<Reply> { | |
| 145 | + let body = match body { | |
| 146 | + Some(value) => Bytes::from(serde_json::to_vec(&value)?), | |
| 147 | + None => Bytes::new(), | |
| 148 | + }; | |
| 149 | + let (response, _sender) = self.send(self.request(method, path, body)?).await?; | |
| 150 | + let status = response.status(); | |
| 151 | + let body = response | |
| 152 | + .into_body() | |
| 153 | + .collect() | |
| 154 | + .await | |
| 155 | + .context("read Docker response")? | |
| 156 | + .to_bytes(); | |
| 157 | + Ok(Reply { status, body }) | |
| 158 | + } | |
| 159 | + | |
| 160 | + /// `call`, failing on any non-success status with the daemon's message. | |
| 161 | + pub async fn expect( | |
| 162 | + &self, | |
| 163 | + method: &str, | |
| 164 | + path: &str, | |
| 165 | + body: Option<serde_json::Value>, | |
| 166 | + what: &str, | |
| 167 | + ) -> anyhow::Result<Reply> { | |
| 168 | + let reply = self.call(method, path, body).await?; | |
| 169 | + if !reply.status.is_success() { | |
| 170 | + return Err(anyhow!( | |
| 171 | + "{what} failed with [{}] {}", | |
| 172 | + reply.status.as_u16(), | |
| 173 | + reply.message() | |
| 174 | + )); | |
| 175 | + } | |
| 176 | + Ok(reply) | |
| 177 | + } | |
| 178 | + | |
| 179 | + /// Upload a request body that is not JSON: `POST /images/load` takes a | |
| 180 | + /// tar. The whole body is in memory, which bounds an image at what a | |
| 181 | + /// node can hold; a streaming upload is the next step when an image | |
| 182 | + /// outgrows that. | |
| 183 | + pub async fn post_octets(&self, path: &str, body: Bytes, what: &str) -> anyhow::Result<Reply> { | |
| 184 | + let request = Request::builder() | |
| 185 | + .method("POST") | |
| 186 | + .uri(format!("{API}{path}")) | |
| 187 | + .header(HOST, "docker") | |
| 188 | + .header(CONTENT_TYPE, "application/x-tar") | |
| 189 | + .body(Full::new(body)) | |
| 190 | + .context("build Docker request")?; | |
| 191 | + let (response, _sender) = self.send(request).await?; | |
| 192 | + let status = response.status(); | |
| 193 | + let body = response | |
| 194 | + .into_body() | |
| 195 | + .collect() | |
| 196 | + .await | |
| 197 | + .context("read Docker response")? | |
| 198 | + .to_bytes(); | |
| 199 | + let reply = Reply { status, body }; | |
| 200 | + if !reply.status.is_success() { | |
| 201 | + return Err(anyhow!( | |
| 202 | + "{what} failed with [{}] {}", | |
| 203 | + reply.status.as_u16(), | |
| 204 | + reply.message() | |
| 205 | + )); | |
| 206 | + } | |
| 207 | + Ok(reply) | |
| 208 | + } | |
| 209 | + | |
| 210 | + /// `POST /exec/{id}/start` with `Upgrade: tcp`: the daemon answers 101 | |
| 211 | + /// and the connection becomes the process's stdin and its multiplexed | |
| 212 | + /// stdout/stderr. The returned stream is that connection. | |
| 213 | + pub async fn hijack( | |
| 214 | + &self, | |
| 215 | + path: &str, | |
| 216 | + body: serde_json::Value, | |
| 217 | + ) -> anyhow::Result<Box<dyn Stream>> { | |
| 218 | + let request = Request::builder() | |
| 219 | + .method("POST") | |
| 220 | + .uri(format!("{API}{path}")) | |
| 221 | + .header(HOST, "docker") | |
| 222 | + .header(CONTENT_TYPE, "application/json") | |
| 223 | + .header(CONNECTION, "Upgrade") | |
| 224 | + .header(UPGRADE, "tcp") | |
| 225 | + .body(Full::new(Bytes::from(serde_json::to_vec(&body)?))) | |
| 226 | + .context("build Docker request")?; | |
| 227 | + let (mut response, _sender) = self.send(request).await?; | |
| 228 | + if response.status() != StatusCode::SWITCHING_PROTOCOLS { | |
| 229 | + let status = response.status(); | |
| 230 | + let body = response | |
| 231 | + .into_body() | |
| 232 | + .collect() | |
| 233 | + .await | |
| 234 | + .map(|body| body.to_bytes()) | |
| 235 | + .unwrap_or_default(); | |
| 236 | + let reply = Reply { status, body }; | |
| 237 | + return Err(anyhow!( | |
| 238 | + "exec start failed with [{}] {}", | |
| 239 | + status.as_u16(), | |
| 240 | + reply.message() | |
| 241 | + )); | |
| 242 | + } | |
| 243 | + let upgraded = hyper::upgrade::on(&mut response) | |
| 244 | + .await | |
| 245 | + .context("upgrade the exec connection")?; | |
| 246 | + Ok(Box::new(TokioIo::new(upgraded))) | |
| 247 | + } | |
| 248 | +} | |
| 249 | + | |
| 250 | +/// Poll the connection to completion. The daemon socket is outside the | |
| 251 | +/// execution boundary: no engine decision depends on when the daemon | |
| 252 | +/// answers, which is why the ambient runtime drives it, as `ws_client` | |
| 253 | +/// drives its handshakes. | |
| 254 | +#[allow(clippy::disallowed_methods)] | |
| 255 | +fn drive(connection: hyper::client::conn::http1::Connection<TokioIo<UnixStream>, Full<Bytes>>) { | |
| 256 | + tokio::spawn(async move { | |
| 257 | + let _ = connection.with_upgrades().await; | |
| 258 | + }); | |
| 259 | +} | |
| 260 | + | |
| 261 | +/// Parse one frame header of Docker's multiplexed stream: one byte of | |
| 262 | +/// stream id (1 stdout, 2 stderr), three reserved, four of big-endian | |
| 263 | +/// length. | |
| 264 | +pub fn frame_header(header: &[u8; 8]) -> (u8, usize) { | |
| 265 | + let length = u32::from_be_bytes([header[4], header[5], header[6], header[7]]) as usize; | |
| 266 | + (header[0], length) | |
| 267 | +} |
modifiedcrates/celld/env_vars.rs+196−47View file
| @@ -9,42 +9,213 @@ | ||
| 9 | 9 | use anyhow::{anyhow, bail}; |
| 10 | 10 | |
| 11 | 11 | pub const DEFAULT_SHUTDOWN_TOTAL_MS: u64 = 40_000; |
| 12 | -pub const DEFAULT_DRAIN_TOKEN_WAIT_MS: u64 = 30_000; | |
| 13 | -pub const MAX_DRAIN_TOKEN_WAIT_NUMERATOR: u64 = 3; | |
| 14 | -pub const MAX_DRAIN_TOKEN_WAIT_DENOMINATOR: u64 = 4; | |
| 15 | - | |
| 16 | -/// Calculate the largest drain-token wait that preserves the shutdown work | |
| 17 | -/// share. The split operations avoid overflow for a `u64` process bound. | |
| 18 | -pub const fn maximum_drain_token_wait_ms(total_ms: u64) -> u64 { | |
| 19 | - (total_ms / MAX_DRAIN_TOKEN_WAIT_DENOMINATOR) * MAX_DRAIN_TOKEN_WAIT_NUMERATOR | |
| 20 | - + (total_ms % MAX_DRAIN_TOKEN_WAIT_DENOMINATOR) * MAX_DRAIN_TOKEN_WAIT_NUMERATOR | |
| 21 | - / MAX_DRAIN_TOKEN_WAIT_DENOMINATOR | |
| 22 | -} | |
| 23 | - | |
| 24 | -const _: () = | |
| 25 | - assert!(DEFAULT_DRAIN_TOKEN_WAIT_MS == maximum_drain_token_wait_ms(DEFAULT_SHUTDOWN_TOTAL_MS)); | |
| 26 | - | |
| 27 | -/// The two shutdown values whose relationship controls whether handoff work | |
| 28 | -/// can start after the drain-token wait. | |
| 12 | +/// One process stop budget and the internal waits derived from it. | |
| 13 | +/// The absolute deadline also bounds progress extensions, so neither wait | |
| 14 | +/// grants time beyond the supervisor-facing process budget. | |
| 29 | 15 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 30 | 16 | pub struct ShutdownTiming { |
| 31 | 17 | pub total_ms: u64, |
| 32 | 18 | pub drain_token_wait_ms: u64, |
| 19 | + pub drain_no_progress_ms: u64, | |
| 33 | 20 | } |
| 34 | 21 | |
| 22 | +impl ShutdownTiming { | |
| 23 | + fn from_total_ms(total_ms: u64) -> Self { | |
| 24 | + // Preserve the 30-second token wait and 25-second no-progress window | |
| 25 | + // at the default 40-second bound. Derive both when that bound changes: | |
| 26 | + // independent defaults made a shorter supervisor grace fail startup. | |
| 27 | + // Split the arithmetic so even the largest accepted u64 cannot wrap. | |
| 28 | + let drain_token_wait_ms = (total_ms / 4) * 3 + (total_ms % 4) * 3 / 4; | |
| 29 | + let drain_no_progress_ms = ((total_ms / 8) * 5 + (total_ms % 8) * 5 / 8).max(1); | |
| 30 | + Self { | |
| 31 | + total_ms, | |
| 32 | + drain_token_wait_ms, | |
| 33 | + drain_no_progress_ms, | |
| 34 | + } | |
| 35 | + } | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// A variable celld no longer reads, and the sentence that names what an | |
| 39 | +/// operator must write instead. | |
| 40 | +/// | |
| 41 | +/// The lists below enumerate the names celld knows, so a name that is not on | |
| 42 | +/// one of them is never looked at and never reported. That is correct for a | |
| 43 | +/// name celld never had, but wrong for one it removed: the operator set the | |
| 44 | +/// removed name on purpose, and the behaviour it bought is gone. A node whose | |
| 45 | +/// unit file still carries the name would boot clean, log nothing, and serve a | |
| 46 | +/// deployment that no longer has the binding, so the defect would surface as a | |
| 47 | +/// `TypeError` in a request handler on a node the operator believes they just | |
| 48 | +/// configured. Refusing the boot moves that failure to the moment the operator | |
| 49 | +/// can still read the unit file. | |
| 50 | +struct Removed { | |
| 51 | + name: &'static str, | |
| 52 | + /// What the operator must write in place of the line they delete. | |
| 53 | + replacement: &'static str, | |
| 54 | + /// Whether the removed reader ignored an empty value. Only a value that | |
| 55 | + /// once changed the node is stale, so this decides whether `NAME=` is a | |
| 56 | + /// line to delete or a line that never did anything. It is a property of | |
| 57 | + /// the reader that went away, so each entry must state it for itself: a | |
| 58 | + /// removed variable whose reader treated `NAME=` as meaningful sets | |
| 59 | + /// `false`, and an operator who templated it to an empty string then still | |
| 60 | + /// gets the refusal they need. | |
| 61 | + empty_was_inert: bool, | |
| 62 | +} | |
| 63 | + | |
| 64 | +const REMOVED: &[Removed] = &[ | |
| 65 | + Removed { | |
| 66 | + name: "CELLD_TEST_OTEL_SWEEP_MS", | |
| 67 | + replacement: "remove this setting; celld manages the telemetry retention cadence", | |
| 68 | + empty_was_inert: false, | |
| 69 | + }, | |
| 70 | + Removed { | |
| 71 | + name: "CELLD_OTEL_SINK", | |
| 72 | + replacement: "set CELLD_OTEL=1 for the fleet bucket or CELLD_OTEL=<collector URL> for OTLP", | |
| 73 | + empty_was_inert: false, | |
| 74 | + }, | |
| 75 | + Removed { | |
| 76 | + name: "CELLD_AI_BINDING", | |
| 77 | + replacement: "remove this setting; call the AI provider from application code", | |
| 78 | + empty_was_inert: false, | |
| 79 | + }, | |
| 80 | + Removed { | |
| 81 | + name: "CELLD_AI_URL", | |
| 82 | + replacement: "remove this setting; call the AI provider from application code", | |
| 83 | + empty_was_inert: false, | |
| 84 | + }, | |
| 85 | + Removed { | |
| 86 | + name: "CELLD_PACED_HANDOFF", | |
| 87 | + replacement: | |
| 88 | + "remove this setting; celld hands off ownership within CELLD_SHUTDOWN_TOTAL_MS", | |
| 89 | + empty_was_inert: false, | |
| 90 | + }, | |
| 91 | + Removed { | |
| 92 | + name: "CELLD_LOG_GROUP_COMMIT_MS", | |
| 93 | + replacement: "remove this setting; celld uses its built-in Queue batching policy", | |
| 94 | + empty_was_inert: false, | |
| 95 | + }, | |
| 96 | + Removed { | |
| 97 | + name: "CELLD_QUEUE_PRODUCER_GROUP_MS", | |
| 98 | + replacement: "remove this setting; celld uses its built-in Queue batching policy", | |
| 99 | + empty_was_inert: false, | |
| 100 | + }, | |
| 101 | + Removed { | |
| 102 | + name: "CELLD_LOG_BUNDLE", | |
| 103 | + replacement: "remove this setting; fleet durability uses bundled tiering", | |
| 104 | + empty_was_inert: false, | |
| 105 | + }, | |
| 106 | + Removed { | |
| 107 | + name: "CELLD_PRESENCE_SHADOW", | |
| 108 | + replacement: | |
| 109 | + "remove this setting; managed presence no longer compares a shadow lease report", | |
| 110 | + empty_was_inert: false, | |
| 111 | + }, | |
| 112 | + Removed { | |
| 113 | + name: "CELLD_STORAGE_PROBE", | |
| 114 | + replacement: "remove this setting; celld checks the storage contract before serving", | |
| 115 | + empty_was_inert: false, | |
| 116 | + }, | |
| 117 | + Removed { | |
| 118 | + name: "CELLD_EVICTIONS", | |
| 119 | + replacement: "remove this setting; celld uses its built-in scheduling limits", | |
| 120 | + empty_was_inert: false, | |
| 121 | + }, | |
| 122 | + Removed { | |
| 123 | + name: "CELLD_LOG_CAPTURE_WORKERS", | |
| 124 | + replacement: "remove this setting; celld uses its built-in scheduling limits", | |
| 125 | + empty_was_inert: false, | |
| 126 | + }, | |
| 127 | + Removed { | |
| 128 | + name: "CELLD_REBALANCE_BATCH_CELLS", | |
| 129 | + replacement: "remove this setting; celld uses its built-in scheduling limits", | |
| 130 | + empty_was_inert: false, | |
| 131 | + }, | |
| 132 | + Removed { | |
| 133 | + name: "CELLD_CLOUD_RESTART_ON_DEPLOY", | |
| 134 | + replacement: "remove this setting; managed deployments are adopted in place", | |
| 135 | + empty_was_inert: false, | |
| 136 | + }, | |
| 137 | + Removed { | |
| 138 | + name: "CELLD_OUTPUT_GATE", | |
| 139 | + replacement: "remove this setting; celld always waits for durability proof", | |
| 140 | + empty_was_inert: false, | |
| 141 | + }, | |
| 142 | + Removed { | |
| 143 | + name: "CELLD_DRAIN_TOKEN_WAIT_MS", | |
| 144 | + replacement: "set only CELLD_SHUTDOWN_TOTAL_MS; celld derives the drain-token wait", | |
| 145 | + // Zero disabled the token wait, and an empty value failed parsing. | |
| 146 | + empty_was_inert: false, | |
| 147 | + }, | |
| 148 | + Removed { | |
| 149 | + name: "CELLD_SHUTDOWN_DRAIN_MS", | |
| 150 | + replacement: | |
| 151 | + "set only CELLD_SHUTDOWN_TOTAL_MS; celld derives the handoff no-progress interval", | |
| 152 | + empty_was_inert: false, | |
| 153 | + }, | |
| 154 | + Removed { | |
| 155 | + name: "CELLD_MAX_LOADED_WORKERS", | |
| 156 | + replacement: "remove this setting; celld manages Dynamic Worker admission", | |
| 157 | + // Even an empty value failed in the old typed reader. Refuse it rather | |
| 158 | + // than silently changing the operator's configured admission policy. | |
| 159 | + empty_was_inert: false, | |
| 160 | + }, | |
| 161 | + Removed { | |
| 162 | + name: "CELLD_WORKER_LOADER", | |
| 163 | + replacement: "declare `worker_loaders` in the project config", | |
| 164 | + // The reader this replaced was | |
| 165 | + // `var("CELLD_WORKER_LOADER").ok().filter(|name| !name.is_empty())`, so | |
| 166 | + // an empty value never bound a loader. A deployment system that | |
| 167 | + // templates every known name to an empty string must not lose an | |
| 168 | + // upgrade on a node that never used the feature. | |
| 169 | + empty_was_inert: true, | |
| 170 | + }, | |
| 171 | + Removed { | |
| 172 | + name: "CELLD_VARS_FILE", | |
| 173 | + replacement: "set `vars` in the Wrangler config, or `.dev.vars` for `celld dev`", | |
| 174 | + // The former reader used the path verbatim, so `CELLD_VARS_FILE=` | |
| 175 | + // selected an empty path and failed instead of doing nothing. An | |
| 176 | + // operator must therefore delete the empty setting. | |
| 177 | + empty_was_inert: false, | |
| 178 | + }, | |
| 179 | +]; | |
| 180 | + | |
| 181 | +/// The removed `CELLD_VAR_<NAME>` family. It is a prefix and not a name, so | |
| 182 | +/// the table above cannot hold it: celld never knew which names an operator | |
| 183 | +/// used. A node started with any of them would run with no override at all, | |
| 184 | +/// which reads inside a Worker as a missing secret with nothing in the log. | |
| 185 | +const REMOVED_PREFIX: (&str, &str) = ( | |
| 186 | + "CELLD_VAR_", | |
| 187 | + "set `vars` in the Wrangler config, or `.dev.vars` for `celld dev`", | |
| 188 | +); | |
| 189 | + | |
| 35 | 190 | /// Validate every typed production variable before the runtime starts. |
| 36 | 191 | /// |
| 37 | 192 | /// Some consumers cache a value or read it from a synchronous callback, so |
| 38 | 193 | /// they cannot return a configuration error at the point of use. This pass |
| 39 | 194 | /// makes those reads infallible without giving malformed values a default. |
| 40 | 195 | pub fn validate() -> anyhow::Result<()> { |
| 196 | + // Each entry carries its own empty-value rule, because whether `NAME=` was | |
| 197 | + // inert is a property of the reader that went away and not of removal. | |
| 198 | + for removed in REMOVED { | |
| 199 | + let Some(value) = std::env::var_os(removed.name) else { | |
| 200 | + continue; | |
| 201 | + }; | |
| 202 | + if removed.empty_was_inert && value.is_empty() { | |
| 203 | + continue; | |
| 204 | + } | |
| 205 | + bail!("{} is removed; {}", removed.name, removed.replacement); | |
| 206 | + } | |
| 207 | + let (prefix, replacement) = REMOVED_PREFIX; | |
| 208 | + if let Some(name) = std::env::vars_os().find_map(|(name, _)| { | |
| 209 | + let name = name.to_string_lossy().into_owned(); | |
| 210 | + name.starts_with(prefix).then_some(name) | |
| 211 | + }) { | |
| 212 | + bail!("{name} is removed; {replacement}"); | |
| 213 | + } | |
| 214 | + | |
| 41 | 215 | for name in [ |
| 42 | 216 | "CELLD_CLOUD", |
| 43 | - "CELLD_CLOUD_RESTART_ON_DEPLOY", | |
| 44 | 217 | "CELLD_LTX_COMPACTION", |
| 45 | 218 | "CELLD_LTX_PAGED", |
| 46 | - "CELLD_OUTPUT_GATE", | |
| 47 | - "CELLD_PRESENCE_SHADOW", | |
| 48 | 219 | "CELLD_TRUST_FORWARDED_HEADERS", |
| 49 | 220 | "CELLD_UNSAFE_PUBLIC_ADVERTISE", |
| 50 | 221 | ] { |
| @@ -54,16 +225,13 @@ | ||
| 54 | 225 | for name in [ |
| 55 | 226 | "CELLD_ACTIVATIONS", |
| 56 | 227 | "CELLD_DEPLOY_POLL_S", |
| 57 | - "CELLD_EVICTIONS", | |
| 58 | 228 | "CELLD_FETCH_TIMEOUT_S", |
| 59 | 229 | "CELLD_HANDLER_BUDGET_S", |
| 60 | 230 | "CELLD_IDLE_EVICT_S", |
| 61 | - "CELLD_LOG_CAPTURE_WORKERS", | |
| 62 | 231 | "CELLD_LOG_PIPELINE", |
| 63 | 232 | "CELLD_LTX_COMPACTIONS", |
| 64 | 233 | "CELLD_LTX_COMPACTION_MIN_TXIDS", |
| 65 | 234 | "CELLD_LTX_DURABILITY_TIMEOUT_SECS", |
| 66 | - "CELLD_MAX_LOADED_WORKERS", | |
| 67 | 235 | "CELLD_MAX_CELL_REQUESTS", |
| 68 | 236 | "CELLD_MAX_OUTBOUND_WEBSOCKETS", |
| 69 | 237 | "CELLD_MAX_REQUEST_BODY_BYTES", |
| @@ -73,9 +241,7 @@ | ||
| 73 | 241 | "CELLD_MAX_STATELESS_ISOLATES", |
| 74 | 242 | "CELLD_OPERATION_DEADLINE_MS", |
| 75 | 243 | "CELLD_PLACEMENT_WEIGHT", |
| 76 | - "CELLD_REBALANCE_BATCH_CELLS", | |
| 77 | 244 | "CELLD_RELEASES", |
| 78 | - "CELLD_SHUTDOWN_DRAIN_MS", | |
| 79 | 245 | "CELLD_TOKIO_THREADS", |
| 80 | 246 | "CELLD_TTL_MS", |
| 81 | 247 | "CELLD_WAKER_TICK_MS", |
| @@ -90,13 +256,11 @@ | ||
| 90 | 256 | "CELLD_DEPLOY_MAX_AGE_S", |
| 91 | 257 | "CELLD_LOCAL_CACHE_MAX_BYTES", |
| 92 | 258 | "CELLD_LTX_TRUNCATE_PAGES", |
| 93 | - "CELLD_LOG_GROUP_COMMIT_MS", | |
| 94 | 259 | "CELLD_LOG_HEDGE_MS", |
| 95 | 260 | "CELLD_LOG_WINDOW", |
| 96 | 261 | "CELLD_LOG_WINDOW_BYTES", |
| 97 | 262 | "CELLD_MAX_RESIDENT_CELLS", |
| 98 | 263 | "CELLD_MAX_RSS_MB", |
| 99 | - "CELLD_QUEUE_PRODUCER_GROUP_MS", | |
| 100 | 264 | "CELLD_READY_FLEET_GATE_MS", |
| 101 | 265 | "CELLD_REBALANCE_INTERVAL_MS", |
| 102 | 266 | ] { |
| @@ -134,28 +298,13 @@ | ||
| 134 | 298 | Ok(()) |
| 135 | 299 | } |
| 136 | 300 | |
| 137 | -/// Read the complete shutdown bound and the drain-token wait together. | |
| 138 | -/// | |
| 139 | -/// The wait can use at most three quarters of the complete bound. The | |
| 140 | -/// remaining quarter is available for request drain, ownership handoff, | |
| 141 | -/// connection flush, and local durability shutdown. | |
| 301 | +/// Resolve all shutdown timing from the operator's complete process bound. | |
| 302 | +/// Token acquisition consumes at most three quarters of that bound. The | |
| 303 | +/// no-progress interval is five eighths, with a one-millisecond minimum. | |
| 304 | +/// The process deadline still caps every shutdown phase and progress reset. | |
| 142 | 305 | pub fn shutdown_timing() -> anyhow::Result<ShutdownTiming> { |
| 143 | 306 | let total_ms = positive("CELLD_SHUTDOWN_TOTAL_MS")?.unwrap_or(DEFAULT_SHUTDOWN_TOTAL_MS); |
| 144 | - let drain_token_wait_ms = | |
| 145 | - with_default("CELLD_DRAIN_TOKEN_WAIT_MS", DEFAULT_DRAIN_TOKEN_WAIT_MS)?; | |
| 146 | - let maximum_wait_ms = maximum_drain_token_wait_ms(total_ms); | |
| 147 | - if drain_token_wait_ms > maximum_wait_ms { | |
| 148 | - bail!( | |
| 149 | - "CELLD_DRAIN_TOKEN_WAIT_MS must be at most \ | |
| 150 | - {MAX_DRAIN_TOKEN_WAIT_NUMERATOR}/{MAX_DRAIN_TOKEN_WAIT_DENOMINATOR} of \ | |
| 151 | - CELLD_SHUTDOWN_TOTAL_MS; maximum is {maximum_wait_ms} for {total_ms}, \ | |
| 152 | - not {drain_token_wait_ms}" | |
| 153 | - ); | |
| 154 | - } | |
| 155 | - Ok(ShutdownTiming { | |
| 156 | - total_ms, | |
| 157 | - drain_token_wait_ms, | |
| 158 | - }) | |
| 307 | + Ok(ShutdownTiming::from_total_ms(total_ms)) | |
| 159 | 308 | } |
| 160 | 309 | |
| 161 | 310 | pub fn value(name: &str) -> anyhow::Result<Option<String>> { |
modifiedcrates/celld/fleet.rs+67−60View file
| @@ -107,7 +107,6 @@ | ||
| 107 | 107 | }) |
| 108 | 108 | } |
| 109 | 109 | } |
| 110 | -use std::collections::BTreeMap; | |
| 111 | 110 | use std::time::Duration; |
| 112 | 111 | use tracing::info; |
| 113 | 112 | |
| @@ -290,7 +289,7 @@ | ||
| 290 | 289 | } |
| 291 | 290 | bail!( |
| 292 | 291 | "the bucket does not keep the storage contract, so celld cannot serve cells \ |
| 293 | - safely on it: {reason}. Set CELLD_STORAGE_PROBE=0 to start without this test" | |
| 292 | + safely on it: {reason}. Use a store that supports the required operations" | |
| 294 | 293 | ) |
| 295 | 294 | } |
| 296 | 295 | Err(error) if attempt < ATTEMPTS => { |
| @@ -604,6 +603,7 @@ | ||
| 604 | 603 | let bucket = options.bucket.expect("validated deployment bucket"); |
| 605 | 604 | let store = bucket_client(&bucket, options.endpoint.as_deref(), ®ion)?; |
| 606 | 605 | validate_bucket(&store).await?; |
| 606 | + crate::wake_format::ensure_ready(&store).await?; | |
| 607 | 607 | let started = std::time::Instant::now(); |
| 608 | 608 | deploy::write(&store, &built).await?; |
| 609 | 609 | let location = format!( |
| @@ -655,6 +655,36 @@ | ||
| 655 | 655 | load_worker_from_pointer(bucket, CURRENT_POINTER_KEY, node).await |
| 656 | 656 | } |
| 657 | 657 | |
| 658 | +/// Block until the fleet-wide pointer exists, so a self-hosted node that | |
| 659 | +/// starts before its first `celld deploy` idles instead of exiting. | |
| 660 | +/// | |
| 661 | +/// The boot path reads `deploy/current.json` and treats "no such key" as | |
| 662 | +/// fatal, so a node started against an empty bucket exits and systemd | |
| 663 | +/// restarts it in a loop until a deployment appears. The pointer is the | |
| 664 | +/// authority, so the node waits for it and then serves it, with no | |
| 665 | +/// operator restart. A bucket or transport error still returns `Err`, so | |
| 666 | +/// a misconfigured bucket fails the boot rather than waiting forever. | |
| 667 | +pub async fn wait_for_deployment_pointer(bucket: &Bucket) -> anyhow::Result<()> { | |
| 668 | + let mut waited = false; | |
| 669 | + loop { | |
| 670 | + if bucket.get(CURRENT_POINTER_KEY).await?.is_some() { | |
| 671 | + if waited { | |
| 672 | + tracing::info!(event = "initial_deployment_found"); | |
| 673 | + } | |
| 674 | + return Ok(()); | |
| 675 | + } | |
| 676 | + if !waited { | |
| 677 | + waited = true; | |
| 678 | + tracing::info!( | |
| 679 | + event = "awaiting_initial_deployment", | |
| 680 | + "no deployment yet; run `celld deploy` and the node serves it \ | |
| 681 | + without a restart" | |
| 682 | + ); | |
| 683 | + } | |
| 684 | + tokio::time::sleep(std::time::Duration::from_secs(2)).await; | |
| 685 | + } | |
| 686 | +} | |
| 687 | + | |
| 658 | 688 | /// Read the fleet-wide pointer without loading what it names. The watcher |
| 659 | 689 | /// compares it with the serving generation before it loads anything. |
| 660 | 690 | pub async fn read_current_pointer(bucket: &Bucket) -> anyhow::Result<DeployPointer> { |
| @@ -747,6 +777,12 @@ | ||
| 747 | 777 | } |
| 748 | 778 | crate::protocol::validate_required_features(&manifest.required_features)?; |
| 749 | 779 | crate::protocol::validate_queue_manifest(&manifest)?; |
| 780 | + // Old managed uploads can contain AI metadata without a required-feature | |
| 781 | + // gate. Refuse it before loading code, rather than serve a missing binding. | |
| 782 | + anyhow::ensure!( | |
| 783 | + bindings(&manifest, "ai").next().is_none(), | |
| 784 | + "AI bindings are not supported; call the provider from application code" | |
| 785 | + ); | |
| 750 | 786 | let prefix = &pointer.prefix; |
| 751 | 787 | let mut fetched = |
| 752 | 788 | futures_util::future::try_join_all(manifest.modules.iter().map(|module| async move { |
| @@ -855,12 +891,13 @@ | ||
| 855 | 891 | }) |
| 856 | 892 | }) |
| 857 | 893 | .collect(); |
| 858 | - let ai_binding = configured_ai_binding( | |
| 859 | - bindings(&manifest, "ai") | |
| 860 | - .find_map(|binding| binding.get("name")?.as_str().map(str::to_string)), | |
| 861 | - ); | |
| 894 | + // The `worker_loaders` key of the deployed config. Every entry becomes a | |
| 895 | + // binding of its own, because each loader caches the Workers it loaded. | |
| 896 | + let loader_bindings = bindings(&manifest, "worker_loader") | |
| 897 | + .filter_map(|binding| binding.get("name")?.as_str().map(str::to_string)) | |
| 898 | + .collect(); | |
| 862 | 899 | let services = service_bindings(&manifest); |
| 863 | - let vars = worker_vars(&manifest)?; | |
| 900 | + let vars = worker_vars(&manifest); | |
| 864 | 901 | let compat = crate::worker_compat(&manifest.raw_metadata); |
| 865 | 902 | let assets = match &manifest.assets { |
| 866 | 903 | Some(reference) => Some( |
| @@ -891,6 +928,8 @@ | ||
| 891 | 928 | let version = manifest.version.clone(); |
| 892 | 929 | let prefix = pointer.prefix.clone(); |
| 893 | 930 | let crons = manifest.crons.clone(); |
| 931 | + let containers = manifest.containers.clone(); | |
| 932 | + let fence_image = manifest.fence_image.clone(); | |
| 894 | 933 | Ok(LoadedDeployment { |
| 895 | 934 | options: WorkerConfigOptions { |
| 896 | 935 | src, |
| @@ -903,7 +942,6 @@ | ||
| 903 | 942 | queue_bindings, |
| 904 | 943 | queue_consumers: manifest.queue_consumers, |
| 905 | 944 | workflow_bindings, |
| 906 | - ai_binding, | |
| 907 | 945 | vars, |
| 908 | 946 | node, |
| 909 | 947 | modules, |
| @@ -913,29 +951,34 @@ | ||
| 913 | 951 | version, |
| 914 | 952 | prefix, |
| 915 | 953 | asset_binding, |
| 954 | + loader_bindings, | |
| 916 | 955 | assets, |
| 917 | 956 | services, |
| 918 | 957 | crons, |
| 958 | + containers, | |
| 959 | + fence_image, | |
| 919 | 960 | }) |
| 920 | 961 | } |
| 921 | 962 | |
| 922 | -/// Apply celld's manifest-first precedence for the optional AI binding. | |
| 923 | -pub fn configured_ai_binding(manifest_binding: Option<String>) -> Option<String> { | |
| 924 | - manifest_binding | |
| 925 | - .or_else(|| std::env::var("CELLD_AI_BINDING").ok()) | |
| 926 | - .or_else(|| std::env::var_os("CELLD_AI_URL").map(|_| "AI".to_string())) | |
| 927 | -} | |
| 928 | - | |
| 929 | 963 | pub struct LoadedDeployment { |
| 930 | 964 | pub options: WorkerConfigOptions, |
| 931 | 965 | pub script_name: String, |
| 932 | 966 | pub version: String, |
| 933 | 967 | pub prefix: String, |
| 934 | 968 | pub asset_binding: Option<String>, |
| 969 | + /// `env` names of this script's Worker Loaders, from its | |
| 970 | + /// `worker_loaders` config. A script reaches no loader that it does not | |
| 971 | + /// declare, and each loader keeps a cache of its own loaded Workers. | |
| 972 | + pub loader_bindings: Vec<String>, | |
| 935 | 973 | pub assets: Option<crate::assets::AssetResolver>, |
| 936 | 974 | pub services: Vec<(String, String, Option<String>)>, |
| 937 | 975 | /// `triggers.crons` from the manifest, driving the reserved cron cell. |
| 938 | 976 | pub crons: Vec<String>, |
| 977 | + /// `containers` from the manifest: the classes whose cells supervise a | |
| 978 | + /// container. | |
| 979 | + pub containers: Vec<crate::container::ContainerSpec>, | |
| 980 | + /// See `Manifest::fence_image`. | |
| 981 | + pub fence_image: Option<String>, | |
| 939 | 982 | } |
| 940 | 983 | |
| 941 | 984 | fn bindings<'a>( |
| @@ -968,49 +1011,13 @@ | ||
| 968 | 1011 | .collect() |
| 969 | 1012 | } |
| 970 | 1013 | |
| 971 | -fn worker_vars(manifest: &Manifest) -> anyhow::Result<Vec<(String, String)>> { | |
| 972 | - let mut vars = BTreeMap::new(); | |
| 973 | - for binding in bindings(manifest, "plain_text") { | |
| 974 | - if let (Some(name), Some(value)) = ( | |
| 975 | - binding.get("name").and_then(serde_json::Value::as_str), | |
| 976 | - binding.get("text").and_then(serde_json::Value::as_str), | |
| 977 | - ) { | |
| 978 | - vars.insert(name.to_string(), value.to_string()); | |
| 979 | - } | |
| 980 | - } | |
| 981 | - if let Ok(path) = std::env::var("CELLD_VARS_FILE") { | |
| 982 | - let contents = std::fs::read_to_string(&path) | |
| 983 | - .with_context(|| format!("read Worker vars file {path}"))?; | |
| 984 | - for line in contents.lines().map(str::trim) { | |
| 985 | - if line.is_empty() || line.starts_with('#') { | |
| 986 | - continue; | |
| 987 | - } | |
| 988 | - let Some((name, raw)) = line.split_once('=') else { | |
| 989 | - continue; | |
| 990 | - }; | |
| 991 | - let name = name.trim(); | |
| 992 | - if name.is_empty() { | |
| 993 | - continue; | |
| 994 | - } | |
| 995 | - let raw = raw.trim(); | |
| 996 | - let value = raw | |
| 997 | - .strip_prefix('"') | |
| 998 | - .and_then(|value| value.strip_suffix('"')) | |
| 999 | - .or_else(|| { | |
| 1000 | - raw.strip_prefix('\'') | |
| 1001 | - .and_then(|value| value.strip_suffix('\'')) | |
| 1002 | - }) | |
| 1003 | - .unwrap_or(raw); | |
| 1004 | - vars.insert(name.to_string(), value.to_string()); | |
| 1005 | - } | |
| 1006 | - } | |
| 1007 | - for (name, value) in std::env::vars() { | |
| 1008 | - if let Some(name) = name | |
| 1009 | - .strip_prefix("CELLD_VAR_") | |
| 1010 | - .filter(|name| !name.is_empty()) | |
| 1011 | - { | |
| 1012 | - vars.insert(name.to_string(), value); | |
| 1013 | - } | |
| 1014 | - } | |
| 1015 | - Ok(vars.into_iter().collect()) | |
| 1014 | +fn worker_vars(manifest: &Manifest) -> Vec<(String, String)> { | |
| 1015 | + bindings(manifest, "plain_text") | |
| 1016 | + .filter_map(|binding| { | |
| 1017 | + Some(( | |
| 1018 | + binding.get("name")?.as_str()?.to_string(), | |
| 1019 | + binding.get("text")?.as_str()?.to_string(), | |
| 1020 | + )) | |
| 1021 | + }) | |
| 1022 | + .collect() | |
| 1016 | 1023 | } |
modifiedcrates/celld/generation.rs+8−8View file
| @@ -35,9 +35,9 @@ | ||
| 35 | 35 | |
| 36 | 36 | /// Ask the node to adopt the deployment `deploy/current.json` names now. |
| 37 | 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. | |
| 38 | + /// Rebuild even when the pointer names the current deployment, so a | |
| 39 | + /// memoised failure is retried and fresh isolates replace the serving | |
| 40 | + /// ones. `POST /reload` sets it; a poll tick and a managed nudge do not. | |
| 41 | 41 | pub force: bool, |
| 42 | 42 | /// Where to report the outcome. A poll tick has nobody to tell. |
| 43 | 43 | pub reply: Option<tokio::sync::oneshot::Sender<ReloadOutcome>>, |
| @@ -267,7 +267,6 @@ | ||
| 267 | 267 | |
| 268 | 268 | /// Node-level inputs `Generation::build` needs beside the deployment itself. |
| 269 | 269 | pub struct GenerationOptions { |
| 270 | - pub loader_binding: Option<String>, | |
| 271 | 270 | pub node: String, |
| 272 | 271 | pub region: String, |
| 273 | 272 | } |
| @@ -293,10 +292,11 @@ | ||
| 293 | 292 | pub(crate) cell_isolates: HashMap<String, Arc<crate::pool::Pool>>, |
| 294 | 293 | pub(crate) default_do_class: Option<Arc<str>>, |
| 295 | 294 | 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>, | |
| 295 | + /// Every container class of every script in the graph. | |
| 296 | + pub(crate) containers: Vec<crate::container::ContainerSpec>, | |
| 297 | + /// See `Manifest::fence_image`; the first script's, they are all the | |
| 298 | + /// same image when one celld deployed them. | |
| 299 | + pub(crate) fence_image: Option<String>, | |
| 300 | 300 | } |
| 301 | 301 | |
| 302 | 302 | impl Generation { |
modifiedcrates/celld/js.rs+0−0View file
This diff is too large to display.
modifiedcrates/celld/js/atob_btoa.js+53−28View file
| @@ -1,42 +1,67 @@ | ||
| 1 | 1 | // atob / btoa. |
| 2 | 2 | // Own IIFE: captures the host ops it needs, attaches to |
| 3 | 3 | // globalThis, exits. The $$-prefixed host ops stay defined |
| 4 | -// for the life of the isolate — non-enumerable (see the ops | |
| 4 | +// for the life of the isolate -- non-enumerable (see the ops | |
| 5 | 5 | // macro in js.rs), not removed. DOMException is installed |
| 6 | 6 | // later, by harness.js, and is only referenced at call time. |
| 7 | 7 | (function () { |
| 8 | + // The host op does the whole WHATWG forgiving-base64 decode, including | |
| 9 | + // ASCII whitespace removal, so this wrapper only does what Web IDL asks | |
| 10 | + // for: argument-count and DOMString conversion, and the DOMException | |
| 11 | + // re-wrap the op cannot build (the op throws a plain Error). | |
| 12 | + // | |
| 13 | + // Both wrappers are method shorthands rather than arrow functions for | |
| 14 | + // two reasons an arrow cannot satisfy: an arrow has no `arguments`, so | |
| 15 | + // it cannot tell `atob()` from `atob(undefined)`, and an arrow's `name` | |
| 16 | + // would be the empty string instead of "atob". A function declaration | |
| 17 | + // would fix the name but is constructible, and Workerd's `atob` is not. | |
| 8 | 18 | const _atob = $$atob; |
| 9 | 19 | const _btoa = $$btoa; |
| 10 | 20 | |
| 11 | - // WHATWG infra: atob strips ASCII whitespace | |
| 12 | - // (U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, | |
| 13 | - // U+0020 SPACE) from input before decoding, and | |
| 14 | - // throws DOMException("InvalidCharacterError") on | |
| 15 | - // bad input (not a plain Error). The Rust op does | |
| 16 | - // neither — preprocess and re-wrap here. | |
| 17 | - globalThis.atob = (s) => { | |
| 18 | - s = String(s).replace(/[\t\n\f\r ]/g, ""); | |
| 19 | - try { | |
| 20 | - return _atob(s); | |
| 21 | - } catch (e) { | |
| 22 | - throw new DOMException( | |
| 23 | - e && e.message | |
| 24 | - ? String(e.message) | |
| 25 | - : "atob: invalid base64", | |
| 26 | - "InvalidCharacterError", | |
| 27 | - ); | |
| 28 | - } | |
| 29 | - }; | |
| 30 | - globalThis.btoa = (s) => { | |
| 31 | - s = String(s); | |
| 32 | - for (let i = 0; i < s.length; i++) { | |
| 33 | - if (s.charCodeAt(i) > 0xff) { | |
| 21 | + globalThis.atob = { | |
| 22 | + atob(s) { | |
| 23 | + // Web IDL: a missing argument for a required parameter is a | |
| 24 | + // TypeError, while an explicit `undefined` converts to the string | |
| 25 | + // "undefined" and fails later as invalid base64. | |
| 26 | + if (arguments.length === 0) { | |
| 27 | + throw new TypeError( | |
| 28 | + "Failed to execute 'atob': 1 argument required, but only 0 present.", | |
| 29 | + ); | |
| 30 | + } | |
| 31 | + // Template ToString, not String(): String(Symbol()) returns | |
| 32 | + // "Symbol()" and would decode as base64, while Web IDL DOMString | |
| 33 | + // conversion must throw a TypeError for a Symbol. | |
| 34 | + s = `${s}`; | |
| 35 | + try { | |
| 36 | + return _atob(s); | |
| 37 | + } catch (e) { | |
| 34 | 38 | throw new DOMException( |
| 35 | - "String contains a code point > U+00FF", | |
| 39 | + e && e.message | |
| 40 | + ? String(e.message) | |
| 41 | + : "atob: invalid base64", | |
| 36 | 42 | "InvalidCharacterError", |
| 37 | 43 | ); |
| 38 | 44 | } |
| 39 | - } | |
| 40 | - return _btoa(s); | |
| 41 | - }; | |
| 45 | + }, | |
| 46 | + }.atob; | |
| 47 | + | |
| 48 | + globalThis.btoa = { | |
| 49 | + btoa(s) { | |
| 50 | + if (arguments.length === 0) { | |
| 51 | + throw new TypeError( | |
| 52 | + "Failed to execute 'btoa': 1 argument required, but only 0 present.", | |
| 53 | + ); | |
| 54 | + } | |
| 55 | + s = `${s}`; | |
| 56 | + for (let i = 0; i < s.length; i++) { | |
| 57 | + if (s.charCodeAt(i) > 0xff) { | |
| 58 | + throw new DOMException( | |
| 59 | + "String contains a code point > U+00FF", | |
| 60 | + "InvalidCharacterError", | |
| 61 | + ); | |
| 62 | + } | |
| 63 | + } | |
| 64 | + return _btoa(s); | |
| 65 | + }, | |
| 66 | + }.btoa; | |
| 42 | 67 | })(); |
modifiedcrates/celld/js/bootstrap.rs+341−201View file
| @@ -14,27 +14,167 @@ | ||
| 14 | 14 | /// largest slice of cold-wake latency. The first isolate compiles |
| 15 | 15 | /// eagerly and publishes the cache; every later isolate consumes it and only |
| 16 | 16 | /// executes. |
| 17 | +/// | |
| 18 | +/// Keyed by script name alone. Each script compiles as a function whose | |
| 19 | +/// parameter list is `op_names()`, and V8's cache check does not cover that | |
| 20 | +/// list, so a cache is only valid while the list is the same for every | |
| 21 | +/// isolate of the process. `op_names()` is fixed at build time; an op that | |
| 22 | +/// varies per worker would have to enter the key. | |
| 17 | 23 | type BootstrapCache = std::collections::HashMap<&'static str, std::sync::Arc<Vec<u8>>>; |
| 18 | 24 | |
| 25 | +macro_rules! static_source { | |
| 26 | + ($name:ident, $file:literal) => { | |
| 27 | + static $name: v8::OneByteConst = | |
| 28 | + v8::String::create_external_onebyte_const(include_bytes!($file)); | |
| 29 | + }; | |
| 30 | +} | |
| 31 | + | |
| 32 | +struct BootstrapSource { | |
| 33 | + name: &'static str, | |
| 34 | + source: &'static v8::OneByteConst, | |
| 35 | +} | |
| 36 | + | |
| 37 | +static_source!(TEXT_ENCODING_SOURCE, "text_encoding.js"); | |
| 38 | +static_source!(URL_SEARCH_PARAMS_SOURCE, "url_search_params.js"); | |
| 39 | +static_source!(URL_SOURCE, "url.js"); | |
| 40 | +static_source!(ATOB_BTOA_SOURCE, "atob_btoa.js"); | |
| 41 | +static_source!(HEADERS_SOURCE, "headers.js"); | |
| 42 | +static_source!(STREAMS_SOURCE, "streams.js"); | |
| 43 | +static_source!(WRITABLE_STREAM_SOURCE, "writable_stream.js"); | |
| 44 | +static_source!(TEXT_ENCODING_STREAMS_SOURCE, "text_encoding_streams.js"); | |
| 45 | +static_source!(MESSAGE_CHANNEL_SOURCE, "message_channel.js"); | |
| 46 | +static_source!(EVENT_SOURCE_SOURCE, "event_source.js"); | |
| 47 | +static_source!(CACHE_SOURCE, "cache.js"); | |
| 48 | +static_source!(SOCKETS_SOURCE, "sockets.js"); | |
| 49 | +static_source!(HTML_REWRITER_SOURCE, "html_rewriter.js"); | |
| 50 | +static_source!(CRYPTO_SOURCE, "crypto.js"); | |
| 51 | + | |
| 52 | +static PRELUDE: &[BootstrapSource] = &[ | |
| 53 | + BootstrapSource { | |
| 54 | + name: "text_encoding.js", | |
| 55 | + source: &TEXT_ENCODING_SOURCE, | |
| 56 | + }, | |
| 57 | + BootstrapSource { | |
| 58 | + name: "url_search_params.js", | |
| 59 | + source: &URL_SEARCH_PARAMS_SOURCE, | |
| 60 | + }, | |
| 61 | + BootstrapSource { | |
| 62 | + name: "url.js", | |
| 63 | + source: &URL_SOURCE, | |
| 64 | + }, | |
| 65 | + BootstrapSource { | |
| 66 | + name: "atob_btoa.js", | |
| 67 | + source: &ATOB_BTOA_SOURCE, | |
| 68 | + }, | |
| 69 | + BootstrapSource { | |
| 70 | + name: "headers.js", | |
| 71 | + source: &HEADERS_SOURCE, | |
| 72 | + }, | |
| 73 | + BootstrapSource { | |
| 74 | + name: "streams.js", | |
| 75 | + source: &STREAMS_SOURCE, | |
| 76 | + }, | |
| 77 | + BootstrapSource { | |
| 78 | + name: "writable_stream.js", | |
| 79 | + source: &WRITABLE_STREAM_SOURCE, | |
| 80 | + }, | |
| 81 | + BootstrapSource { | |
| 82 | + name: "text_encoding_streams.js", | |
| 83 | + source: &TEXT_ENCODING_STREAMS_SOURCE, | |
| 84 | + }, | |
| 85 | +]; | |
| 86 | + | |
| 87 | +static POST_HARNESS: &[BootstrapSource] = &[ | |
| 88 | + BootstrapSource { | |
| 89 | + name: "message_channel.js", | |
| 90 | + source: &MESSAGE_CHANNEL_SOURCE, | |
| 91 | + }, | |
| 92 | + BootstrapSource { | |
| 93 | + name: "event_source.js", | |
| 94 | + source: &EVENT_SOURCE_SOURCE, | |
| 95 | + }, | |
| 96 | + BootstrapSource { | |
| 97 | + name: "cache.js", | |
| 98 | + source: &CACHE_SOURCE, | |
| 99 | + }, | |
| 100 | + BootstrapSource { | |
| 101 | + name: "sockets.js", | |
| 102 | + source: &SOCKETS_SOURCE, | |
| 103 | + }, | |
| 104 | + BootstrapSource { | |
| 105 | + name: "html_rewriter.js", | |
| 106 | + source: &HTML_REWRITER_SOURCE, | |
| 107 | + }, | |
| 108 | + BootstrapSource { | |
| 109 | + name: "crypto.js", | |
| 110 | + source: &CRYPTO_SOURCE, | |
| 111 | + }, | |
| 112 | +]; | |
| 113 | + | |
| 114 | +// The harness is fixed process data, so copying its ~450 KiB source into every | |
| 115 | +// isolate only gives V8 another owner for the same bytes. `OneByteConst` keeps | |
| 116 | +// one external buffer in the binary and checks the ASCII requirement at | |
| 117 | +// compile time. Compiled code and the objects created by the script remain | |
| 118 | +// isolate-local; this shares only the original source buffer. | |
| 119 | +#[cfg(any(not(celld_internal_tests), all(test, celld_internal_tests)))] | |
| 120 | +static HARNESS_SOURCE: v8::OneByteConst = | |
| 121 | + v8::String::create_external_onebyte_const(include_bytes!("harness.js")); | |
| 122 | + | |
| 19 | 123 | fn bootstrap_code_cache() -> &'static std::sync::Mutex<BootstrapCache> { |
| 20 | 124 | static CACHE: std::sync::OnceLock<std::sync::Mutex<BootstrapCache>> = |
| 21 | 125 | std::sync::OnceLock::new(); |
| 22 | 126 | CACHE.get_or_init(Default::default) |
| 23 | 127 | } |
| 24 | 128 | |
| 25 | -fn run_bootstrap_script(scope: &mut v8::PinScope, name: &'static str, src: &str) -> Result<()> { | |
| 129 | +#[cfg(celld_internal_tests)] | |
| 130 | +fn run_bootstrap_script<'s>( | |
| 131 | + scope: &mut v8::PinScope<'s, '_>, | |
| 132 | + name: &'static str, | |
| 133 | + src: &str, | |
| 134 | + arguments: &InternalArguments<'s>, | |
| 135 | +) -> Result<()> { | |
| 136 | + let code = v8::String::new(scope, src).unwrap(); | |
| 137 | + run_internal_script(scope, Some(name), code, arguments)?; | |
| 138 | + Ok(()) | |
| 139 | +} | |
| 140 | + | |
| 141 | +fn run_bootstrap_static_script<'s>( | |
| 142 | + scope: &mut v8::PinScope<'s, '_>, | |
| 143 | + source: &'static BootstrapSource, | |
| 144 | + arguments: &InternalArguments<'s>, | |
| 145 | +) -> Result<()> { | |
| 146 | + let code = v8_strings::source(scope, source.source); | |
| 147 | + run_internal_script(scope, Some(source.name), code, arguments)?; | |
| 148 | + Ok(()) | |
| 149 | +} | |
| 150 | + | |
| 151 | +/// Compile an internal script as one function whose parameters are the | |
| 152 | +/// internals object and the host ops, and run it. A script and not a | |
| 153 | +/// module, because the harness is one scope shared by every prelude file; | |
| 154 | +/// a function and not a global script, because a global script's top-level | |
| 155 | +/// declarations become bindings user code can name, and its ops would have | |
| 156 | +/// to be globals too. Returns what the body `return`s: a lazy global's | |
| 157 | +/// exports, or undefined. | |
| 158 | +pub(super) fn run_internal_script<'s>( | |
| 159 | + scope: &mut v8::PinScope<'s, '_>, | |
| 160 | + cache: Option<&'static str>, | |
| 161 | + code: v8::Local<'s, v8::String>, | |
| 162 | + arguments: &InternalArguments<'s>, | |
| 163 | +) -> Result<v8::Local<'s, v8::Value>> { | |
| 26 | 164 | use v8::script_compiler::CompileOptions; |
| 27 | 165 | use v8::script_compiler::NoCacheReason; |
| 28 | - let code = v8::String::new(scope, src).unwrap(); | |
| 29 | - let cached = bootstrap_code_cache().lock().unwrap().get(name).cloned(); | |
| 30 | - let unbound = match cached { | |
| 166 | + let name = cache.unwrap_or("lazy script"); | |
| 167 | + let cached = cache.and_then(|name| bootstrap_code_cache().lock().unwrap().get(name).cloned()); | |
| 168 | + let function = match cached { | |
| 31 | 169 | // `CachedData` borrows `bytes`; the Arc binding outlives the Source. |
| 32 | 170 | Some(bytes) => { |
| 33 | 171 | let data = v8::script_compiler::CachedData::new(&bytes); |
| 34 | 172 | let mut source = v8::script_compiler::Source::new_with_cached_data(code, None, data); |
| 35 | - let unbound = v8::script_compiler::compile_unbound_script( | |
| 173 | + let function = v8::script_compiler::compile_function( | |
| 36 | 174 | scope, |
| 37 | 175 | &mut source, |
| 176 | + &arguments.names, | |
| 177 | + &[], | |
| 38 | 178 | CompileOptions::ConsumeCodeCache, |
| 39 | 179 | NoCacheReason::NoReason, |
| 40 | 180 | ) |
| @@ -43,58 +183,82 @@ | ||
| 43 | 183 | !source.get_cached_data().is_some_and(|data| data.rejected()), |
| 44 | 184 | "code cache rejected for {name}" |
| 45 | 185 | ); |
| 46 | - unbound | |
| 186 | + function | |
| 47 | 187 | } |
| 188 | + // Eager for a cached bootstrap script: a lazily-compiled cache would | |
| 189 | + // push function-body compile cost back into every consumer's first | |
| 190 | + // request. A lazy script keeps V8's lazy compile: most of a builtin | |
| 191 | + // module is never called. | |
| 48 | 192 | None => { |
| 49 | 193 | let mut source = v8::script_compiler::Source::new(code, None); |
| 50 | - // Eager: a lazily-compiled cache would push function-body compile | |
| 51 | - // cost back into every consumer's first request. | |
| 52 | - let unbound = v8::script_compiler::compile_unbound_script( | |
| 194 | + let options = match cache { | |
| 195 | + Some(_) => CompileOptions::EagerCompile, | |
| 196 | + None => CompileOptions::NoCompileOptions, | |
| 197 | + }; | |
| 198 | + let function = v8::script_compiler::compile_function( | |
| 53 | 199 | scope, |
| 54 | 200 | &mut source, |
| 55 | - CompileOptions::EagerCompile, | |
| 201 | + &arguments.names, | |
| 202 | + &[], | |
| 203 | + options, | |
| 56 | 204 | NoCacheReason::NoReason, |
| 57 | 205 | ) |
| 58 | 206 | .ok_or_else(|| anyhow!("bootstrap compile {name}"))?; |
| 59 | - if let Some(data) = unbound.create_code_cache() { | |
| 207 | + if let Some((name, data)) = cache.zip(function.create_code_cache()) { | |
| 60 | 208 | bootstrap_code_cache() |
| 61 | 209 | .lock() |
| 62 | 210 | .unwrap() |
| 63 | 211 | .insert(name, std::sync::Arc::new(data.to_vec())); |
| 64 | 212 | } |
| 65 | - unbound | |
| 213 | + function | |
| 66 | 214 | } |
| 67 | 215 | }; |
| 68 | - unbound | |
| 69 | - .bind_to_current_context(scope) | |
| 70 | - .run(scope) | |
| 71 | - .ok_or_else(|| anyhow!("bootstrap run {name}"))?; | |
| 72 | - Ok(()) | |
| 216 | + // The global receiver keeps top-level `this` what a script had. | |
| 217 | + let receiver = scope.get_current_context().global(scope).into(); | |
| 218 | + function | |
| 219 | + .call(scope, receiver, &arguments.values) | |
| 220 | + .ok_or_else(|| anyhow!("bootstrap run {name}")) | |
| 73 | 221 | } |
| 74 | 222 | |
| 223 | +#[cfg(all(test, celld_internal_tests))] | |
| 224 | +pub(super) fn harness_source_for_test<'s>( | |
| 225 | + scope: &mut v8::PinScope<'s, '_>, | |
| 226 | +) -> v8::Local<'s, v8::String> { | |
| 227 | + shipping_harness_source(scope) | |
| 228 | +} | |
| 229 | + | |
| 230 | +#[cfg(all(test, celld_internal_tests))] | |
| 231 | +pub(super) fn bootstrap_sources_for_test<'s>( | |
| 232 | + scope: &mut v8::PinScope<'s, '_>, | |
| 233 | +) -> Vec<(&'static str, v8::Local<'s, v8::String>)> { | |
| 234 | + PRELUDE | |
| 235 | + .iter() | |
| 236 | + .chain(POST_HARNESS) | |
| 237 | + .map(|source| (source.name, v8_strings::source(scope, source.source))) | |
| 238 | + .collect() | |
| 239 | +} | |
| 240 | + | |
| 241 | +#[cfg(any(not(celld_internal_tests), all(test, celld_internal_tests)))] | |
| 242 | +fn shipping_harness_source<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::String> { | |
| 243 | + v8::String::new_from_onebyte_const(scope, &HARNESS_SOURCE).expect("static harness source") | |
| 244 | +} | |
| 245 | + | |
| 75 | 246 | /// WPT-conformant Web APIs: TextEncoder, URL/URLSearchParams, atob/btoa, and |
| 76 | 247 | /// Headers. Run once per isolate before the Cells/Cloudflare-specific harness. |
| 77 | -pub(super) fn install_prelude(scope: &mut v8::PinScope) -> Result<()> { | |
| 78 | - const PRELUDE: &[(&str, &str)] = &[ | |
| 79 | - ("text_encoding.js", include_str!("text_encoding.js")), | |
| 80 | - ("url_search_params.js", include_str!("url_search_params.js")), | |
| 81 | - ("url.js", include_str!("url.js")), | |
| 82 | - ("atob_btoa.js", include_str!("atob_btoa.js")), | |
| 83 | - ("headers.js", include_str!("headers.js")), | |
| 84 | - ("streams.js", include_str!("streams.js")), | |
| 85 | - ("writable_stream.js", include_str!("writable_stream.js")), | |
| 86 | - ( | |
| 87 | - "text_encoding_streams.js", | |
| 88 | - include_str!("text_encoding_streams.js"), | |
| 89 | - ), | |
| 90 | - ]; | |
| 91 | - for (name, src) in PRELUDE { | |
| 92 | - run_bootstrap_script(scope, name, src)?; | |
| 248 | +pub(super) fn install_prelude<'s>( | |
| 249 | + scope: &mut v8::PinScope<'s, '_>, | |
| 250 | + arguments: &InternalArguments<'s>, | |
| 251 | +) -> Result<()> { | |
| 252 | + for source in PRELUDE { | |
| 253 | + run_bootstrap_static_script(scope, source, arguments)?; | |
| 93 | 254 | } |
| 94 | 255 | Ok(()) |
| 95 | 256 | } |
| 96 | 257 | |
| 97 | -pub(super) fn install_harness(scope: &mut v8::PinScope) -> Result<()> { | |
| 258 | +pub(super) fn install_harness<'s>( | |
| 259 | + scope: &mut v8::PinScope<'s, '_>, | |
| 260 | + arguments: &InternalArguments<'s>, | |
| 261 | +) -> Result<()> { | |
| 98 | 262 | #[cfg(celld_internal_tests)] |
| 99 | 263 | let harness = include_str!("harness.js") |
| 100 | 264 | .replace( |
| @@ -106,8 +270,8 @@ | ||
| 106 | 270 | "__test_workflow_meta_created();", |
| 107 | 271 | ) |
| 108 | 272 | .replace( |
| 109 | - "/*__CELLD_TEST_WORKFLOW_ALARM_DELETED__*/", | |
| 110 | - "__test_workflow_alarm_deleted();", | |
| 273 | + "/*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/", | |
| 274 | + "__test_workflow_terminal_alarm_set();", | |
| 111 | 275 | ) |
| 112 | 276 | .replace( |
| 113 | 277 | "/*__CELLD_TEST_WORKFLOW_BEFORE_PAUSE_SETTLE__*/", |
| @@ -126,22 +290,17 @@ | ||
| 126 | 290 | ), |
| 127 | 291 | ); |
| 128 | 292 | #[cfg(celld_internal_tests)] |
| 129 | - let harness = harness.as_str(); | |
| 293 | + run_bootstrap_script(scope, "harness.js", harness.as_str(), arguments)?; | |
| 130 | 294 | #[cfg(not(celld_internal_tests))] |
| 131 | - let harness = include_str!("harness.js"); | |
| 132 | - run_bootstrap_script(scope, "harness.js", harness)?; | |
| 295 | + { | |
| 296 | + let harness = shipping_harness_source(scope); | |
| 297 | + run_internal_script(scope, Some("harness.js"), harness, arguments)?; | |
| 298 | + } | |
| 133 | 299 | // After the harness: both build on its EventTarget, and EventSource |
| 134 | 300 | // uses its fetch and timers. |
| 135 | - run_bootstrap_script( | |
| 136 | - scope, | |
| 137 | - "message_channel.js", | |
| 138 | - include_str!("message_channel.js"), | |
| 139 | - )?; | |
| 140 | - run_bootstrap_script(scope, "event_source.js", include_str!("event_source.js"))?; | |
| 141 | - run_bootstrap_script(scope, "cache.js", include_str!("cache.js"))?; | |
| 142 | - run_bootstrap_script(scope, "sockets.js", include_str!("sockets.js"))?; | |
| 143 | - run_bootstrap_script(scope, "html_rewriter.js", include_str!("html_rewriter.js"))?; | |
| 144 | - run_bootstrap_script(scope, "crypto.js", include_str!("crypto.js"))?; | |
| 301 | + for source in POST_HARNESS { | |
| 302 | + run_bootstrap_static_script(scope, source, arguments)?; | |
| 303 | + } | |
| 145 | 304 | // Resolving the event hooks belongs to installing the harness, not to the |
| 146 | 305 | // first event: the harness is what defines them, and a caller that |
| 147 | 306 | // installed the harness without them would silently fall back to nothing |
| @@ -153,10 +312,10 @@ | ||
| 153 | 312 | /// See [`EventHooks`] for why all four resolve together. |
| 154 | 313 | fn install_event_hooks(scope: &mut v8::PinScope) -> Result<()> { |
| 155 | 314 | let hooks = EventHooks { |
| 156 | - begin_event: global_function(scope, "__beginEvent")?, | |
| 157 | - end_event: global_function(scope, "__endEvent")?, | |
| 158 | - advance_io_time: global_function(scope, "__advanceIoTime")?, | |
| 159 | - abort_incoming_request: global_function(scope, "__abortIncomingRequest")?, | |
| 315 | + begin_event: internal_global(scope, "__beginEvent")?, | |
| 316 | + end_event: internal_global(scope, "__endEvent")?, | |
| 317 | + advance_io_time: internal_global(scope, "__advanceIoTime")?, | |
| 318 | + abort_incoming_request: internal_global(scope, "__abortIncomingRequest")?, | |
| 160 | 319 | }; |
| 161 | 320 | actor_runtime_state(scope) |
| 162 | 321 | .event_hooks |
| @@ -164,14 +323,8 @@ | ||
| 164 | 323 | .map_err(|_| anyhow!("event hooks were already installed")) |
| 165 | 324 | } |
| 166 | 325 | |
| 167 | -fn global_function(scope: &mut v8::PinScope, name: &str) -> Result<v8::Global<v8::Function>> { | |
| 168 | - let global = scope.get_current_context().global(scope); | |
| 169 | - let key = v8::String::new(scope, name).unwrap(); | |
| 170 | - let function: v8::Local<v8::Function> = global | |
| 171 | - .get(scope, key.into()) | |
| 172 | - .ok_or_else(|| anyhow!("no {name}"))? | |
| 173 | - .try_into() | |
| 174 | - .map_err(|_| anyhow!("{name} is not a function"))?; | |
| 326 | +fn internal_global(scope: &mut v8::PinScope, name: &str) -> Result<v8::Global<v8::Function>> { | |
| 327 | + let function = internal_function(scope, name)?; | |
| 175 | 328 | Ok(v8::Global::new(scope, function)) |
| 176 | 329 | } |
| 177 | 330 | |
| @@ -180,14 +333,7 @@ | ||
| 180 | 333 | name: &str, |
| 181 | 334 | cls: v8::Local<v8::Value>, |
| 182 | 335 | ) -> Result<()> { |
| 183 | - let ctx = scope.get_current_context(); | |
| 184 | - let global = ctx.global(scope); | |
| 185 | - let ck = static_key(scope, &v8_strings::CELL); | |
| 186 | - let cell = global | |
| 187 | - .get(scope, ck.into()) | |
| 188 | - .unwrap() | |
| 189 | - .to_object(scope) | |
| 190 | - .unwrap(); | |
| 336 | + let cell = cell_state(scope)?; | |
| 191 | 337 | let clk = v8::String::new(scope, "classes").unwrap(); |
| 192 | 338 | let classes = cell |
| 193 | 339 | .get(scope, clk.into()) |
| @@ -208,21 +354,12 @@ | ||
| 208 | 354 | ns: v8::Local<v8::Object>, |
| 209 | 355 | do_classes: &[String], |
| 210 | 356 | ) -> Result<()> { |
| 211 | - let context = scope.get_current_context(); | |
| 212 | - let global = context.global(scope); | |
| 213 | - let cf = global | |
| 214 | - .get(scope, v8::String::new(scope, "__cf").unwrap().into()) | |
| 215 | - .and_then(|value| value.to_object(scope)) | |
| 216 | - .ok_or_else(|| anyhow!("missing __cf runtime state"))?; | |
| 357 | + let cf = internal_object(scope, "__cf")?; | |
| 217 | 358 | let exports = cf |
| 218 | 359 | .get(scope, v8::String::new(scope, "exports").unwrap().into()) |
| 219 | 360 | .and_then(|value| value.to_object(scope)) |
| 220 | 361 | .ok_or_else(|| anyhow!("missing __cf.exports"))?; |
| 221 | - let cell_key = static_key(scope, &v8_strings::CELL); | |
| 222 | - let cell = global | |
| 223 | - .get(scope, cell_key.into()) | |
| 224 | - .and_then(|value| value.to_object(scope)) | |
| 225 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 362 | + let cell = cell_state(scope)?; | |
| 226 | 363 | let make_ns: v8::Local<v8::Function> = cell |
| 227 | 364 | .get( |
| 228 | 365 | scope, |
| @@ -260,13 +397,7 @@ | ||
| 260 | 397 | script_name: &str, |
| 261 | 398 | do_classes: &[String], |
| 262 | 399 | ) -> Result<()> { |
| 263 | - let context = scope.get_current_context(); | |
| 264 | - let global = context.global(scope); | |
| 265 | - let cell_key = static_key(scope, &v8_strings::CELL); | |
| 266 | - let cell = global | |
| 267 | - .get(scope, cell_key.into()) | |
| 268 | - .and_then(|value| value.to_object(scope)) | |
| 269 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 400 | + let cell = cell_state(scope)?; | |
| 270 | 401 | let keys_key = v8::String::new(scope, "namespaceKeys").unwrap(); |
| 271 | 402 | let keys = cell |
| 272 | 403 | .get(scope, keys_key.into()) |
| @@ -295,13 +426,7 @@ | ||
| 295 | 426 | /// an alarm the previous deployment armed. Absent `triggers.crons`, the list |
| 296 | 427 | /// is empty and the cron cell retires itself. |
| 297 | 428 | pub(super) fn inject_crons(scope: &mut v8::PinScope, crons: &[String]) -> Result<()> { |
| 298 | - let context = scope.get_current_context(); | |
| 299 | - let global = context.global(scope); | |
| 300 | - let cell_key = static_key(scope, &v8_strings::CELL); | |
| 301 | - let cell = global | |
| 302 | - .get(scope, cell_key.into()) | |
| 303 | - .and_then(|value| value.to_object(scope)) | |
| 304 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 429 | + let cell = cell_state(scope)?; | |
| 305 | 430 | let list = v8::Array::new(scope, crons.len() as i32); |
| 306 | 431 | for (index, cron) in crons.iter().enumerate() { |
| 307 | 432 | let value = v8::String::new(scope, cron).ok_or_else(|| anyhow!("cron expression"))?; |
| @@ -321,12 +446,7 @@ | ||
| 321 | 446 | script_name: &str, |
| 322 | 447 | workflow_bindings: &[WorkflowBinding], |
| 323 | 448 | ) -> Result<()> { |
| 324 | - let context = scope.get_current_context(); | |
| 325 | - let global = context.global(scope); | |
| 326 | - let cell = global | |
| 327 | - .get(scope, v8::String::new(scope, "__cell").unwrap().into()) | |
| 328 | - .and_then(|value| value.to_object(scope)) | |
| 329 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 449 | + let cell = cell_state(scope)?; | |
| 330 | 450 | let map = v8::Object::new(scope); |
| 331 | 451 | for binding in workflow_bindings { |
| 332 | 452 | let key = |
| @@ -349,6 +469,26 @@ | ||
| 349 | 469 | Ok(()) |
| 350 | 470 | } |
| 351 | 471 | |
| 472 | +/// `__cell.containers`: the classes whose objects get a `ctx.container`. | |
| 473 | +/// A class outside this map gets none, which is what the | |
| 474 | +/// `@cloudflare/containers` constructor checks. | |
| 475 | +pub(super) fn inject_containers( | |
| 476 | + scope: &mut v8::PinScope, | |
| 477 | + containers: &[crate::container::ContainerSpec], | |
| 478 | +) -> Result<()> { | |
| 479 | + let cell = cell_state(scope)?; | |
| 480 | + let map = v8::Object::new(scope); | |
| 481 | + for spec in containers { | |
| 482 | + let key = | |
| 483 | + v8::String::new(scope, &spec.class_name).ok_or_else(|| anyhow!("container class"))?; | |
| 484 | + let value = v8::Boolean::new(scope, true); | |
| 485 | + map.set(scope, key.into(), value.into()); | |
| 486 | + } | |
| 487 | + let key = v8::String::new(scope, "containers").unwrap(); | |
| 488 | + cell.set(scope, key.into(), map.into()); | |
| 489 | + Ok(()) | |
| 490 | +} | |
| 491 | + | |
| 352 | 492 | /// Register the workflow cell class under its script-scoped name. |
| 353 | 493 | /// |
| 354 | 494 | /// `harness.js` registers `__WorkflowCell` under the bare `__Workflow` at |
| @@ -395,12 +535,7 @@ | ||
| 395 | 535 | /// this runs on every isolate load. |
| 396 | 536 | pub(super) fn inject_kv_limits(scope: &mut v8::PinScope) -> Result<()> { |
| 397 | 537 | use celld_logic::kv; |
| 398 | - let context = scope.get_current_context(); | |
| 399 | - let global = context.global(scope); | |
| 400 | - let cell = global | |
| 401 | - .get(scope, v8::String::new(scope, "__cell").unwrap().into()) | |
| 402 | - .and_then(|value| value.to_object(scope)) | |
| 403 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 538 | + let cell = cell_state(scope)?; | |
| 404 | 539 | let limits = v8::Object::new(scope); |
| 405 | 540 | let set = |scope: &mut v8::PinScope, name: &str, value: f64| { |
| 406 | 541 | let key = v8::String::new(scope, name).unwrap(); |
| @@ -429,11 +564,6 @@ | ||
| 429 | 564 | // These are test-only and they read the production environment rather than |
| 430 | 565 | // sitting behind `cfg(celld_internal_tests)`, because the code they steer |
| 431 | 566 | // is JavaScript in the harness and a cfg cannot reach it. |
| 432 | - // `CELLD_TEST_OTEL_SWEEP_MS` is the existing precedent for a | |
| 433 | - // controlled-timing override living in production code. Collapsing them | |
| 434 | - // into one name keeps that surface at a single documented variable however | |
| 435 | - // many knobs the feature grows, rather than a new `CELLD_TEST_KV_*` for | |
| 436 | - // each -- which is what this had already become. | |
| 437 | 567 | // |
| 438 | 568 | // What each is for, and why a test cannot do without it: |
| 439 | 569 | // |
| @@ -538,22 +668,21 @@ | ||
| 538 | 668 | let kv_bindings = config.kv_bindings.as_slice(); |
| 539 | 669 | let queue_bindings = config.queue_bindings.as_slice(); |
| 540 | 670 | let workflow_bindings = config.workflow_bindings.as_slice(); |
| 541 | - let ai_binding = config.ai_binding.as_deref(); | |
| 542 | 671 | let vars = config.vars.as_slice(); |
| 543 | 672 | let services = config.services.as_slice(); |
| 544 | 673 | let asset_binding = config.asset_binding.as_deref(); |
| 545 | 674 | // call the harness: for each binding, env[bindingName] = makeNamespace(className) |
| 546 | 675 | let src = { |
| 547 | - let mut lines = String::from("(() => { const e = __cell.env;\n"); | |
| 676 | + let mut lines = String::from("const e = __celld.__cell.env;\n"); | |
| 548 | 677 | for (bname, cname) in bindings { |
| 549 | 678 | lines.push_str(&format!( |
| 550 | - "e[{:?}] = __cell.makeNamespace({:?});\n", | |
| 679 | + "e[{:?}] = __celld.__cell.makeNamespace({:?});\n", | |
| 551 | 680 | bname, cname |
| 552 | 681 | )); |
| 553 | 682 | } |
| 554 | 683 | for (name, bucket) in r2_bindings { |
| 555 | 684 | lines.push_str(&format!( |
| 556 | - "e[{:?}] = __makeR2Bucket({:?}, {:?});\n", | |
| 685 | + "e[{:?}] = __celld.__makeR2Bucket({:?}, {:?});\n", | |
| 557 | 686 | name, name, bucket |
| 558 | 687 | )); |
| 559 | 688 | } |
| @@ -566,7 +695,7 @@ | ||
| 566 | 695 | // rather than fail. When shards outnumber one, this becomes a name |
| 567 | 696 | // per shard and the choice moves here too. |
| 568 | 697 | lines.push_str(&format!( |
| 569 | - "e[{:?}] = __makeKvNamespace({:?}, {:?});\n", | |
| 698 | + "e[{:?}] = __celld.__makeKvNamespace({:?}, {:?});\n", | |
| 570 | 699 | binding, |
| 571 | 700 | id, |
| 572 | 701 | celld_logic::kv::cell_name(id, 0), |
| @@ -574,7 +703,7 @@ | ||
| 574 | 703 | } |
| 575 | 704 | for binding in queue_bindings { |
| 576 | 705 | lines.push_str(&format!( |
| 577 | - "e[{:?}] = __makeQueue({:?}, {:?}, {});\n", | |
| 706 | + "e[{:?}] = __celld.__makeQueue({:?}, {:?}, {});\n", | |
| 578 | 707 | binding.environment, |
| 579 | 708 | binding.queue, |
| 580 | 709 | celld_logic::queue::cell_name(&binding.queue), |
| @@ -583,26 +712,23 @@ | ||
| 583 | 712 | } |
| 584 | 713 | for (name, database) in d1_bindings { |
| 585 | 714 | lines.push_str(&format!( |
| 586 | - "e[{:?}] = __makeD1Database({:?});\n", | |
| 715 | + "e[{:?}] = __celld.__makeD1Database({:?});\n", | |
| 587 | 716 | name, database |
| 588 | 717 | )); |
| 589 | 718 | } |
| 590 | 719 | for binding in workflow_bindings { |
| 591 | 720 | lines.push_str(&format!( |
| 592 | - "e[{:?}] = __makeWorkflow({:?});\n", | |
| 721 | + "e[{:?}] = __celld.__makeWorkflow({:?});\n", | |
| 593 | 722 | binding.environment, binding.workflow |
| 594 | 723 | )); |
| 595 | 724 | } |
| 596 | - if let (Some(name), Ok(url)) = (ai_binding, std::env::var("CELLD_AI_URL")) { | |
| 597 | - lines.push_str(&format!("e[{:?}] = __makeAiBinding({:?});\n", name, url)); | |
| 598 | - } | |
| 599 | 725 | for (binding, script, entrypoint) in services { |
| 600 | 726 | let entrypoint = match entrypoint { |
| 601 | 727 | Some(name) => format!("{name:?}"), |
| 602 | 728 | None => "null".to_string(), |
| 603 | 729 | }; |
| 604 | 730 | lines.push_str(&format!( |
| 605 | - "e[{:?}] = __makeServiceBinding({:?}, {});\n", | |
| 731 | + "e[{:?}] = __celld.__makeServiceBinding({:?}, {});\n", | |
| 606 | 732 | binding, script, entrypoint |
| 607 | 733 | )); |
| 608 | 734 | } |
| @@ -611,24 +737,45 @@ | ||
| 611 | 737 | } |
| 612 | 738 | if let Some(name) = asset_binding { |
| 613 | 739 | lines.push_str(&format!( |
| 614 | - "e[{:?}] = __makeAssetsBinding({:?});\n", | |
| 740 | + "e[{:?}] = __celld.__makeAssetsBinding({:?});\n", | |
| 615 | 741 | name, script_name |
| 616 | 742 | )); |
| 617 | 743 | } |
| 618 | - if let Some(name) = config.loader_binding.as_deref() { | |
| 619 | - lines.push_str(&format!("e[{:?}] = __makeLoader();\n", name)); | |
| 744 | + // One `__makeLoader()` call for each binding. Each call builds its own | |
| 745 | + // `byName` cache, so two loaders are two namespaces, as they are in | |
| 746 | + // workerd. Sharing one loader object between the names would merge the | |
| 747 | + // caches and return one Worker for two different `get()` calls. | |
| 748 | + for name in &config.loader_bindings { | |
| 749 | + lines.push_str(&format!("e[{:?}] = __celld.__makeLoader();\n", name)); | |
| 620 | 750 | } |
| 621 | - // A loaded worker's caller-supplied `env` (plain JSON values only in | |
| 622 | - // the walking skeleton) merges last, over the declared bindings. | |
| 623 | - if let Some(env) = config.loader_env.as_deref() { | |
| 624 | - lines.push_str(&format!("Object.assign(e, {});\n", env)); | |
| 625 | - } | |
| 626 | - lines.push_str("})();"); | |
| 627 | 751 | lines |
| 628 | 752 | }; |
| 629 | - let code = v8::String::new(scope, &src).unwrap(); | |
| 630 | - let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("env compile"))?; | |
| 631 | - s.run(scope).ok_or_else(|| anyhow!("env run"))?; | |
| 753 | + run_internal_snippet(scope, &src).ok_or_else(|| anyhow!("env install failed"))?; | |
| 754 | + if let Some(env) = &config.loader_env { | |
| 755 | + let installer = internal_function(scope, "__installLoaderEnv")?; | |
| 756 | + // A flat [script, entrypoint, props, ...] array avoids one V8 array | |
| 757 | + // allocation for every capability that the parent transfers. | |
| 758 | + let routes = v8::Array::new(scope, env.routes.len().saturating_mul(3) as i32); | |
| 759 | + for (index, route) in env.routes.iter().enumerate() { | |
| 760 | + let offset = (index * 3) as u32; | |
| 761 | + let script = v8::String::new(scope, &route.script).unwrap(); | |
| 762 | + routes.set_index(scope, offset, script.into()); | |
| 763 | + let entrypoint: v8::Local<v8::Value> = match &route.entrypoint { | |
| 764 | + Some(name) => v8::String::new(scope, name).unwrap().into(), | |
| 765 | + None => v8::null(scope).into(), | |
| 766 | + }; | |
| 767 | + routes.set_index(scope, offset + 1, entrypoint); | |
| 768 | + let props = super::bytes_value(scope, route.props.clone()); | |
| 769 | + routes.set_index(scope, offset + 2, props); | |
| 770 | + } | |
| 771 | + let bytes = super::bytes_value(scope, env.bytes.clone()); | |
| 772 | + let tc = std::pin::pin!(v8::TryCatch::new(scope)); | |
| 773 | + let tc = &mut tc.init(); | |
| 774 | + let receiver = v8::undefined(tc).into(); | |
| 775 | + installer | |
| 776 | + .call(tc, receiver, &[bytes, routes.into()]) | |
| 777 | + .ok_or_else(|| anyhow!("loader env install: {}", exc!(tc)))?; | |
| 778 | + } | |
| 632 | 779 | Ok(()) |
| 633 | 780 | } |
| 634 | 781 | |
| @@ -725,12 +872,7 @@ | ||
| 725 | 872 | /// shared `__Queue` class cannot dispatch according to whichever producer |
| 726 | 873 | /// registered the class first. |
| 727 | 874 | pub(super) fn inject_queue_config(scope: &mut v8::PinScope, config: &WorkerConfig) -> Result<()> { |
| 728 | - let context = scope.get_current_context(); | |
| 729 | - let global = context.global(scope); | |
| 730 | - let cell = global | |
| 731 | - .get(scope, v8::String::new(scope, "__cell").unwrap().into()) | |
| 732 | - .and_then(|value| value.to_object(scope)) | |
| 733 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 875 | + let cell = cell_state(scope)?; | |
| 734 | 876 | let consumers = v8::Object::new(scope); |
| 735 | 877 | for registration in &config.queue_consumers { |
| 736 | 878 | let value = v8::Object::new(scope); |
| @@ -803,7 +945,7 @@ | ||
| 803 | 945 | set_limit( |
| 804 | 946 | scope, |
| 805 | 947 | "producerGroupMs", |
| 806 | - crate::env_vars::optional::<u64>("CELLD_QUEUE_PRODUCER_GROUP_MS")?.unwrap_or(4) as f64, | |
| 948 | + crate::queue_batching::timing().producer_ms as f64, | |
| 807 | 949 | ); |
| 808 | 950 | set_limit( |
| 809 | 951 | scope, |
| @@ -840,13 +982,7 @@ | ||
| 840 | 982 | scope: &mut v8::PinScope, |
| 841 | 983 | ns: v8::Local<v8::Object>, |
| 842 | 984 | ) -> Result<()> { |
| 843 | - let context = scope.get_current_context(); | |
| 844 | - let global = context.global(scope); | |
| 845 | - let cell_key = static_key(scope, &v8_strings::CELL); | |
| 846 | - let cell = global | |
| 847 | - .get(scope, cell_key.into()) | |
| 848 | - .and_then(|value| value.to_object(scope)) | |
| 849 | - .ok_or_else(|| anyhow!("missing __cell runtime state"))?; | |
| 985 | + let cell = cell_state(scope)?; | |
| 850 | 986 | let key = v8::String::new(scope, "entrypoints").unwrap(); |
| 851 | 987 | let entrypoints = cell |
| 852 | 988 | .get(scope, key.into()) |
| @@ -867,11 +1003,7 @@ | ||
| 867 | 1003 | .get(scope, key.into()) |
| 868 | 1004 | .and_then(|value| value.to_object(scope)) |
| 869 | 1005 | .ok_or_else(|| anyhow!("missing Durable Object class registry"))?; |
| 870 | - let cf_key = v8::String::new(scope, "__cf").unwrap(); | |
| 871 | - let cf = global | |
| 872 | - .get(scope, cf_key.into()) | |
| 873 | - .and_then(|value| value.to_object(scope)) | |
| 874 | - .ok_or_else(|| anyhow!("missing __cf"))?; | |
| 1006 | + let cf = internal_object(scope, "__cf")?; | |
| 875 | 1007 | let key = v8::String::new(scope, "WorkerEntrypoint").unwrap(); |
| 876 | 1008 | let entrypoint_base = cf |
| 877 | 1009 | .get(scope, key.into()) |
| @@ -928,13 +1060,7 @@ | ||
| 928 | 1060 | if workflow_bindings.is_empty() { |
| 929 | 1061 | return Ok(()); |
| 930 | 1062 | } |
| 931 | - let context = scope.get_current_context(); | |
| 932 | - let global = context.global(scope); | |
| 933 | - let cf_key = v8::String::new(scope, "__cf").unwrap(); | |
| 934 | - let cf = global | |
| 935 | - .get(scope, cf_key.into()) | |
| 936 | - .and_then(|value| value.to_object(scope)) | |
| 937 | - .ok_or_else(|| anyhow!("missing __cf"))?; | |
| 1063 | + let cf = internal_object(scope, "__cf")?; | |
| 938 | 1064 | let key = v8::String::new(scope, "WorkflowEntrypoint").unwrap(); |
| 939 | 1065 | let base = cf |
| 940 | 1066 | .get(scope, key.into()) |
| @@ -994,10 +1120,8 @@ | ||
| 994 | 1120 | /// Record the node id. Every cell scope routes through the host, whichever node |
| 995 | 1121 | /// owns it. |
| 996 | 1122 | pub(super) fn inject_routing(scope: &mut v8::PinScope, node: &str) -> Result<()> { |
| 997 | - let src = format!("(() => {{ __cell.node = {node:?}; }})();"); | |
| 998 | - let code = v8::String::new(scope, &src).unwrap(); | |
| 999 | - let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("routing compile"))?; | |
| 1000 | - s.run(scope).ok_or_else(|| anyhow!("routing run"))?; | |
| 1123 | + let src = format!("__celld.__cell.node = {node:?};"); | |
| 1124 | + run_internal_snippet(scope, &src).ok_or_else(|| anyhow!("routing install failed"))?; | |
| 1001 | 1125 | Ok(()) |
| 1002 | 1126 | } |
| 1003 | 1127 | |
| @@ -1018,6 +1142,7 @@ | ||
| 1018 | 1142 | cell, |
| 1019 | 1143 | cell_storage.path, |
| 1020 | 1144 | cell_storage.epoch, |
| 1145 | + cell_storage.replicated_wake, | |
| 1021 | 1146 | cell_storage.vfs, |
| 1022 | 1147 | compat.sqlite_vec, |
| 1023 | 1148 | ) |
| @@ -1026,28 +1151,56 @@ | ||
| 1026 | 1151 | finish_cell_adoption(tc, cell, owned) |
| 1027 | 1152 | } |
| 1028 | 1153 | |
| 1154 | +pub(super) struct EmbeddedStartup<'a> { | |
| 1155 | + pub id: &'a str, | |
| 1156 | + pub props_sc: Vec<u8>, | |
| 1157 | + pub restored_image: Option<Vec<u8>>, | |
| 1158 | +} | |
| 1159 | + | |
| 1029 | 1160 | pub(super) fn adopt_embedded_cell( |
| 1030 | 1161 | tc: &mut v8::PinScope, |
| 1031 | 1162 | cell: &str, |
| 1032 | 1163 | parent: &storage::StorageIdentity, |
| 1033 | 1164 | name: &str, |
| 1034 | - id: &str, | |
| 1035 | - props_json: &str, | |
| 1165 | + startup: EmbeddedStartup<'_>, | |
| 1036 | 1166 | compat: Compat, |
| 1037 | 1167 | ) -> Result<Option<i64>> { |
| 1038 | - storage::open_embedded(cell, parent, name, compat.sqlite_vec) | |
| 1039 | - .context("facet storage open failed")?; | |
| 1168 | + storage::open_embedded( | |
| 1169 | + cell, | |
| 1170 | + parent, | |
| 1171 | + name, | |
| 1172 | + startup.restored_image, | |
| 1173 | + compat.sqlite_vec, | |
| 1174 | + ) | |
| 1175 | + .context("facet storage open failed")?; | |
| 1040 | 1176 | let alarm = finish_cell_adoption(tc, cell, true)?; |
| 1041 | 1177 | let depth = parent.facet_path.len() + 1; |
| 1042 | - let source = format!( | |
| 1043 | - "__cell.facetConfigs[{cell:?}] = {{ id: {id:?}, props: JSON.parse({props_json:?}), depth: {depth} }};" | |
| 1044 | - ); | |
| 1045 | - let code = v8::String::new(tc, &source).unwrap(); | |
| 1046 | - let script = | |
| 1047 | - v8::Script::compile(tc, code, None).ok_or_else(|| anyhow!("facet config compile"))?; | |
| 1048 | - script | |
| 1049 | - .run(tc) | |
| 1050 | - .ok_or_else(|| anyhow!("facet config install"))?; | |
| 1178 | + // Decode in the loaded isolate and install the value directly. A JSON | |
| 1179 | + // source string flattened structured-clone types before the constructor | |
| 1180 | + // could read them, and it represented absent props as an explicit null. | |
| 1181 | + let cell_state = cell_state(tc)?; | |
| 1182 | + let configs_key = v8::String::new(tc, "facetConfigs").unwrap(); | |
| 1183 | + let configs = cell_state | |
| 1184 | + .get(tc, configs_key.into()) | |
| 1185 | + .and_then(|value| value.to_object(tc)) | |
| 1186 | + .ok_or_else(|| anyhow!("missing facet config registry"))?; | |
| 1187 | + let config = v8::Object::new(tc); | |
| 1188 | + let id_key = v8::String::new(tc, "id").unwrap(); | |
| 1189 | + let id_value = v8::String::new(tc, startup.id).unwrap(); | |
| 1190 | + config.set(tc, id_key.into(), id_value.into()); | |
| 1191 | + let props = if startup.props_sc.is_empty() { | |
| 1192 | + v8::undefined(tc).into() | |
| 1193 | + } else { | |
| 1194 | + storage_ops::deserialize_storage_value(tc, storage::StoredValue::V8(startup.props_sc)) | |
| 1195 | + .ok_or_else(|| anyhow!("decode facet props"))? | |
| 1196 | + }; | |
| 1197 | + let props_key = v8::String::new(tc, "props").unwrap(); | |
| 1198 | + config.set(tc, props_key.into(), props); | |
| 1199 | + let depth_key = v8::String::new(tc, "depth").unwrap(); | |
| 1200 | + let depth_value = v8::Integer::new(tc, depth as i32); | |
| 1201 | + config.set(tc, depth_key.into(), depth_value.into()); | |
| 1202 | + let cell_key = v8::String::new(tc, cell).unwrap(); | |
| 1203 | + configs.set(tc, cell_key.into(), config.into()); | |
| 1051 | 1204 | Ok(alarm) |
| 1052 | 1205 | } |
| 1053 | 1206 | |
| @@ -1075,10 +1228,8 @@ | ||
| 1075 | 1228 | // The release loses nothing the cell needs back: `register_actor_name` |
| 1076 | 1229 | // persists the id name before writing it here, so the take-in below reads |
| 1077 | 1230 | // it back. |
| 1078 | - let source = format!("(() => {{ const s = {cell:?}; __cell.release(s); }})();"); | |
| 1079 | - let code = v8::String::new(tc, &source).unwrap(); | |
| 1080 | - let script = v8::Script::compile(tc, code, None).ok_or_else(|| anyhow!("adopt compile"))?; | |
| 1081 | - script.run(tc).ok_or_else(|| anyhow!("adopt run"))?; | |
| 1231 | + let source = format!("__celld.__cell.release({cell:?});"); | |
| 1232 | + run_internal_snippet(tc, &source).ok_or_else(|| anyhow!("adopt failed"))?; | |
| 1082 | 1233 | if !owned { |
| 1083 | 1234 | storage::close(cell); |
| 1084 | 1235 | return Ok(None); |
| @@ -1090,23 +1241,19 @@ | ||
| 1090 | 1241 | |
| 1091 | 1242 | pub(super) fn inject_storage_compatibility(scope: &mut v8::PinScope, compat: Compat) -> Result<()> { |
| 1092 | 1243 | let source = format!( |
| 1093 | - "__cell.deleteAllDeletesAlarm = {};\n\ | |
| 1094 | - __cell.compat.jsRpc = {};\n\ | |
| 1095 | - __cell.compat.fetcherGetPutDelete = {};\n\ | |
| 1096 | - __cell.compat.websocketStandardBinaryType = {};\n\ | |
| 1097 | - __cell.compat.queueJsonMessages = {};", | |
| 1244 | + "const c = __celld.__cell;\n\ | |
| 1245 | + c.deleteAllDeletesAlarm = {};\n\ | |
| 1246 | + c.compat.jsRpc = {};\n\ | |
| 1247 | + c.compat.fetcherGetPutDelete = {};\n\ | |
| 1248 | + c.compat.websocketStandardBinaryType = {};\n\ | |
| 1249 | + c.compat.queueJsonMessages = {};", | |
| 1098 | 1250 | compat.delete_all_deletes_alarm, |
| 1099 | 1251 | compat.js_rpc, |
| 1100 | 1252 | compat.fetcher_get_put_delete, |
| 1101 | 1253 | compat.websocket_standard_binary_type, |
| 1102 | 1254 | compat.queue_json_messages, |
| 1103 | 1255 | ); |
| 1104 | - let code = v8::String::new(scope, &source).unwrap(); | |
| 1105 | - let script = | |
| 1106 | - v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compatibility compile"))?; | |
| 1107 | - script | |
| 1108 | - .run(scope) | |
| 1109 | - .ok_or_else(|| anyhow!("compatibility run"))?; | |
| 1256 | + run_internal_snippet(scope, &source).ok_or_else(|| anyhow!("compatibility install failed"))?; | |
| 1110 | 1257 | Ok(()) |
| 1111 | 1258 | } |
| 1112 | 1259 | |
| @@ -1121,14 +1268,7 @@ | ||
| 1121 | 1268 | pub(super) fn harness_env<'s>( |
| 1122 | 1269 | scope: &mut v8::PinScope<'s, '_>, |
| 1123 | 1270 | ) -> Result<v8::Local<'s, v8::Value>> { |
| 1124 | - let ctx = scope.get_current_context(); | |
| 1125 | - let global = ctx.global(scope); | |
| 1126 | - let ck = static_key(scope, &v8_strings::CELL); | |
| 1127 | - let cell = global | |
| 1128 | - .get(scope, ck.into()) | |
| 1129 | - .unwrap() | |
| 1130 | - .to_object(scope) | |
| 1131 | - .unwrap(); | |
| 1271 | + let cell = cell_state(scope)?; | |
| 1132 | 1272 | let ek = static_key(scope, &v8_strings::ENV); |
| 1133 | 1273 | Ok(cell.get(scope, ek.into()).unwrap()) |
| 1134 | 1274 | } |
modifiedcrates/celld/js/byte_streams.js+2−2View file
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | // a source with no start() is started synchronously (mirroring the |
| 14 | 14 | // writable's sink handling), and close() settles parked BYOB reads (see |
| 15 | 15 | // _closeCommit) instead of leaving them for respond(0). |
| 16 | -(() => { | |
| 16 | +return (() => { | |
| 17 | 17 | |
| 18 | 18 | const _brand = Symbol('ReadableByteStreamController'); |
| 19 | 19 | const INVALIDATED = |
| @@ -573,7 +573,7 @@ | ||
| 573 | 573 | } |
| 574 | 574 | |
| 575 | 575 | // Workerd extension: resolve only once at least `min` bytes are in |
| 576 | - // `view` (or the stream ends first — then with what arrived). | |
| 576 | + // `view` (or the stream ends first -- then with what arrived). | |
| 577 | 577 | readAtLeast(min, view) { |
| 578 | 578 | return this.read(view, { min }); |
| 579 | 579 | } |
modifiedcrates/celld/js/cache.js+2−2View file
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | // exactly that cache. Refusing the API would break the large class of |
| 5 | 5 | // Workers that treat `caches.default` as a best-effort layer over their |
| 6 | 6 | // own origin logic, so celld accepts the surface, validates it with |
| 7 | -// Workerd's rules and messages, and misses every match — the same | |
| 7 | +// Workerd's rules and messages, and misses every match -- the same | |
| 8 | 8 | // posture as `passThroughOnException()`, which is a documented no-op |
| 9 | 9 | // because there is no CDN behind it. A per-node in-memory cache can |
| 10 | 10 | // replace the miss without changing any observable contract. |
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | const kCreate = Symbol("celld.Cache.create"); |
| 13 | 13 | |
| 14 | 14 | // A key is a Request or URL string, and it must parse as an absolute |
| 15 | - // http(s) URL — the same rule and message as Workerd's validateUrl. | |
| 15 | + // http(s) URL -- the same rule and message as Workerd's validateUrl. | |
| 16 | 16 | const asKey = (request) => { |
| 17 | 17 | const url = request instanceof Request ? request.url : String(request); |
| 18 | 18 | let parsed = null; |
modifiedcrates/celld/js/compression_streams.js+2−2View file
| @@ -1,4 +1,4 @@ | ||
| 1 | -// CompressionStream / DecompressionStream — WHATWG Compression Streams, | |
| 1 | +// CompressionStream / DecompressionStream -- WHATWG Compression Streams, | |
| 2 | 2 | // each a TransformStream over one stateful native zlib stream |
| 3 | 3 | // (__zlib_stream_new / push / end / drop). Output streams chunk by chunk |
| 4 | 4 | // as input is written; the terminal block arrives from flush() when the |
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | // |
| 8 | 8 | // Compiled on first access (see LAZY_GLOBALS); a bundle that never names |
| 9 | 9 | // either global never pays for this file. |
| 10 | -(() => { | |
| 10 | +return (() => { | |
| 11 | 11 | |
| 12 | 12 | // Per spec the chunk must be a BufferSource; anything else is a |
| 13 | 13 | // TypeError, which errors both sides of the transform. |
addedcrates/celld/js/container.rs+325−0View file
| @@ -1,0 +1,325 @@ | ||
| 1 | +//! Host ops behind `ctx.container`. | |
| 2 | +//! | |
| 3 | +//! JavaScript owns the surface and every validation message, copied from | |
| 4 | +//! workerd's `api/container.c++`; these ops perform the effects through | |
| 5 | +//! `crate::container`. Each takes the cell scope as its first argument, | |
| 6 | +//! the way the storage ops do, and an exec process is addressed by the id | |
| 7 | +//! `__container_exec` returned. | |
| 8 | + | |
| 9 | +use super::*; | |
| 10 | +use crate::container::{self, CellContainer, ContainerEngine, ExecParams, StartParams}; | |
| 11 | +use std::time::Duration; | |
| 12 | + | |
| 13 | +async fn cell_for(scope: &str) -> Result<(Arc<ContainerEngine>, Arc<CellContainer>), String> { | |
| 14 | + let engine = container::engine() | |
| 15 | + .await | |
| 16 | + .map_err(|error| format!("{error:#}"))?; | |
| 17 | + let cell = engine | |
| 18 | + .cell(scope) | |
| 19 | + .ok_or_else(|| "this Durable Object has no container".to_string())?; | |
| 20 | + Ok((engine, cell)) | |
| 21 | +} | |
| 22 | + | |
| 23 | +fn string_arg( | |
| 24 | + scope: &mut v8::PinScope, | |
| 25 | + args: &v8::FunctionCallbackArguments, | |
| 26 | + index: i32, | |
| 27 | +) -> String { | |
| 28 | + args.get(index).to_rust_string_lossy(scope) | |
| 29 | +} | |
| 30 | + | |
| 31 | +fn number_arg(scope: &mut v8::PinScope, args: &v8::FunctionCallbackArguments, index: i32) -> u64 { | |
| 32 | + args.get(index).integer_value(scope).unwrap_or(0).max(0) as u64 | |
| 33 | +} | |
| 34 | + | |
| 35 | +pub(super) fn op_container_running( | |
| 36 | + scope: &mut v8::PinScope, | |
| 37 | + args: v8::FunctionCallbackArguments, | |
| 38 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 39 | +) { | |
| 40 | + let cell = string_arg(scope, &args, 0); | |
| 41 | + let running = container::engine_if_ready() | |
| 42 | + .and_then(|engine| engine.cell(&cell)) | |
| 43 | + .is_some_and(|cell| cell.running()); | |
| 44 | + rv.set(v8::Boolean::new(scope, running).into()); | |
| 45 | +} | |
| 46 | + | |
| 47 | +/// `host:port` the node dials for `getTcpPort(port)`, or a throw. | |
| 48 | +pub(super) fn op_container_address( | |
| 49 | + scope: &mut v8::PinScope, | |
| 50 | + args: v8::FunctionCallbackArguments, | |
| 51 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 52 | +) { | |
| 53 | + let cell = string_arg(scope, &args, 0); | |
| 54 | + let port = number_arg(scope, &args, 1) as u16; | |
| 55 | + let address = container::engine_if_ready() | |
| 56 | + .and_then(|engine| engine.cell(&cell)) | |
| 57 | + .ok_or_else(|| "this Durable Object has no container".to_string()) | |
| 58 | + .and_then(|cell| cell.address(port)); | |
| 59 | + match address { | |
| 60 | + Ok(address) => rv.set(v8::String::new(scope, &address).unwrap().into()), | |
| 61 | + Err(message) => loader_throw(scope, &message), | |
| 62 | + } | |
| 63 | +} | |
| 64 | + | |
| 65 | +#[derive(serde::Deserialize)] | |
| 66 | +#[serde(rename_all = "camelCase")] | |
| 67 | +struct StartArgs { | |
| 68 | + entrypoint: Option<Vec<String>>, | |
| 69 | + #[serde(default)] | |
| 70 | + env: Vec<(String, String)>, | |
| 71 | + #[serde(default)] | |
| 72 | + enable_internet: bool, | |
| 73 | + #[serde(default)] | |
| 74 | + labels: Vec<(String, String)>, | |
| 75 | +} | |
| 76 | + | |
| 77 | +pub(super) fn op_container_start( | |
| 78 | + scope: &mut v8::PinScope, | |
| 79 | + args: v8::FunctionCallbackArguments, | |
| 80 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 81 | +) { | |
| 82 | + let cell = string_arg(scope, &args, 0); | |
| 83 | + let raw = string_arg(scope, &args, 1); | |
| 84 | + let request: StartArgs = match serde_json::from_str(&raw) { | |
| 85 | + Ok(request) => request, | |
| 86 | + Err(error) => return loader_throw(scope, &format!("start(): {error}")), | |
| 87 | + }; | |
| 88 | + // The run opens here, on the calling thread, so the monitor() that | |
| 89 | + // follows this call in the same turn waits for this start's exit. | |
| 90 | + let run = container::engine_if_ready() | |
| 91 | + .and_then(|engine| engine.cell(&cell)) | |
| 92 | + .map(|cell| cell.begin_run()); | |
| 93 | + let async_id = asyncrt::enqueue_io_context(async move { | |
| 94 | + let (engine, cell) = cell_for(&cell).await?; | |
| 95 | + let run = run.unwrap_or_else(|| cell.begin_run()); | |
| 96 | + engine | |
| 97 | + .start( | |
| 98 | + &cell, | |
| 99 | + run, | |
| 100 | + StartParams { | |
| 101 | + entrypoint: request.entrypoint, | |
| 102 | + env: request.env, | |
| 103 | + enable_internet: request.enable_internet, | |
| 104 | + labels: request.labels, | |
| 105 | + }, | |
| 106 | + ) | |
| 107 | + .await | |
| 108 | + .map_err(|error| format!("{error:#}"))?; | |
| 109 | + Ok::<String, String>(String::new()) | |
| 110 | + }); | |
| 111 | + rv.set(promise_for(scope, async_id)); | |
| 112 | +} | |
| 113 | + | |
| 114 | +/// Resolves with the root process's exit code as text once the current | |
| 115 | +/// run ends. Unrefed: a handler can await it, but once the handler has | |
| 116 | +/// answered it cannot keep the event, and so the cell, alive. A drain | |
| 117 | +/// would otherwise wait on a promise that settles only when the container | |
| 118 | +/// exits. After the event, `running` reports the host's state. | |
| 119 | +pub(super) fn op_container_monitor( | |
| 120 | + scope: &mut v8::PinScope, | |
| 121 | + args: v8::FunctionCallbackArguments, | |
| 122 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 123 | +) { | |
| 124 | + let cell = string_arg(scope, &args, 0); | |
| 125 | + let run = container::engine_if_ready() | |
| 126 | + .and_then(|engine| engine.cell(&cell)) | |
| 127 | + .map_or(0, |cell| cell.current_run()); | |
| 128 | + let async_id = asyncrt::enqueue_unrefed(async move { | |
| 129 | + let (engine, cell) = cell_for(&cell).await?; | |
| 130 | + let code = engine.monitor(&cell, run).await?; | |
| 131 | + Ok::<String, String>(code.to_string()) | |
| 132 | + }); | |
| 133 | + rv.set(promise_for(scope, async_id)); | |
| 134 | +} | |
| 135 | + | |
| 136 | +pub(super) fn op_container_destroy( | |
| 137 | + scope: &mut v8::PinScope, | |
| 138 | + args: v8::FunctionCallbackArguments, | |
| 139 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 140 | +) { | |
| 141 | + let cell = string_arg(scope, &args, 0); | |
| 142 | + let async_id = asyncrt::enqueue(async move { | |
| 143 | + let (engine, cell) = cell_for(&cell).await?; | |
| 144 | + engine | |
| 145 | + .destroy(&cell) | |
| 146 | + .await | |
| 147 | + .map_err(|error| format!("{error:#}"))?; | |
| 148 | + Ok::<String, String>(String::new()) | |
| 149 | + }); | |
| 150 | + rv.set(promise_for(scope, async_id)); | |
| 151 | +} | |
| 152 | + | |
| 153 | +pub(super) fn op_container_signal( | |
| 154 | + scope: &mut v8::PinScope, | |
| 155 | + args: v8::FunctionCallbackArguments, | |
| 156 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 157 | +) { | |
| 158 | + let cell = string_arg(scope, &args, 0); | |
| 159 | + let signal = number_arg(scope, &args, 1) as u32; | |
| 160 | + let async_id = asyncrt::enqueue(async move { | |
| 161 | + let (engine, cell) = cell_for(&cell).await?; | |
| 162 | + engine | |
| 163 | + .signal(&cell, signal) | |
| 164 | + .await | |
| 165 | + .map_err(|error| format!("{error:#}"))?; | |
| 166 | + Ok::<String, String>(String::new()) | |
| 167 | + }); | |
| 168 | + rv.set(promise_for(scope, async_id)); | |
| 169 | +} | |
| 170 | + | |
| 171 | +pub(super) fn op_container_inactivity( | |
| 172 | + scope: &mut v8::PinScope, | |
| 173 | + args: v8::FunctionCallbackArguments, | |
| 174 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 175 | +) { | |
| 176 | + let cell = string_arg(scope, &args, 0); | |
| 177 | + let duration = number_arg(scope, &args, 1); | |
| 178 | + let async_id = asyncrt::enqueue(async move { | |
| 179 | + let (_, cell) = cell_for(&cell).await?; | |
| 180 | + cell.set_inactivity(Duration::from_millis(duration)); | |
| 181 | + Ok::<String, String>(String::new()) | |
| 182 | + }); | |
| 183 | + rv.set(promise_for(scope, async_id)); | |
| 184 | +} | |
| 185 | + | |
| 186 | +#[derive(serde::Deserialize)] | |
| 187 | +struct ExecArgs { | |
| 188 | + cmd: Vec<String>, | |
| 189 | + #[serde(default)] | |
| 190 | + env: Vec<(String, String)>, | |
| 191 | + cwd: Option<String>, | |
| 192 | + user: Option<String>, | |
| 193 | + #[serde(default)] | |
| 194 | + combined: bool, | |
| 195 | +} | |
| 196 | + | |
| 197 | +pub(super) fn op_container_exec( | |
| 198 | + scope: &mut v8::PinScope, | |
| 199 | + args: v8::FunctionCallbackArguments, | |
| 200 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 201 | +) { | |
| 202 | + let cell = string_arg(scope, &args, 0); | |
| 203 | + let raw = string_arg(scope, &args, 1); | |
| 204 | + let request: ExecArgs = match serde_json::from_str(&raw) { | |
| 205 | + Ok(request) => request, | |
| 206 | + Err(error) => return loader_throw(scope, &format!("exec(): {error}")), | |
| 207 | + }; | |
| 208 | + let async_id = asyncrt::enqueue(async move { | |
| 209 | + let (engine, cell) = cell_for(&cell).await?; | |
| 210 | + let process = engine | |
| 211 | + .exec( | |
| 212 | + &cell, | |
| 213 | + ExecParams { | |
| 214 | + cmd: request.cmd, | |
| 215 | + env: request.env, | |
| 216 | + cwd: request.cwd, | |
| 217 | + user: request.user, | |
| 218 | + combined: request.combined, | |
| 219 | + }, | |
| 220 | + ) | |
| 221 | + .await | |
| 222 | + .map_err(|error| format!("{error:#}"))?; | |
| 223 | + Ok::<String, String>( | |
| 224 | + serde_json::json!({ "id": process.id, "pid": process.pid }).to_string(), | |
| 225 | + ) | |
| 226 | + }); | |
| 227 | + rv.set(promise_for(scope, async_id)); | |
| 228 | +} | |
| 229 | + | |
| 230 | +// The process ops below are unrefed like `monitor()`: a handler awaits | |
| 231 | +// them, and a process left running when the handler answers does not pin | |
| 232 | +// the cell. | |
| 233 | +fn process_arg( | |
| 234 | + scope: &mut v8::PinScope, | |
| 235 | + args: &v8::FunctionCallbackArguments, | |
| 236 | +) -> Result<Arc<container::ExecProcess>, String> { | |
| 237 | + let id = number_arg(scope, args, 0); | |
| 238 | + container::process(id).ok_or_else(|| "the process is closed".to_string()) | |
| 239 | +} | |
| 240 | + | |
| 241 | +/// One chunk of stdout (1) or stderr (2); an empty chunk is the end. | |
| 242 | +pub(super) fn op_container_exec_read( | |
| 243 | + scope: &mut v8::PinScope, | |
| 244 | + args: v8::FunctionCallbackArguments, | |
| 245 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 246 | +) { | |
| 247 | + let process = process_arg(scope, &args); | |
| 248 | + let which = number_arg(scope, &args, 1) as u8; | |
| 249 | + let async_id = asyncrt::enqueue_unrefed(async move { | |
| 250 | + let process = process?; | |
| 251 | + Ok::<Vec<u8>, String>(process.read(which).await.to_vec()) | |
| 252 | + }); | |
| 253 | + rv.set(promise_for(scope, async_id)); | |
| 254 | +} | |
| 255 | + | |
| 256 | +pub(super) fn op_container_exec_write( | |
| 257 | + scope: &mut v8::PinScope, | |
| 258 | + args: v8::FunctionCallbackArguments, | |
| 259 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 260 | +) { | |
| 261 | + let process = process_arg(scope, &args); | |
| 262 | + let Some(bytes) = view_bytes(args.get(1)) else { | |
| 263 | + return loader_throw(scope, "stdin write needs bytes"); | |
| 264 | + }; | |
| 265 | + let async_id = asyncrt::enqueue_unrefed(async move { | |
| 266 | + process?.write(&bytes).await?; | |
| 267 | + Ok::<String, String>(String::new()) | |
| 268 | + }); | |
| 269 | + rv.set(promise_for(scope, async_id)); | |
| 270 | +} | |
| 271 | + | |
| 272 | +pub(super) fn op_container_exec_close( | |
| 273 | + scope: &mut v8::PinScope, | |
| 274 | + args: v8::FunctionCallbackArguments, | |
| 275 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 276 | +) { | |
| 277 | + let process = process_arg(scope, &args); | |
| 278 | + let async_id = asyncrt::enqueue_unrefed(async move { | |
| 279 | + process?.close_stdin().await; | |
| 280 | + Ok::<String, String>(String::new()) | |
| 281 | + }); | |
| 282 | + rv.set(promise_for(scope, async_id)); | |
| 283 | +} | |
| 284 | + | |
| 285 | +pub(super) fn op_container_exec_wait( | |
| 286 | + scope: &mut v8::PinScope, | |
| 287 | + args: v8::FunctionCallbackArguments, | |
| 288 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 289 | +) { | |
| 290 | + let process = process_arg(scope, &args); | |
| 291 | + let async_id = asyncrt::enqueue_unrefed(async move { | |
| 292 | + let code = process? | |
| 293 | + .wait() | |
| 294 | + .await | |
| 295 | + .map_err(|error| format!("{error:#}"))?; | |
| 296 | + Ok::<String, String>(code.to_string()) | |
| 297 | + }); | |
| 298 | + rv.set(promise_for(scope, async_id)); | |
| 299 | +} | |
| 300 | + | |
| 301 | +pub(super) fn op_container_exec_kill( | |
| 302 | + scope: &mut v8::PinScope, | |
| 303 | + args: v8::FunctionCallbackArguments, | |
| 304 | + mut rv: v8::ReturnValue<v8::Value>, | |
| 305 | +) { | |
| 306 | + let process = process_arg(scope, &args); | |
| 307 | + let signal = number_arg(scope, &args, 1) as u32; | |
| 308 | + let async_id = asyncrt::enqueue_unrefed(async move { | |
| 309 | + process? | |
| 310 | + .kill(signal) | |
| 311 | + .await | |
| 312 | + .map_err(|error| format!("{error:#}"))?; | |
| 313 | + Ok::<String, String>(String::new()) | |
| 314 | + }); | |
| 315 | + rv.set(promise_for(scope, async_id)); | |
| 316 | +} | |
| 317 | + | |
| 318 | +pub(super) fn op_container_exec_drop( | |
| 319 | + scope: &mut v8::PinScope, | |
| 320 | + args: v8::FunctionCallbackArguments, | |
| 321 | + _rv: v8::ReturnValue<v8::Value>, | |
| 322 | +) { | |
| 323 | + let id = number_arg(scope, &args, 0); | |
| 324 | + container::drop_process(id); | |
| 325 | +} |
modifiedcrates/celld/js/crypto.js+2−14View file
| @@ -115,7 +115,7 @@ | ||
| 115 | 115 | // echoes the request's hash string fails with a TypeError. The host |
| 116 | 116 | // parses every asymmetric key, so its details are the source here. |
| 117 | 117 | // |
| 118 | - // `algorithm` is the caller's request, or null when there is none — a | |
| 118 | + // `algorithm` is the caller's request, or null when there is none -- a | |
| 119 | 119 | // node:crypto KeyObject crossing to Web Crypto has only the parsed key. |
| 120 | 120 | // RSA is the one algorithm whose hash the key itself does not carry, so |
| 121 | 121 | // the request is the only source for it and a missing one means SHA-256. |
| @@ -797,17 +797,5 @@ | ||
| 797 | 797 | // a second one by hand, which drifted: it named every EC curve P-256 and |
| 798 | 798 | // left the exponent off an RSA key. The loop below hides this name, and |
| 799 | 799 | // the module is lazy, so it always resolves after this script runs. |
| 800 | - globalThis.$$keyAlgorithm = _keyAlgorithm; | |
| 800 | + __celld.$$keyAlgorithm = _keyAlgorithm; | |
| 801 | 801 | })(); |
| 802 | - | |
| 803 | -// Last harness script, so this sees every internal the others declared. | |
| 804 | -// Runtime plumbing must not show up in `for (const k in globalThis)`: a | |
| 805 | -// bundle walking the globals should find the Web platform and nothing | |
| 806 | -// else. Host ops are already non-enumerable; these are the JS-side ones. | |
| 807 | -for (const n of Object.getOwnPropertyNames(globalThis)) | |
| 808 | - if (n.startsWith("__") || n.startsWith("$$")) | |
| 809 | - // A top-level `function` declaration is non-configurable, so a | |
| 810 | - // couple of harness helpers cannot be hidden. Harmless: a walker | |
| 811 | - // sees a function either way. | |
| 812 | - try { Object.defineProperty(globalThis, n, { enumerable: false }); } | |
| 813 | - catch { /* non-configurable */ } |
modifiedcrates/celld/js/event_source.js+1−1View file
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | // EventSource over the streaming fetch path, following Workerd |
| 2 | 2 | // (src/workerd/api/eventsource.c++): same reconnection ladder (2 s |
| 3 | 3 | // default retry clamped to [1 s, 10 s], one no-body response retries and |
| 4 | -// a second fails), same header set, and the same parser — a message's | |
| 4 | +// a second fails), same header set, and the same parser -- a message's | |
| 5 | 5 | // data lines join with "\n", an empty joined data dispatches nothing, |
| 6 | 6 | // and `id:` persists as the Last-Event-ID for reconnects. |
| 7 | 7 | (function () { |
modifiedcrates/celld/js/harness.js+12178−11166View file
| @@ -90,11172 +90,12184 @@ | ||
| 90 | 90 | } |
| 91 | 91 | // Workerd's "gen" bodies: async iterables become a body stream; |
| 92 | 92 | // sync iterables of buffers/views concatenate eagerly. Called only |
| 93 | -// for object bodies that are not streams or Blobs — an object with | |
| 94 | -// a custom toString/@@toPrimitive stringifies instead, unless it is | |
| 95 | -// an array or async-iterable (Workerd's precedence). Returns null | |
| 96 | -// for the string-coercion path. | |
| 97 | -function __iterableBody(body) { | |
| 98 | - if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) | |
| 99 | - return null; | |
| 100 | - const asyncIter = body[Symbol.asyncIterator]; | |
| 101 | - if (typeof asyncIter === "function") { | |
| 102 | - const iterator = asyncIter.call(body); | |
| 103 | - return new ReadableStream({ | |
| 104 | - async pull(controller) { | |
| 105 | - const result = await iterator.next(); | |
| 106 | - if (result.done) { controller.close(); return; } | |
| 107 | - controller.enqueue(__chunkBytes(result.value)); | |
| 108 | - }, | |
| 109 | - cancel(reason) { | |
| 110 | - if (typeof iterator.return === "function") | |
| 111 | - iterator.return(reason); | |
| 112 | - }, | |
| 113 | - }, { highWaterMark: 0 }); | |
| 114 | - } | |
| 115 | - if (!Array.isArray(body) && | |
| 116 | - (body.toString !== Object.prototype.toString || | |
| 117 | - body[Symbol.toPrimitive] !== undefined)) | |
| 118 | - return null; | |
| 119 | - if (typeof body[Symbol.iterator] !== "function") return null; | |
| 120 | - const chunks = []; | |
| 121 | - let length = 0; | |
| 122 | - for (const chunk of body) { | |
| 123 | - if (!(chunk instanceof ArrayBuffer) && !ArrayBuffer.isView(chunk)) | |
| 124 | - return null; | |
| 125 | - const view = __chunkBytes(chunk); | |
| 126 | - chunks.push(view); | |
| 127 | - length += view.byteLength; | |
| 128 | - } | |
| 129 | - const bytes = new Uint8Array(length); | |
| 130 | - let offset = 0; | |
| 131 | - for (const view of chunks) { | |
| 132 | - bytes.set(view, offset); | |
| 133 | - offset += view.byteLength; | |
| 134 | - } | |
| 135 | - return bytes; | |
| 136 | -} | |
| 137 | -// Drain a Request/Response body stream, caching the result on the | |
| 138 | -// instance so later consumers see the materialized bytes. | |
| 139 | -async function __drainBody(target) { | |
| 140 | - const chunks = []; | |
| 141 | - let length = 0; | |
| 142 | - const reader = target.body.getReader(); | |
| 143 | - for (;;) { | |
| 144 | - const result = await reader.read(); | |
| 145 | - if (result.done) break; | |
| 146 | - chunks.push(result.value); | |
| 147 | - length += result.value.byteLength; | |
| 148 | - } | |
| 149 | - const bytes = new Uint8Array(length); | |
| 150 | - let offset = 0; | |
| 151 | - for (const chunk of chunks) { | |
| 152 | - bytes.set(chunk, offset); | |
| 153 | - offset += chunk.byteLength; | |
| 154 | - } | |
| 155 | - target._bodyBytes = bytes; | |
| 156 | - // text() memoizes into _body on demand. Decoding here charges every | |
| 157 | - // binary passthrough the cost of a string it never reads. | |
| 158 | - target._body = undefined; | |
| 159 | - return bytes; | |
| 160 | -} | |
| 161 | -class CelldBodyStream extends ReadableStream { | |
| 162 | - constructor(owner) { | |
| 163 | - // Couple the stream to its buffered owner, so _bodyBytes and the stream | |
| 164 | - // cannot be installed from different arrays. Copying the owner's bytes | |
| 165 | - // again here doubles the external memory held for every constructed body. | |
| 166 | - if (!(owner instanceof globalThis.Request) && | |
| 167 | - !(owner instanceof globalThis.Response)) | |
| 168 | - throw new TypeError("CelldBodyStream requires a buffered body owner"); | |
| 169 | - const bytes = owner._bodyBytes; | |
| 170 | - if (!(bytes instanceof Uint8Array)) | |
| 171 | - throw new TypeError("CelldBodyStream owner requires buffered body bytes"); | |
| 172 | - const st = { bytes, off: 0 }; | |
| 173 | - super({ | |
| 174 | - pull(controller) { | |
| 175 | - if (st.off >= st.bytes.byteLength) { | |
| 176 | - controller.close(); | |
| 177 | - return; | |
| 178 | - } | |
| 179 | - const end = Math.min(st.off + 64 * 1024, st.bytes.byteLength); | |
| 180 | - controller.enqueue(st.bytes.subarray(st.off, end)); | |
| 181 | - st.off = end; | |
| 182 | - }, | |
| 183 | - }, { highWaterMark: 0 }); | |
| 184 | - this._st = st; | |
| 185 | - this.__celldBodyBytes = bytes; | |
| 186 | - // Known length, so re-using this stream as a subrequest body | |
| 187 | - // still advertises Content-Length. | |
| 188 | - this._expectedLength = bytes.byteLength; | |
| 189 | - } | |
| 190 | - get __celldBodyText() { return new TextDecoder().decode(this.__celldBodyBytes); } | |
| 191 | - // Workerd body streams are internal streams, so BYOB readers | |
| 192 | - // work on them. Naming ReadableStreamBYOBReader compiles the | |
| 193 | - // lazy byte-stream prelude; a worker that never asks for byob | |
| 194 | - // mode never pays for it. | |
| 195 | - getReader(options) { | |
| 196 | - if (options !== undefined && options !== null && | |
| 197 | - options.mode !== undefined) { | |
| 198 | - if (String(options.mode) !== "byob") | |
| 199 | - throw new TypeError(`Invalid reader mode '${options.mode}'`); | |
| 200 | - if (this._ictl === undefined) | |
| 201 | - this._ictl = ReadableStreamBYOBReader._buffered(this._st); | |
| 202 | - return new ReadableStreamBYOBReader(this); | |
| 203 | - } | |
| 204 | - return super.getReader(options); | |
| 205 | - } | |
| 206 | - // Cancelling a body stream poisons later consumption: text() | |
| 207 | - // and friends reject, as they would over a real socket. | |
| 208 | - _cancel(reason) { | |
| 209 | - this._cancelled = true; | |
| 210 | - return super._cancel(reason); | |
| 211 | - } | |
| 212 | -} | |
| 213 | -class CelldHttpBodyStream extends ReadableStream { | |
| 214 | - constructor(streamId) { | |
| 215 | - const id = Number(streamId); | |
| 216 | - super({ | |
| 217 | - async pull(controller) { | |
| 218 | - // A chunk arrives as a Uint8Array. The host moves it in without | |
| 219 | - // a copy. The end of the stream arrives as a string. | |
| 220 | - const chunk = await __http_stream_read(id); | |
| 221 | - if (typeof chunk === "string") controller.close(); | |
| 222 | - else controller.enqueue(chunk); | |
| 223 | - }, | |
| 224 | - cancel() { __http_stream_cancel(id); }, | |
| 225 | - }, { highWaterMark: 0 }); | |
| 226 | - this.__celldStreamId = id; | |
| 227 | - } | |
| 228 | - tee() { | |
| 229 | - if (this.locked) throw new TypeError("ReadableStream is locked"); | |
| 230 | - this._locked = true; | |
| 231 | - this._disturbed = true; | |
| 232 | - const [left, right] = JSON.parse( | |
| 233 | - __http_stream_tee(this.__celldStreamId), | |
| 234 | - ); | |
| 235 | - return [ | |
| 236 | - new CelldHttpBodyStream(left), | |
| 237 | - new CelldHttpBodyStream(right), | |
| 238 | - ]; | |
| 239 | - } | |
| 240 | -} | |
| 241 | -globalThis.Response = class Response { | |
| 242 | - constructor(body, init = {}) { | |
| 243 | - // Streaming/iterable detection runs only for object bodies, so | |
| 244 | - // the common string path skips every instanceof below. | |
| 245 | - let stream = null; | |
| 246 | - let typed = null; | |
| 247 | - if (body !== null && typeof body === "object") { | |
| 248 | - if (body instanceof ReadableStream) stream = body; | |
| 249 | - else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ } | |
| 250 | - else { | |
| 251 | - const iterable = __iterableBody(body); | |
| 252 | - if (iterable instanceof ReadableStream) stream = iterable; | |
| 253 | - else if (iterable !== null) body = iterable; | |
| 254 | - } | |
| 255 | - } | |
| 256 | - this._bodyBytes = stream !== null | |
| 257 | - ? null | |
| 258 | - : typed ? typed.bytes : __bodyBytes(body); | |
| 259 | - // Never decoded eagerly: a whole-body UTF-8 decode costs seconds for a | |
| 260 | - // large binary body (an archive, a git pack) and can exceed V8's string | |
| 261 | - // length. On Response the field is deliberately write-only — text() | |
| 262 | - // decodes fresh from _bodyBytes and only Request.text() memoizes into | |
| 263 | - // _body — but the assignment stays: __drainBody and __adoptBody assign | |
| 264 | - // _body on both classes, so defining it here keeps the hidden-class | |
| 265 | - // shape stable. Do not add a Response reader; do not "simplify" this | |
| 266 | - // away. | |
| 267 | - this._body = undefined; | |
| 268 | - // Hono rebuilds a response after middleware with | |
| 269 | - // `new Response(response.body, response)`; the held stream (or a | |
| 270 | - // fresh CelldBodyStream) preserves the payload across that | |
| 271 | - // standard clone shape. | |
| 272 | - this.body = body == null | |
| 273 | - ? null | |
| 274 | - : stream !== null | |
| 275 | - ? stream | |
| 276 | - : new CelldBodyStream(this); | |
| 277 | - this.status = init.status === undefined ? 200 : Number(init.status); | |
| 278 | - this.statusText = init.statusText === undefined ? "" : String(init.statusText); | |
| 279 | - this.headers = new Headers(init.headers); | |
| 280 | - if (typed && typed.type && !this.headers.has("content-type")) | |
| 281 | - this.headers.set("content-type", typed.type); | |
| 282 | - this.webSocket = init.webSocket; | |
| 283 | - this._wsTarget = init.__wsTarget || init._wsTarget || null; | |
| 284 | - this.ok = this.status >= 200 && this.status <= 299; | |
| 285 | - this.redirected = false; | |
| 286 | - this.type = "default"; | |
| 287 | - this.url = ""; | |
| 288 | - this.bodyUsed = false; | |
| 289 | - if (init.cf !== undefined) this.cf = init.cf; | |
| 290 | - } | |
| 291 | - static json(data, init = {}) { | |
| 292 | - const headers = new Headers(init.headers || {}); | |
| 293 | - if (!headers.has("content-type")) | |
| 294 | - headers.set("content-type", "application/json"); | |
| 295 | - return new Response(JSON.stringify(data), { ...init, headers }); | |
| 296 | - } | |
| 297 | - static redirect(url, status = 302) { | |
| 298 | - const input = String(url); | |
| 299 | - const statusCode = Number(status) | 0; | |
| 300 | - if (![301, 302, 303, 307, 308].includes(statusCode)) { | |
| 301 | - throw new RangeError( | |
| 302 | - `${statusCode} is not a redirect status code. ` + | |
| 303 | - "It must be one of: 301, 302, 303, 307, or 308."); | |
| 304 | - } | |
| 305 | - const response = new Response(null, { | |
| 306 | - status: statusCode, | |
| 307 | - headers: { Location: new URL(input).href }, | |
| 308 | - }); | |
| 309 | - // A redirect response owns a guarded header list. Without the guard, an | |
| 310 | - // application can rewrite Location after construction, which differs | |
| 311 | - // from both Fetch and Workerd even though the initial response is valid. | |
| 312 | - Object.defineProperty(response.headers, "_immutable", { value: true }); | |
| 313 | - return response; | |
| 314 | - } | |
| 315 | - static error() { | |
| 316 | - const response = new Response(null); | |
| 317 | - response.status = 0; | |
| 318 | - response.ok = false; | |
| 319 | - response.type = "error"; | |
| 320 | - return response; | |
| 321 | - } | |
| 322 | - async _consume() { | |
| 323 | - if (this._bodyBytes !== null) { | |
| 324 | - if (this.body !== null && this.body._cancelled) | |
| 325 | - throw new TypeError( | |
| 326 | - "Body has already been used. It can only be used once. " + | |
| 327 | - "Use tee() first if you need to read it multiple times."); | |
| 328 | - return this._bodyBytes; | |
| 329 | - } | |
| 330 | - return __drainBody(this); | |
| 331 | - } | |
| 332 | - async text() { | |
| 333 | - this.bodyUsed = true; | |
| 334 | - return new TextDecoder().decode(await this._consume()); | |
| 335 | - } | |
| 336 | - async json() { return JSON.parse(await this.text()); } | |
| 337 | - async formData() { | |
| 338 | - // The undecoded bytes, not `text()`: a UTF-8 decode replaces each invalid | |
| 339 | - // sequence in a binary file part with one U+FFFD, so both the bytes and | |
| 340 | - // the length change. | |
| 341 | - this.bodyUsed = true; | |
| 342 | - return __parseFormData( | |
| 343 | - await this._consume(), this.headers.get('content-type')); | |
| 344 | - } | |
| 345 | - async arrayBuffer() { | |
| 346 | - this.bodyUsed = true; | |
| 347 | - return (await this._consume()).slice().buffer; | |
| 348 | - } | |
| 349 | - async blob() { | |
| 350 | - return new Blob([await this.arrayBuffer()], | |
| 351 | - { type: this.headers.get("content-type") || "" }); | |
| 352 | - } | |
| 353 | - clone() { | |
| 354 | - if (this.bodyUsed) throw new TypeError("Body has already been consumed"); | |
| 355 | - if (this._bodyBytes === null) | |
| 356 | - throw new TypeError("Cannot clone a streaming response before consumption"); | |
| 357 | - const response = new Response( | |
| 358 | - this.body === null ? null : this._bodyBytes, | |
| 359 | - { | |
| 360 | - status: this.status, statusText: this.statusText, headers: this.headers, | |
| 361 | - webSocket: this.webSocket, __wsTarget: this._wsTarget, cf: this.cf, | |
| 362 | - }, | |
| 363 | - ); | |
| 364 | - response.type = this.type; | |
| 365 | - return response; | |
| 366 | - } | |
| 367 | -}; | |
| 368 | -// Hoisted: this would otherwise allocate an array and scan it on | |
| 369 | -// every Request construction, which is the HTTP hot path. | |
| 370 | -const __HTTP_METHODS = new Set( | |
| 371 | - ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]); | |
| 372 | -const __FETCH_REDIRECT_MODES = new Set(["follow", "manual", "error"]); | |
| 373 | -globalThis.Request = class Request { | |
| 374 | - constructor(input, init = {}) { | |
| 375 | - const prior = input instanceof Request ? input : null; | |
| 376 | - const suppliedSignal = init.signal !== undefined; | |
| 377 | - // The cache option needs the cache_option_enabled compat flag, | |
| 378 | - // which Cells does not implement (Workerd's cache-disabled path). | |
| 379 | - if (init.cache !== undefined) | |
| 380 | - throw new Error("The 'cache' field on 'RequestInitializerDict' " + | |
| 381 | - "is not implemented."); | |
| 382 | - this.url = prior ? prior.url : String(input); | |
| 383 | - { | |
| 384 | - // Workers upper-cases every method (the | |
| 385 | - // upper_case_all_http_methods flag) but rejects anything outside | |
| 386 | - // the known set, reporting the original casing. | |
| 387 | - const raw = String(init.method === undefined | |
| 388 | - ? (prior ? prior.method : "GET") : init.method); | |
| 389 | - const upper = raw.toUpperCase(); | |
| 390 | - if (!__HTTP_METHODS.has(upper)) | |
| 391 | - throw new TypeError(`Invalid HTTP method string: ${raw}`); | |
| 392 | - this.method = upper; | |
| 393 | - } | |
| 394 | - const hasBody = | |
| 395 | - Object.prototype.hasOwnProperty.call(init, "body"); | |
| 396 | - let body = hasBody ? init.body : null; | |
| 397 | - let stream = null; | |
| 398 | - let typed = null; | |
| 399 | - if (hasBody && body !== null && typeof body === "object") { | |
| 400 | - if (body instanceof ReadableStream) stream = body; | |
| 401 | - else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ } | |
| 402 | - else { | |
| 403 | - const iterable = __iterableBody(body); | |
| 404 | - if (iterable instanceof ReadableStream) stream = iterable; | |
| 405 | - else if (iterable !== null) body = iterable; | |
| 406 | - } | |
| 407 | - } | |
| 408 | - if (!hasBody && prior && prior._bodyBytes === null) { | |
| 409 | - // Adopt the prior request's stream; per spec the prior body | |
| 410 | - // is disturbed by the new request. | |
| 411 | - stream = prior.body; | |
| 412 | - prior.bodyUsed = true; | |
| 413 | - } | |
| 414 | - this._bodyBytes = stream !== null | |
| 415 | - ? null | |
| 416 | - : hasBody | |
| 417 | - ? (typed ? typed.bytes : __bodyBytes(body)) | |
| 418 | - : (prior ? prior._bodyBytes.slice() : new Uint8Array()); | |
| 419 | - // Body text is decoded on the first text()/json(), not here: a request | |
| 420 | - // whose body is never read never pays the decode. | |
| 421 | - this._body = undefined; | |
| 422 | - // Headers are stored raw and built on the first `.headers` access. The | |
| 423 | - // hot paths -- a hello world, a Worker that only forwards to a cell -- | |
| 424 | - // read none, so `new Headers` and the JSON.parse behind it never run. | |
| 425 | - if (init.__headersJson !== undefined) { | |
| 426 | - this._headersJson = init.__headersJson; | |
| 427 | - this._headersInit = undefined; | |
| 428 | - } else if (init.headers === undefined && prior) { | |
| 429 | - this._headersJson = prior._headersJson; | |
| 430 | - // Per spec `new Request(request)` copies the header list. The prior | |
| 431 | - // request's `Headers` object cannot stand in for it: `new Headers(h)` | |
| 432 | - // reads `h` through its iterator, which sorts, lower-cases and | |
| 433 | - // combines, so forwarding a request whose headers were read would | |
| 434 | - // undo the wire shape the outbound paths preserve. | |
| 435 | - this._headersInit = prior._headers | |
| 436 | - ? prior._headers.__celldHeaderList | |
| 437 | - : prior._headersInit; | |
| 438 | - } else { | |
| 439 | - this._headersJson = undefined; | |
| 440 | - this._headersInit = init.headers; | |
| 441 | - } | |
| 442 | - this._headers = null; | |
| 443 | - // A typed body's default content-type must land now; only user-built | |
| 444 | - // typed bodies reach this, never the incoming request path. | |
| 445 | - if (typed && typed.type && !this.headers.has("content-type")) { | |
| 446 | - this.headers.set("content-type", typed.type); | |
| 447 | - } | |
| 448 | - this.bodyUsed = false; | |
| 449 | - // The body stream and the signal stay eager, own properties: the RPC and | |
| 450 | - // storage serializers fall back to the lift-into-marker path only when a | |
| 451 | - // value is not directly structured-cloneable, and a Request's un-cloneable | |
| 452 | - // body stream (or AbortSignal) is what triggers that. Making them lazy | |
| 453 | - // getters let `__sc_encode` clone the Request into a broken plain object | |
| 454 | - // and skip the lift -- the serializeHttpTypes conformance failure. | |
| 455 | - this.body = stream !== null | |
| 456 | - ? stream | |
| 457 | - : ["GET", "HEAD"].includes(this.method) | |
| 458 | - ? null : new CelldBodyStream(this); | |
| 459 | - this.redirect = String(init.redirect === undefined | |
| 460 | - ? (prior ? prior.redirect : "follow") | |
| 461 | - : init.redirect); | |
| 462 | - if (!__FETCH_REDIRECT_MODES.has(this.redirect)) { | |
| 463 | - throw new TypeError(`Invalid redirect mode: ${this.redirect}`); | |
| 464 | - } | |
| 465 | - const cf = init.cf === undefined | |
| 466 | - ? (prior ? prior.cf : undefined) : init.cf; | |
| 467 | - if (cf !== undefined) this.cf = cf; | |
| 468 | - this.signal = suppliedSignal | |
| 469 | - ? init.signal | |
| 470 | - : (prior ? prior.signal : new AbortController().signal); | |
| 471 | - this._signalForSubrequests = init.__celldIncomingSignal | |
| 472 | - ? null | |
| 473 | - : suppliedSignal | |
| 474 | - ? this.signal | |
| 475 | - : (prior ? prior._signalForSubrequests : null); | |
| 476 | - } | |
| 477 | - get headers() { | |
| 478 | - if (this._headers === null) { | |
| 479 | - const src = this._headersJson !== undefined | |
| 480 | - ? JSON.parse(this._headersJson) | |
| 481 | - : this._headersInit; | |
| 482 | - this._headers = new Headers(src); | |
| 483 | - this._headersJson = undefined; | |
| 484 | - this._headersInit = undefined; | |
| 485 | - } | |
| 486 | - return this._headers; | |
| 487 | - } | |
| 488 | - set headers(value) { | |
| 489 | - this._headers = value instanceof Headers ? value : new Headers(value); | |
| 490 | - this._headersJson = undefined; | |
| 491 | - this._headersInit = undefined; | |
| 492 | - } | |
| 493 | - async _consume() { | |
| 494 | - if (this._bodyBytes !== null) return this._bodyBytes; | |
| 495 | - return __drainBody(this); | |
| 496 | - } | |
| 497 | - async text() { | |
| 498 | - this.bodyUsed = true; | |
| 499 | - const bytes = await this._consume(); | |
| 500 | - return this._body ??= new TextDecoder().decode(bytes); | |
| 501 | - } | |
| 502 | - async json() { return JSON.parse(await this.text()); } | |
| 503 | - async formData() { | |
| 504 | - // The undecoded bytes, not `text()`: a UTF-8 decode replaces each invalid | |
| 505 | - // sequence in a binary file part with one U+FFFD, so both the bytes and | |
| 506 | - // the length change. | |
| 507 | - this.bodyUsed = true; | |
| 508 | - return __parseFormData( | |
| 509 | - await this._consume(), this.headers.get('content-type')); | |
| 510 | - } | |
| 511 | - async arrayBuffer() { | |
| 512 | - this.bodyUsed = true; | |
| 513 | - return (await this._consume()).slice().buffer; | |
| 514 | - } | |
| 515 | - async blob() { | |
| 516 | - return new Blob([await this.arrayBuffer()], | |
| 517 | - { type: this.headers.get("content-type") || "" }); | |
| 518 | - } | |
| 519 | - clone() { | |
| 520 | - if (this.bodyUsed) throw new TypeError("Body has already been consumed"); | |
| 521 | - if (this._bodyBytes === null) { | |
| 522 | - // Streaming body: tee, keep one branch, clone the other. | |
| 523 | - const [left, right] = this.body.tee(); | |
| 524 | - this.body = left; | |
| 525 | - return new Request(this, { body: right }); | |
| 526 | - } | |
| 527 | - return new Request(this); | |
| 528 | - } | |
| 529 | -}; | |
| 530 | -globalThis.__makeRequest = ( | |
| 531 | - url, method, body, headersJson = "[]", signal = undefined, | |
| 532 | - incomingSignal = false, | |
| 533 | -) => new Request(url, { | |
| 534 | - // The raw header JSON, not a parsed object: an incoming request whose | |
| 535 | - // handler never reads `.headers` (a hello world, or a Worker that only | |
| 536 | - // routes to a cell) then never parses it. See `get headers()`. | |
| 537 | - method, body, __headersJson: headersJson, signal, | |
| 538 | - __celldIncomingSignal: incomingSignal, | |
| 539 | -}); | |
| 540 | -const __fmt = (a) => a.map((x) => { | |
| 541 | - if (typeof x === "string") return x; | |
| 542 | - if (x instanceof Error) return x.stack || (x.name + ": " + x.message); | |
| 543 | - try { return JSON.stringify(x); } catch { return String(x); } | |
| 544 | -}).join(" "); | |
| 545 | -const __consoleNoop = () => {}; | |
| 546 | -globalThis.console = { | |
| 547 | - debug: (...a) => __log(__fmt(a)), | |
| 548 | - error: (...a) => __log("ERROR " + __fmt(a)), | |
| 549 | - info: (...a) => __log(__fmt(a)), | |
| 550 | - log: (...a) => __log(__fmt(a)), | |
| 551 | - warn: (...a) => __log("WARN " + __fmt(a)), | |
| 552 | - clear: __consoleNoop, | |
| 553 | - count: __consoleNoop, | |
| 554 | - group: __consoleNoop, | |
| 555 | - table: __consoleNoop, | |
| 556 | - trace: __consoleNoop, | |
| 557 | - assert: __consoleNoop, | |
| 558 | - countReset: __consoleNoop, | |
| 559 | - dir: __consoleNoop, | |
| 560 | - dirxml: __consoleNoop, | |
| 561 | - groupCollapsed: __consoleNoop, | |
| 562 | - groupEnd: __consoleNoop, | |
| 563 | - profile: __consoleNoop, | |
| 564 | - profileEnd: __consoleNoop, | |
| 565 | - time: __consoleNoop, | |
| 566 | - timeEnd: __consoleNoop, | |
| 567 | - timeLog: __consoleNoop, | |
| 568 | - timeStamp: __consoleNoop, | |
| 569 | - createTask: () => { | |
| 570 | - throw new Error("console.createTask() is not implemented"); | |
| 571 | - }, | |
| 572 | -}; | |
| 573 | - | |
| 574 | -// async-op shims: outbound fetch + timers, driven by the host event loop. | |
| 575 | -// Move one request body through a host subrequest seam. A body that already | |
| 576 | -// names a host stream keeps that stream incremental. An ordinary JavaScript | |
| 577 | -// stream has no host owner, so it uses the existing byte fallback. | |
| 578 | -const __subrequestBody = async (req, absent = false) => { | |
| 579 | - if (absent) return { body: undefined, streamId: undefined }; | |
| 580 | - if (req._bodyBytes !== null) | |
| 581 | - return { body: req._bodyBytes, streamId: undefined }; | |
| 582 | - const streamId = req.body?.__celldStreamId; | |
| 583 | - if (streamId === undefined) { | |
| 584 | - req.bodyUsed = true; | |
| 585 | - return { body: await req._consume(), streamId: undefined }; | |
| 586 | - } | |
| 587 | - // The receiver now owns the one host source. Lock the wrapper so a later | |
| 588 | - // read fails instead of racing the receiver, and expose the transfer through | |
| 589 | - // the standard Body flag. | |
| 590 | - req.bodyUsed = true; | |
| 591 | - req.body.getReader(); | |
| 592 | - return { body: new Uint8Array(), streamId }; | |
| 593 | -}; | |
| 594 | -// A data: URL carries its response inline; RFC 2397 percent-decoding | |
| 595 | -// happens byte-wise, so a payload that is deliberately invalid UTF-8 | |
| 596 | -// survives to the consumer (HTMLRewriter's own suite depends on it). | |
| 597 | -const __dataUrlResponse = (url) => { | |
| 598 | - // The URL parser strips leading and trailing C0 controls and spaces | |
| 599 | - // before doing anything else; a literal trailing space in a data: URL | |
| 600 | - // is therefore not part of the payload, while an encoded %20 is. | |
| 601 | - url = url.replace(/^[\x00-\x20]+/, "").replace(/[\x00-\x20]+$/, ""); | |
| 602 | - const match = /^data:([^,]*),([\s\S]*)$/.exec(url); | |
| 603 | - if (!match) throw new TypeError("Invalid data: URL"); | |
| 604 | - let [, meta, payload] = match; | |
| 605 | - const base64 = /;base64$/i.test(meta); | |
| 606 | - if (base64) meta = meta.replace(/;base64$/i, ""); | |
| 607 | - let bytes; | |
| 608 | - if (base64) { | |
| 609 | - const bin = atob(payload); | |
| 610 | - bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0)); | |
| 611 | - } else { | |
| 612 | - const out = []; | |
| 613 | - for (let i = 0; i < payload.length; i++) { | |
| 614 | - const c = payload[i]; | |
| 615 | - if (c === "%" && /^[0-9A-Fa-f]{2}$/.test(payload.slice(i + 1, i + 3))) { | |
| 616 | - out.push(parseInt(payload.slice(i + 1, i + 3), 16)); | |
| 617 | - i += 2; | |
| 618 | - } else { | |
| 619 | - out.push(payload.charCodeAt(i) & 0xff); | |
| 620 | - } | |
| 621 | - } | |
| 622 | - bytes = Uint8Array.from(out); | |
| 623 | - } | |
| 624 | - return new Response(bytes, { | |
| 625 | - headers: { "content-type": meta || "text/plain;charset=US-ASCII" }, | |
| 626 | - }); | |
| 627 | -}; | |
| 628 | -globalThis.fetch = async (input, init) => { | |
| 629 | - const rawUrl = typeof input === "string" ? input : input?.url; | |
| 630 | - if (typeof rawUrl === "string" && rawUrl.startsWith("data:")) { | |
| 631 | - return __dataUrlResponse(rawUrl); | |
| 632 | - } | |
| 633 | - const req = new Request(input, init); | |
| 634 | - // `fetch(url, { headers: { Upgrade: "websocket" } })` is the other way | |
| 635 | - // Cloudflare opens an outbound socket, and the one most examples use. | |
| 636 | - if ((req.headers.get("upgrade") ?? "").toLowerCase() === "websocket") { | |
| 637 | - return await __fetchWebSocketUpgrade(req); | |
| 638 | - } | |
| 639 | - // The caller's signal, never the incoming request's own. | |
| 640 | - const signal = req._signalForSubrequests; | |
| 641 | - if (signal?.aborted) throw signal.reason; | |
| 642 | - // The bytes go to the host as a typed array, the same way every other | |
| 643 | - // subrequest op takes a body. Encoding them as a JSON number array cost | |
| 644 | - // roughly ten times the body in transient allocation, and it corrupted | |
| 645 | - // nothing only because the host decoded the same shape back. | |
| 646 | - const { body, streamId } = await __subrequestBody( | |
| 647 | - req, ["GET", "HEAD"].includes(req.method)); | |
| 648 | - // The header list, not the iterator: the iterator sorts, lower-cases and | |
| 649 | - // combines, so `Array.from(req.headers)` would send one `X-Trace: a, b` | |
| 650 | - // for two appends and put celld's casing on the wire in place of the | |
| 651 | - // author's. `op_fetch` builds the request with `RequestBuilder::header`, | |
| 652 | - // which appends, so repeats survive. | |
| 653 | - let raw; | |
| 654 | - try { | |
| 655 | - const dispatch = __op_fetch( | |
| 656 | - req.method, req.url, body, | |
| 657 | - JSON.stringify(req.headers.__celldHeaderList), req.redirect, | |
| 658 | - streamId, signal != null, | |
| 659 | - ); | |
| 660 | - if (signal) { | |
| 661 | - // An abort and the response can cross, leaving a body stream nobody | |
| 662 | - // reads holding its upstream connection until the sweeper expires it. | |
| 663 | - // Every arm is silenced because the caller already owns both outcomes. | |
| 664 | - dispatch.then((late) => { | |
| 665 | - if (!signal.aborted) return; | |
| 666 | - const abandoned = JSON.parse(late).streamId; | |
| 667 | - if (abandoned !== undefined) __http_stream_cancel(abandoned); | |
| 668 | - }, () => {}).catch(() => {}); | |
| 669 | - } | |
| 670 | - raw = await (signal ? __awaitCancellableDoCall(dispatch, signal) : dispatch); | |
| 671 | - } catch (error) { | |
| 672 | - // An abort is the caller's reason, not a network error, so it skips | |
| 673 | - // every translation below. | |
| 674 | - if (signal?.aborted && error === signal.reason) throw error; | |
| 675 | - // The Fetch API represents a redirect refusal as a network error, which | |
| 676 | - // rejects with TypeError. Keep the host message for diagnostics. | |
| 677 | - if (req.redirect === "error") { | |
| 678 | - throw new TypeError(error?.message ?? String(error)); | |
| 679 | - } | |
| 680 | - throw error; | |
| 681 | - } | |
| 682 | - const r = JSON.parse(raw); | |
| 683 | - const response = new Response( | |
| 684 | - new CelldHttpBodyStream(r.streamId), | |
| 685 | - { status: r.status, headers: r.headers }, | |
| 686 | - ); | |
| 687 | - response.url = req.url; | |
| 688 | - return response; | |
| 689 | -}; | |
| 690 | -globalThis.__fetchWebSocketUpgrade = async (req) => { | |
| 691 | - const scope = __currentActorScope(); | |
| 692 | - const id = __ws_alloc(); | |
| 693 | - const socket = __makeSocket(id); | |
| 694 | - socket._outbound = true; | |
| 695 | - socket._polled = !scope; | |
| 696 | - socket.url = req.url; | |
| 697 | - socket.readyState = WebSocket.READY_STATE_CONNECTING; | |
| 698 | - __sockets.set(id, socket); | |
| 699 | - let raw; | |
| 700 | - try { | |
| 701 | - raw = JSON.parse(await __ws_upgrade( | |
| 702 | - id, | |
| 703 | - scope, | |
| 704 | - req.url, | |
| 705 | - // The iterator, not the header list, unlike every other outbound | |
| 706 | - // path. The handshake builder on the host side puts these into a | |
| 707 | - // `HeaderMap` with `insert`, which replaces, and it reads the | |
| 708 | - // offered subprotocols with a first-match `find`. Both would drop | |
| 709 | - // every repeat but one. Sending the combined form keeps | |
| 710 | - // `Sec-WebSocket-Protocol: a` plus `: b` meaning `a, b`, which is | |
| 711 | - // what the peer must see. Moving this to the header list needs the | |
| 712 | - // host to append instead, so it is a separate change. | |
| 713 | - JSON.stringify(Array.from(req.headers)), | |
| 714 | - )); | |
| 715 | - } catch (error) { | |
| 716 | - __sockets.delete(id); | |
| 717 | - throw error; | |
| 718 | - } | |
| 719 | - if (!raw.upgraded) { | |
| 720 | - // The server answered without upgrading. That is an ordinary response, | |
| 721 | - // not a connection error, and it is returned unchanged. | |
| 722 | - __sockets.delete(id); | |
| 723 | - const response = new Response(new Uint8Array(raw.body), { | |
| 724 | - status: raw.status, | |
| 725 | - headers: raw.headers, | |
| 726 | - }); | |
| 727 | - response.url = req.url; | |
| 728 | - return response; | |
| 729 | - } | |
| 730 | - socket.protocol = raw.protocol ?? ""; | |
| 731 | - const response = new Response(null, { status: 101 }); | |
| 732 | - response.webSocket = socket; | |
| 733 | - response.url = req.url; | |
| 734 | - return response; | |
| 735 | -}; | |
| 736 | -globalThis.__makeAssetsBinding = (script) => ({ | |
| 737 | - async fetch(input, init) { | |
| 738 | - const req = input instanceof Request ? new Request(input, init) : new Request(input, init); | |
| 739 | - const r = JSON.parse(await __asset_fetch( | |
| 740 | - script, | |
| 741 | - req.method, | |
| 742 | - req.url, | |
| 743 | - JSON.stringify(Array.from(req.headers)), | |
| 744 | - )); | |
| 745 | - const responseBody = r.streamId !== undefined | |
| 746 | - ? new CelldHttpBodyStream(r.streamId) | |
| 747 | - : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); | |
| 748 | - const response = new Response( | |
| 749 | - responseBody, | |
| 750 | - { status: r.status, headers: r.headers }, | |
| 751 | - ); | |
| 752 | - response.url = req.url; | |
| 753 | - return response; | |
| 754 | - }, | |
| 755 | -}); | |
| 756 | -// An `r2_buckets` binding, served out of the fleet bucket under the | |
| 757 | -// reserved `r2/<bucketName>/` prefix. celld runs on blob storage rather | |
| 758 | -// than providing it, so a binding gets the store the node already holds | |
| 759 | -// credentials for; a node started without a bucket has nowhere to put a | |
| 760 | -// blob and every method says so. | |
| 761 | -// | |
| 762 | -// The whole `R2Bucket` surface is here: `head`, `get`, `put`, `delete`, | |
| 763 | -// `list`, `createMultipartUpload` and `resumeMultipartUpload`, with | |
| 764 | -// `httpMetadata`, `customMetadata`, `checksums`, `storageClass`, `onlyIf` | |
| 765 | -// and every range spelling. What celld cannot honor still fails loudly | |
| 766 | -// rather than pretending — a silent gap is the failure mode the binding | |
| 767 | -// is written to avoid. Those are `ssecKey` (celld has no customer-key | |
| 768 | -// encryption), a conditional `put` of a body too big for one request, and | |
| 769 | -// a multipart upload resumed on a node other than the one that opened it. | |
| 770 | -const __r2Reject = (bucket, method, detail) => { | |
| 771 | - throw new Error( | |
| 772 | - `R2 ${method} is not implemented in celld (binding ${bucket})` + | |
| 773 | - (detail ? `: ${detail}` : ""), | |
| 774 | - ); | |
| 775 | -}; | |
| 776 | -// R2's key rules, checked here so a key the real thing refuses is refused | |
| 777 | -// here too rather than quietly written. | |
| 778 | -const __r2Key = (binding, method, key) => { | |
| 779 | - const text = String(key); | |
| 780 | - const length = new TextEncoder().encode(text).length; | |
| 781 | - if (length === 0 || length > 1024) { | |
| 782 | - throw new Error( | |
| 783 | - `R2 ${method} (binding ${binding}): a key is 1 to 1024 bytes, not ${length}`, | |
| 784 | - ); | |
| 785 | - } | |
| 786 | - return text; | |
| 787 | -}; | |
| 788 | -const __r2Hex = (value) => { | |
| 789 | - if (typeof value === "string") return value.trim().toLowerCase(); | |
| 790 | - const bytes = value instanceof ArrayBuffer | |
| 791 | - ? new Uint8Array(value) | |
| 792 | - : ArrayBuffer.isView(value) | |
| 793 | - ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) | |
| 794 | - : null; | |
| 795 | - if (!bytes) return null; | |
| 796 | - let out = ""; | |
| 797 | - for (const byte of bytes) out += byte.toString(16).padStart(2, "0"); | |
| 798 | - return out; | |
| 799 | -}; | |
| 800 | -const __r2Bytes = (hex) => { | |
| 801 | - const out = new Uint8Array(hex.length >> 1); | |
| 802 | - for (let at = 0; at < out.length; at++) { | |
| 803 | - out[at] = parseInt(hex.substr(at * 2, 2), 16); | |
| 804 | - } | |
| 805 | - return out.buffer; | |
| 806 | -}; | |
| 807 | -// Read a `ReadableStream` to one `Uint8Array`. Bodies drained this way | |
| 808 | -// are the ones the caller asked to have whole. | |
| 809 | -const __r2Drain = async (stream) => { | |
| 810 | - const reader = stream.getReader(); | |
| 811 | - const chunks = []; | |
| 812 | - let total = 0; | |
| 813 | - for (;;) { | |
| 814 | - const { done, value } = await reader.read(); | |
| 815 | - if (done) break; | |
| 816 | - chunks.push(value); | |
| 817 | - total += value.length; | |
| 818 | - } | |
| 819 | - const out = new Uint8Array(total); | |
| 820 | - let at = 0; | |
| 821 | - for (const chunk of chunks) { | |
| 822 | - out.set(chunk, at); | |
| 823 | - at += chunk.length; | |
| 824 | - } | |
| 825 | - return out; | |
| 826 | -}; | |
| 827 | -const __r2Ms = (value) => { | |
| 828 | - if (value === undefined || value === null) return undefined; | |
| 829 | - const ms = value instanceof Date ? value.getTime() : Number(value); | |
| 830 | - return Number.isFinite(ms) ? ms : undefined; | |
| 831 | -}; | |
| 832 | -// `httpMetadata` is either an `R2HTTPMetadata` or a `Headers`, and R2 | |
| 833 | -// takes both on the way in. | |
| 834 | -const __r2Http = (value) => { | |
| 835 | - if (value === undefined || value === null) return {}; | |
| 836 | - const from = (name, key) => | |
| 837 | - typeof value.get === "function" ? value.get(name) ?? undefined : value[key]; | |
| 838 | - const http = { | |
| 839 | - contentType: from("content-type", "contentType"), | |
| 840 | - contentLanguage: from("content-language", "contentLanguage"), | |
| 841 | - contentDisposition: from("content-disposition", "contentDisposition"), | |
| 842 | - contentEncoding: from("content-encoding", "contentEncoding"), | |
| 843 | - cacheControl: from("cache-control", "cacheControl"), | |
| 844 | - cacheExpiry: __r2Ms( | |
| 845 | - typeof value.get === "function" ? value.get("expires") : value.cacheExpiry, | |
| 846 | - ), | |
| 847 | - }; | |
| 848 | - for (const [name, entry] of Object.entries(http)) { | |
| 849 | - if (entry === undefined || entry === null) delete http[name]; | |
| 850 | - else if (name !== "cacheExpiry") http[name] = String(entry); | |
| 851 | - } | |
| 852 | - return http; | |
| 853 | -}; | |
| 854 | -// `onlyIf` is either an `R2Conditional` or a `Headers`; the header | |
| 855 | -// spelling of "only if it has not changed since" is If-Unmodified-Since, | |
| 856 | -// which is `uploadedBefore`. | |
| 857 | -const __r2OnlyIf = (value) => { | |
| 858 | - if (value === undefined || value === null) return undefined; | |
| 859 | - const only = typeof value.get === "function" | |
| 860 | - ? { | |
| 861 | - etagMatches: value.get("if-match") ?? undefined, | |
| 862 | - etagDoesNotMatch: value.get("if-none-match") ?? undefined, | |
| 863 | - uploadedAfter: __r2Ms(Date.parse(value.get("if-modified-since") ?? "")), | |
| 864 | - uploadedBefore: __r2Ms(Date.parse(value.get("if-unmodified-since") ?? "")), | |
| 865 | - } | |
| 866 | - : { | |
| 867 | - etagMatches: value.etagMatches, | |
| 868 | - etagDoesNotMatch: value.etagDoesNotMatch, | |
| 869 | - uploadedAfter: __r2Ms(value.uploadedAfter), | |
| 870 | - uploadedBefore: __r2Ms(value.uploadedBefore), | |
| 871 | - }; | |
| 872 | - for (const [name, entry] of Object.entries(only)) { | |
| 873 | - if (entry === undefined || entry === null || Number.isNaN(entry)) { | |
| 874 | - delete only[name]; | |
| 875 | - } else if (name.startsWith("etag")) only[name] = String(entry); | |
| 876 | - } | |
| 877 | - return Object.keys(only).length ? only : undefined; | |
| 878 | -}; | |
| 879 | -// A range is an `R2Range` or a `Headers` carrying a Range header. R2 | |
| 880 | -// takes `offset` alone, `length` alone, both, or `suffix`. | |
| 881 | -const __r2Range = (binding, value) => { | |
| 882 | - if (value === undefined || value === null) return undefined; | |
| 883 | - if (typeof value.get === "function") { | |
| 884 | - const header = value.get("range"); | |
| 885 | - if (!header) return undefined; | |
| 886 | - const parsed = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); | |
| 887 | - if (!parsed) { | |
| 888 | - __r2Reject(binding, "get(range)", `celld cannot parse ${header}`); | |
| 889 | - } | |
| 890 | - const [, first, last] = parsed; | |
| 891 | - if (first === "") return { suffix: Number(last) }; | |
| 892 | - if (last === "") return { offset: Number(first) }; | |
| 893 | - return { offset: Number(first), length: Number(last) - Number(first) + 1 }; | |
| 894 | - } | |
| 895 | - const range = {}; | |
| 896 | - if (value.suffix !== undefined && value.suffix !== null) { | |
| 897 | - range.suffix = Number(value.suffix); | |
| 898 | - } | |
| 899 | - if (value.offset !== undefined && value.offset !== null) { | |
| 900 | - range.offset = Number(value.offset); | |
| 901 | - } | |
| 902 | - if (value.length !== undefined && value.length !== null) { | |
| 903 | - range.length = Number(value.length); | |
| 904 | - } | |
| 905 | - for (const [name, entry] of Object.entries(range)) { | |
| 906 | - if (!Number.isFinite(entry) || entry < 0) { | |
| 907 | - __r2Reject(binding, "get(range)", `\`${name}\` must be a whole number`); | |
| 908 | - } | |
| 909 | - } | |
| 910 | - return Object.keys(range).length ? range : undefined; | |
| 911 | -}; | |
| 912 | -// R2 hashes an object's bytes and hands the digests back as | |
| 913 | -// `ArrayBuffer`s, with a `toJSON()` that spells them in hex. | |
| 914 | -const __r2Checksums = (hex) => { | |
| 915 | - const checksums = { | |
| 916 | - toJSON() { | |
| 917 | - const json = {}; | |
| 918 | - for (const [name, digest] of Object.entries(hex)) json[name] = digest; | |
| 919 | - return json; | |
| 920 | - }, | |
| 921 | - }; | |
| 922 | - for (const [name, digest] of Object.entries(hex)) { | |
| 923 | - checksums[name] = __r2Bytes(digest); | |
| 924 | - } | |
| 925 | - return checksums; | |
| 926 | -}; | |
| 927 | -// One object as R2 describes it. `object` is the host's record; `body`, | |
| 928 | -// when there is one, makes this an `R2ObjectBody`. | |
| 929 | -const __r2Object = (object, body) => { | |
| 930 | - const http = { ...object.http }; | |
| 931 | - if (http.cacheExpiry !== undefined) { | |
| 932 | - http.cacheExpiry = new Date(http.cacheExpiry); | |
| 933 | - } | |
| 934 | - const etag = object.etag ? String(object.etag).replace(/^"|"$/g, "") : ""; | |
| 935 | - const r2 = { | |
| 936 | - key: object.key, | |
| 937 | - version: object.version ?? etag, | |
| 938 | - size: object.size, | |
| 939 | - etag, | |
| 940 | - httpEtag: etag ? `"${etag}"` : "", | |
| 941 | - uploaded: new Date(object.uploaded), | |
| 942 | - httpMetadata: http, | |
| 943 | - customMetadata: object.custom ?? {}, | |
| 944 | - checksums: __r2Checksums(object.checksums ?? {}), | |
| 945 | - storageClass: object.storageClass ?? "Standard", | |
| 946 | - // R2 fills the response headers from the object's own metadata, which | |
| 947 | - // is what makes `return new Response(object.body, { headers })` serve | |
| 948 | - // a stored file correctly. | |
| 949 | - writeHttpMetadata(headers) { | |
| 950 | - const write = (name, value) => { | |
| 951 | - if (value !== undefined && value !== null) headers.set(name, value); | |
| 952 | - }; | |
| 953 | - write("content-type", http.contentType); | |
| 954 | - write("content-language", http.contentLanguage); | |
| 955 | - write("content-disposition", http.contentDisposition); | |
| 956 | - write("content-encoding", http.contentEncoding); | |
| 957 | - write("cache-control", http.cacheControl); | |
| 958 | - if (http.cacheExpiry !== undefined) { | |
| 959 | - headers.set("expires", http.cacheExpiry.toUTCString()); | |
| 960 | - } | |
| 961 | - }, | |
| 962 | - }; | |
| 963 | - if (object.range) r2.range = { ...object.range }; | |
| 964 | - if (!body) return r2; | |
| 965 | - const drain = () => __r2Drain(body); | |
| 966 | - r2.body = body; | |
| 967 | - Object.defineProperty(r2, "bodyUsed", { | |
| 968 | - get: () => body.locked || body._disturbed === true, | |
| 969 | - }); | |
| 970 | - r2.arrayBuffer = async () => (await drain()).buffer; | |
| 971 | - r2.bytes = drain; | |
| 972 | - r2.text = async () => new TextDecoder().decode(await drain()); | |
| 973 | - r2.json = async () => JSON.parse(new TextDecoder().decode(await drain())); | |
| 974 | - r2.blob = async () => new Blob([await drain()]); | |
| 975 | - return r2; | |
| 976 | -}; | |
| 977 | -// The write-side options every writing method shares, in the shape the | |
| 978 | -// host ops read. | |
| 979 | -const __r2WriteOptions = (binding, method, options) => { | |
| 980 | - const o = options ?? {}; | |
| 981 | - if (o.ssecKey !== undefined) { | |
| 982 | - __r2Reject( | |
| 983 | - binding, | |
| 984 | - `${method}(ssecKey)`, | |
| 985 | - "celld has no customer-key encryption", | |
| 986 | - ); | |
| 987 | - } | |
| 988 | - const custom = {}; | |
| 989 | - for (const [name, value] of Object.entries(o.customMetadata ?? {})) { | |
| 990 | - custom[name] = String(value); | |
| 991 | - } | |
| 992 | - const verify = {}; | |
| 993 | - for (const name of ["md5", "sha1", "sha256", "sha384", "sha512"]) { | |
| 994 | - if (o[name] === undefined || o[name] === null) continue; | |
| 995 | - const hex = __r2Hex(o[name]); | |
| 996 | - if (hex === null) { | |
| 997 | - __r2Reject( | |
| 998 | - binding, | |
| 999 | - `${method}(${name})`, | |
| 1000 | - "a checksum is hex or an ArrayBuffer", | |
| 1001 | - ); | |
| 1002 | - } | |
| 1003 | - verify[name] = hex; | |
| 1004 | - } | |
| 1005 | - const storageClass = o.storageClass === undefined || o.storageClass === null | |
| 1006 | - ? undefined | |
| 1007 | - : String(o.storageClass); | |
| 1008 | - if (storageClass !== undefined && | |
| 1009 | - !["Standard", "InfrequentAccess"].includes(storageClass) | |
| 1010 | - ) { | |
| 1011 | - __r2Reject( | |
| 1012 | - binding, | |
| 1013 | - `${method}(storageClass)`, | |
| 1014 | - `${storageClass} is not an R2 storage class`, | |
| 1015 | - ); | |
| 1016 | - } | |
| 1017 | - return { | |
| 1018 | - http: __r2Http(o.httpMetadata), | |
| 1019 | - custom, | |
| 1020 | - storageClass, | |
| 1021 | - onlyIf: __r2OnlyIf(o.onlyIf), | |
| 1022 | - verify, | |
| 1023 | - }; | |
| 1024 | -}; | |
| 1025 | -// A `put` body, as either the bytes to send in one request or the stream | |
| 1026 | -// to feed the host chunk by chunk. R2 takes all of these. | |
| 1027 | -const __r2Value = async (binding, value) => { | |
| 1028 | - if (value === undefined || value === null) return new Uint8Array(0); | |
| 1029 | - if (typeof value === "string") return new TextEncoder().encode(value); | |
| 1030 | - if (value instanceof Uint8Array) return value; | |
| 1031 | - if (ArrayBuffer.isView(value)) { | |
| 1032 | - return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); | |
| 1033 | - } | |
| 1034 | - if (value instanceof ArrayBuffer) return new Uint8Array(value); | |
| 1035 | - if (typeof Blob !== "undefined" && value instanceof Blob) { | |
| 1036 | - return new Uint8Array(await value.arrayBuffer()); | |
| 1037 | - } | |
| 1038 | - if (value && typeof value.getReader === "function") return value; | |
| 1039 | - return __r2Reject( | |
| 1040 | - binding, | |
| 1041 | - "put", | |
| 1042 | - "a body is a string, an ArrayBuffer, a view, a Blob, a ReadableStream, or null", | |
| 1043 | - ); | |
| 1044 | -}; | |
| 1045 | -// Feed a `ReadableStream` body to the host one chunk at a time. The host | |
| 1046 | -// writes one request when the whole body fits in a part and a multipart | |
| 1047 | -// upload when it does not, so a Worker can stream a body far larger than | |
| 1048 | -// its heap. | |
| 1049 | -const __r2PutStream = async (bucketName, key, stream, options) => { | |
| 1050 | - const id = Number(await __r2_put_begin(bucketName, key, JSON.stringify(options))); | |
| 1051 | - const reader = stream.getReader(); | |
| 1052 | - try { | |
| 1053 | - for (;;) { | |
| 1054 | - const { done, value } = await reader.read(); | |
| 1055 | - if (done) break; | |
| 1056 | - if (!value || value.length === 0) continue; | |
| 1057 | - await __r2_put_chunk( | |
| 1058 | - id, | |
| 1059 | - value instanceof Uint8Array | |
| 1060 | - ? value | |
| 1061 | - : new Uint8Array(value.buffer, value.byteOffset, value.byteLength), | |
| 1062 | - ); | |
| 1063 | - } | |
| 1064 | - } catch (error) { | |
| 1065 | - await __r2_put_end(id, true); | |
| 1066 | - throw error; | |
| 1067 | - } | |
| 1068 | - return JSON.parse(await __r2_put_end(id, false)); | |
| 1069 | -}; | |
| 1070 | -// One open multipart upload. `id` resolves to the host's upload id, so | |
| 1071 | -// `resumeMultipartUpload` can hand back a handle without awaiting — as R2 | |
| 1072 | -// does — and surface a bad id on the first method that uses it. | |
| 1073 | -const __r2Multipart = (binding, bucketName, key, id) => ({ | |
| 1074 | - key, | |
| 1075 | - get uploadId() { | |
| 1076 | - return String(id.value ?? ""); | |
| 1077 | - }, | |
| 1078 | - async uploadPart(partNumber, value, options) { | |
| 1079 | - if (options?.ssecKey !== undefined) { | |
| 1080 | - __r2Reject(binding, "uploadPart(ssecKey)", "celld has no customer-key encryption"); | |
| 1081 | - } | |
| 1082 | - const body = await __r2Value(binding, value); | |
| 1083 | - const bytes = body instanceof Uint8Array ? body : await __r2Drain(body); | |
| 1084 | - const r = JSON.parse(await __r2_mp_part(await id.host, partNumber | 0, bytes)); | |
| 1085 | - // The object store owns the part list this completion acts on, so it | |
| 1086 | - // never hands back a part etag to name one with. | |
| 1087 | - return { partNumber: r.partNumber, etag: "" }; | |
| 1088 | - }, | |
| 1089 | - async complete(parts) { | |
| 1090 | - const numbers = (parts ?? []).map((part) => part.partNumber | 0); | |
| 1091 | - return __r2Object(JSON.parse( | |
| 1092 | - await __r2_mp_complete(await id.host, JSON.stringify(numbers)), | |
| 1093 | - )); | |
| 1094 | - }, | |
| 1095 | - async abort() { | |
| 1096 | - await __r2_mp_abort(await id.host); | |
| 1097 | - }, | |
| 1098 | -}); | |
| 1099 | -globalThis.__makeR2Bucket = (binding, bucketName) => ({ | |
| 1100 | - async head(key) { | |
| 1101 | - const name = __r2Key(binding, "head", key); | |
| 1102 | - const r = JSON.parse(await __r2_head(bucketName, name)); | |
| 1103 | - return r.state === "miss" ? null : __r2Object(r.object); | |
| 1104 | - }, | |
| 1105 | - async get(key, options) { | |
| 1106 | - const name = __r2Key(binding, "get", key); | |
| 1107 | - const o = options ?? {}; | |
| 1108 | - if (o.ssecKey !== undefined) { | |
| 1109 | - __r2Reject(binding, "get(ssecKey)", "celld has no customer-key encryption"); | |
| 1110 | - } | |
| 1111 | - const request = { | |
| 1112 | - range: __r2Range(binding, o.range), | |
| 1113 | - onlyIf: __r2OnlyIf(o.onlyIf), | |
| 1114 | - }; | |
| 1115 | - const r = JSON.parse(await __r2_get(bucketName, name, JSON.stringify(request))); | |
| 1116 | - if (r.state === "miss") return null; | |
| 1117 | - // A refused `onlyIf` answers the object without its body, which is how | |
| 1118 | - // a caller tells "not modified" from "not there". | |
| 1119 | - if (r.state === "unmet") return __r2Object(r.object); | |
| 1120 | - return __r2Object(r.object, new CelldHttpBodyStream(r.streamId)); | |
| 1121 | - }, | |
| 1122 | - async put(key, value, options) { | |
| 1123 | - const name = __r2Key(binding, "put", key); | |
| 1124 | - const write = __r2WriteOptions(binding, "put", options); | |
| 1125 | - const body = await __r2Value(binding, value); | |
| 1126 | - const r = body instanceof Uint8Array | |
| 1127 | - ? JSON.parse(await __r2_put(bucketName, name, body, JSON.stringify(write))) | |
| 1128 | - : await __r2PutStream(bucketName, name, body, write); | |
| 1129 | - // R2 answers a refused `onlyIf` with `null` rather than throwing. | |
| 1130 | - return r.stored ? __r2Object(r.object) : null; | |
| 1131 | - }, | |
| 1132 | - async delete(keys) { | |
| 1133 | - const list = (Array.isArray(keys) ? keys : [keys]).map((key) => | |
| 1134 | - __r2Key(binding, "delete", key) | |
| 1135 | - ); | |
| 1136 | - if (list.length > 1000) { | |
| 1137 | - throw new Error( | |
| 1138 | - `R2 delete (binding ${binding}) takes at most 1000 keys, not ${list.length}`, | |
| 1139 | - ); | |
| 1140 | - } | |
| 1141 | - if (list.length) await __r2_delete(bucketName, JSON.stringify(list)); | |
| 1142 | - }, | |
| 1143 | - async list(options) { | |
| 1144 | - const o = options ?? {}; | |
| 1145 | - const include = Array.isArray(o.include) ? o.include : []; | |
| 1146 | - for (const entry of include) { | |
| 1147 | - if (!["httpMetadata", "customMetadata"].includes(entry)) { | |
| 1148 | - __r2Reject(binding, "list(include)", `${entry} is not an R2 listing extra`); | |
| 1149 | - } | |
| 1150 | - } | |
| 1151 | - const request = { | |
| 1152 | - prefix: o.prefix === undefined || o.prefix === null ? "" : String(o.prefix), | |
| 1153 | - cursor: o.cursor === undefined || o.cursor === null ? null : String(o.cursor), | |
| 1154 | - startAfter: o.startAfter === undefined || o.startAfter === null | |
| 1155 | - ? null | |
| 1156 | - : String(o.startAfter), | |
| 1157 | - limit: o.limit === undefined || o.limit === null ? 0 : o.limit | 0, | |
| 1158 | - delimiter: o.delimiter === undefined || o.delimiter === null | |
| 1159 | - ? null | |
| 1160 | - : String(o.delimiter), | |
| 1161 | - include: include.length > 0, | |
| 1162 | - }; | |
| 1163 | - const r = JSON.parse(await __r2_list(bucketName, JSON.stringify(request))); | |
| 1164 | - const objects = r.objects.map((object) => { | |
| 1165 | - // A listing carries the extras it was asked for and nothing else, | |
| 1166 | - // so a caller cannot mistake an empty map for an empty object. | |
| 1167 | - if (!include.includes("httpMetadata")) object.http = {}; | |
| 1168 | - if (!include.includes("customMetadata")) object.custom = {}; | |
| 1169 | - return __r2Object(object); | |
| 1170 | - }); | |
| 1171 | - // R2 omits `cursor` entirely when the listing is complete, and callers | |
| 1172 | - // test `truncated` before reading it. | |
| 1173 | - const page = { objects, truncated: r.truncated, delimitedPrefixes: r.prefixes }; | |
| 1174 | - if (r.truncated && r.cursor) page.cursor = r.cursor; | |
| 1175 | - return page; | |
| 1176 | - }, | |
| 1177 | - async createMultipartUpload(key, options) { | |
| 1178 | - const name = __r2Key(binding, "createMultipartUpload", key); | |
| 1179 | - const write = __r2WriteOptions(binding, "createMultipartUpload", options); | |
| 1180 | - if (write.onlyIf) { | |
| 1181 | - __r2Reject( | |
| 1182 | - binding, | |
| 1183 | - "createMultipartUpload(onlyIf)", | |
| 1184 | - "a multipart completion takes no precondition", | |
| 1185 | - ); | |
| 1186 | - } | |
| 1187 | - // R2 takes a checksum on `put`, which sees the whole body, and not on a | |
| 1188 | - // multipart upload, which never does. | |
| 1189 | - for (const name of Object.keys(write.verify)) { | |
| 1190 | - __r2Reject(binding, `createMultipartUpload(${name})`, "R2 takes a checksum on `put`"); | |
| 1191 | - } | |
| 1192 | - const uploadId = await __r2_mp_begin(bucketName, name, JSON.stringify(write)); | |
| 1193 | - return __r2Multipart(binding, bucketName, name, { | |
| 1194 | - value: uploadId, | |
| 1195 | - host: Promise.resolve(Number(uploadId)), | |
| 1196 | - }); | |
| 1197 | - }, | |
| 1198 | - // R2 hands back a handle without checking it; so does this, and the | |
| 1199 | - // first method that uses it says whether the upload is still open. | |
| 1200 | - resumeMultipartUpload(key, uploadId) { | |
| 1201 | - const name = __r2Key(binding, "resumeMultipartUpload", key); | |
| 1202 | - const id = String(uploadId); | |
| 1203 | - const host = __r2_mp_resume(bucketName, name, id).then(Number); | |
| 1204 | - // A handle nobody uses must not become an unhandled rejection; the | |
| 1205 | - // first method that awaits `host` still sees the failure. | |
| 1206 | - host.catch(() => {}); | |
| 1207 | - return __r2Multipart(binding, bucketName, name, { value: id, host }); | |
| 1208 | - }, | |
| 1209 | -}); | |
| 1210 | -// Tear down an upstream body the caller has given up on. The host source goes | |
| 1211 | -// first, because that drops the upstream connection and `ReadableStream.cancel` | |
| 1212 | -// rejects on the locked stream a reader holds. Erroring the stream then gives | |
| 1213 | -// the reader the caller's reason instead of the registry's "expired or is not | |
| 1214 | -// registered", which reads as an engine fault. | |
| 1215 | -const __aiCancelBody = (response, reason) => { | |
| 1216 | - const body = response?.body; | |
| 1217 | - if (body?.__celldStreamId === undefined) return; | |
| 1218 | - __http_stream_cancel(body.__celldStreamId); | |
| 1219 | - body._controller?.error(reason); | |
| 1220 | -}; | |
| 1221 | -// Workers AI passes a third argument to `run()`. `returnRawResponse` hands the | |
| 1222 | -// caller an unconsumed Response for a streaming completion, whatever its | |
| 1223 | -// status; parsing stays the default, and only that default rejects a non-2xx | |
| 1224 | -// status. `fetch` covers the signal up to the response head, after which the | |
| 1225 | -// body is a host stream, so the raw path installs its own abort listener. | |
| 1226 | -globalThis.__makeAiBinding = (url) => ({ | |
| 1227 | - async run(model, input, options) { | |
| 1228 | - const signal = options?.signal; | |
| 1229 | - const response = await fetch(url, { | |
| 1230 | - method: "POST", | |
| 1231 | - headers: { "content-type": "application/json" }, | |
| 1232 | - body: JSON.stringify({ model, input }), | |
| 1233 | - signal, | |
| 1234 | - }); | |
| 1235 | - // The raw path returns ahead of every status test, so no arrangement of | |
| 1236 | - // this function can convert a non-2xx response into a throw. Workers AI | |
| 1237 | - // hands the error Response back as well, and the status is the only thing | |
| 1238 | - // an OpenAI-compatible client has to classify the failure with. A throw | |
| 1239 | - // reaches such a client as a failed fetch, which it reports as a connection | |
| 1240 | - // error and retries, so a permanent 403 becomes an unbounded retry loop. | |
| 1241 | - // The body stays unconsumed here, because the caller owns it. | |
| 1242 | - if (options?.returnRawResponse) { | |
| 1243 | - if (signal) { | |
| 1244 | - signal.addEventListener( | |
| 1245 | - "abort", () => __aiCancelBody(response, signal.reason), { once: true }); | |
| 1246 | - } | |
| 1247 | - return response; | |
| 1248 | - } | |
| 1249 | - if (!response.ok) { | |
| 1250 | - // Draining the body is the work `__aiCancelBody` did here before, so the | |
| 1251 | - // cancel stays only for a read that fails and leaves the source live. | |
| 1252 | - // `fetch` covers the signal to the response head only, so the read is | |
| 1253 | - // raced: an upstream that stalls its error body must not hang a caller. | |
| 1254 | - const read = response.text().catch((error) => { | |
| 1255 | - __aiCancelBody(response, error); | |
| 1256 | - return ""; | |
| 1257 | - }); | |
| 1258 | - const detail = signal | |
| 1259 | - ? await __raceCallerAbort( | |
| 1260 | - read, signal, () => __aiCancelBody(response, signal.reason)) | |
| 1261 | - : await read; | |
| 1262 | - // An upstream body is unbounded and this message reaches a log. | |
| 1263 | - const suffix = detail ? `: ${detail.slice(0, 512)}` : ""; | |
| 1264 | - throw new Error(`AI binding returned ${response.status}${suffix}`); | |
| 1265 | - } | |
| 1266 | - const parse = response.json(); | |
| 1267 | - return signal | |
| 1268 | - ? await __raceCallerAbort( | |
| 1269 | - parse, signal, () => __aiCancelBody(response, signal.reason)) | |
| 1270 | - : await parse; | |
| 1271 | - }, | |
| 1272 | -}); | |
| 1273 | -// A host timer op resolves once, so an interval arms a new one after every | |
| 1274 | -// round. `__timers` maps the id the caller holds to the op that is armed | |
| 1275 | -// right now: for a timeout that is the same id, and for an interval it is a | |
| 1276 | -// fresh id each round. Clearing therefore cancels the armed op, not the id. | |
| 1277 | -const __timers = new Map(); | |
| 1278 | -const __clearTimer = (id) => { | |
| 1279 | - const armed = __timers.get(id); | |
| 1280 | - if (armed === undefined) return; | |
| 1281 | - __timers.delete(id); | |
| 1282 | - __timer_cancel(armed); | |
| 1283 | -}; | |
| 1284 | -globalThis.setTimeout = (cb, ms, ...a) => { | |
| 1285 | - const id = __timer_alloc(); | |
| 1286 | - __timers.set(id, id); | |
| 1287 | - __op_timer(id, ms | 0).then(() => { | |
| 1288 | - if (!__timers.delete(id)) return; | |
| 1289 | - cb(...a); | |
| 1290 | - }); | |
| 1291 | - return id; | |
| 1292 | -}; | |
| 1293 | -globalThis.setInterval = (cb, ms, ...a) => { | |
| 1294 | - const id = __timer_alloc(); | |
| 1295 | - const delay = ms | 0; | |
| 1296 | - const arm = (armed) => { | |
| 1297 | - __timers.set(id, armed); | |
| 1298 | - __op_timer(armed, delay).then(() => { | |
| 1299 | - // Cancelling drops the entry and cancelling then re-arming replaces | |
| 1300 | - // it, so a round whose op is no longer the armed one is dead and | |
| 1301 | - // stops here. A cancelled op still resolves, which is why this test | |
| 1302 | - // is on identity and not on the op alone. | |
| 1303 | - if (__timers.get(id) !== armed) return; | |
| 1304 | - // Arm the next round before the callback runs. A `clearInterval` | |
| 1305 | - // inside the callback must end the interval, and arming after the | |
| 1306 | - // callback would undo it. | |
| 1307 | - arm(__timer_alloc()); | |
| 1308 | - cb(...a); | |
| 1309 | - }); | |
| 1310 | - }; | |
| 1311 | - arm(id); | |
| 1312 | - return id; | |
| 1313 | -}; | |
| 1314 | -// One id space and one cancel, because a caller can cross the two. | |
| 1315 | -globalThis.clearTimeout = __clearTimer; | |
| 1316 | -globalThis.clearInterval = __clearTimer; | |
| 1317 | - | |
| 1318 | -const __sqlCursorFinalizer = typeof FinalizationRegistry === "function" | |
| 1319 | - ? new FinalizationRegistry((cursorId) => __sql_cursor_close(cursorId)) | |
| 1320 | - : null; | |
| 1321 | - | |
| 1322 | -// A `SqlStorageCursor` over one exec's result (Cloudflare DO SQL API). | |
| 1323 | -class SqlCursor { | |
| 1324 | - // `res` is what `__sql_cursor_start` returns: V8 values throughout, with the | |
| 1325 | - // first row already stepped. A failing query throws out of the op, so there | |
| 1326 | - // is no in-band error field to test here. | |
| 1327 | - constructor(res) { | |
| 1328 | - this.columns = res.columns; | |
| 1329 | - this.rowsWritten = Number(res.rowsWritten || 0); | |
| 1330 | - this.reusedCachedQueryForTest = Boolean(res.reusedCachedQuery); | |
| 1331 | - this._deferredError = null; | |
| 1332 | - this._cursorId = Number(res.cursorId || 0); | |
| 1333 | - this._prefetched = res.row; | |
| 1334 | - this.rowsRead = this._prefetched === null ? 0 : 1; | |
| 1335 | - this._finalizerToken = null; | |
| 1336 | - if (this._cursorId && __sqlCursorFinalizer) { | |
| 1337 | - this._finalizerToken = {}; | |
| 1338 | - __sqlCursorFinalizer.register( | |
| 1339 | - this, this._cursorId, this._finalizerToken, | |
| 1340 | - ); | |
| 1341 | - } | |
| 1342 | - } | |
| 1343 | - _obj(r) { const o = {}; for (let i = 0; i < this.columns.length; i++) o[this.columns[i]] = r[i]; return o; } | |
| 1344 | - _finishNative() { | |
| 1345 | - if (this._finalizerToken && __sqlCursorFinalizer) | |
| 1346 | - __sqlCursorFinalizer.unregister(this._finalizerToken); | |
| 1347 | - this._finalizerToken = null; | |
| 1348 | - this._cursorId = 0; | |
| 1349 | - } | |
| 1350 | - _advanceNative() { | |
| 1351 | - if (!this._cursorId) { | |
| 1352 | - this._prefetched = null; | |
| 1353 | - return; | |
| 1354 | - } | |
| 1355 | - // The op answers with V8 values, not JSON: an array is a row, a number is | |
| 1356 | - // the cursor's final rowsWritten, and a failure throws. The throw is | |
| 1357 | - // caught and deferred, because a consumer must still receive the last good | |
| 1358 | - // row -- the error belongs to the call after it, not to this one. | |
| 1359 | - let result; | |
| 1360 | - try { | |
| 1361 | - result = __sql_cursor_next(this._cursorId); | |
| 1362 | - } catch (error) { | |
| 1363 | - this._deferredError = error; | |
| 1364 | - this._prefetched = null; | |
| 1365 | - this._finishNative(); | |
| 1366 | - return; | |
| 1367 | - } | |
| 1368 | - if (Array.isArray(result)) { | |
| 1369 | - this._prefetched = result; | |
| 1370 | - this.rowsRead++; | |
| 1371 | - return; | |
| 1372 | - } | |
| 1373 | - this.rowsWritten = Number(result || this.rowsWritten); | |
| 1374 | - this._prefetched = null; | |
| 1375 | - this._finishNative(); | |
| 1376 | - } | |
| 1377 | - _nextRaw() { | |
| 1378 | - if (this._deferredError) { | |
| 1379 | - const error = this._deferredError; | |
| 1380 | - this._deferredError = null; | |
| 1381 | - throw error; | |
| 1382 | - } | |
| 1383 | - if (this._prefetched === null) return { done: true }; | |
| 1384 | - const value = this._prefetched; | |
| 1385 | - this._advanceNative(); | |
| 1386 | - return { done: false, value }; | |
| 1387 | - } | |
| 1388 | - toArray() { | |
| 1389 | - const rows = []; | |
| 1390 | - while (true) { | |
| 1391 | - const result = this.next(); | |
| 1392 | - if (result.done) return rows; | |
| 1393 | - rows.push(result.value); | |
| 1394 | - if (__heap_limit_excessively_exceeded()) | |
| 1395 | - throw new Error( | |
| 1396 | - "the isolate is over its V8 heap limit, so it stopped " + | |
| 1397 | - "materializing a result set (see CELLD_V8_HEAP_LIMIT_MB)"); | |
| 1398 | - } | |
| 1399 | - } | |
| 1400 | - one() { | |
| 1401 | - const first = this.next(); | |
| 1402 | - if (first.done) | |
| 1403 | - throw new Error("Expected exactly one result from SQL query, but got no results"); | |
| 1404 | - if (!this.next().done) | |
| 1405 | - throw new Error("Expected exactly one result from SQL query, but got multiple results"); | |
| 1406 | - return first.value; | |
| 1407 | - } | |
| 1408 | - *raw() { | |
| 1409 | - while (true) { | |
| 1410 | - const result = this._nextRaw(); | |
| 1411 | - if (result.done) return; | |
| 1412 | - yield result.value; | |
| 1413 | - } | |
| 1414 | - } | |
| 1415 | - get columnNames() { return this.columns; } | |
| 1416 | - next() { | |
| 1417 | - const result = this._nextRaw(); | |
| 1418 | - return result.done ? result : { done: false, value: this._obj(result.value) }; | |
| 1419 | - } | |
| 1420 | - [Symbol.iterator]() { return this; } | |
| 1421 | -} | |
| 1422 | -class SqlStorage { | |
| 1423 | - // The state is what the abort guard in `exec` reads; a storage built | |
| 1424 | - // without one would bypass the guard silently. | |
| 1425 | - constructor(scope, state, storage) { | |
| 1426 | - if (!state) throw new TypeError("SqlStorage requires its DurableObjectState"); | |
| 1427 | - this._scope = scope; | |
| 1428 | - this._state = state; | |
| 1429 | - this._storage = storage; | |
| 1430 | - } | |
| 1431 | - prepare(query) { | |
| 1432 | - this._storage._assertTransactionActive("sql.prepare"); | |
| 1433 | - const storage = this; | |
| 1434 | - const source = String(query); | |
| 1435 | - return (...binds) => storage.exec(source, ...binds); | |
| 1436 | - } | |
| 1437 | - exec(query, ...binds) { | |
| 1438 | - this._storage._assertTransactionActive("sql.exec"); | |
| 1439 | - // A callback that outlived its block runs on an object that was reset, | |
| 1440 | - // whose replacement uses the same connection: a statement from it | |
| 1441 | - // would land in the replacement's state. The KV surface drops such | |
| 1442 | - // writes silently; SQL refuses aloud, since a cursor can carry reads. | |
| 1443 | - if (this._state._aborted) { | |
| 1444 | - throw new Error("the Durable Object was reset; this event's storage is closed"); | |
| 1445 | - } | |
| 1446 | - const encode = (value) => { | |
| 1447 | - if (value instanceof ArrayBuffer) | |
| 1448 | - return { __celld_bytes: Array.from(new Uint8Array(value)) }; | |
| 1449 | - if (ArrayBuffer.isView(value)) | |
| 1450 | - return { __celld_bytes: Array.from( | |
| 1451 | - new Uint8Array(value.buffer, value.byteOffset, value.byteLength), | |
| 1452 | - ) }; | |
| 1453 | - return value; | |
| 1454 | - }; | |
| 1455 | - return new SqlCursor(__sql_cursor_start( | |
| 1456 | - this._scope, query, JSON.stringify(binds.map(encode)), | |
| 1457 | - )); | |
| 1458 | - } | |
| 1459 | - ingest(input) { | |
| 1460 | - this._storage._assertTransactionActive("sql.ingest"); | |
| 1461 | - const result = JSON.parse(__sql_ingest(this._scope, String(input))); | |
| 1462 | - if (result.error) throw new Error("SQL error: " + result.error); | |
| 1463 | - return result; | |
| 1464 | - } | |
| 1465 | - get databaseSize() { | |
| 1466 | - this._storage._assertTransactionActive("sql.databaseSize"); | |
| 1467 | - return __sql_database_size(this._scope); | |
| 1468 | - } | |
| 1469 | - setMaxPageCountForTest(pages) { | |
| 1470 | - if (typeof __sql_set_max_page_count_for_test !== "function") | |
| 1471 | - throw new Error("setMaxPageCountForTest is only available in tests"); | |
| 1472 | - __sql_set_max_page_count_for_test(this._scope, Number(pages)); | |
| 1473 | - } | |
| 1474 | - setWriteFaultForTest(enabled) { | |
| 1475 | - if (typeof __sql_set_write_fault_for_test !== "function") | |
| 1476 | - throw new Error("setWriteFaultForTest is only available in tests"); | |
| 1477 | - __sql_set_write_fault_for_test(!!enabled); | |
| 1478 | - } | |
| 1479 | - setCacheSizeForTest(pages) { | |
| 1480 | - if (typeof __sql_set_cache_size_for_test !== "function") | |
| 1481 | - throw new Error("setCacheSizeForTest is only available in tests"); | |
| 1482 | - __sql_set_cache_size_for_test(this._scope, Number(pages)); | |
| 1483 | - } | |
| 1484 | - setInterruptFaultForTest(enabled) { | |
| 1485 | - if (typeof __sql_set_interrupt_fault_for_test !== "function") | |
| 1486 | - throw new Error( | |
| 1487 | - "setInterruptFaultForTest is only available in tests"); | |
| 1488 | - __sql_set_interrupt_fault_for_test(this._scope, !!enabled); | |
| 1489 | - } | |
| 1490 | - registerNomemFunctionForTest() { | |
| 1491 | - if (typeof __sql_register_nomem_function_for_test !== "function") | |
| 1492 | - throw new Error( | |
| 1493 | - "registerNomemFunctionForTest is only available in tests"); | |
| 1494 | - __sql_register_nomem_function_for_test(this._scope); | |
| 1495 | - } | |
| 1496 | -} | |
| 1497 | -function __readStoredValue(scope, key, read) { | |
| 1498 | - try { | |
| 1499 | - return read(); | |
| 1500 | - } catch (error) { | |
| 1501 | - const message = String(error && error.message || error); | |
| 1502 | - if (!message.toLowerCase().includes("deserialize cloned data")) | |
| 1503 | - throw error; | |
| 1504 | - const contextual = new Error( | |
| 1505 | - "actor storage deserialization failed; actorId = " + | |
| 1506 | - scope + "; key = " + key + "; " + message, | |
| 1507 | - ); | |
| 1508 | - contextual.cause = error; | |
| 1509 | - throw contextual; | |
| 1510 | - } | |
| 1511 | -} | |
| 1512 | -class SyncKvListIterator { | |
| 1513 | - constructor(root, generation, cursor) { | |
| 1514 | - this._root = root; | |
| 1515 | - this._generation = generation; | |
| 1516 | - this._cursor = cursor; | |
| 1517 | - } | |
| 1518 | - [Symbol.iterator]() { return this; } | |
| 1519 | - next() { | |
| 1520 | - if (this._generation !== this._root._syncKvListGeneration) { | |
| 1521 | - throw new Error( | |
| 1522 | - "kv.list() iterator was invalidated because a new call to kv.list() was started. " + | |
| 1523 | - "Only one kv.list() iterator can exist at a time.", | |
| 1524 | - ); | |
| 1525 | - } | |
| 1526 | - const value = | |
| 1527 | - __storage_sync_list_next(this._cursor, __storedSentinel); | |
| 1528 | - if (value === null) return { done: true, value: undefined }; | |
| 1529 | - value[1] = __unwrapStored(value[1]); | |
| 1530 | - return { done: false, value }; | |
| 1531 | - } | |
| 1532 | -} | |
| 1533 | -class SyncKvStorage { | |
| 1534 | - constructor(storage) { | |
| 1535 | - this._storage = storage; | |
| 1536 | - this._root = storage._transactionRoot; | |
| 1537 | - } | |
| 1538 | - get(key) { | |
| 1539 | - this._storage._assertTransactionActive("kv.get"); | |
| 1540 | - key = String(key); | |
| 1541 | - return __unwrapStored(__readStoredValue( | |
| 1542 | - this._storage._scope, key, | |
| 1543 | - () => __storage_get(this._storage._scope, key, | |
| 1544 | - __storedSentinel), | |
| 1545 | - )); | |
| 1546 | - } | |
| 1547 | - put(key, value) { | |
| 1548 | - this._storage._assertTransactionActive("kv.put"); | |
| 1549 | - key = String(key); | |
| 1550 | - try { | |
| 1551 | - __storage_put(this._storage._scope, key, value); | |
| 1552 | - } catch (error) { | |
| 1553 | - __storage_put_serialized(this._storage._scope, key, | |
| 1554 | - __storedBytes(value, error)); | |
| 1555 | - } | |
| 1556 | - } | |
| 1557 | - delete(key) { | |
| 1558 | - this._storage._assertTransactionActive("kv.delete"); | |
| 1559 | - return __storage_delete(this._storage._scope, String(key)); | |
| 1560 | - } | |
| 1561 | - list(options = {}) { | |
| 1562 | - this._storage._assertTransactionActive("kv.list"); | |
| 1563 | - const generation = ++this._root._syncKvListGeneration; | |
| 1564 | - const cursor = __storage_sync_list_start( | |
| 1565 | - this._storage._scope, JSON.stringify(options), | |
| 1566 | - ); | |
| 1567 | - return new SyncKvListIterator( | |
| 1568 | - this._root, generation, cursor, | |
| 1569 | - ); | |
| 1570 | - } | |
| 1571 | -} | |
| 1572 | -class DurableObjectStorage { | |
| 1573 | - constructor( | |
| 1574 | - scope, | |
| 1575 | - state = null, | |
| 1576 | - transactionRoot = null, | |
| 1577 | - transactionDepth = 0, | |
| 1578 | - transactionControl = null, | |
| 1579 | - ) { | |
| 1580 | - this._scope = scope; | |
| 1581 | - this._state = state; | |
| 1582 | - this.sql = new SqlStorage(scope, state, this); | |
| 1583 | - this._transactionRoot = transactionRoot || this; | |
| 1584 | - this._transactionDepth = transactionDepth; | |
| 1585 | - this._transactionControl = transactionControl; | |
| 1586 | - if (!transactionRoot) { | |
| 1587 | - this._transactionSerial = 0; | |
| 1588 | - this._transactionTail = Promise.resolve(); | |
| 1589 | - this._syncKvListGeneration = 0; | |
| 1590 | - } | |
| 1591 | - this._kv = new SyncKvStorage(this); | |
| 1592 | - } | |
| 1593 | - get kv() { return this._kv; } | |
| 1594 | - _transactionStatus() { | |
| 1595 | - let status = null; | |
| 1596 | - for (let control = this._transactionControl; control; control = control.parent) { | |
| 1597 | - if (control.rolledBack) return "rolled back"; | |
| 1598 | - if (control.committed) status = "committed"; | |
| 1599 | - } | |
| 1600 | - return status; | |
| 1601 | - } | |
| 1602 | - _assertTransactionActive(operation) { | |
| 1603 | - const status = this._transactionStatus(); | |
| 1604 | - if (status) throw new Error("Cannot " + operation + "() on " + status + " transaction"); | |
| 1605 | - } | |
| 1606 | - _flushPendingPuts() { | |
| 1607 | - // An admitted put can resume after its boundary flushed and ended the | |
| 1608 | - // transaction. Its promise completes without flushing a later scope. | |
| 1609 | - if (this._transactionStatus()) return false; | |
| 1610 | - if (this._state && this._state._aborted) return false; | |
| 1611 | - __storage_flush_pending_puts(this._scope); | |
| 1612 | - return true; | |
| 1613 | - } | |
| 1614 | - async get(k) { | |
| 1615 | - this._assertTransactionActive("get"); | |
| 1616 | - // Transaction operations reach SQLite before their caller can roll back. | |
| 1617 | - if (!this._transactionControl) await Promise.resolve(); | |
| 1618 | - if (!this._flushPendingPuts()) return; | |
| 1619 | - const key = Array.isArray(k) ? JSON.stringify(k) : String(k); | |
| 1620 | - return __readStoredValue(this._scope, key, () => { | |
| 1621 | - if (Array.isArray(k)) | |
| 1622 | - return __unwrapStoredMap( | |
| 1623 | - __storage_get_many(this._scope, k, __storedSentinel)); | |
| 1624 | - return __unwrapStored( | |
| 1625 | - __storage_get(this._scope, k, __storedSentinel)); | |
| 1626 | - }); | |
| 1627 | - } | |
| 1628 | - async put(k, val) { | |
| 1629 | - this._assertTransactionActive("put"); | |
| 1630 | - if (typeof k === "string") { | |
| 1631 | - try { | |
| 1632 | - __storage_queue_put(this._scope, k, val); | |
| 1633 | - } catch (error) { | |
| 1634 | - __storage_queue_put_serialized(this._scope, k, | |
| 1635 | - __storedBytes(val, error)); | |
| 1636 | - } | |
| 1637 | - await Promise.resolve(); | |
| 1638 | - this._flushPendingPuts(); | |
| 1639 | - return; | |
| 1640 | - } | |
| 1641 | - const source = k instanceof Map ? Array.from(k) : Object.entries(k); | |
| 1642 | - if (source.length === 0) return; | |
| 1643 | - const entries = | |
| 1644 | - source.map(([key, value]) => [String(key), value]); | |
| 1645 | - try { | |
| 1646 | - __storage_queue_put_many(this._scope, entries); | |
| 1647 | - } catch (error) { | |
| 1648 | - // A batch with a stub entry: encode every entry first (plain | |
| 1649 | - // entries keep their native clone bytes, stub entries take | |
| 1650 | - // the stored-stub envelope), then queue — so a genuinely | |
| 1651 | - // uncloneable entry still queues nothing, like the batch op, | |
| 1652 | - // which serializes fully before queueing. | |
| 1653 | - const encoded = entries.map(([key, value]) => { | |
| 1654 | - try { | |
| 1655 | - return [key, __sc_encode(value)]; | |
| 1656 | - } catch (error_) { | |
| 1657 | - return [key, __storedBytes(value, error_)]; | |
| 1658 | - } | |
| 1659 | - }); | |
| 1660 | - for (const [key, bytes] of encoded) | |
| 1661 | - __storage_queue_put_serialized(this._scope, key, bytes); | |
| 1662 | - } | |
| 1663 | - await Promise.resolve(); | |
| 1664 | - this._flushPendingPuts(); | |
| 1665 | - } | |
| 1666 | - async delete(k) { | |
| 1667 | - this._assertTransactionActive("delete"); | |
| 1668 | - if (!this._transactionControl) await Promise.resolve(); | |
| 1669 | - if (!this._flushPendingPuts()) return; | |
| 1670 | - if (Array.isArray(k)) { | |
| 1671 | - if (k.length === 0) return 0; | |
| 1672 | - return __storage_delete_many(this._scope, k); | |
| 1673 | - } | |
| 1674 | - return __storage_delete(this._scope, k); | |
| 1675 | - } | |
| 1676 | - async list(options = {}) { | |
| 1677 | - this._assertTransactionActive("list"); | |
| 1678 | - if (!this._transactionControl) await Promise.resolve(); | |
| 1679 | - if (!this._flushPendingPuts()) return new Map(); | |
| 1680 | - return __unwrapStoredMap(__storage_list( | |
| 1681 | - this._scope, JSON.stringify(options), __storedSentinel)); | |
| 1682 | - } | |
| 1683 | - async deleteAll() { | |
| 1684 | - this._assertTransactionActive("deleteAll"); | |
| 1685 | - if (!this._transactionControl) await Promise.resolve(); | |
| 1686 | - if (!this._flushPendingPuts()) return; | |
| 1687 | - __storage_delete_all(this._scope, __cell.deleteAllDeletesAlarm); | |
| 1688 | - } | |
| 1689 | - // Resolves once every write this cell committed before the call is | |
| 1690 | - // proven durable, by the proof the output gate requires before it releases | |
| 1691 | - // an egress. Workerd resolves when the pending writes have completed; on | |
| 1692 | - // celld the local file is a cache, so "completed" is "proven". The host op | |
| 1693 | - // rejects when that proof fails or times out, so an application never | |
| 1694 | - // treats a lost write as safe. | |
| 1695 | - async sync() { | |
| 1696 | - this._assertTransactionActive("sync"); | |
| 1697 | - await Promise.resolve(); | |
| 1698 | - const status = this._transactionStatus(); | |
| 1699 | - // An admitted sync can resume after transactionSync commits or rolls | |
| 1700 | - // back. Its boundary settled the queued puts, so prove the surviving | |
| 1701 | - // state without flushing a later transaction through this handle. A | |
| 1702 | - // new call after that boundary still fails the entry guard above. | |
| 1703 | - if (this._state?._aborted || (status === null && !this._flushPendingPuts())) | |
| 1704 | - throw new Error( | |
| 1705 | - "storage.sync: " + this._scope + " was aborted; the object is no " + | |
| 1706 | - "longer running"); | |
| 1707 | - await __storage_sync(this._scope); | |
| 1708 | - } | |
| 1709 | - async setAlarm(t) { | |
| 1710 | - this._assertTransactionActive("setAlarm"); | |
| 1711 | - if (!this._transactionControl) await Promise.resolve(); | |
| 1712 | - if (!this._flushPendingPuts()) return; | |
| 1713 | - if (this._state?._facetDepth > 0) | |
| 1714 | - throw new Error("Facets currently cannot set alarms."); | |
| 1715 | - __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); | |
| 1716 | - } | |
| 1717 | - async getAlarm() { | |
| 1718 | - this._assertTransactionActive("getAlarm"); | |
| 1719 | - if (!this._transactionControl) await Promise.resolve(); | |
| 1720 | - if (!this._flushPendingPuts()) return null; | |
| 1721 | - const v = __alarm_get(this._scope); | |
| 1722 | - return v === null ? null : v; | |
| 1723 | - } | |
| 1724 | - async deleteAlarm() { | |
| 1725 | - this._assertTransactionActive("deleteAlarm"); | |
| 1726 | - if (!this._transactionControl) await Promise.resolve(); | |
| 1727 | - if (!this._flushPendingPuts()) return; | |
| 1728 | - __alarm_delete(this._scope); | |
| 1729 | - } | |
| 1730 | - _transactionStart() { | |
| 1731 | - const root = this._transactionRoot; | |
| 1732 | - const savepoint = "cells_tx_" + (++root._transactionSerial); | |
| 1733 | - __storage_transaction_control( | |
| 1734 | - this._scope, "start", this._transactionDepth > 0, savepoint, | |
| 1735 | - ); | |
| 1736 | - return savepoint; | |
| 1737 | - } | |
| 1738 | - _transactionCommit(savepoint) { | |
| 1739 | - __storage_transaction_control( | |
| 1740 | - this._scope, "commit", this._transactionDepth > 0, savepoint, | |
| 1741 | - ); | |
| 1742 | - } | |
| 1743 | - _transactionRollback(savepoint, explicit = false) { | |
| 1744 | - __storage_transaction_control( | |
| 1745 | - this._scope, | |
| 1746 | - explicit ? "rollback_explicit" : "rollback", | |
| 1747 | - this._transactionDepth > 0, | |
| 1748 | - savepoint, | |
| 1749 | - ); | |
| 1750 | - } | |
| 1751 | - _transactionView(transactionControl) { | |
| 1752 | - return new DurableObjectStorage( | |
| 1753 | - this._scope, | |
| 1754 | - this._state, | |
| 1755 | - this._transactionRoot, | |
| 1756 | - this._transactionDepth + 1, | |
| 1757 | - transactionControl, | |
| 1758 | - ); | |
| 1759 | - } | |
| 1760 | - rollback() { | |
| 1761 | - const control = this._transactionControl; | |
| 1762 | - if (!control) | |
| 1763 | - throw new TypeError("rollback() must be called on a transaction"); | |
| 1764 | - if (control.rolledBack) return; | |
| 1765 | - this._assertTransactionActive("rollback"); | |
| 1766 | - control.rollback(); | |
| 1767 | - control.rolledBack = true; | |
| 1768 | - } | |
| 1769 | - transactionSync(f) { | |
| 1770 | - this._assertTransactionActive("transactionSync"); | |
| 1771 | - const savepoint = this._transactionStart(); | |
| 1772 | - const control = this._newTransactionControl(savepoint); | |
| 1773 | - try { | |
| 1774 | - const value = f(this._transactionView(control)); | |
| 1775 | - if (!control.rolledBack) { | |
| 1776 | - this._transactionCommit(savepoint); | |
| 1777 | - control.committed = true; | |
| 1778 | - } | |
| 1779 | - return value; | |
| 1780 | - } catch (error) { | |
| 1781 | - if (!control.rolledBack) { | |
| 1782 | - try { | |
| 1783 | - this._transactionRollback(savepoint); | |
| 1784 | - control.rolledBack = true; | |
| 1785 | - } catch (rollbackError) { | |
| 1786 | - this._abortAfterFailedRollback(rollbackError, error); | |
| 1787 | - } | |
| 1788 | - } | |
| 1789 | - throw error; | |
| 1790 | - } | |
| 1791 | - } | |
| 1792 | - _newTransactionControl(savepoint) { | |
| 1793 | - return { | |
| 1794 | - rolledBack: false, | |
| 1795 | - committed: false, | |
| 1796 | - parent: this._transactionControl, | |
| 1797 | - rollback: () => this._transactionRollback(savepoint, true), | |
| 1798 | - }; | |
| 1799 | - } | |
| 1800 | - async _runTransactionWith(f, savepoint, control) { | |
| 1801 | - try { | |
| 1802 | - const value = await f(this._transactionView(control)); | |
| 1803 | - if (!control.rolledBack) { | |
| 1804 | - this._transactionCommit(savepoint); | |
| 1805 | - control.committed = true; | |
| 1806 | - } | |
| 1807 | - return value; | |
| 1808 | - } catch (error) { | |
| 1809 | - if (!control.rolledBack) { | |
| 1810 | - // The flag records a rollback that happened, not one that was | |
| 1811 | - // attempted: a rollback that fails leaves the savepoint open, and a | |
| 1812 | - // later transaction on the same connection would commit its writes. | |
| 1813 | - // Nothing can be said about the connection then, so the object is | |
| 1814 | - // aborted rather than left to serve from it. | |
| 1815 | - try { | |
| 1816 | - this._transactionRollback(savepoint); | |
| 1817 | - control.rolledBack = true; | |
| 1818 | - } catch (rollbackError) { | |
| 1819 | - this._abortAfterFailedRollback(rollbackError, error); | |
| 1820 | - } | |
| 1821 | - } | |
| 1822 | - throw error; | |
| 1823 | - } | |
| 1824 | - } | |
| 1825 | - // `cause` is the failure that led to the rollback; the abort's error keeps | |
| 1826 | - // it, so a debugger can walk back to the callback's own throw. The | |
| 1827 | - // rollback failure is reported even when the object is already aborted, | |
| 1828 | - // as it is after a block's limit: the abort then changes nothing, and the | |
| 1829 | - // log line is the only trace the failure leaves. | |
| 1830 | - _abortAfterFailedRollback(rollbackError, cause) { | |
| 1831 | - // Inside a catch, so the log must not become the throw that leaves it: | |
| 1832 | - // the slot release after the caller's rethrow depends on that. | |
| 1833 | - try { console.error("transaction rollback failed", rollbackError); } catch {} | |
| 1834 | - const state = this._transactionRoot._state; | |
| 1835 | - if (state && !state._aborted) { | |
| 1836 | - state.abort( | |
| 1837 | - new Error( | |
| 1838 | - "a transaction rollback failed: " + __describeFailure(rollbackError), | |
| 1839 | - { cause }, | |
| 1840 | - ), | |
| 1841 | - ); | |
| 1842 | - } | |
| 1843 | - } | |
| 1844 | - async _runTransaction(f) { | |
| 1845 | - const savepoint = this._transactionStart(); | |
| 1846 | - return this._runTransactionWith(f, savepoint, this._newTransactionControl(savepoint)); | |
| 1847 | - } | |
| 1848 | - async transaction(f) { | |
| 1849 | - this._assertTransactionActive("transaction"); | |
| 1850 | - if (this._transactionDepth > 0) return this._runTransaction(f); | |
| 1851 | - // Workerd runs the callback under blockConcurrencyWhile: the input gate | |
| 1852 | - // shuts, so no other event starts in the object while the transaction is | |
| 1853 | - // open. Without it another event's reads saw uncommitted rows, its | |
| 1854 | - // writes joined the open transaction on the same connection, and a | |
| 1855 | - // rollback discarded a write celld had already acknowledged (#714). The | |
| 1856 | - // callback's failure is caught inside the block: a failed transaction | |
| 1857 | - // rolls back and rejects, and must not reset the object the way a failed | |
| 1858 | - // critical section does. | |
| 1859 | - // | |
| 1860 | - // The tail orders transactions one event starts concurrently, which the | |
| 1861 | - // gate does not separate. Its slot is taken here, in call order: taken | |
| 1862 | - // inside the block it would be taken in the order the gate woke the | |
| 1863 | - // callers, which is not theirs to keep. It is released inside the block, | |
| 1864 | - // when the callback has settled, and not when the block has: a second | |
| 1865 | - // transaction the same event starts while the first runs rides the | |
| 1866 | - // outer hold as a nested block, and the outer block waits for nested | |
| 1867 | - // ones before it releases, so a slot held until the block's end would | |
| 1868 | - // wait on itself. | |
| 1869 | - const root = this._transactionRoot; | |
| 1870 | - const previous = root._transactionTail; | |
| 1871 | - let release; | |
| 1872 | - root._transactionTail = new Promise((resolve) => { release = resolve; }); | |
| 1873 | - let control = null; | |
| 1874 | - let started = false; | |
| 1875 | - let abandoned = null; | |
| 1876 | - const guarded = async () => { | |
| 1877 | - started = true; | |
| 1878 | - try { | |
| 1879 | - await previous; | |
| 1880 | - // The block ended while this waited for its slot, or the object was | |
| 1881 | - // reset under it by an enclosing block that failed: the caller has | |
| 1882 | - // its rejection and the gate is open again, so starting the | |
| 1883 | - // transaction now would run it beside whatever the object serves. | |
| 1884 | - if (abandoned !== null) return { error: abandoned }; | |
| 1885 | - if (root._state._aborted) { | |
| 1886 | - return { error: new Error("the Durable Object was reset before the transaction started") }; | |
| 1887 | - } | |
| 1888 | - // The start is a host op that can fail like any other statement, and | |
| 1889 | - // a failure there is the transaction's to report, not the block's: | |
| 1890 | - // a throw that escaped here would reset the object. | |
| 1891 | - try { | |
| 1892 | - const savepoint = this._transactionStart(); | |
| 1893 | - control = this._newTransactionControl(savepoint); | |
| 1894 | - return { value: await this._runTransactionWith(f, savepoint, control) }; | |
| 1895 | - } catch (error) { | |
| 1896 | - return { error }; | |
| 1897 | - } | |
| 1898 | - } finally { | |
| 1899 | - release(); | |
| 1900 | - } | |
| 1901 | - }; | |
| 1902 | - let outcome; | |
| 1903 | - try { | |
| 1904 | - outcome = await root._state.blockConcurrencyWhile(guarded); | |
| 1905 | - } catch (error) { | |
| 1906 | - // The block itself failed: its limit ended the callback while it still | |
| 1907 | - // ran, or the block ahead of it failed and this one never started. A | |
| 1908 | - // transaction the callback still holds would otherwise stay open on | |
| 1909 | - // the connection the object's replacement uses, and the callback's | |
| 1910 | - // late commit would carry the replacement's writes with it. Roll it | |
| 1911 | - // back now, unless the callback's continuation committed in the same | |
| 1912 | - // tick the limit won; the callback's own commit is skipped from here | |
| 1913 | - // on. The slot stays with the callback until it settles: the callback | |
| 1914 | - // still runs on the connection, and a transaction started beside it | |
| 1915 | - // would interleave with its remaining statements. A block that failed | |
| 1916 | - // before the callback started holds nothing, so its slot is released | |
| 1917 | - // here or nothing ever would. | |
| 1918 | - abandoned = error; | |
| 1919 | - if (control && !control.rolledBack && !control.committed) { | |
| 1920 | - try { | |
| 1921 | - control.rollback(); | |
| 1922 | - control.rolledBack = true; | |
| 1923 | - } catch (rollbackError) { | |
| 1924 | - this._abortAfterFailedRollback(rollbackError, error); | |
| 1925 | - } | |
| 1926 | - } | |
| 1927 | - if (!started) release(); | |
| 1928 | - throw error; | |
| 1929 | - } | |
| 1930 | - if ("error" in outcome) throw outcome.error; | |
| 1931 | - return outcome.value; | |
| 1932 | - } | |
| 1933 | -} | |
| 1934 | -class DurableObjectId { | |
| 1935 | - constructor(className, value, name = undefined) { | |
| 1936 | - Object.defineProperties(this, { | |
| 1937 | - _className: { value: className }, | |
| 1938 | - _value: { value }, | |
| 1939 | - }); | |
| 1940 | - this.name = name; | |
| 1941 | - this.jurisdiction = undefined; | |
| 1942 | - } | |
| 1943 | - toString() { return this._value; } | |
| 1944 | - equals(other) { | |
| 1945 | - return other instanceof DurableObjectId && other._value === this._value; | |
| 1946 | - } | |
| 1947 | - _scope() { return this._className + ":" + this._value; } | |
| 1948 | -} | |
| 1949 | -globalThis.DurableObjectRoutingError = class DurableObjectRoutingError | |
| 1950 | - extends Error { | |
| 1951 | - constructor(detail = {}) { | |
| 1952 | - super("The Durable Object owner is currently unreachable"); | |
| 1953 | - this.name = "DurableObjectRoutingError"; | |
| 1954 | - this.code = "owner_unreachable"; | |
| 1955 | - this.retryable = true; | |
| 1956 | - if (typeof detail.scope === "string") this.scope = detail.scope; | |
| 1957 | - if (typeof detail.owner === "string") this.owner = detail.owner; | |
| 1958 | - } | |
| 1959 | -}; | |
| 1960 | -const __durableObjectRoutingError = (error) => { | |
| 1961 | - const marker = "__CELLD_DO_ROUTING_ERROR__:"; | |
| 1962 | - const message = String(error && error.message || error); | |
| 1963 | - const offset = message.indexOf(marker); | |
| 1964 | - if (offset < 0) return null; | |
| 1965 | - try { | |
| 1966 | - return new DurableObjectRoutingError( | |
| 1967 | - JSON.parse(message.slice(offset + marker.length)), | |
| 1968 | - ); | |
| 1969 | - } catch { | |
| 1970 | - return new DurableObjectRoutingError(); | |
| 1971 | - } | |
| 1972 | -}; | |
| 1973 | -// A cell's input gate as the isolate sees it, for the one delivery | |
| 1974 | -// point that is inside the isolate rather than in front of it: an | |
| 1975 | -// RPC stub op. `events` records every block that has asked for the | |
| 1976 | -// gate, so no window exists in which a block has started and the | |
| 1977 | -// isolate still thinks the cell is open. `holder` names the block | |
| 1978 | -// actually running; another event can still be queued. | |
| 1979 | -// | |
| 1980 | -// A stub minted while a block runs carries that block's token and | |
| 1981 | -// re-enters it instead of queueing behind it. That is Workerd's | |
| 1982 | -// `IoContext::makeReentryCallback`, and without it a callback the | |
| 1983 | -// block itself sent out could never come back. | |
| 1984 | -const __cellBlocks = new Map(); | |
| 1985 | -const __blockEnter = (scope, event, owner) => { | |
| 1986 | - let settleReady; | |
| 1987 | - let rejectReady; | |
| 1988 | - const ready = new Promise((resolve, reject) => { | |
| 1989 | - settleReady = resolve; | |
| 1990 | - rejectReady = reject; | |
| 1991 | - }); | |
| 1992 | - const record = { | |
| 1993 | - owner, | |
| 1994 | - reaction: String(__io_context_id()), | |
| 1995 | - actorEvent: __currentActorEvent(), | |
| 1996 | - retired: false, | |
| 1997 | - ready, | |
| 1998 | - settleReady, | |
| 1999 | - rejectReady, | |
| 2000 | - }; | |
| 2001 | - const block = __cellBlocks.get(scope); | |
| 2002 | - if (block !== undefined) { | |
| 2003 | - block.events.set(event, record); | |
| 2004 | - return { block, record }; | |
| 2005 | - } | |
| 2006 | - const fresh = { | |
| 2007 | - holder: null, | |
| 2008 | - events: new Map([[event, record]]), | |
| 2009 | - }; | |
| 2010 | - __cellBlocks.set(scope, fresh); | |
| 2011 | - return { block: fresh, record }; | |
| 2012 | -}; | |
| 2013 | -const __blockLeave = (scope, block, event) => { | |
| 2014 | - if (!block.events.delete(event)) return; | |
| 2015 | - if (block.holder === event) block.holder = null; | |
| 2016 | - if (block.events.size === 0 && __cellBlocks.get(scope) === block) | |
| 2017 | - __cellBlocks.delete(scope); | |
| 2018 | -}; | |
| 2019 | -const __durableClassMeta = new WeakMap(); | |
| 2020 | -let __nextFacetOwner = 1; | |
| 2021 | -const __makeDurableObjectClass = (idPromise, name, options = {}) => { | |
| 2022 | - const value = {}; | |
| 2023 | - __durableClassMeta.set(value, { | |
| 2024 | - idPromise, | |
| 2025 | - name: name === null || name === undefined ? "default" : String(name), | |
| 2026 | - props: options?.props, | |
| 2027 | - }); | |
| 2028 | - return value; | |
| 2029 | -}; | |
| 2030 | -class DurableObjectFacets { | |
| 2031 | - constructor(state) { | |
| 2032 | - this._state = state; | |
| 2033 | - this._owner = String(__nextFacetOwner++); | |
| 2034 | - this._next = 1; | |
| 2035 | - this._running = new Map(); | |
| 2036 | - this._barriers = new Map(); | |
| 2037 | - } | |
| 2038 | - _validName(name) { | |
| 2039 | - name = String(name); | |
| 2040 | - if (new TextEncoder().encode(name).length > 256) | |
| 2041 | - throw new TypeError("Facet name is too long (max 256 characters)."); | |
| 2042 | - return name; | |
| 2043 | - } | |
| 2044 | - get(name, getStartupOptions) { | |
| 2045 | - name = this._validName(name); | |
| 2046 | - if (this._state._facetDepth >= 3) | |
| 2047 | - throw new Error( | |
| 2048 | - "Facet nesting depth limit exceeded. The maximum depth including the root Durable Object is 4."); | |
| 2049 | - if (typeof getStartupOptions !== "function") | |
| 2050 | - throw new TypeError("The facet startup callback must be a function."); | |
| 2051 | - let record = this._running.get(name); | |
| 2052 | - if (record !== undefined) return record.stub; | |
| 2053 | - // Each run gets a distinct host scope. An aborted request can still have | |
| 2054 | - // a pending continuation, so reusing its scope would let that continuation | |
| 2055 | - // enter the replacement instance after the abort barrier opens. | |
| 2056 | - record = { | |
| 2057 | - aborted: false, | |
| 2058 | - error: undefined, | |
| 2059 | - owner: this._owner + ":" + this._next++, | |
| 2060 | - started: null, | |
| 2061 | - stub: null, | |
| 2062 | - }; | |
| 2063 | - const barrier = this._barriers.get(name); | |
| 2064 | - const start = () => record.started ??= Promise.resolve(barrier) | |
| 2065 | - .then(getStartupOptions) | |
| 2066 | - .then(async (options) => { | |
| 2067 | - const meta = __durableClassMeta.get(options?.class); | |
| 2068 | - if (meta === undefined) | |
| 2069 | - throw new TypeError( | |
| 2070 | - "FacetStartupOptions.class must be a DurableObjectClass."); | |
| 2071 | - const loader = await meta.idPromise; | |
| 2072 | - const id = options.id instanceof DurableObjectId | |
| 2073 | - ? options.id.toString() | |
| 2074 | - : options.id === undefined ? this._state.id.toString() : String(options.id); | |
| 2075 | - return [loader, meta.name, id, meta.props]; | |
| 2076 | - }); | |
| 2077 | - const invoke = async (operation) => { | |
| 2078 | - if (record.aborted) throw record.error; | |
| 2079 | - return operation(await start()); | |
| 2080 | - }; | |
| 2081 | - const target = {}; | |
| 2082 | - // Methods share the loaded-worker RPC transport. A facet stub is not | |
| 2083 | - // awaitable, and a property is a single callable pipeline node. | |
| 2084 | - const session = { | |
| 2085 | - get: () => Promise.reject(new Error( | |
| 2086 | - "Awaitable properties on facets are not supported yet.")), | |
| 2087 | - call: (path, args) => invoke(async ([loader, className, id, props]) => { | |
| 2088 | - if (path.length !== 1) | |
| 2089 | - throw new Error( | |
| 2090 | - "Pipelined property paths on facets are not supported yet."); | |
| 2091 | - return __rpcDes(await __facet_rpc( | |
| 2092 | - loader, className, this._state._scope, record.owner, name, id, | |
| 2093 | - JSON.stringify(props ?? null), path[0], __rpcOut(args, false))); | |
| 2094 | - }), | |
| 2095 | - }; | |
| 2096 | - // Arrow closures retain the manager because `target.fetch`'s method | |
| 2097 | - // receiver is the target object, not the DurableObjectFacets instance. | |
| 2098 | - const manager = this; | |
| 2099 | - target.fetch = async function(input, init) { | |
| 2100 | - return invoke(async ([loader, className, id, props]) => { | |
| 2101 | - const req = new Request(input, init); | |
| 2102 | - const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 2103 | - const { body, streamId } = await __subrequestBody(req); | |
| 2104 | - const response = JSON.parse(await __facet_fetch( | |
| 2105 | - loader, className, manager._state._scope, record.owner, name, id, | |
| 2106 | - JSON.stringify(props ?? null), req.url, req.method, body, headers, streamId)); | |
| 2107 | - const responseBody = response.streamId !== undefined | |
| 2108 | - ? new CelldHttpBodyStream(response.streamId) | |
| 2109 | - : response.body !== undefined ? response.body | |
| 2110 | - : Uint8Array.from(response.bodyBytes || []); | |
| 2111 | - return __wrapServiceResponse(new Response(responseBody, { | |
| 2112 | - status: response.status, | |
| 2113 | - headers: response.headers, | |
| 2114 | - }), req.url); | |
| 2115 | - }); | |
| 2116 | - }; | |
| 2117 | - record.stub = new Proxy(target, { | |
| 2118 | - get(base, prop) { | |
| 2119 | - if (prop === "then") return undefined; | |
| 2120 | - if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 2121 | - if (typeof prop !== "string") return undefined; | |
| 2122 | - return __makeNode(session, [prop], null); | |
| 2123 | - }, | |
| 2124 | - }); | |
| 2125 | - this._running.set(name, record); | |
| 2126 | - return record.stub; | |
| 2127 | - } | |
| 2128 | - _abort(name, reason) { | |
| 2129 | - name = this._validName(name); | |
| 2130 | - const record = this._running.get(name); | |
| 2131 | - if (record === undefined) return Promise.resolve(); | |
| 2132 | - record.aborted = true; | |
| 2133 | - record.error = reason; | |
| 2134 | - this._running.delete(name); | |
| 2135 | - const barrier = record.started === null ? Promise.resolve() : record.started | |
| 2136 | - .then(([loader, className]) => | |
| 2137 | - __facet_abort( | |
| 2138 | - loader, className, this._state._scope, record.owner, name), () => {}); | |
| 2139 | - this._barriers.set(name, barrier); | |
| 2140 | - const clear = () => { | |
| 2141 | - if (this._barriers.get(name) === barrier) this._barriers.delete(name); | |
| 2142 | - }; | |
| 2143 | - barrier.then(clear, clear); | |
| 2144 | - return barrier; | |
| 2145 | - } | |
| 2146 | - abort(name, reason) { | |
| 2147 | - this._abort(name, reason); | |
| 2148 | - } | |
| 2149 | - delete(name) { | |
| 2150 | - name = this._validName(name); | |
| 2151 | - const barrier = this._abort(name, new Error("Facet was deleted.")).then(() => | |
| 2152 | - __facet_delete(this._state._scope, name)); | |
| 2153 | - this._barriers.set(name, barrier); | |
| 2154 | - const clear = () => { | |
| 2155 | - if (this._barriers.get(name) === barrier) this._barriers.delete(name); | |
| 2156 | - }; | |
| 2157 | - // Keep a failed delete as the name's barrier. Clearing it would let the | |
| 2158 | - // next get reload the image which the failed operation did not delete. | |
| 2159 | - barrier.then(clear, () => {}); | |
| 2160 | - } | |
| 2161 | - _release() { | |
| 2162 | - for (const name of Array.from(this._running.keys())) | |
| 2163 | - this._abort(name, new Error("The parent Durable Object was released.")); | |
| 2164 | - } | |
| 2165 | -} | |
| 2166 | -// The reason a failed critical section gives its waiters. It must not throw: | |
| 2167 | -// it runs where a throw would skip the gate's release, and a value with no | |
| 2168 | -// string form, such as `Object.create(null)`, is a legal thing to throw. | |
| 2169 | -function __describeFailure(error) { | |
| 2170 | - try { | |
| 2171 | - return String((error && error.message) || error); | |
| 2172 | - } catch { | |
| 2173 | - return "critical section failed"; | |
| 2174 | - } | |
| 2175 | -} | |
| 2176 | -class DurableObjectState { | |
| 2177 | - constructor(scope) { | |
| 2178 | - this._scope = scope; | |
| 2179 | - this._aborted = false; | |
| 2180 | - this.storage = new DurableObjectStorage(scope, this); | |
| 2181 | - this.facets = new DurableObjectFacets(this); | |
| 2182 | - this._gate = Promise.resolve(); | |
| 2183 | - this._blockDepth = 0; | |
| 2184 | - const facet = __cell.facetConfigs[scope]; | |
| 2185 | - this._facetDepth = facet?.depth ?? 0; | |
| 2186 | - const separator = scope.indexOf(":"); | |
| 2187 | - const className = separator < 0 ? scope : scope.slice(0, separator); | |
| 2188 | - const value = facet?.id ?? (separator < 0 ? scope : scope.slice(separator + 1)); | |
| 2189 | - this.id = new DurableObjectId( | |
| 2190 | - className, value, __cell.idNames[scope], | |
| 2191 | - ); | |
| 2192 | - this.props = facet?.props; | |
| 2193 | - } | |
| 2194 | - // Workerd's DurableObjectState.exports (actor-state.h): the same | |
| 2195 | - // loopback surface as ctx.exports on stateless entrypoints. | |
| 2196 | - get exports() { return __ctxExports(); } | |
| 2197 | - blockConcurrencyWhile(f) { | |
| 2198 | - if (typeof f !== "function") | |
| 2199 | - throw new TypeError("blockConcurrencyWhile() requires a function"); | |
| 2200 | - if (this._blockDepth >= 64) | |
| 2201 | - throw new Error( | |
| 2202 | - "blockConcurrencyWhile() calls are nested too deeply.", | |
| 2203 | - ); | |
| 2204 | - if (this._blockDepth > 0) { | |
| 2205 | - // A nested block rides the outer hold. One the outer body starts and | |
| 2206 | - // does not await would outlive that hold, and a `transaction()` | |
| 2207 | - // started that way is the shape that mattered: the outer block | |
| 2208 | - // returned, the gate opened, and another event wrote into the still | |
| 2209 | - // open transaction (#714). The outer block drains these before it | |
| 2210 | - // releases, so the hold lasts as long as any block under it. A nested | |
| 2211 | - // block that fails resets the object as any block does, and the outer | |
| 2212 | - // release must carry that failure, or the waiters would be admitted to | |
| 2213 | - // an object that no longer exists: the drain records it. | |
| 2214 | - const nested = this._runConcurrencyBlock(f); | |
| 2215 | - (this._nestedBlocks ||= []).push(nested.then(() => null, __describeFailure)); | |
| 2216 | - return nested; | |
| 2217 | - } | |
| 2218 | - // The host owns the gate (celld_logic::gate::InputGate). It replaces a | |
| 2219 | - // promise chain that could only order blocks against each other; the | |
| 2220 | - // gate sits at the delivery points, so nothing else is delivered to this | |
| 2221 | - // cell at all while the block runs. | |
| 2222 | - // | |
| 2223 | - // The acquire waits. It used to be synchronous, and had to be: a cell's | |
| 2224 | - // events came off one channel, so yielding even one microtask reopened a | |
| 2225 | - // window in which this cell delivered an event that then waited on a | |
| 2226 | - // gate nothing would release. Events are independent tasks now, so two | |
| 2227 | - // can reach a block together and the second has to queue — and nothing | |
| 2228 | - // nests, so waiting cannot deadlock on an event suspended beneath it. | |
| 2229 | - // Asked for synchronously, awaited asynchronously, and the split is the | |
| 2230 | - // whole point. The op shuts the gate in this very call, so no event can | |
| 2231 | - // be delivered to this cell from here on — that immediacy is what makes | |
| 2232 | - // `failCriticalSection()` reject a `ping()` issued right after it. | |
| 2233 | - // Waiting for the *ticket* is separate: events are independent tasks | |
| 2234 | - // now, so two of them can reach a block together and the second has to | |
| 2235 | - // queue behind the first. Calling this inside the async body instead | |
| 2236 | - // costs one microtask, and an event delivered in that window walks | |
| 2237 | - // straight into the critical section. | |
| 2238 | - const [eventText, owner, acquired] = __gate_acquire(this._scope); | |
| 2239 | - const event = Number(eventText); | |
| 2240 | - const { block, record } = __blockEnter(this._scope, event, owner); | |
| 2241 | - const next = (async () => { | |
| 2242 | - try { | |
| 2243 | - await acquired; | |
| 2244 | - // A shutdown can retire the promise reaction while another event | |
| 2245 | - // owns this queued acquisition. The owner still has to consume its | |
| 2246 | - // ticket, but the retired callback must not run. | |
| 2247 | - if (record.retired) { | |
| 2248 | - __gate_release(this._scope, event, owner, null); | |
| 2249 | - return; | |
| 2250 | - } | |
| 2251 | - block.holder = event; | |
| 2252 | - // A critical section that fails resets the actor, so whatever queued | |
| 2253 | - // behind its gate must be refused rather than handed to the reset | |
| 2254 | - // one — it was sent to a cell whose state no longer exists. The | |
| 2255 | - // failure rides with the release for that: waiters are woken with it | |
| 2256 | - // instead of merely woken. | |
| 2257 | - let failure = null; | |
| 2258 | - try { | |
| 2259 | - return await this._runConcurrencyBlock(f); | |
| 2260 | - } catch (error) { | |
| 2261 | - failure = __describeFailure(error); | |
| 2262 | - throw error; | |
| 2263 | - } finally { | |
| 2264 | - // Nested blocks are drained only after a body that returned: a | |
| 2265 | - // body that failed has reset the object, its waiters are refused | |
| 2266 | - // whatever the nested blocks do, and waiting for them would only | |
| 2267 | - // delay the refusal and a transaction's rollback behind it. Each | |
| 2268 | - // nested block has its own limit, so a drain is bounded by the | |
| 2269 | - // last one started, as workerd's nested critical sections are. | |
| 2270 | - while (failure === null && this._nestedBlocks && this._nestedBlocks.length > 0) { | |
| 2271 | - for (const nestedFailure of await Promise.all(this._nestedBlocks.splice(0))) { | |
| 2272 | - if (nestedFailure !== null && failure === null) failure = nestedFailure; | |
| 2273 | - } | |
| 2274 | - } | |
| 2275 | - this._nestedBlocks = undefined; | |
| 2276 | - __gate_release(this._scope, event, owner, failure); | |
| 2277 | - } | |
| 2278 | - } finally { | |
| 2279 | - // Also on a rejected `acquired`: the block ahead failed, this one | |
| 2280 | - // never ran, and the cell must not stay shut on its behalf. | |
| 2281 | - __blockLeave(this._scope, block, event); | |
| 2282 | - } | |
| 2283 | - })(); | |
| 2284 | - // `_ready()` awaits this. The host gate stops *other* events, but a | |
| 2285 | - // block taken in the constructor runs inside the very event that is | |
| 2286 | - // being delivered, so nothing external can hold that event back — the | |
| 2287 | - // promise does. Concurrent blocks within one event go through | |
| 2288 | - // `_blockDepth` above and never reach here. | |
| 2289 | - this._gate = Promise.all([this._gate, record.ready]).then(() => undefined); | |
| 2290 | - // `_ready()` observes the original promise. This extra handler prevents | |
| 2291 | - // a constructor-time rejection from becoming unhandled before an event | |
| 2292 | - // reaches `_ready()`. | |
| 2293 | - this._gate.catch(() => {}); | |
| 2294 | - next.then(record.settleReady, record.rejectReady); | |
| 2295 | - return next; | |
| 2296 | - } | |
| 2297 | - _runConcurrencyBlock(f) { | |
| 2298 | - this._blockDepth++; | |
| 2299 | - let result; | |
| 2300 | - try { | |
| 2301 | - result = f(); | |
| 2302 | - } catch (error) { | |
| 2303 | - this._blockDepth--; | |
| 2304 | - this._resetAfterConcurrencyFailure(error); | |
| 2305 | - throw error; | |
| 2306 | - } | |
| 2307 | - const timerId = __timer_alloc(); | |
| 2308 | - let settled = false; | |
| 2309 | - const timeout = __op_timer( | |
| 2310 | - timerId, | |
| 2311 | - 30_000, | |
| 2312 | - ).then(() => { | |
| 2313 | - if (!settled) { | |
| 2314 | - throw new Error( | |
| 2315 | - "A call to blockConcurrencyWhile() in a Durable Object waited for " + | |
| 2316 | - "too long. The call was canceled and the Durable Object was reset.", | |
| 2317 | - ); | |
| 2318 | - } | |
| 2319 | - }); | |
| 2320 | - return Promise.race([Promise.resolve(result), timeout]).then( | |
| 2321 | - (value) => { | |
| 2322 | - settled = true; | |
| 2323 | - __timer_cancel(timerId); | |
| 2324 | - this._blockDepth--; | |
| 2325 | - return value; | |
| 2326 | - }, | |
| 2327 | - (error) => { | |
| 2328 | - settled = true; | |
| 2329 | - __timer_cancel(timerId); | |
| 2330 | - this._blockDepth--; | |
| 2331 | - this._resetAfterConcurrencyFailure(error); | |
| 2332 | - throw error; | |
| 2333 | - }, | |
| 2334 | - ); | |
| 2335 | - } | |
| 2336 | - _resetAfterConcurrencyFailure(error) { | |
| 2337 | - if (this._aborted) return; | |
| 2338 | - this._aborted = true; | |
| 2339 | - __storage_cancel_pending_puts(this._scope); | |
| 2340 | - const instance = __cell.instances[this._scope]; | |
| 2341 | - if (instance && instance.__celldState === this) | |
| 2342 | - delete __cell.instances[this._scope]; | |
| 2343 | - // Under a stub-mediated caller (this scope is not the current | |
| 2344 | - // event) the failure breaks the actor, as Workerd joins it | |
| 2345 | - // into the on-abort promise; a direct event keeps reset-only | |
| 2346 | - // semantics — its caller sees the rejection itself. | |
| 2347 | - if (__currentActorScope() !== this._scope) | |
| 2348 | - __actorBreak(this._scope, error); | |
| 2349 | - } | |
| 2350 | - abort(reason) { | |
| 2351 | - if (this._aborted) return; | |
| 2352 | - this._aborted = true; | |
| 2353 | - __storage_cancel_pending_puts(this._scope); | |
| 2354 | - const instance = __cell.instances[this._scope]; | |
| 2355 | - if (instance && instance.__celldState === this) | |
| 2356 | - delete __cell.instances[this._scope]; | |
| 2357 | - const message = reason instanceof Error | |
| 2358 | - ? reason.message | |
| 2359 | - : String(reason); | |
| 2360 | - // Direct host-dispatched event on this actor: the uncatchable | |
| 2361 | - // terminate_execution path. Under a same-isolate stub caller, | |
| 2362 | - // termination would unwind the caller too, so break in JS. | |
| 2363 | - if (__currentActorScope() === this._scope) { | |
| 2364 | - __actor_abort(this._scope, message); | |
| 2365 | - return; | |
| 2366 | - } | |
| 2367 | - __actorBreak(this._scope, | |
| 2368 | - reason instanceof Error ? reason : new Error(message)); | |
| 2369 | - } | |
| 2370 | - _ready() { return this._gate; } | |
| 2371 | - getWebSockets(tag) { | |
| 2372 | - return JSON.parse(__ws_list(this._scope, tag)).map((row) => __socketFromRow(row)); | |
| 2373 | - } | |
| 2374 | - getTags(ws) { | |
| 2375 | - if (!(ws instanceof WebSocket) || !ws._hibernatable) { | |
| 2376 | - throw new Error( | |
| 2377 | - "you must call 'acceptWebSocket()' before attempting to access " + | |
| 2378 | - "the tags of a WebSocket."); | |
| 2379 | - } | |
| 2380 | - return Array.from(ws._tags); | |
| 2381 | - } | |
| 2382 | - acceptWebSocket(ws, tags = []) { | |
| 2383 | - if (__heap_over_admission_share()) | |
| 2384 | - throw new Error( | |
| 2385 | - "the isolate is near its V8 heap limit, so it refused a " + | |
| 2386 | - "WebSocket (see CELLD_V8_HEAP_LIMIT_MB)"); | |
| 2387 | - ws._target = { id: ws._id, scope: this._scope }; | |
| 2388 | - if (ws._peer) ws._peer._target = ws._target; | |
| 2389 | - ws._hibernatable = true; | |
| 2390 | - if (ws._peer) ws._peer._hibernatable = true; | |
| 2391 | - ws._tags = Array.from(tags, String); | |
| 2392 | - __ws_accept(ws._id, this._scope, JSON.stringify(ws._tags)); | |
| 2393 | - __sockets.set(ws._id, ws); | |
| 2394 | - } | |
| 2395 | - _socket(id) { | |
| 2396 | - return __sockets.get(Number(id)) || | |
| 2397 | - this.getWebSockets().find((ws) => ws._id === id) || | |
| 2398 | - __wsStub(id); | |
| 2399 | - } | |
| 2400 | - // Workerd actor-state.c++ setWebSocketAutoResponse: no pair unsets, and | |
| 2401 | - // each side is capped at 2048 UTF-8 bytes. The pair itself lives in the | |
| 2402 | - // shell — a matched message is answered without waking this cell. | |
| 2403 | - setWebSocketAutoResponse(pair) { | |
| 2404 | - if (pair === undefined || pair === null) { | |
| 2405 | - __ws_auto_response_set(this._scope, null, null); | |
| 2406 | - return; | |
| 2407 | - } | |
| 2408 | - if (!(pair instanceof WebSocketRequestResponsePair)) | |
| 2409 | - throw new TypeError( | |
| 2410 | - "Failed to execute 'setWebSocketAutoResponse' on " + | |
| 2411 | - "'DurableObjectState': parameter 1 is not of type " + | |
| 2412 | - "'WebSocketRequestResponsePair'.", | |
| 2413 | - ); | |
| 2414 | - const max = 2048; | |
| 2415 | - const bytes = (s) => new TextEncoder().encode(s).length; | |
| 2416 | - const requestSize = bytes(pair.request); | |
| 2417 | - if (requestSize > max) | |
| 2418 | - throw new RangeError( | |
| 2419 | - `Request cannot be larger than ${max} bytes. ` + | |
| 2420 | - `A request of size ${requestSize} was provided.`, | |
| 2421 | - ); | |
| 2422 | - const responseSize = bytes(pair.response); | |
| 2423 | - if (responseSize > max) | |
| 2424 | - throw new RangeError( | |
| 2425 | - `Response cannot be larger than ${max} bytes. ` + | |
| 2426 | - `A response of size ${responseSize} was provided.`, | |
| 2427 | - ); | |
| 2428 | - __ws_auto_response_set(this._scope, pair.request, pair.response); | |
| 2429 | - } | |
| 2430 | - getWebSocketAutoResponse() { | |
| 2431 | - const pair = JSON.parse(__ws_auto_response_get(this._scope)); | |
| 2432 | - if (pair === null) return null; | |
| 2433 | - return new WebSocketRequestResponsePair(pair[0], pair[1]); | |
| 2434 | - } | |
| 2435 | - getWebSocketAutoResponseTimestamp(ws) { | |
| 2436 | - const ms = __ws_auto_response_ts(ws._id); | |
| 2437 | - return ms === null ? null : new Date(ms); | |
| 2438 | - } | |
| 2439 | - waitUntil(promise) { | |
| 2440 | - globalThis.__registerWaitUntil(promise); | |
| 2441 | - } | |
| 2442 | -} | |
| 2443 | -function _instance(scope) { | |
| 2444 | - let inst = __cell.instances[scope]; | |
| 2445 | - if (!inst) { | |
| 2446 | - const className = scope.split(":")[0]; | |
| 2447 | - const cls = __cell.classes[className]; | |
| 2448 | - if (!cls) throw new Error("no DO class " + className); | |
| 2449 | - const state = new DurableObjectState(scope); | |
| 2450 | - inst = new cls(state, __cell.env); | |
| 2451 | - Object.defineProperty(inst, "__celldState", { value: state }); | |
| 2452 | - // Workerd worker-rpc.c++ getTargetInfo(): RPC needs `extends | |
| 2453 | - // DurableObject` unless the js_rpc compat flag is on. Decided | |
| 2454 | - // once here; dispatch reads a boolean. | |
| 2455 | - state._rpcOk = __cell.compat.jsRpc || | |
| 2456 | - __cell.doExports[className] === true; | |
| 2457 | - __cell.instances[scope] = inst; | |
| 2458 | - } | |
| 2459 | - return inst; | |
| 2460 | -} | |
| 2461 | -async function _readyInstance(scope) { | |
| 2462 | - const inst = _instance(scope); | |
| 2463 | - await inst.__celldState._ready(); | |
| 2464 | - return inst; | |
| 2465 | -} | |
| 2466 | -const __actorEventStack = []; | |
| 2467 | -const __currentActorEvent = () => { | |
| 2468 | - const context = String(__io_context_id()); | |
| 2469 | - if (context === "") return undefined; | |
| 2470 | - for (let index = __actorEventStack.length - 1; index >= 0; index--) { | |
| 2471 | - const event = __actorEventStack[index]; | |
| 2472 | - if (event.context === context) return event; | |
| 2473 | - } | |
| 2474 | - return undefined; | |
| 2475 | -}; | |
| 2476 | -const __currentActorScope = () => __currentActorEvent()?.scope ?? ""; | |
| 2477 | -const __beginActorEvent = (scope) => { | |
| 2478 | - const event = { scope, context: String(__io_context_id()) }; | |
| 2479 | - __actorEventStack.push(event); | |
| 2480 | - return event; | |
| 2481 | -}; | |
| 2482 | -const __endActorEvent = (event) => { | |
| 2483 | - const index = __actorEventStack.lastIndexOf(event); | |
| 2484 | - if (index >= 0) __actorEventStack.splice(index, 1); | |
| 2485 | -}; | |
| 2486 | -const __endActorEventsForContext = (context) => { | |
| 2487 | - for (let index = __actorEventStack.length - 1; index >= 0; index--) { | |
| 2488 | - if (__actorEventStack[index].context === context) | |
| 2489 | - __actorEventStack.splice(index, 1); | |
| 2490 | - } | |
| 2491 | -}; | |
| 2492 | -const __incomingRequestSignals = new Map(); | |
| 2493 | -const __abortSignal = (signal, reason) => { | |
| 2494 | - if (signal.aborted) return; | |
| 2495 | - signal.aborted = true; | |
| 2496 | - signal.reason = reason; | |
| 2497 | - signal.dispatchEvent(new Event("abort")); | |
| 2498 | -}; | |
| 2499 | -globalThis.__abortIncomingRequest = (requestId) => { | |
| 2500 | - const signal = __incomingRequestSignals.get(String(requestId)); | |
| 2501 | - if (signal && !signal.aborted) { | |
| 2502 | - __abortSignal(signal, new Error("The client has disconnected")); | |
| 2503 | - return true; | |
| 2504 | - } | |
| 2505 | - return false; | |
| 2506 | -}; | |
| 2507 | -globalThis.__registerIncomingRequest = (requestId, request) => { | |
| 2508 | - __incomingRequestSignals.set(String(requestId), request.signal); | |
| 2509 | -}; | |
| 2510 | -globalThis.__finishIncomingRequest = (requestId) => { | |
| 2511 | - __incomingRequestSignals.delete(String(requestId)); | |
| 2512 | -}; | |
| 2513 | -globalThis.__retireInputGateContext = (context) => { | |
| 2514 | - for (const [scope, block] of __cellBlocks) { | |
| 2515 | - const retired = [...block.events].filter(([, record]) => | |
| 2516 | - record.owner === context || record.reaction === context | |
| 2517 | - ); | |
| 2518 | - if (retired.length === 0) continue; | |
| 2519 | - const holder = retired.find(([event]) => block.holder === event); | |
| 2520 | - if (holder === undefined) { | |
| 2521 | - // A queued callback has not changed the actor. Remove only that | |
| 2522 | - // callback, and let an unrelated holder continue with the same state. | |
| 2523 | - for (const [event, record] of retired) { | |
| 2524 | - record.retired = true; | |
| 2525 | - record.settleReady(); | |
| 2526 | - block.events.delete(event); | |
| 2527 | - if (record.actorEvent !== undefined) | |
| 2528 | - __endActorEvent(record.actorEvent); | |
| 2529 | - } | |
| 2530 | - if (block.events.size === 0 && __cellBlocks.get(scope) === block) | |
| 2531 | - __cellBlocks.delete(scope); | |
| 2532 | - continue; | |
| 2533 | - } | |
| 2534 | - // A running callback changed this actor and cannot reach its own | |
| 2535 | - // `finally`. Reset the actor, and release the host gate when the context | |
| 2536 | - // that started the callback differs from the turn that owns its work. | |
| 2537 | - const [holderEvent, holderRecord] = holder; | |
| 2538 | - __gate_release( | |
| 2539 | - scope, | |
| 2540 | - holderEvent, | |
| 2541 | - holderRecord.owner, | |
| 2542 | - "the cell's critical section ended without releasing", | |
| 2543 | - ); | |
| 2544 | - const instance = __cell.instances[scope]; | |
| 2545 | - if (instance !== undefined) instance.__celldState._aborted = true; | |
| 2546 | - __storage_cancel_pending_puts(scope); | |
| 2547 | - if (instance !== undefined && __cell.instances[scope] === instance) | |
| 2548 | - delete __cell.instances[scope]; | |
| 2549 | - for (const record of block.events.values()) { | |
| 2550 | - record.retired = true; | |
| 2551 | - record.settleReady(); | |
| 2552 | - if (record.actorEvent !== undefined) | |
| 2553 | - __endActorEvent(record.actorEvent); | |
| 2554 | - } | |
| 2555 | - // The old actor cannot run any block `finally`. A later event creates an | |
| 2556 | - // instance whose ready promise contains none of this actor's work. | |
| 2557 | - if (__cellBlocks.get(scope) === block) __cellBlocks.delete(scope); | |
| 2558 | - } | |
| 2559 | - __endActorEventsForContext(context); | |
| 2560 | -}; | |
| 2561 | -// Race a pending dispatch against the caller's abort signal: on abort, | |
| 2562 | -// run `abandon` (which reaches the target's side) and reject with the | |
| 2563 | -// caller's reason. The dispatch keeps its settle handlers, so a late | |
| 2564 | -// settlement after abandonment cannot trip the unhandled-rejection | |
| 2565 | -// signal. | |
| 2566 | -const __raceCallerAbort = (dispatch, signal, abandon) => | |
| 2567 | - new Promise((resolve, reject) => { | |
| 2568 | - let settled = false; | |
| 2569 | - const onAbort = () => { | |
| 2570 | - if (settled) return; | |
| 2571 | - settled = true; | |
| 2572 | - abandon(); | |
| 2573 | - reject(signal.reason); | |
| 2574 | - }; | |
| 2575 | - signal.addEventListener("abort", onAbort, { once: true }); | |
| 2576 | - dispatch.then( | |
| 2577 | - (value) => { | |
| 2578 | - if (settled) return; | |
| 2579 | - settled = true; | |
| 2580 | - signal.removeEventListener("abort", onAbort); | |
| 2581 | - resolve(value); | |
| 2582 | - }, | |
| 2583 | - (error) => { | |
| 2584 | - if (settled) return; | |
| 2585 | - settled = true; | |
| 2586 | - signal.removeEventListener("abort", onAbort); | |
| 2587 | - reject(error); | |
| 2588 | - }, | |
| 2589 | - ); | |
| 2590 | - }); | |
| 2591 | -const __awaitCancellableDoCall = (operation, signal) => { | |
| 2592 | - if (signal.aborted) { | |
| 2593 | - __do_call_cancel(operation.__celldCancelId); | |
| 2594 | - return Promise.reject(signal.reason); | |
| 2595 | - } | |
| 2596 | - return __raceCallerAbort(operation, signal, | |
| 2597 | - () => __do_call_cancel(operation.__celldCancelId)); | |
| 2598 | -}; | |
| 2599 | -// Workerd semantics: a Response crossing a service binding is a fresh | |
| 2600 | -// fetch-shaped Response — immutable headers, default reason phrase, | |
| 2601 | -// the request URL, and a real body stream — never the callee's own | |
| 2602 | -// mutable object. | |
| 2603 | -const __STATUS_TEXT = { | |
| 2604 | - 100: "Continue", 101: "Switching Protocols", 102: "Processing", | |
| 2605 | - 103: "Early Hints", 200: "OK", 201: "Created", 202: "Accepted", | |
| 2606 | - 203: "Non-Authoritative Information", 204: "No Content", | |
| 2607 | - 205: "Reset Content", 206: "Partial Content", 207: "Multi-Status", | |
| 2608 | - 208: "Already Reported", 226: "IM Used", 300: "Multiple Choices", | |
| 2609 | - 301: "Moved Permanently", 302: "Found", 303: "See Other", | |
| 2610 | - 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", | |
| 2611 | - 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", | |
| 2612 | - 402: "Payment Required", 403: "Forbidden", 404: "Not Found", | |
| 2613 | - 405: "Method Not Allowed", 406: "Not Acceptable", | |
| 2614 | - 407: "Proxy Authentication Required", 408: "Request Timeout", | |
| 2615 | - 409: "Conflict", 410: "Gone", 411: "Length Required", | |
| 2616 | - 412: "Precondition Failed", 413: "Payload Too Large", | |
| 2617 | - 414: "URI Too Long", 415: "Unsupported Media Type", | |
| 2618 | - 416: "Range Not Satisfiable", 417: "Expectation Failed", | |
| 2619 | - 418: "I'm a teapot", 421: "Misdirected Request", | |
| 2620 | - 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", | |
| 2621 | - 425: "Too Early", 426: "Upgrade Required", | |
| 2622 | - 428: "Precondition Required", 429: "Too Many Requests", | |
| 2623 | - 431: "Request Header Fields Too Large", | |
| 2624 | - 451: "Unavailable For Legal Reasons", 500: "Internal Server Error", | |
| 2625 | - 501: "Not Implemented", 502: "Bad Gateway", | |
| 2626 | - 503: "Service Unavailable", 504: "Gateway Timeout", | |
| 2627 | - 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", | |
| 2628 | - 507: "Insufficient Storage", 508: "Loop Detected", | |
| 2629 | - 510: "Not Extended", 511: "Network Authentication Required", | |
| 2630 | -}; | |
| 2631 | -const __ERROR_RESPONSE_MESSAGE = | |
| 2632 | - "Return value from serve handler must not be an error " + | |
| 2633 | - "response (like Response.error())"; | |
| 2634 | -const __wrapServiceResponse = (res, url) => { | |
| 2635 | - // Response.error() represents a Fetch network error, not an HTTP response. | |
| 2636 | - // Letting status 0 cross this seam turns it into an ordinary response and | |
| 2637 | - // makes callers continue after the target explicitly reported failure. | |
| 2638 | - if (res.type === "error" || res.status === 0) { | |
| 2639 | - throw new TypeError(__ERROR_RESPONSE_MESSAGE); | |
| 2640 | - } | |
| 2641 | - // A 101 that crossed isolates carries a target rather than a socket: the | |
| 2642 | - // pair's other end is in the isolate that answered, and the two cannot be | |
| 2643 | - // linked the way the loopback below links them. Give the caller a client | |
| 2644 | - // end the host can join to that target, on the same terms as a Durable | |
| 2645 | - // Object subrequest -- nothing binds until `accept()`, so a response | |
| 2646 | - // passed straight back out keeps the direct route to the real client. | |
| 2647 | - const bound = !res.webSocket && res._wsTarget && res.status === 101 | |
| 2648 | - ? new WebSocket(undefined, [], res._wsTarget) | |
| 2649 | - : undefined; | |
| 2650 | - const wrapped = new Response( | |
| 2651 | - // Buffered bodies re-stream (an empty buffer still yields a | |
| 2652 | - // stream, as over real HTTP); a streaming body passes through. | |
| 2653 | - res._bodyBytes !== null ? res._bodyBytes : res.body, | |
| 2654 | - { | |
| 2655 | - status: res.status, | |
| 2656 | - statusText: | |
| 2657 | - res.statusText || __STATUS_TEXT[res.status] || "", | |
| 2658 | - headers: res.headers, | |
| 2659 | - webSocket: res.webSocket || bound, | |
| 2660 | - __wsTarget: res._wsTarget, | |
| 2661 | - }, | |
| 2662 | - ); | |
| 2663 | - // The constructor copies headers, so mark the copy. | |
| 2664 | - Object.defineProperty(wrapped.headers, "_immutable", { value: true }); | |
| 2665 | - wrapped.url = url; | |
| 2666 | - // An upgraded pair whose both ends live in this isolate: link them | |
| 2667 | - // directly — the host connection seam only reaches external | |
| 2668 | - // clients. Frames the handler queued before linking flush first. | |
| 2669 | - const client = wrapped.webSocket; | |
| 2670 | - if (wrapped.status === 101 && client && client._peer) { | |
| 2671 | - const server = client._peer; | |
| 2672 | - client._loopback = server; | |
| 2673 | - server._loopback = client; | |
| 2674 | - for (const frame of server._pending.splice(0)) { | |
| 2675 | - // "send-binary" joined this queue with outbound sockets; without a case | |
| 2676 | - // of its own it fell through to the close branch and tore the pair down | |
| 2677 | - // instead of delivering the frame. | |
| 2678 | - if (frame[0] === "send") | |
| 2679 | - queueMicrotask(() => client._dispatchMessage(frame[1])); | |
| 2680 | - else if (frame[0] === "send-binary") | |
| 2681 | - queueMicrotask(() => { | |
| 2682 | - const data = frame[1]; | |
| 2683 | - client._dispatchMessage( | |
| 2684 | - data instanceof ArrayBuffer ? data : data.buffer.slice( | |
| 2685 | - data.byteOffset, | |
| 2686 | - data.byteOffset + data.byteLength, | |
| 2687 | - ), | |
| 2688 | - ); | |
| 2689 | - }); | |
| 2690 | - else | |
| 2691 | - queueMicrotask( | |
| 2692 | - () => client._dispatchClose(frame[1], frame[2], true)); | |
| 2693 | - } | |
| 2694 | - } | |
| 2695 | - return wrapped; | |
| 2696 | -}; | |
| 2697 | -// `[[services]]` binding: a Fetcher pointed at another Worker in this | |
| 2698 | -// process. No identity to resolve, so it goes straight to __svc_call. | |
| 2699 | -// Worker Loader (Code Mode): spawn a fresh isolate from supplied code and | |
| 2700 | -// invoke it. Walking skeleton — only `load(code)` and a default-entrypoint | |
| 2701 | -// `fetch()` are wired, mirroring the cross-isolate service-binding path below. | |
| 2702 | -globalThis.__makeLoader = () => { | |
| 2703 | - // `get(name, …)` is memoized by name to one isolate; `load()` is anonymous. | |
| 2704 | - // A stub holds a Promise<id> so `getCode` may be async and load lazily. | |
| 2705 | - const byName = new Map(); | |
| 2706 | - const makeEntrypoint = (idPromise, entrypoint) => { | |
| 2707 | - const target = { | |
| 2708 | - async fetch(input, init) { | |
| 2709 | - const id = await idPromise; | |
| 2710 | - const req = new Request(input, init); | |
| 2711 | - // The verbatim header list; see the note on the outbound `fetch`. | |
| 2712 | - // The loaded worker rebuilds a `Headers` from these pairs, so a | |
| 2713 | - // repeat and its casing survive the isolate boundary. | |
| 2714 | - const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 2715 | - const { body, streamId } = await __subrequestBody(req); | |
| 2716 | - const r = JSON.parse( | |
| 2717 | - await __loader_fetch(id, req.url, req.method, body, headers, streamId)); | |
| 2718 | - const responseBody = r.streamId !== undefined | |
| 2719 | - ? new CelldHttpBodyStream(r.streamId) | |
| 2720 | - : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); | |
| 2721 | - return __wrapServiceResponse( | |
| 2722 | - new Response(responseBody, { status: r.status, headers: r.headers }), | |
| 2723 | - req.url); | |
| 2724 | - }, | |
| 2725 | - }; | |
| 2726 | - // Both the default and named entrypoints expose RPC: property access is a | |
| 2727 | - // callable pipeline node dispatched via __loader_rpc to that entrypoint in | |
| 2728 | - // the loaded worker (default -> the "default" export, which | |
| 2729 | - // register_entrypoints registers like any other). fetch stays on the | |
| 2730 | - // target. Only single-method calls are supported for now. | |
| 2731 | - const session = { | |
| 2732 | - get: () => Promise.reject(new Error( | |
| 2733 | - "Awaitable properties on loaded workers are not supported yet.")), | |
| 2734 | - call: (path, args) => (async () => { | |
| 2735 | - if (path.length !== 1) | |
| 2736 | - throw new Error( | |
| 2737 | - "Pipelined property paths on loaded workers are not supported " + | |
| 2738 | - "yet."); | |
| 2739 | - const id = await idPromise; | |
| 2740 | - return __rpcDes( | |
| 2741 | - await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false))); | |
| 2742 | - })(), | |
| 2743 | - }; | |
| 2744 | - return new Proxy(target, { | |
| 2745 | - get: (base, prop) => { | |
| 2746 | - if (prop === "then") return undefined; | |
| 2747 | - if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 2748 | - if (typeof prop !== "string") return undefined; | |
| 2749 | - return __makeNode(session, [prop], null); | |
| 2750 | - }, | |
| 2751 | - }); | |
| 2752 | - }; | |
| 2753 | - // Anonymous load() workers are evicted when their only stub is GC'd: the | |
| 2754 | - // finalizer drops the worker's isolate so it does not leak. Named get() | |
| 2755 | - // workers are retained by `byName` (memoized) and so are not registered. | |
| 2756 | - const finalizer = typeof FinalizationRegistry === "function" | |
| 2757 | - ? new FinalizationRegistry((id) => __loader_drop(id)) | |
| 2758 | - : null; | |
| 2759 | - const makeStub = (idPromise, evictable) => { | |
| 2760 | - // Explicit disposal evicts the worker deterministically; the finalizer is | |
| 2761 | - // a GC backstop for anonymous stubs that are dropped without disposing. | |
| 2762 | - // __loader_drop is idempotent, so the two paths cannot double-free. | |
| 2763 | - const drop = () => { idPromise.then((id) => __loader_drop(id), () => {}); }; | |
| 2764 | - const stub = { | |
| 2765 | - getEntrypoint(name = null, _options = {}) { | |
| 2766 | - return makeEntrypoint(idPromise, name === null ? "default" : name); | |
| 2767 | - }, | |
| 2768 | - getDurableObjectClass(name = null, options = {}) { | |
| 2769 | - return __makeDurableObjectClass(idPromise, name, options); | |
| 2770 | - }, | |
| 2771 | - dispose: drop, | |
| 2772 | - }; | |
| 2773 | - if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; | |
| 2774 | - if (evictable && finalizer) | |
| 2775 | - idPromise.then((id) => finalizer.register(stub, id), () => {}); | |
| 2776 | - return stub; | |
| 2777 | - }; | |
| 2778 | - // JSON.stringify silently drops binary values, so each non-string module — | |
| 2779 | - // wasm bytes as a BufferSource, or workerd's `{ wasm }` / `{ esModule }` | |
| 2780 | - // module shapes — is normalized first: ES modules to plain strings, wasm | |
| 2781 | - // pulled out into a side-band `[name, Uint8Array]` list the op reads | |
| 2782 | - // directly, so multi-MB blobs never take a base64/JSON round-trip. | |
| 2783 | - const toBytes = (v) => v instanceof ArrayBuffer ? new Uint8Array(v) | |
| 2784 | - : ArrayBuffer.isView(v) | |
| 2785 | - ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : null; | |
| 2786 | - const encodeModules = (c) => { | |
| 2787 | - if (c === null || typeof c !== "object" || c.modules === null | |
| 2788 | - || typeof c.modules !== "object") return { config: c, wasm: [] }; | |
| 2789 | - const modules = {}; | |
| 2790 | - const wasm = []; | |
| 2791 | - for (const [name, value] of Object.entries(c.modules)) { | |
| 2792 | - const wrapped = value !== null && typeof value === "object" ? value : {}; | |
| 2793 | - const bytes = toBytes(value) ?? toBytes(wrapped.wasm); | |
| 2794 | - if (bytes !== null) wasm.push([name, bytes]); | |
| 2795 | - else if (typeof wrapped.esModule === "string") modules[name] = wrapped.esModule; | |
| 2796 | - else modules[name] = value; | |
| 2797 | - } | |
| 2798 | - return { config: { ...c, modules }, wasm }; | |
| 2799 | - }; | |
| 2800 | - // getCode is deferred into a microtask so a throw (or async getCode) | |
| 2801 | - // surfaces as a rejection when the worker is first used, not at get()/load(). | |
| 2802 | - const loadFrom = (getCode) => | |
| 2803 | - Promise.resolve().then(getCode) | |
| 2804 | - .then((c) => { | |
| 2805 | - const { config, wasm } = encodeModules(c); | |
| 2806 | - return __loader_load(JSON.stringify(config), wasm); | |
| 2807 | - }); | |
| 2808 | - return { | |
| 2809 | - load(code) { return makeStub(loadFrom(() => code), true); }, | |
| 2810 | - get(name, getCode) { | |
| 2811 | - let idPromise = byName.get(name); | |
| 2812 | - if (idPromise === undefined) { | |
| 2813 | - idPromise = loadFrom(getCode); | |
| 2814 | - byName.set(name, idPromise); | |
| 2815 | - } | |
| 2816 | - return makeStub(idPromise, false); | |
| 2817 | - }, | |
| 2818 | - }; | |
| 2819 | -}; | |
| 2820 | - | |
| 2821 | -globalThis.__makeServiceBinding = (script, entrypoint = null) => { | |
| 2822 | - const target = { | |
| 2823 | - async fetch(input, init) { | |
| 2824 | - const req = new Request(input, init); | |
| 2825 | - const signal = req._signalForSubrequests; | |
| 2826 | - if (signal?.aborted) throw signal.reason; | |
| 2827 | - // A stream body advertises its length the way the HTTP layer | |
| 2828 | - // would: known length → Content-Length, unknown → chunked. | |
| 2829 | - if (req._bodyBytes === null && | |
| 2830 | - !req.headers.has("content-length") && | |
| 2831 | - !req.headers.has("transfer-encoding")) { | |
| 2832 | - const length = req.body._expectedLength; | |
| 2833 | - if (length === undefined) | |
| 2834 | - req.headers.set("transfer-encoding", "chunked"); | |
| 2835 | - else req.headers.set("content-length", String(length)); | |
| 2836 | - } | |
| 2837 | - // Fast path: the target is this same script, so its handler lives in | |
| 2838 | - // this isolate. Skip the op + pool-thread hop and call it directly, | |
| 2839 | - // inside its own event so the target's waitUntil does not attach to | |
| 2840 | - // the caller's. Cross-script targets still need their own isolate. | |
| 2841 | - if (script === __cell.script && entrypoint !== null) { | |
| 2842 | - // Mirror __dispatchTo: the target sees a fresh incoming signal, | |
| 2843 | - // aborted with "The client has disconnected" when the caller | |
| 2844 | - // abandons the call or cancels the response body; the caller's | |
| 2845 | - // own signal races the dispatch so an abandoned call rejects | |
| 2846 | - // immediately instead of pinning on a hung target. | |
| 2847 | - const requestController = new AbortController(); | |
| 2848 | - const dispatch = __dispatchEntrypointFetch( | |
| 2849 | - entrypoint, | |
| 2850 | - new Request(req, { | |
| 2851 | - signal: requestController.signal, | |
| 2852 | - __celldIncomingSignal: true, | |
| 2853 | - })); | |
| 2854 | - const response = signal | |
| 2855 | - ? await __raceCallerAbort(dispatch, signal, () => | |
| 2856 | - requestController.abort( | |
| 2857 | - new Error("The client has disconnected"))) | |
| 2858 | - : await dispatch; | |
| 2859 | - __attachResponseRequestCancellation( | |
| 2860 | - response, requestController, true); | |
| 2861 | - return __wrapServiceResponse(response, req.url); | |
| 2862 | - } | |
| 2863 | - if (entrypoint !== null) | |
| 2864 | - throw new Error( | |
| 2865 | - "Cross-script service bindings with an entrypoint do not " + | |
| 2866 | - "support fetch() yet; only same-script targets do."); | |
| 2867 | - if (script === __cell.script && typeof __cell.selfFetch === "function") { | |
| 2868 | - if (__cell.svcDepth >= 8) | |
| 2869 | - throw new Error( | |
| 2870 | - "Service binding recursion limit exceeded (8)"); | |
| 2871 | - __cell.svcDepth = (__cell.svcDepth || 0) + 1; | |
| 2872 | - const ctx = __beginEvent(); | |
| 2873 | - try { | |
| 2874 | - return __wrapServiceResponse( | |
| 2875 | - await __ctxRun(undefined, | |
| 2876 | - () => __cell.selfFetch(req, __cell.env, ctx)), | |
| 2877 | - req.url); | |
| 2878 | - } finally { | |
| 2879 | - __cell.svcDepth--; | |
| 2880 | - __endEvent(); | |
| 2881 | - } | |
| 2882 | - } | |
| 2883 | - // The verbatim header list; see the note on the outbound `fetch`. The | |
| 2884 | - // target isolate rebuilds a `Headers` from these pairs, so a repeat and | |
| 2885 | - // its casing survive the crossing. | |
| 2886 | - const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 2887 | - // Cross-isolate calls carry exact bytes. A host-backed stream transfers | |
| 2888 | - // its one source to the target, and another stream uses the byte fallback. | |
| 2889 | - const { body, streamId } = await __subrequestBody(req); | |
| 2890 | - const r = JSON.parse(await (signal | |
| 2891 | - ? __awaitCancellableDoCall( | |
| 2892 | - __svc_call_cancellable( | |
| 2893 | - script, req.url, req.method, body, headers, streamId), | |
| 2894 | - signal) | |
| 2895 | - : __svc_call( | |
| 2896 | - script, req.url, req.method, body, headers, streamId))); | |
| 2897 | - const responseBody = r.streamId !== undefined | |
| 2898 | - ? new CelldHttpBodyStream(r.streamId) | |
| 2899 | - : r.body !== undefined | |
| 2900 | - ? r.body | |
| 2901 | - : Uint8Array.from(r.bodyBytes || []); | |
| 2902 | - return __wrapServiceResponse( | |
| 2903 | - new Response(responseBody, { | |
| 2904 | - status: r.status, headers: r.headers, __wsTarget: r.wsTarget, | |
| 2905 | - }), | |
| 2906 | - req.url); | |
| 2907 | - }, | |
| 2908 | - // Workerd's test-visible Fetcher.scheduled(): invoke the target's | |
| 2909 | - // scheduled handler and report the outcome. | |
| 2910 | - async scheduled(options = {}) { | |
| 2911 | - if (script !== __cell.script || entrypoint !== null || | |
| 2912 | - typeof __cell.selfScheduled !== "function") | |
| 2913 | - throw new Error( | |
| 2914 | - "scheduled() is only implemented for same-script service " + | |
| 2915 | - "bindings whose target has a scheduled handler"); | |
| 2916 | - let noRetry = false; | |
| 2917 | - const ctrl = { | |
| 2918 | - scheduledTime: options.scheduledTime === undefined | |
| 2919 | - ? Date.now() : Number(options.scheduledTime), | |
| 2920 | - cron: options.cron === undefined ? "" : String(options.cron), | |
| 2921 | - noRetry() { noRetry = true; }, | |
| 2922 | - }; | |
| 2923 | - const ctx = __beginEvent(); | |
| 2924 | - try { | |
| 2925 | - await __cell.selfScheduled(ctrl, __cell.env, ctx); | |
| 2926 | - return { outcome: "ok", noRetry }; | |
| 2927 | - } finally { | |
| 2928 | - __endEvent(); | |
| 2929 | - } | |
| 2930 | - }, | |
| 2931 | - }; | |
| 2932 | - if (entrypoint === null) return target; | |
| 2933 | - // With `entrypoint = "Name"`, any property other than fetch is an | |
| 2934 | - // awaitable/callable pipeline node rooted at that class: awaiting | |
| 2935 | - // resolves the property remotely (a property-GET wire op), calling | |
| 2936 | - // invokes it, and deeper access extends the path, resolved on the | |
| 2937 | - // receiver side in one op. Same-script dispatch stays in this | |
| 2938 | - // isolate, so stub-able values may cross. A property path rooted | |
| 2939 | - // directly at the binding is context-free (ctx null): awaiting it | |
| 2940 | - // starts a fresh session, as in Workerd. | |
| 2941 | - const session = | |
| 2942 | - __entrypointSession(entrypoint, script === __cell.script, script); | |
| 2943 | - return new Proxy(target, { | |
| 2944 | - getPrototypeOf: () => __cf.ServiceStub.prototype, | |
| 2945 | - get: (base, prop) => { | |
| 2946 | - if (prop === "then") return undefined; // a stub is not a thenable | |
| 2947 | - if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 2948 | - if (typeof prop !== "string") return undefined; | |
| 2949 | - // Workerd's test hook: the named method as a callable handle, | |
| 2950 | - // resolved — and refused — on the receiver side. | |
| 2951 | - if (prop === "getRpcMethodForTestOnly") | |
| 2952 | - return (name) => __makeNode(session, [String(name)], null); | |
| 2953 | - return __makeNode(session, [prop], null); | |
| 2954 | - }}); | |
| 2955 | -}; | |
| 2956 | -// RPC marshalling: V8 structured clone (Workerd js-rpc semantics), so | |
| 2957 | -// undefined, Date, Map, Set, BigInt, typed arrays, and cycles survive. | |
| 2958 | -// A value V8 cannot clone throws DataCloneError, as in Workerd. | |
| 2959 | -// | |
| 2960 | -// The envelope's first byte tags the payload. 0xff (the clone version | |
| 2961 | -// header) = plain clone, decoded as-is — the common case pays one | |
| 2962 | -// byte-compare and nothing else. 0x01 = clone of a lifted tree in | |
| 2963 | -// which RpcTarget instances, functions, and Durable Object stubs were | |
| 2964 | -// replaced by stub markers; the lift runs only after a plain clone | |
| 2965 | -// already threw, so plain-data calls never walk. 0x02 = a lifted | |
| 2966 | -// tree carrying only by-value host types (Blob/File, Headers, | |
| 2967 | -// Request/Response) and no capabilities — decoded like 0x01, but a | |
| 2968 | -// reply so tagged does not root its callee context. 0x00 = clone of | |
| 2969 | -// [error, ownProps] — a callee exception crossing as a real Error. | |
| 2970 | -const __dataCloneError = (error) => new DOMException( | |
| 2971 | - String(error && error.message || error), "DataCloneError"); | |
| 2972 | -const __tagged = (tag, sc) => { | |
| 2973 | - const out = new Uint8Array(sc.length + 1); | |
| 2974 | - out[0] = tag; | |
| 2975 | - out.set(sc, 1); | |
| 2976 | - return out; | |
| 2977 | -}; | |
| 2978 | -// ---- request-context confinement ------------------------------- | |
| 2979 | -// Workerd ties I/O objects to the IoContext of the event that made | |
| 2980 | -// them. Cells' equivalent: each dispatched event enters an | |
| 2981 | -// async-context frame (the same CPED the ALS rides, so it survives | |
| 2982 | -// awaits) carrying a context id. Stubs remember their owning | |
| 2983 | -// context and refuse to serialize elsewhere; pipeline nodes refuse | |
| 2984 | -// foreign awaits and calls — each with Workerd's exact error. | |
| 2985 | -let __nextCtxId = 1; | |
| 2986 | -const __ctxKey = Symbol("celld.ctx"); | |
| 2987 | -const __ctxNow = () => { | |
| 2988 | - const frame = __als_get(); | |
| 2989 | - return frame === undefined ? undefined : frame.get(__ctxKey); | |
| 2990 | -}; | |
| 2991 | -// Run `fn` under context `id` (undefined = a fresh one). An async | |
| 2992 | -// fn started inside keeps the frame across its awaits. The prior | |
| 2993 | -// frame is cloned so user AsyncLocalStorage stores still flow into | |
| 2994 | -// same-isolate callees, as they did before contexts existed. | |
| 2995 | -const __ctxRun = (id, fn) => { | |
| 2996 | - const prior = __als_get(); | |
| 2997 | - const frame = new Map(prior); | |
| 2998 | - frame.set(__ctxKey, id ?? __nextCtxId++); | |
| 2999 | - __als_set(frame); | |
| 3000 | - try { | |
| 3001 | - return fn(); | |
| 3002 | - } finally { | |
| 3003 | - __als_set(prior); | |
| 3004 | - } | |
| 3005 | -}; | |
| 3006 | -const __ctxError = (kind) => new Error( | |
| 3007 | - "Cannot perform I/O on behalf of a different request. I/O " + | |
| 3008 | - "objects (such as streams, request/response bodies, and others) " + | |
| 3009 | - "created in the context of one request handler cannot be " + | |
| 3010 | - "accessed from a different request's handler. This is a " + | |
| 3011 | - "limitation of Cloudflare Workers which allows us to improve " + | |
| 3012 | - "overall performance. (I/O type: " + kind + ")"); | |
| 3013 | -// ---- abortable request contexts -------------------------------- | |
| 3014 | -// Workerd's ctx.abort(reason) on an entrypoint aborts the request's | |
| 3015 | -// IoContext: the in-flight call rejects with the reason, and stubs | |
| 3016 | -// the context holds are disposed (their disposal callbacks fire). | |
| 3017 | -// State is allocated only when a context first holds a stub handle | |
| 3018 | -// or aborts, so plain-data dispatch pays nothing; call paths gate | |
| 3019 | -// every abort lookup on `__abortedCtxs.size` (one field read). | |
| 3020 | -// Aborted ids stay recorded: a stub rooted in a dead context must | |
| 3021 | -// keep rejecting with the reason. | |
| 3022 | -const __abortedCtxs = new Map(); | |
| 3023 | -// An actor-flavored abort reason: in-flight ops reject with the | |
| 3024 | -// wrapped reason, later ops with Workerd's post-abort message | |
| 3025 | -// (upstream TODO(bug): should propagate the reason, but doesn't). | |
| 3026 | -class __ActorAbort { constructor(reason) { this.reason = reason; } } | |
| 3027 | -const __postAbortError = (aborted) => aborted instanceof __ActorAbort | |
| 3028 | - ? new Error("The execution context which hosts this callback " + | |
| 3029 | - "is no longer running.") | |
| 3030 | - : aborted; | |
| 3031 | -// ctx id -> Set of live stub handles (metas) the context holds. | |
| 3032 | -const __ctxStubs = new Map(); | |
| 3033 | -// ctx id -> Set of reject callbacks for stub ops in flight against | |
| 3034 | -// that context. A hung callee never settles, so a context abort | |
| 3035 | -// must reject its pending callers directly. | |
| 3036 | -const __ctxPendingOps = new Map(); | |
| 3037 | -const __opTrack = (ctx, reject) => { | |
| 3038 | - let set = __ctxPendingOps.get(ctx); | |
| 3039 | - if (set === undefined) __ctxPendingOps.set(ctx, set = new Set()); | |
| 3040 | - set.add(reject); | |
| 3041 | - return () => { | |
| 3042 | - set.delete(reject); | |
| 3043 | - if (set.size === 0) __ctxPendingOps.delete(ctx); | |
| 3044 | - }; | |
| 3045 | -}; | |
| 3046 | -const __ctxRegister = (meta) => { | |
| 3047 | - if (meta.ctx === undefined) return; | |
| 3048 | - let set = __ctxStubs.get(meta.ctx); | |
| 3049 | - if (set === undefined) __ctxStubs.set(meta.ctx, set = new Set()); | |
| 3050 | - set.add(meta); | |
| 3051 | -}; | |
| 3052 | -const __ctxUnregister = (meta) => { | |
| 3053 | - const set = __ctxStubs.get(meta.ctx); | |
| 3054 | - if (set === undefined) return; | |
| 3055 | - set.delete(meta); | |
| 3056 | - if (set.size === 0) __ctxStubs.delete(meta.ctx); | |
| 3057 | -}; | |
| 3058 | -// Tear down a context: dispose every handle it still holds, so a | |
| 3059 | -// dup() leaked into it reaches the sender's disposal callback. | |
| 3060 | -const __ctxEnd = (id) => { | |
| 3061 | - const set = __ctxStubs.get(id); | |
| 3062 | - if (set === undefined) return; | |
| 3063 | - __ctxStubs.delete(id); | |
| 3064 | - for (const meta of set) __disposeStub(meta); | |
| 3065 | -}; | |
| 3066 | -const __ctxAbort = (id, reason) => { | |
| 3067 | - if (id === undefined || __abortedCtxs.has(id)) return; | |
| 3068 | - const stored = reason === undefined | |
| 3069 | - ? new Error("The execution context has been aborted.") | |
| 3070 | - : reason; | |
| 3071 | - __abortedCtxs.set(id, stored); | |
| 3072 | - __ctxEnd(id); | |
| 3073 | - const pending = __ctxPendingOps.get(id); | |
| 3074 | - if (pending === undefined) return; | |
| 3075 | - __ctxPendingOps.delete(id); | |
| 3076 | - const live = | |
| 3077 | - stored instanceof __ActorAbort ? stored.reason : stored; | |
| 3078 | - for (const reject of pending) reject(live); | |
| 3079 | -}; | |
| 3080 | -// The entrypoint ctx.abort. Instances are cached across calls, so | |
| 3081 | -// the construction-time ctx cannot pin a request id (Workerd | |
| 3082 | -// constructs per request); the current frame's id at abort() time | |
| 3083 | -// is the request being served, which matches Workerd observably. | |
| 3084 | -const __ctxAbortCurrent = | |
| 3085 | - (reason) => __ctxAbort(__ctxNow(), reason); | |
| 3086 | -// ---- same-process RPC stubs ------------------------------------ | |
| 3087 | -// A stub entry owns a local target; `refs` counts live handles | |
| 3088 | -// across dup()s. When the last handle is disposed the target's own | |
| 3089 | -// Symbol.dispose runs (async, matching Workerd's disposal callback). | |
| 3090 | -// Stubs cross same-isolate transports only (same-script entrypoint | |
| 3091 | -// RPC and same-process routed dispatch); a marker revived elsewhere fails | |
| 3092 | -// loudly on use instead of aliasing an unrelated local entry. | |
| 3093 | -// `ctx` records the owning request context: the entry's for | |
| 3094 | -// running its target, the handle's for the serialize-elsewhere | |
| 3095 | -// check. | |
| 3096 | -const __stubEntries = new Map(); | |
| 3097 | -const __stubMeta = new WeakMap(); | |
| 3098 | -let __nextStubId = 1; | |
| 3099 | -const __stubIsolate = Math.random().toString(36).slice(2); | |
| 3100 | -const __newEntry = (target) => { | |
| 3101 | - // `scope` records the actor event that minted the entry (top of | |
| 3102 | - // the event stack at lift time), so an actor breakage can find | |
| 3103 | - // and abort the contexts hosting its exported stubs, and an op on | |
| 3104 | - // the stub can queue on that cell's input gate. `section` is the | |
| 3105 | - // critical section running at lift time, if any — an op on this | |
| 3106 | - // stub re-enters it rather than queueing behind it. | |
| 3107 | - const scope = __currentActorScope() || undefined; | |
| 3108 | - const entry = { | |
| 3109 | - id: __nextStubId++, target, refs: 1, ctx: __ctxNow(), scope, | |
| 3110 | - section: __cellBlocks.get(scope)?.holder ?? null, | |
| 3111 | - }; | |
| 3112 | - __stubEntries.set(entry.id, entry); | |
| 3113 | - return entry; | |
| 3114 | -}; | |
| 3115 | -// Actors broken in JS: scope -> reason. Workerd's DO ctx.abort | |
| 3116 | -// rejects in-flight and future calls; when the abort fires under a | |
| 3117 | -// same-isolate stub caller, terminate_execution would unwind that | |
| 3118 | -// caller too (the routed dispatch re-enters the isolate), so the | |
| 3119 | -// breakage is recorded here instead: contexts hosting the actor's | |
| 3120 | -// exported stubs abort (in-flight ops reject with the reason, | |
| 3121 | -// later ops with the post-abort message) and RPC dispatch to the | |
| 3122 | -// scope rejects with the reason. Direct host-dispatched DO events | |
| 3123 | -// keep the uncatchable terminate_execution path. | |
| 3124 | -const __brokenActors = new Map(); | |
| 3125 | -const __actorBreak = (scope, reason) => { | |
| 3126 | - if (__brokenActors.has(scope)) return; | |
| 3127 | - __brokenActors.set(scope, reason); | |
| 3128 | - for (const entry of __stubEntries.values()) | |
| 3129 | - if (entry.scope === scope) | |
| 3130 | - __ctxAbort(entry.ctx, new __ActorAbort(reason)); | |
| 3131 | -}; | |
| 3132 | -// Everything this isolate holds for one cell scope that belongs to the | |
| 3133 | -// cell's residency rather than to the isolate, so a fresh instance | |
| 3134 | -// inherits none of it. `adopt_cell` calls this on both edges: the | |
| 3135 | -// give-back frees it, the take-in guarantees that no epoch spans. | |
| 3136 | -// Storage is not here — `stop_cell` closes it host-side — and sockets | |
| 3137 | -// live in the host registry, so a hibernated cell keeps them. | |
| 3138 | -const __cellRelease = (scope) => { | |
| 3139 | - __cell.instances[scope]?.ctx?.facets?._release(); | |
| 3140 | - delete __cell.instances[scope]; | |
| 3141 | - delete __cell.idNames[scope]; | |
| 3142 | - delete __cell.facetConfigs[scope]; | |
| 3143 | - __brokenActors.delete(scope); | |
| 3144 | - // An abandoned block can never run `__blockLeave`. A normal eviction | |
| 3145 | - // cannot abandon a block because its event keeps the cell in flight. A | |
| 3146 | - // stop that waits for nobody can, so the release drops every block record | |
| 3147 | - // together with the other state for this residency. | |
| 3148 | - __cellBlocks.delete(scope); | |
| 3149 | - // An entry holds `target`, which can be an object the released | |
| 3150 | - // instance owns. Dropping it ends that reachability; `released` is | |
| 3151 | - // what an already-revived handle reads, since it holds its entry | |
| 3152 | - // directly and never looks in this map again. | |
| 3153 | - for (const entry of __stubEntries.values()) { | |
| 3154 | - if (entry.scope !== scope) continue; | |
| 3155 | - entry.released = true; | |
| 3156 | - __stubEntries.delete(entry.id); | |
| 3157 | - // Break in-flight ops as an abort would, but not through | |
| 3158 | - // `__actorBreak`: that records the scope broken for the life of the | |
| 3159 | - // isolate, which is the state this function drops. | |
| 3160 | - __ctxAbort(entry.ctx, new __ActorAbort(__releasedStubError())); | |
| 3161 | - } | |
| 3162 | -}; | |
| 3163 | -const __releasedStubError = () => new Error( | |
| 3164 | - "The Durable Object that returned this RPC stub no longer runs on " + | |
| 3165 | - "this node."); | |
| 3166 | -const __disposeStub = (meta) => { | |
| 3167 | - if (meta.disposed) return; | |
| 3168 | - meta.disposed = true; | |
| 3169 | - __ctxUnregister(meta); | |
| 3170 | - const entry = meta.entry; | |
| 3171 | - if (--entry.refs > 0) return; | |
| 3172 | - __stubEntries.delete(entry.id); | |
| 3173 | - const disposer = entry.target?.[Symbol.dispose]; | |
| 3174 | - if (typeof disposer === "function") | |
| 3175 | - Promise.resolve().then(() => disposer.call(entry.target)); | |
| 3176 | -}; | |
| 3177 | -const __stubDisposedError = () => | |
| 3178 | - new Error("RPC stub used after being disposed."); | |
| 3179 | -// Shared brand value for RpcTarget instances; see the RpcTarget | |
| 3180 | -// constructor. | |
| 3181 | -const __rpcNoClone = () => {}; | |
| 3182 | -// Workerd method-visibility rules by target kind: an RpcTarget | |
| 3183 | -// exposes inherited methods/accessors (never own instance state, | |
| 3184 | -// never Object.prototype); a plain object or function exposes own | |
| 3185 | -// properties only. Property reads go through normal [[Get]] so | |
| 3186 | -// Proxy handlers participate, as in Workerd. | |
| 3187 | -const __rpcNoSuchMethod = (prop) => new TypeError( | |
| 3188 | - 'The RPC receiver does not implement the method "' + prop + '".'); | |
| 3189 | -// Bind through the intrinsic because a callable proxy can implement `.bind` | |
| 3190 | -// as a remote property. Reading that property can turn a valid named RPC | |
| 3191 | -// method into a non-function. Keep this rule shared by every RPC binding site. | |
| 3192 | -const __rpcBindMethod = (value, receiver) => | |
| 3193 | - Reflect.apply(Function.prototype.bind, value, [receiver]); | |
| 3194 | -const __stubResolve = (target, prop) => { | |
| 3195 | - if (target instanceof __cf.RpcTarget) { | |
| 3196 | - if (Object.hasOwn(target, prop) || !(prop in target) || | |
| 3197 | - prop in Object.prototype) throw __rpcNoSuchMethod(prop); | |
| 3198 | - } else if (!Object.hasOwn(target, prop)) { | |
| 3199 | - throw __rpcNoSuchMethod(prop); | |
| 3200 | - } | |
| 3201 | - const value = target[prop]; | |
| 3202 | - // Keep celld's own stubs and pipeline nodes unwrapped because the wrapper | |
| 3203 | - // would lose their metadata. | |
| 3204 | - return typeof value === "function" && !__stubMeta.has(value) && | |
| 3205 | - !(value instanceof __cf.RpcPromise) && | |
| 3206 | - !(value instanceof __cf.RpcProperty) | |
| 3207 | - ? __rpcBindMethod(value, target) : value; | |
| 3208 | -}; | |
| 3209 | -// ---- streams over RPC ------------------------------------------ | |
| 3210 | -// A live stream crosses as a handle in the caps table: the sender | |
| 3211 | -// locks the origin (reader/writer acquired at lift) behind a | |
| 3212 | -// bridge entry, and the receiver's endpoint is an ordinary | |
| 3213 | -// ReadableStream/WritableStream whose pulls and writes are stub | |
| 3214 | -// ops against the bridge — one bounded reverse call per chunk, | |
| 3215 | -// the clone being the one wire copy. Backpressure is the op in | |
| 3216 | -// flight: hwm 0 pulls only on demand, and the writable carries | |
| 3217 | -// one chunk per op. EOF, close, and errors cross as op results; | |
| 3218 | -// teardown (param disposal, context end, context abort) runs the | |
| 3219 | -// bridge disposer, which cancels or aborts an unfinished origin | |
| 3220 | -// with Workerd's generic disconnect errors — reasons do not | |
| 3221 | -// propagate, matching Workerd's own TODOs (and its verbatim | |
| 3222 | -// "endeded" typo). | |
| 3223 | -const __wsDisconnect = () => new Error( | |
| 3224 | - "WritableStream received over RPC was disconnected because " + | |
| 3225 | - "the remote execution context has endeded."); | |
| 3226 | -const __rsDisconnect = () => new Error( | |
| 3227 | - "ReadableStream received over RPC disconnected prematurely."); | |
| 3228 | -// Receiver wrapper stream -> its handle meta, for forwarding. | |
| 3229 | -const __rpcStreamMeta = new WeakMap(); | |
| 3230 | -const __readableBridge = (reader) => { | |
| 3231 | - const bridge = { | |
| 3232 | - done: false, | |
| 3233 | - async read() { | |
| 3234 | - let result; | |
| 3235 | - try { | |
| 3236 | - result = await reader.read(); | |
| 3237 | - } catch (error) { | |
| 3238 | - bridge.done = true; | |
| 3239 | - throw error; | |
| 3240 | - } | |
| 3241 | - if (result.done) bridge.done = true; | |
| 3242 | - return result; | |
| 3243 | - }, | |
| 3244 | - cancel() { | |
| 3245 | - if (bridge.done) return; | |
| 3246 | - bridge.done = true; | |
| 3247 | - reader.cancel(__rsDisconnect()).catch(() => {}); | |
| 3248 | - }, | |
| 3249 | - [Symbol.dispose]() { bridge.cancel(); }, | |
| 3250 | - }; | |
| 3251 | - return bridge; | |
| 3252 | -}; | |
| 3253 | -const __writableBridge = (writer) => { | |
| 3254 | - const bridge = { | |
| 3255 | - done: false, | |
| 3256 | - write: (chunk) => writer.write(chunk), | |
| 3257 | - close() { | |
| 3258 | - bridge.done = true; | |
| 3259 | - return writer.close(); | |
| 3260 | - }, | |
| 3261 | - abort() { | |
| 3262 | - bridge.done = true; | |
| 3263 | - return writer.abort(__wsDisconnect()); | |
| 3264 | - }, | |
| 3265 | - [Symbol.dispose]() { | |
| 3266 | - if (!bridge.done) bridge.abort().catch(() => {}); | |
| 3267 | - }, | |
| 3268 | - }; | |
| 3269 | - return bridge; | |
| 3270 | -}; | |
| 3271 | -const __liftStream = (v) => { | |
| 3272 | - const readable = v instanceof ReadableStream; | |
| 3273 | - const key = readable ? "__celld$rs" : "__celld$ws"; | |
| 3274 | - const meta = __rpcStreamMeta.get(v); | |
| 3275 | - if (meta !== undefined && !meta.disposed && !v.locked) { | |
| 3276 | - // Re-serializing a received, untouched stream forwards the | |
| 3277 | - // original handle: the reference moves (like a stub) and | |
| 3278 | - // the local wrapper is dead — a round trip stays one hop. | |
| 3279 | - meta.disposed = true; | |
| 3280 | - __ctxUnregister(meta); | |
| 3281 | - return { [key]: meta.entry.id, t: __stubIsolate }; | |
| 3282 | - } | |
| 3283 | - if (v.locked) | |
| 3284 | - throw new TypeError(readable | |
| 3285 | - ? "The ReadableStream has been locked to a reader." | |
| 3286 | - : "The WritableStream has been locked to a writer."); | |
| 3287 | - const bridge = readable | |
| 3288 | - ? __readableBridge(v.getReader()) | |
| 3289 | - : __writableBridge(v.getWriter()); | |
| 3290 | - return { [key]: __newEntry(bridge).id, t: __stubIsolate }; | |
| 3291 | -}; | |
| 3292 | -// Replace stub-able values with wire markers. Runs only after a | |
| 3293 | -// plain clone failed, so plain-data serialization never pays for | |
| 3294 | -// it. Passing an existing stub transfers its reference: the | |
| 3295 | -// sender's handle is disposed (dup() first to keep one) and the | |
| 3296 | -// receiver adopts it. Returns null when nothing was liftable. | |
| 3297 | -const __stubLift = (value) => { | |
| 3298 | - let lifted = false; | |
| 3299 | - // Capabilities (stubs, disposers) root the callee context; | |
| 3300 | - // by-value host types do not — they pick the 0x02 envelope. | |
| 3301 | - let caps = false; | |
| 3302 | - const seen = new Map(); | |
| 3303 | - const ctx = __ctxNow(); | |
| 3304 | - // A buffered body crosses as its bytes; a live-stream body | |
| 3305 | - // crosses as a stream handle (a capability, so the reply | |
| 3306 | - // roots its callee context and the pulls keep working). | |
| 3307 | - const liftBody = (v) => { | |
| 3308 | - if (v._bodyBytes !== null) return v._bodyBytes; | |
| 3309 | - caps = true; | |
| 3310 | - return __liftStream(v.body); | |
| 3311 | - }; | |
| 3312 | - const lift = (v) => { | |
| 3313 | - if (v === null || | |
| 3314 | - (typeof v !== "object" && typeof v !== "function")) return v; | |
| 3315 | - const cached = seen.get(v); | |
| 3316 | - if (cached !== undefined) return cached; | |
| 3317 | - const meta = __stubMeta.get(v); | |
| 3318 | - if (meta) { | |
| 3319 | - lifted = true; | |
| 3320 | - caps = true; | |
| 3321 | - if (meta.disposed) throw __stubDisposedError(); | |
| 3322 | - // A stub belongs to the request that received it; another | |
| 3323 | - // request cannot serialize it (Workerd's IoContext rule). | |
| 3324 | - if (meta.ctx !== ctx) throw __ctxError("Client"); | |
| 3325 | - meta.disposed = true; // the ref moves to the receiver | |
| 3326 | - __ctxUnregister(meta); | |
| 3327 | - const marker = { "__celld$stub": meta.entry.id, | |
| 3328 | - t: __stubIsolate, c: meta.callable }; | |
| 3329 | - seen.set(v, marker); | |
| 3330 | - return marker; | |
| 3331 | - } | |
| 3332 | - const svc = __svcMeta.get(v); | |
| 3333 | - if (svc !== undefined) { | |
| 3334 | - // A loopback service stub (ctx.exports): name + props cross | |
| 3335 | - // as plain data and revive as a fresh loopback stub. Props | |
| 3336 | - // are lifted too — they may nest further stubs (Workerd's | |
| 3337 | - // nested channel tokens). | |
| 3338 | - lifted = true; | |
| 3339 | - caps = true; | |
| 3340 | - const marker = { "__celld$svc": svc.name, t: __stubIsolate }; | |
| 3341 | - seen.set(v, marker); | |
| 3342 | - if (svc.props !== undefined) marker.p = lift(svc.props); | |
| 3343 | - return marker; | |
| 3344 | - } | |
| 3345 | - // Workerd refuses to serialize its promise/property handles. | |
| 3346 | - if (v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty) | |
| 3347 | - throw new DOMException( | |
| 3348 | - 'Could not serialize object of type "' + | |
| 3349 | - (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + | |
| 3350 | - '". This type does not support serialization.', | |
| 3351 | - "DataCloneError"); | |
| 3352 | - if (typeof v === "function" || v instanceof __cf.RpcTarget) { | |
| 3353 | - lifted = true; | |
| 3354 | - caps = true; | |
| 3355 | - const marker = { "__celld$stub": __newEntry(v).id, | |
| 3356 | - t: __stubIsolate, | |
| 3357 | - c: typeof v === "function" }; | |
| 3358 | - seen.set(v, marker); | |
| 3359 | - return marker; | |
| 3360 | - } | |
| 3361 | - const doId = v.__celldDo; | |
| 3362 | - if (doId !== undefined) { | |
| 3363 | - lifted = true; | |
| 3364 | - caps = true; | |
| 3365 | - const marker = { "__celld$do": doId._className, | |
| 3366 | - v: doId._value, n: v.name ?? null }; | |
| 3367 | - seen.set(v, marker); | |
| 3368 | - return marker; | |
| 3369 | - } | |
| 3370 | - // HTTP host types cross by value, as in Workerd's RPC | |
| 3371 | - // serialization: entry lists for Headers, the buffered bytes | |
| 3372 | - // for bodies (the marker aliases the live buffer; the clone | |
| 3373 | - // is the one wire copy), and no signal — the receiver mints | |
| 3374 | - // a fresh one. A live stream body cannot cross yet. | |
| 3375 | - let marker; | |
| 3376 | - if (v instanceof Headers) { | |
| 3377 | - marker = { "__celld$hdr": [...v] }; | |
| 3378 | - } else if (v instanceof Blob) { | |
| 3379 | - marker = { "__celld$blob": v._bytes, y: v.type }; | |
| 3380 | - if (v instanceof File) { | |
| 3381 | - marker.n = v.name; | |
| 3382 | - marker.m = v.lastModified; | |
| 3383 | - } | |
| 3384 | - } else if (v instanceof Request) { | |
| 3385 | - marker = { "__celld$req": v.url, m: v.method, | |
| 3386 | - h: [...v.headers], r: v.redirect, c: v.cf, | |
| 3387 | - b: liftBody(v) }; | |
| 3388 | - } else if (v instanceof Response) { | |
| 3389 | - marker = { "__celld$res": v.status, | |
| 3390 | - t: v.statusText || | |
| 3391 | - __STATUS_TEXT[v.status] || "", | |
| 3392 | - h: [...v.headers], c: v.cf, | |
| 3393 | - e: v.type === "error", | |
| 3394 | - b: v.body === null ? null : liftBody(v) }; | |
| 3395 | - } else if (v instanceof ReadableStream || | |
| 3396 | - v instanceof WritableStream) { | |
| 3397 | - caps = true; | |
| 3398 | - marker = __liftStream(v); | |
| 3399 | - } else if (v instanceof AbortSignal) { | |
| 3400 | - // A live signal handle: the receiver mints a fresh signal | |
| 3401 | - // wired to this one (same isolate); foreign bytes revive | |
| 3402 | - // a snapshot of the aborted flag. | |
| 3403 | - caps = true; | |
| 3404 | - marker = { "__celld$sig": __newEntry(v).id, | |
| 3405 | - t: __stubIsolate, a: v.aborted }; | |
| 3406 | - } | |
| 3407 | - if (marker !== undefined) { | |
| 3408 | - lifted = true; | |
| 3409 | - seen.set(v, marker); | |
| 3410 | - return marker; | |
| 3411 | - } | |
| 3412 | - const proto = Object.getPrototypeOf(v); | |
| 3413 | - if (!Array.isArray(v) && | |
| 3414 | - proto !== Object.prototype && proto !== null) { | |
| 3415 | - // A Proxy emulating neither a plain object nor an RpcTarget | |
| 3416 | - // is Workerd's canonical proxy serialization error. | |
| 3417 | - if (__util_proxy_details(v) !== undefined) | |
| 3418 | - throw new DOMException( | |
| 3419 | - "Proxy could not be serialized because it is not a " + | |
| 3420 | - "valid RPC receiver type. The Proxy must emulate either " + | |
| 3421 | - "a plain object or an RpcTarget, as indicated by the " + | |
| 3422 | - "Proxy's prototype chain.", "DataCloneError"); | |
| 3423 | - return v; // host/other: leave to the clone | |
| 3424 | - } | |
| 3425 | - const out = Array.isArray(v) ? [] : {}; | |
| 3426 | - seen.set(v, out); | |
| 3427 | - for (const key of Object.keys(v)) out[key] = lift(v[key]); | |
| 3428 | - const disposer = v[Symbol.dispose]; | |
| 3429 | - if (!Array.isArray(v) && typeof disposer === "function") { | |
| 3430 | - lifted = true; | |
| 3431 | - caps = true; | |
| 3432 | - out["__celld$disp"] = __newEntry(__rpcBindMethod(disposer, v)).id; | |
| 3433 | - } | |
| 3434 | - return out; | |
| 3435 | - }; | |
| 3436 | - const tree = lift(value); | |
| 3437 | - return lifted ? { tree, caps } : null; | |
| 3438 | -}; | |
| 3439 | -// Revive host-type markers into real instances, adopting the wire | |
| 3440 | -// bytes directly — no copy beyond the clone's own. | |
| 3441 | -const __reviveBlob = (marker, bytes) => { | |
| 3442 | - const blob = marker.n !== undefined | |
| 3443 | - ? new File([], marker.n, | |
| 3444 | - { type: marker.y, lastModified: marker.m }) | |
| 3445 | - : new Blob([], { type: marker.y }); | |
| 3446 | - blob._bytes = bytes; | |
| 3447 | - blob.size = bytes.byteLength; | |
| 3448 | - return blob; | |
| 3449 | -}; | |
| 3450 | -const __adoptBody = (target, bytes) => { | |
| 3451 | - target._bodyBytes = bytes; | |
| 3452 | - target._body = undefined; // decoded lazily on the first text()/json() | |
| 3453 | - const body = target.body; | |
| 3454 | - if (body !== null) { | |
| 3455 | - body._st.bytes = bytes; | |
| 3456 | - body.__celldBodyBytes = bytes; | |
| 3457 | - body._expectedLength = bytes.byteLength; | |
| 3458 | - } | |
| 3459 | -}; | |
| 3460 | -// A non-bytes `b` is a live-stream body marker: revive it and | |
| 3461 | -// let the constructor adopt it as a streaming body. | |
| 3462 | -const __reviveRequest = (marker, url, revive) => { | |
| 3463 | - if (!(marker.b instanceof Uint8Array)) | |
| 3464 | - return new Request(url, { method: marker.m, | |
| 3465 | - headers: marker.h, redirect: marker.r, cf: marker.c, | |
| 3466 | - body: revive(marker.b) }); | |
| 3467 | - const req = new Request(url, { method: marker.m, | |
| 3468 | - headers: marker.h, redirect: marker.r, cf: marker.c }); | |
| 3469 | - __adoptBody(req, marker.b); | |
| 3470 | - return req; | |
| 3471 | -}; | |
| 3472 | -const __reviveResponse = (marker, revive) => { | |
| 3473 | - const bytes = marker.b instanceof Uint8Array; | |
| 3474 | - const res = new Response( | |
| 3475 | - marker.b === null ? null : bytes ? "" : revive(marker.b), { | |
| 3476 | - status: marker["__celld$res"], statusText: marker.t, | |
| 3477 | - headers: marker.h, cf: marker.c }); | |
| 3478 | - if (bytes) __adoptBody(res, marker.b); | |
| 3479 | - if (marker.e) res.type = "error"; | |
| 3480 | - return res; | |
| 3481 | -}; | |
| 3482 | -// Wire a received stream handle to a local endpoint built with | |
| 3483 | -// the ordinary constructors — nothing new threads through the | |
| 3484 | -// stream hot paths. Read errors surface as Workerd's generic | |
| 3485 | -// premature-disconnect; write errors propagate (Workerd sends | |
| 3486 | -// real errors back through the write loop). | |
| 3487 | -const __foreignStreamOp = () => Promise.reject(new Error( | |
| 3488 | - "RPC streams cannot cross isolate boundaries yet.")); | |
| 3489 | -const __reviveStream = (marker, id, readable, handles) => { | |
| 3490 | - const entry = marker.t === __stubIsolate | |
| 3491 | - ? __stubEntries.get(id) : undefined; | |
| 3492 | - if (entry === undefined) | |
| 3493 | - return readable | |
| 3494 | - ? new ReadableStream({ pull: __foreignStreamOp }) | |
| 3495 | - : new WritableStream({ write: __foreignStreamOp, | |
| 3496 | - close: __foreignStreamOp, abort: __foreignStreamOp }); | |
| 3497 | - const meta = { entry, disposed: false, ctx: __ctxNow() }; | |
| 3498 | - __ctxRegister(meta); | |
| 3499 | - handles.push(meta); | |
| 3500 | - const stream = readable | |
| 3501 | - ? new ReadableStream({ | |
| 3502 | - async pull(controller) { | |
| 3503 | - let result; | |
| 3504 | - try { | |
| 3505 | - result = await __stubOp(meta, ["read"], []); | |
| 3506 | - } catch { | |
| 3507 | - throw __rsDisconnect(); | |
| 3508 | - } | |
| 3509 | - if (result.done) controller.close(); | |
| 3510 | - else controller.enqueue(result.value); | |
| 3511 | - }, | |
| 3512 | - cancel: () => | |
| 3513 | - __stubOp(meta, ["cancel"], []).catch(() => {}), | |
| 3514 | - }, { highWaterMark: 0 }) | |
| 3515 | - : new WritableStream({ | |
| 3516 | - write: (chunk) => __stubOp(meta, ["write"], [chunk]), | |
| 3517 | - close: () => __stubOp(meta, ["close"], []), | |
| 3518 | - abort: () => | |
| 3519 | - __stubOp(meta, ["abort"], []).catch(() => {}), | |
| 3520 | - }); | |
| 3521 | - __rpcStreamMeta.set(stream, meta); | |
| 3522 | - return stream; | |
| 3523 | -}; | |
| 3524 | -const __reviveSignal = (marker, id) => { | |
| 3525 | - const entry = marker.t === __stubIsolate | |
| 3526 | - ? __stubEntries.get(id) : undefined; | |
| 3527 | - const controller = new AbortController(); | |
| 3528 | - if (entry === undefined) { | |
| 3529 | - if (marker.a) controller.abort(); | |
| 3530 | - return controller.signal; | |
| 3531 | - } | |
| 3532 | - __stubEntries.delete(id); | |
| 3533 | - const signal = entry.target; | |
| 3534 | - if (signal.aborted) controller.abort(signal.reason); | |
| 3535 | - else signal.addEventListener("abort", | |
| 3536 | - () => controller.abort(signal.reason), { once: true }); | |
| 3537 | - return controller.signal; | |
| 3538 | -}; | |
| 3539 | -// The inverse: markers become live handles. `handles` collects the | |
| 3540 | -// revived stubs (for call-end param disposal or result-tree | |
| 3541 | -// disposal); `disposers` collects remote Symbol.dispose entries. | |
| 3542 | -const __stubRevive = (value) => { | |
| 3543 | - const handles = []; | |
| 3544 | - const disposers = []; | |
| 3545 | - const seen = new Set(); | |
| 3546 | - const revive = (v) => { | |
| 3547 | - if (v === null || typeof v !== "object") return v; | |
| 3548 | - const stubId = v["__celld$stub"]; | |
| 3549 | - if (stubId !== undefined) { | |
| 3550 | - const entry = v.t === __stubIsolate | |
| 3551 | - ? __stubEntries.get(stubId) : undefined; | |
| 3552 | - const stub = entry === undefined | |
| 3553 | - ? __foreignStub() | |
| 3554 | - : __makeStub(entry, v.c); | |
| 3555 | - const meta = __stubMeta.get(stub); | |
| 3556 | - if (meta) handles.push(meta); | |
| 3557 | - return stub; | |
| 3558 | - } | |
| 3559 | - const svcName = v["__celld$svc"]; | |
| 3560 | - if (svcName !== undefined) | |
| 3561 | - return v.t === __stubIsolate | |
| 3562 | - ? __entrypointStub(svcName, revive(v.p)) | |
| 3563 | - : __foreignStub(); | |
| 3564 | - const doClass = v["__celld$do"]; | |
| 3565 | - if (doClass !== undefined) { | |
| 3566 | - const namespace = __cell.makeNamespace(doClass); | |
| 3567 | - return namespace.get( | |
| 3568 | - new DurableObjectId(doClass, v.v, v.n ?? undefined)); | |
| 3569 | - } | |
| 3570 | - const hdr = v["__celld$hdr"]; | |
| 3571 | - if (hdr !== undefined) return new Headers(hdr); | |
| 3572 | - const blobBytes = v["__celld$blob"]; | |
| 3573 | - if (blobBytes !== undefined) return __reviveBlob(v, blobBytes); | |
| 3574 | - const reqUrl = v["__celld$req"]; | |
| 3575 | - if (reqUrl !== undefined) | |
| 3576 | - return __reviveRequest(v, reqUrl, revive); | |
| 3577 | - if (v["__celld$res"] !== undefined) | |
| 3578 | - return __reviveResponse(v, revive); | |
| 3579 | - const rsId = v["__celld$rs"]; | |
| 3580 | - if (rsId !== undefined) | |
| 3581 | - return __reviveStream(v, rsId, true, handles); | |
| 3582 | - const wsId = v["__celld$ws"]; | |
| 3583 | - if (wsId !== undefined) | |
| 3584 | - return __reviveStream(v, wsId, false, handles); | |
| 3585 | - const sigId = v["__celld$sig"]; | |
| 3586 | - if (sigId !== undefined) return __reviveSignal(v, sigId); | |
| 3587 | - if (seen.has(v)) return v; | |
| 3588 | - seen.add(v); | |
| 3589 | - if (Array.isArray(v)) { | |
| 3590 | - for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); | |
| 3591 | - return v; | |
| 3592 | - } | |
| 3593 | - const proto = Object.getPrototypeOf(v); | |
| 3594 | - if (proto !== Object.prototype && proto !== null) return v; | |
| 3595 | - for (const key of Object.keys(v)) { | |
| 3596 | - if (key === "__celld$disp") { | |
| 3597 | - const entry = __stubEntries.get(v[key]); | |
| 3598 | - if (entry) disposers.push(entry); | |
| 3599 | - delete v[key]; | |
| 3600 | - continue; | |
| 3601 | - } | |
| 3602 | - v[key] = revive(v[key]); | |
| 3603 | - } | |
| 3604 | - return v; | |
| 3605 | - }; | |
| 3606 | - return { value: revive(value), handles, disposers }; | |
| 3607 | -}; | |
| 3608 | -// A marker that crossed an isolate boundary: fail on use, loudly. | |
| 3609 | -const __foreignStub = () => new Proxy(function () {}, { | |
| 3610 | - get: (_b, prop) => { | |
| 3611 | - if (prop === "then" || typeof prop !== "string") return undefined; | |
| 3612 | - return () => Promise.reject(new Error( | |
| 3613 | - "RPC stubs cannot cross isolate boundaries yet.")); | |
| 3614 | - }, | |
| 3615 | - apply: () => Promise.reject(new Error( | |
| 3616 | - "RPC stubs cannot cross isolate boundaries yet.")), | |
| 3617 | -}); | |
| 3618 | -// Workerd's entrypoint method-visibility rules (worker-rpc.c++): | |
| 3619 | -// reserved lifecycle names are refused outright; only prototype | |
| 3620 | -// methods and accessors are visible — never own instance state | |
| 3621 | -// (env/ctx live there) and never Object.prototype. | |
| 3622 | -const __entrypointReserved = new Set([ | |
| 3623 | - "constructor", "fetch", "connect", "alarm", "scheduled", | |
| 3624 | - "webSocketMessage", "webSocketClose", "webSocketError", "dup", | |
| 3625 | -]); | |
| 3626 | -const __entrypointResolve = (inst, prop) => { | |
| 3627 | - if (__entrypointReserved.has(prop)) | |
| 3628 | - throw new TypeError("'" + prop + | |
| 3629 | - "' is a reserved method and cannot be called over RPC."); | |
| 3630 | - if (Object.hasOwn(inst, prop) || !(prop in inst) || | |
| 3631 | - prop in Object.prototype) | |
| 3632 | - throw __rpcNoSuchMethod(prop); | |
| 3633 | - const value = inst[prop]; | |
| 3634 | - return typeof value === "function" && !__stubMeta.has(value) && | |
| 3635 | - !(value instanceof __cf.RpcPromise) && | |
| 3636 | - !(value instanceof __cf.RpcProperty) | |
| 3637 | - ? __rpcBindMethod(value, inst) : value; | |
| 3638 | -}; | |
| 3639 | -// A pipeline hop may continue only through plain data, functions, | |
| 3640 | -// RpcTargets, and stubs — never through an RPC promise/property | |
| 3641 | -// handle or a class instance (Workerd's receiver rules). | |
| 3642 | -const __walkable = (v) => | |
| 3643 | - v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty | |
| 3644 | - ? false | |
| 3645 | - : typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 3646 | - (typeof v === "object" && v !== null && | |
| 3647 | - (Object.getPrototypeOf(v) === Object.prototype || | |
| 3648 | - Array.isArray(v))); | |
| 3649 | -// Receiver-side pipeline walk: resolve `path` from `root`, then | |
| 3650 | -// GET the final member (`args` null) or CALL it. Errors name the | |
| 3651 | -// path walked so far, as Workerd's do. A stub mid-walk continues | |
| 3652 | -// against its own target, in the stub's owning context. | |
| 3653 | -const __rpcWalk = async (root, path, args, entrypointRoot) => { | |
| 3654 | - let value = root; | |
| 3655 | - for (let i = 0; i < path.length; i++) { | |
| 3656 | - const meta = __stubMeta.get(value); | |
| 3657 | - if (meta) { | |
| 3658 | - if (meta.disposed) throw __stubDisposedError(); | |
| 3659 | - const rest = path.slice(i); | |
| 3660 | - return await __ctxRun(meta.entry.ctx, | |
| 3661 | - () => __rpcWalk(meta.entry.target, rest, args, false)); | |
| 3662 | - } | |
| 3663 | - if (i > 0 && !__walkable(value)) | |
| 3664 | - throw __rpcNoSuchMethod(path[i - 1]); | |
| 3665 | - const prop = path[i]; | |
| 3666 | - const next = entrypointRoot && i === 0 | |
| 3667 | - ? __entrypointResolve(value, prop) | |
| 3668 | - : __stubResolve(value, prop); | |
| 3669 | - if (i === path.length - 1) { | |
| 3670 | - if (args === null) return next; | |
| 3671 | - if (typeof next !== "function") | |
| 3672 | - throw new TypeError( | |
| 3673 | - '"' + path.join(".") + '" is not a function.'); | |
| 3674 | - return next(...args); | |
| 3675 | - } | |
| 3676 | - if (next instanceof __cf.RpcPromise || | |
| 3677 | - next instanceof __cf.RpcProperty) | |
| 3678 | - throw __rpcNoSuchMethod(prop); | |
| 3679 | - value = next; | |
| 3680 | - } | |
| 3681 | - // An empty path applies the root itself (a callable stub). | |
| 3682 | - if (args === null) return value; | |
| 3683 | - if (typeof value !== "function") | |
| 3684 | - throw new TypeError("The RPC stub is not callable."); | |
| 3685 | - return value(...args); | |
| 3686 | -}; | |
| 3687 | -// One stub-mediated op: clone through the RPC envelope both ways, | |
| 3688 | -// so nested stubs, errors, and uncloneables behave exactly as a | |
| 3689 | -// dispatched call. Args serialize in the caller's context (its | |
| 3690 | -// stubs must be its own to transfer); the decode, the walk, and | |
| 3691 | -// the reply serialization run in the stub's owning context, so | |
| 3692 | -// stubs minted by the target belong to the target's context. | |
| 3693 | -// Params received by the target are disposed when the op ends | |
| 3694 | -// (Workerd's param-disposal rule). | |
| 3695 | -const __stubOp = (meta, path, args) => { | |
| 3696 | - if (meta.disposed) return Promise.reject(__stubDisposedError()); | |
| 3697 | - const entry = meta.entry; | |
| 3698 | - // The cell that minted this stub left residency, so `entry.target` | |
| 3699 | - // belongs to an instance this node released. The stub fails here | |
| 3700 | - // rather than calling into it. | |
| 3701 | - if (entry.released) return Promise.reject(__releasedStubError()); | |
| 3702 | - // A stub rooted in an aborted context is broken: reject with the | |
| 3703 | - // abort reason, before and after the dispatch (the target may | |
| 3704 | - // abort its own context mid-call). Gated on one field read. | |
| 3705 | - if (__abortedCtxs.size !== 0) { | |
| 3706 | - const aborted = __abortedCtxs.get(entry.ctx); | |
| 3707 | - if (aborted !== undefined) | |
| 3708 | - return Promise.reject(__postAbortError(aborted)); | |
| 3709 | - } | |
| 3710 | - const argsSc = args === null ? null : __rpcOut(args, true); | |
| 3711 | - const dispatch = (async () => { | |
| 3712 | - // Workerd delivers RPC asynchronously: the callee must not run | |
| 3713 | - // before the caller's synchronous code. A call made just after | |
| 3714 | - // a not-yet-delivered ctx.abort counts as in flight (rejects | |
| 3715 | - // with the reason, not the post-abort message). Bodies queue | |
| 3716 | - // in call order, so e-order holds. | |
| 3717 | - await null; | |
| 3718 | - // The cell that minted this stub gates it like any other event. | |
| 3719 | - // The op is dispatched inside the isolate and never becomes a | |
| 3720 | - // drive, so it is the one delivery point that has to ask here | |
| 3721 | - // rather than in Rust. A stub carrying the running critical | |
| 3722 | - // section re-enters it; everything else queues, and a section | |
| 3723 | - // that failed refuses what queued. | |
| 3724 | - const cell = entry.scope; | |
| 3725 | - if (cell !== undefined) { | |
| 3726 | - const block = __cellBlocks.get(cell); | |
| 3727 | - if (block !== undefined && (entry.section === null || | |
| 3728 | - entry.section !== block.holder)) | |
| 3729 | - await __gate_wait(cell); | |
| 3730 | - } | |
| 3731 | - const reply = await __ctxRun(entry.ctx, | |
| 3732 | - () => __rpcRun(async () => { | |
| 3733 | - const decoded = | |
| 3734 | - argsSc === null ? null : __rpcDesArgs(argsSc); | |
| 3735 | - try { | |
| 3736 | - return await __rpcWalk(entry.target, path, | |
| 3737 | - decoded === null ? null : decoded.args, false); | |
| 3738 | - } finally { | |
| 3739 | - if (decoded !== null) | |
| 3740 | - for (const handle of decoded.received) | |
| 3741 | - __disposeStub(handle); | |
| 3742 | - } | |
| 3743 | - }, true)); | |
| 3744 | - if (__abortedCtxs.size !== 0) { | |
| 3745 | - const aborted = __abortedCtxs.get(entry.ctx); | |
| 3746 | - if (aborted !== undefined) | |
| 3747 | - throw aborted instanceof __ActorAbort | |
| 3748 | - ? aborted.reason : aborted; | |
| 3749 | - } | |
| 3750 | - return __rpcDes(reply); | |
| 3751 | - })(); | |
| 3752 | - if (entry.ctx === undefined) return dispatch; | |
| 3753 | - // Race the op against its hosting context's abort: a hung callee | |
| 3754 | - // never settles, so the settlement check above cannot reach it. | |
| 3755 | - // A late settlement lands on an already-settled promise (no-op). | |
| 3756 | - return new Promise((resolve, reject) => { | |
| 3757 | - const untrack = __opTrack(entry.ctx, reject); | |
| 3758 | - dispatch.then( | |
| 3759 | - (value) => { untrack(); resolve(value); }, | |
| 3760 | - (error) => { untrack(); reject(error); }); | |
| 3761 | - }); | |
| 3762 | -}; | |
| 3763 | -// Resolve a path against a local, already-revived value. A hop | |
| 3764 | -// landing on a same-isolate stub delegates the rest of the path | |
| 3765 | -// to the stub's target; everything else is a plain [[Get]] so | |
| 3766 | -// Durable Object stubs and Proxies participate. | |
| 3767 | -const __walkLocal = (parent, path, args) => { | |
| 3768 | - for (let i = 0; i < path.length; i++) { | |
| 3769 | - const meta = __stubMeta.get(parent); | |
| 3770 | - if (meta) return __stubOp(meta, path.slice(i), args); | |
| 3771 | - const prop = path[i]; | |
| 3772 | - const member = parent == null ? undefined : parent[prop]; | |
| 3773 | - if (i < path.length - 1) { | |
| 3774 | - parent = member; | |
| 3775 | - continue; | |
| 3776 | - } | |
| 3777 | - if (args === null) return member; | |
| 3778 | - if (typeof member !== "function") { | |
| 3779 | - if (member === undefined) throw __rpcNoSuchMethod(prop); | |
| 3780 | - throw new TypeError('"' + prop + '" is not a function.'); | |
| 3781 | - } | |
| 3782 | - // [[Call]] directly: `.apply` on a stub proxy would be a | |
| 3783 | - // remote property access, not an invocation. | |
| 3784 | - return Reflect.apply(member, parent, args); | |
| 3785 | - } | |
| 3786 | - if (args === null) return parent; | |
| 3787 | - const meta = __stubMeta.get(parent); | |
| 3788 | - if (meta) return __stubOp(meta, [], args); | |
| 3789 | - if (typeof parent !== "function") | |
| 3790 | - throw new TypeError("The RPC value is not callable."); | |
| 3791 | - return parent(...args); | |
| 3792 | -}; | |
| 3793 | -// A session is one place pipeline ops resolve: the local value a | |
| 3794 | -// call returned, a same-isolate stub's target, or a named | |
| 3795 | -// entrypoint (whose paths resolve receiver-side in one op). | |
| 3796 | -const __valueSession = (promise) => ({ | |
| 3797 | - root: () => promise, | |
| 3798 | - get: (path) => promise.then((v) => __walkLocal(v, path, null)), | |
| 3799 | - call: (path, args) => | |
| 3800 | - promise.then((v) => __walkLocal(v, path, args)), | |
| 3801 | -}); | |
| 3802 | -const __stubSession = (meta) => ({ | |
| 3803 | - get: (path) => __stubOp(meta, path, null), | |
| 3804 | - call: (path, args) => __stubOp(meta, path, args), | |
| 3805 | -}); | |
| 3806 | -const __entrypointSession = (name, local, script, makeInst) => ({ | |
| 3807 | - get: (path) => local | |
| 3808 | - ? (async () => __rpcDes( | |
| 3809 | - await __entrypointOp(name, path, null, true, makeInst)))() | |
| 3810 | - : Promise.reject(new Error( | |
| 3811 | - "Awaitable properties on cross-script service bindings " + | |
| 3812 | - "are not supported yet.")), | |
| 3813 | - call: (path, args) => (async () => { | |
| 3814 | - const argsSc = __rpcOut(args, local); | |
| 3815 | - if (local) | |
| 3816 | - return __rpcDes(await __entrypointOp( | |
| 3817 | - name, path, argsSc, true, makeInst)); | |
| 3818 | - if (path.length !== 1) | |
| 3819 | - throw new Error( | |
| 3820 | - "Pipelined property paths on cross-script service " + | |
| 3821 | - "bindings are not supported yet."); | |
| 3822 | - return __rpcDes( | |
| 3823 | - await __svc_rpc(script, name, path[0], argsSc)); | |
| 3824 | - })(), | |
| 3825 | -}); | |
| 3826 | -// Workerd's JsRpcPromise/JsRpcProperty: awaitable, callable, and | |
| 3827 | -// property access extends a path resolved at the far end, so | |
| 3828 | -// intermediates obey Workerd's receiver rules. `ctx` is the node's | |
| 3829 | -// owning request context — null marks a context-free node (a | |
| 3830 | -// property path rooted directly at a service binding, which | |
| 3831 | -// starts a fresh session per await); a foreign context awaiting a | |
| 3832 | -// property or calling through the node gets Workerd's | |
| 3833 | -// cross-context error. Depth is capped like Workerd's | |
| 3834 | -// MAX_PROPERTY_DEPTH. | |
| 3835 | -const __makeNode = (session, path, ctx) => { | |
| 3836 | - let promise; | |
| 3837 | - const value = () => promise ??= (() => { | |
| 3838 | - if (path.length === 0) return session.root(); | |
| 3839 | - if (ctx !== null && ctx !== __ctxNow()) | |
| 3840 | - return Promise.reject(__ctxError("Pipeline")); | |
| 3841 | - return session.get(path); | |
| 3842 | - })(); | |
| 3843 | - const brand = | |
| 3844 | - path.length === 0 ? __cf.RpcPromise : __cf.RpcProperty; | |
| 3845 | - return new Proxy(function () {}, { | |
| 3846 | - getPrototypeOf: () => brand.prototype, | |
| 3847 | - get: (_b, p) => { | |
| 3848 | - if (p === "then") | |
| 3849 | - return (onOk, onErr) => value().then(onOk, onErr); | |
| 3850 | - if (p === "catch") return (onErr) => value().catch(onErr); | |
| 3851 | - if (p === "finally") | |
| 3852 | - return (onDone) => value().finally(onDone); | |
| 3853 | - if (typeof p !== "string") return undefined; | |
| 3854 | - if (path.length >= 5120) | |
| 3855 | - throw new TypeError( | |
| 3856 | - "RPC pipelined property chain is too deep."); | |
| 3857 | - return __makeNode(session, [...path, p], ctx); | |
| 3858 | - }, | |
| 3859 | - apply: (_b, _this, args) => { | |
| 3860 | - let call; | |
| 3861 | - if (ctx !== null && ctx !== __ctxNow()) { | |
| 3862 | - call = Promise.reject(__ctxError("JsRpcPromise")); | |
| 3863 | - call.catch(() => {}); | |
| 3864 | - } else { | |
| 3865 | - // Eager, so concurrent calls keep e-order. | |
| 3866 | - call = session.call(path, args); | |
| 3867 | - } | |
| 3868 | - return __makeNode( | |
| 3869 | - __valueSession(call), [], ctx ?? __ctxNow()); | |
| 3870 | - }, | |
| 3871 | - }); | |
| 3872 | -}; | |
| 3873 | -const __makeStub = (entry, callable) => { | |
| 3874 | - const meta = | |
| 3875 | - { entry, callable, disposed: false, ctx: __ctxNow() }; | |
| 3876 | - __ctxRegister(meta); | |
| 3877 | - const stub = new Proxy(function () {}, { | |
| 3878 | - getPrototypeOf: () => __cf.RpcStub.prototype, | |
| 3879 | - get: (_b, prop) => { | |
| 3880 | - if (prop === "then") return undefined; | |
| 3881 | - if (prop === Symbol.dispose) return () => __disposeStub(meta); | |
| 3882 | - if (prop === "dup") return () => { | |
| 3883 | - if (meta.disposed) throw __stubDisposedError(); | |
| 3884 | - entry.refs++; | |
| 3885 | - return __makeStub(entry, callable); | |
| 3886 | - }; | |
| 3887 | - if (typeof prop !== "string") return undefined; | |
| 3888 | - return __makeNode(__stubSession(meta), [prop], __ctxNow()); | |
| 3889 | - }, | |
| 3890 | - apply: (_b, _this, args) => __makeNode( | |
| 3891 | - __valueSession(__stubOp(meta, [], args)), [], __ctxNow()), | |
| 3892 | - }); | |
| 3893 | - __stubMeta.set(stub, meta); | |
| 3894 | - return stub; | |
| 3895 | -}; | |
| 3896 | -// A loopback service stub for one of this worker's own | |
| 3897 | -// entrypoints — the ctx.exports surface. Calling the stub itself | |
| 3898 | -// returns a new stub carrying per-instance props, delivered to | |
| 3899 | -// the class constructor as ctx.props (Workerd's | |
| 3900 | -// ctx.exports.Name({ props })). | |
| 3901 | -const __svcMeta = new WeakMap(); | |
| 3902 | -const __entrypointStub = (name, props) => { | |
| 3903 | - let inst; | |
| 3904 | - const makeInst = props === undefined ? undefined : () => { | |
| 3905 | - if (inst !== undefined) return inst; | |
| 3906 | - const cls = __cell.entrypoints[name]; | |
| 3907 | - if (typeof cls !== "function") | |
| 3908 | - throw new TypeError( | |
| 3909 | - "The entrypoint " + name + " cannot carry props."); | |
| 3910 | - // Construction gets its own event, like __entrypointInstance. | |
| 3911 | - const ctx = __beginEvent(props); | |
| 3912 | - try { | |
| 3913 | - inst = new cls(ctx, __cell.env); | |
| 3914 | - } finally { | |
| 3915 | - __endEvent(); | |
| 3916 | - } | |
| 3917 | - return inst; | |
| 3918 | - }; | |
| 3919 | - const session = __entrypointSession(name, true, null, makeInst); | |
| 3920 | - const stub = new Proxy(function () {}, { | |
| 3921 | - getPrototypeOf: () => __cf.ServiceStub.prototype, | |
| 3922 | - get: (_b, prop) => { | |
| 3923 | - if (prop === "then") return undefined; | |
| 3924 | - if (typeof prop !== "string") return undefined; | |
| 3925 | - if (prop === "getRpcMethodForTestOnly") | |
| 3926 | - return (n) => __makeNode(session, [String(n)], null); | |
| 3927 | - return __makeNode(session, [prop], null); | |
| 3928 | - }, | |
| 3929 | - apply: (_b, _this, args) => | |
| 3930 | - __entrypointStub(name, args[0]?.props), | |
| 3931 | - }); | |
| 3932 | - __svcMeta.set(stub, { name, props }); | |
| 3933 | - return stub; | |
| 3934 | -}; | |
| 3935 | -// ---- stored stubs ---------------------------------------------- | |
| 3936 | -// Durable Object storage accepts only stubs with durable identity: | |
| 3937 | -// loopback service stubs (entrypoint name + props re-mint a fresh | |
| 3938 | -// stub on read) and Durable Object stubs (HMAC'd id + class revive | |
| 3939 | -// in any isolate). A transient handle — a received RPC stub, a | |
| 3940 | -// function, an RpcTarget — dies with its isolate; persisting its | |
| 3941 | -// entry id would revive garbage after a restart, so it is refused. | |
| 3942 | -// A stub-bearing row is written as 0x01 + clone(marker tree), off | |
| 3943 | -// the plain-clone fast path (the lift runs only after the plain | |
| 3944 | -// clone already threw, exactly like the RPC envelope). Reads hand | |
| 3945 | -// tagged rows to JS as [sentinel, tree]; the sentinel never leaves | |
| 3946 | -// this script and no user value can decode to it, so revival | |
| 3947 | -// cannot be spoofed by data shaped like a marker. | |
| 3948 | -const __storedSentinel = {}; | |
| 3949 | -const __storedLift = (value) => { | |
| 3950 | - let lifted = false; | |
| 3951 | - const seen = new Map(); | |
| 3952 | - const lift = (v) => { | |
| 3953 | - if (v === null || | |
| 3954 | - (typeof v !== "object" && typeof v !== "function")) return v; | |
| 3955 | - const cached = seen.get(v); | |
| 3956 | - if (cached !== undefined) return cached; | |
| 3957 | - // Ordering mirrors __stubLift: identify proxies by their | |
| 3958 | - // side tables and brands before touching any property — a | |
| 3959 | - // stub or pipeline proxy answers every property read with a | |
| 3960 | - // fresh RpcProperty node. | |
| 3961 | - if (__stubMeta.has(v) || v instanceof __cf.RpcTarget) | |
| 3962 | - throw new DOMException( | |
| 3963 | - "Durable Object storage can only store stubs with " + | |
| 3964 | - "durable identity: service stubs from ctx.exports and " + | |
| 3965 | - "Durable Object stubs. This value is a transient RPC " + | |
| 3966 | - "handle that would not survive a restart.", | |
| 3967 | - "DataCloneError"); | |
| 3968 | - const svc = __svcMeta.get(v); | |
| 3969 | - if (svc !== undefined) { | |
| 3970 | - lifted = true; | |
| 3971 | - const marker = { "__celld$svc": svc.name }; | |
| 3972 | - seen.set(v, marker); | |
| 3973 | - if (svc.props !== undefined) marker.p = lift(svc.props); | |
| 3974 | - return marker; | |
| 3975 | - } | |
| 3976 | - if (v instanceof __cf.RpcPromise || | |
| 3977 | - v instanceof __cf.RpcProperty) | |
| 3978 | - throw new DOMException( | |
| 3979 | - 'Could not serialize object of type "' + | |
| 3980 | - (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + | |
| 3981 | - '". This type does not support serialization.', | |
| 3982 | - "DataCloneError"); | |
| 3983 | - if (typeof v === "function") return v; // leave to the clone | |
| 3984 | - const doId = v.__celldDo; | |
| 3985 | - if (doId !== undefined) { | |
| 3986 | - lifted = true; | |
| 3987 | - const marker = { "__celld$do": doId._className, | |
| 3988 | - v: doId._value, n: v.name ?? null }; | |
| 3989 | - seen.set(v, marker); | |
| 3990 | - return marker; | |
| 3991 | - } | |
| 3992 | - if (Array.isArray(v)) { | |
| 3993 | - const out = []; | |
| 3994 | - seen.set(v, out); | |
| 3995 | - for (let i = 0; i < v.length; i++) out[i] = lift(v[i]); | |
| 3996 | - return out; | |
| 3997 | - } | |
| 3998 | - const proto = Object.getPrototypeOf(v); | |
| 3999 | - if (proto !== Object.prototype && proto !== null) | |
| 4000 | - return v; // host/other: leave to the clone | |
| 4001 | - const out = {}; | |
| 4002 | - seen.set(v, out); | |
| 4003 | - for (const key of Object.keys(v)) out[key] = lift(v[key]); | |
| 4004 | - return out; | |
| 4005 | - }; | |
| 4006 | - const tree = lift(value); | |
| 4007 | - return lifted ? tree : null; | |
| 4008 | -}; | |
| 4009 | -// Encode one stub-bearing value for storage. Rethrows the original | |
| 4010 | -// clone error when nothing was liftable, so plain uncloneables | |
| 4011 | -// fail exactly as they always did. | |
| 4012 | -const __storedBytes = (value, error) => { | |
| 4013 | - const tree = __storedLift(value); | |
| 4014 | - if (tree === null) throw error; | |
| 4015 | - return __tagged(1, __sc_encode(tree)); | |
| 4016 | -}; | |
| 4017 | -const __storedRevive = (value) => { | |
| 4018 | - const seen = new Set(); | |
| 4019 | - const revive = (v) => { | |
| 4020 | - if (v === null || typeof v !== "object") return v; | |
| 4021 | - const svcName = v["__celld$svc"]; | |
| 4022 | - if (svcName !== undefined) | |
| 4023 | - return __entrypointStub(svcName, revive(v.p)); | |
| 4024 | - const doClass = v["__celld$do"]; | |
| 4025 | - if (doClass !== undefined) | |
| 4026 | - return __cell.makeNamespace(doClass).get( | |
| 4027 | - new DurableObjectId(doClass, v.v, v.n ?? undefined)); | |
| 4028 | - if (seen.has(v)) return v; | |
| 4029 | - seen.add(v); | |
| 4030 | - if (Array.isArray(v)) { | |
| 4031 | - for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); | |
| 4032 | - return v; | |
| 4033 | - } | |
| 4034 | - const proto = Object.getPrototypeOf(v); | |
| 4035 | - if (proto !== Object.prototype && proto !== null) return v; | |
| 4036 | - for (const key of Object.keys(v)) v[key] = revive(v[key]); | |
| 4037 | - return v; | |
| 4038 | - }; | |
| 4039 | - return revive(value); | |
| 4040 | -}; | |
| 4041 | -const __unwrapStored = (v) => | |
| 4042 | - Array.isArray(v) && v[0] === __storedSentinel | |
| 4043 | - ? __storedRevive(v[1]) : v; | |
| 4044 | -// A map result is wrapped as a whole only when it holds at least | |
| 4045 | -// one tagged row, so the per-entry walk never runs on plain data. | |
| 4046 | -const __unwrapStoredMap = (v) => { | |
| 4047 | - if (!Array.isArray(v) || v[0] !== __storedSentinel) return v; | |
| 4048 | - const map = v[1]; | |
| 4049 | - for (const [key, value] of map) | |
| 4050 | - map.set(key, __unwrapStored(value)); | |
| 4051 | - return map; | |
| 4052 | -}; | |
| 4053 | -// ctx.exports: loopback stubs for every exported entrypoint plus | |
| 4054 | -// this worker's Durable Object namespaces. Built once, on first | |
| 4055 | -// access — ctx construction itself only carries the getter. | |
| 4056 | -let __ctxExportsCache; | |
| 4057 | -const __ctxExports = () => __ctxExportsCache ??= (() => { | |
| 4058 | - const out = {}; | |
| 4059 | - for (const name of Object.keys(__cell.entrypoints)) | |
| 4060 | - out[name] = __entrypointStub(name, undefined); | |
| 4061 | - for (const name of Object.keys(__cell.objectEntrypoints)) | |
| 4062 | - if (name !== "default") | |
| 4063 | - out[name] = __entrypointStub(name, undefined); | |
| 4064 | - for (const name of Object.keys(__cell.namespaceKeys)) | |
| 4065 | - out[name] = __cell.makeNamespace(name); | |
| 4066 | - return out; | |
| 4067 | -})(); | |
| 4068 | -// ---- RPC envelope ---------------------------------------------- | |
| 4069 | -// Serialize one payload. `lift` marks a same-isolate transport, | |
| 4070 | -// where stub-able values may cross as markers; elsewhere they stay | |
| 4071 | -// a DataCloneError, exactly as before stubs existed. | |
| 4072 | -const __rpcOut = (value, lift) => { | |
| 4073 | - try { | |
| 4074 | - return __sc_encode(value); | |
| 4075 | - } catch (error) { | |
| 4076 | - const lifted = lift ? __stubLift(value) : null; | |
| 4077 | - if (lifted === null) throw __dataCloneError(error); | |
| 4078 | - try { | |
| 4079 | - return __tagged( | |
| 4080 | - lifted.caps ? 1 : 2, __sc_encode(lifted.tree)); | |
| 4081 | - } catch (error_) { | |
| 4082 | - throw __dataCloneError(error_); | |
| 4083 | - } | |
| 4084 | - } | |
| 4085 | -}; | |
| 4086 | -// A callee exception as tagged bytes: the Error crosses by value | |
| 4087 | -// (V8 serializes Error natively), custom own properties beside it. | |
| 4088 | -const __rpcErrOut = (error) => { | |
| 4089 | - // `name` rides in the props: V8 only round-trips the standard | |
| 4090 | - // Error subclass names, and e.g. DataCloneError must survive. | |
| 4091 | - const props = error instanceof Error | |
| 4092 | - ? { ...error, name: error.name } : {}; | |
| 4093 | - let sc; | |
| 4094 | - try { | |
| 4095 | - sc = __sc_encode([error, props]); | |
| 4096 | - } catch { | |
| 4097 | - const error_ = new Error(String(error?.message ?? error)); | |
| 4098 | - sc = __sc_encode([error_, { name: String(error?.name ?? "Error") }]); | |
| 4099 | - } | |
| 4100 | - return __tagged(0, sc); | |
| 4101 | -}; | |
| 4102 | -// The callee half of one RPC: run `body`, answer tagged bytes. | |
| 4103 | -const __rpcRun = async (body, lift) => { | |
| 4104 | - try { | |
| 4105 | - return __rpcOut(await body(), lift); | |
| 4106 | - } catch (error) { | |
| 4107 | - return __rpcErrOut(error); | |
| 4108 | - } | |
| 4109 | -}; | |
| 4110 | -const __rpcDesArgs = (bytes) => { | |
| 4111 | - if (bytes[0] === 0xff) | |
| 4112 | - return { args: __sc_decode(bytes), received: [] }; | |
| 4113 | - const revived = __stubRevive(__sc_decode(bytes.subarray(1))); | |
| 4114 | - return { args: revived.value, received: revived.handles }; | |
| 4115 | -}; | |
| 4116 | -// The caller half: decode a reply, rebuilding stubs and rethrowing | |
| 4117 | -// callee exceptions as real Errors with the callee's own | |
| 4118 | -// properties, `.remote`, and a local (caller-side) stack. | |
| 4119 | -const __rpcDes = (bytes) => { | |
| 4120 | - if (bytes[0] === 0xff) return __sc_decode(bytes); | |
| 4121 | - if (bytes[0] === 1 || bytes[0] === 2) { | |
| 4122 | - const { value, handles, disposers } = | |
| 4123 | - __stubRevive(__sc_decode(bytes.subarray(1))); | |
| 4124 | - if (value !== null && typeof value === "object" && | |
| 4125 | - !__stubMeta.has(value) && | |
| 4126 | - (handles.length > 0 || disposers.length > 0)) { | |
| 4127 | - Object.defineProperty(value, Symbol.dispose, { | |
| 4128 | - configurable: true, | |
| 4129 | - value: () => { | |
| 4130 | - for (const handle of handles) __disposeStub(handle); | |
| 4131 | - for (const entry of disposers) { | |
| 4132 | - __stubEntries.delete(entry.id); | |
| 4133 | - Promise.resolve().then(() => entry.target()); | |
| 4134 | - } | |
| 4135 | - }, | |
| 4136 | - }); | |
| 4137 | - } | |
| 4138 | - return value; | |
| 4139 | - } | |
| 4140 | - const [error, props] = __sc_decode(bytes.subarray(1)); | |
| 4141 | - if (error instanceof Error) { | |
| 4142 | - Object.assign(error, props); | |
| 4143 | - error.remote = true; | |
| 4144 | - const local = new Error().stack; | |
| 4145 | - error.stack = error.name + ": " + error.message + | |
| 4146 | - local.slice(local.indexOf("\n")); | |
| 4147 | - } | |
| 4148 | - throw error; | |
| 4149 | -}; | |
| 4150 | -// Deprecated Fetcher `get()`/`put()`/`delete()` HTTP helpers, kept by | |
| 4151 | -// the fetcher_has_get_put_delete compat flag (Workerd http.c++): | |
| 4152 | -// shortcuts for fetch() with the corresponding method. | |
| 4153 | -const __fetcherStatus = (res, method) => { | |
| 4154 | - if (res.status >= 200 && res.status < 300) return; | |
| 4155 | - throw new Error("HTTP " + method + " request failed: " + res.status + | |
| 4156 | - " " + (res.statusText || __STATUS_TEXT[res.status] || "")); | |
| 4157 | -}; | |
| 4158 | -const __fetcherHelper = (fetch, prop) => { | |
| 4159 | - if (prop === "get") return async (url, type) => { | |
| 4160 | - const res = await fetch(url, { method: "GET" }); | |
| 4161 | - if (res.status === 404 || res.status === 410) return null; | |
| 4162 | - __fetcherStatus(res, "GET"); | |
| 4163 | - if (type === "stream") | |
| 4164 | - return res.body ?? new ReadableStream({ start(c) { c.close(); } }); | |
| 4165 | - if (type === "arrayBuffer") return res.arrayBuffer(); | |
| 4166 | - if (type === "json") return res.json(); | |
| 4167 | - return res.text(); | |
| 4168 | - }; | |
| 4169 | - if (prop === "put") return async (url, body, options) => { | |
| 4170 | - const { expiration, expirationTtl } = options ?? {}; | |
| 4171 | - if (expiration !== undefined || expirationTtl !== undefined) { | |
| 4172 | - const url_ = new URL(url); | |
| 4173 | - if (expiration !== undefined) | |
| 4174 | - url_.searchParams.append("expiration", expiration); | |
| 4175 | - if (expirationTtl !== undefined) | |
| 4176 | - url_.searchParams.append("expiration_ttl", expirationTtl); | |
| 4177 | - url = url_.toString(); | |
| 4178 | - } | |
| 4179 | - __fetcherStatus(await fetch(url, { method: "PUT", body }), "PUT"); | |
| 4180 | - }; | |
| 4181 | - return async (url) => { | |
| 4182 | - __fetcherStatus(await fetch(url, { method: "DELETE" }), "DELETE"); | |
| 4183 | - }; | |
| 4184 | -}; | |
| 4185 | -function makeNamespace(className) { | |
| 4186 | - const namespaceKey = __cell.namespaceKeys[className]; | |
| 4187 | - if (typeof namespaceKey !== "string") | |
| 4188 | - throw new Error("no Durable Object namespace key for " + className); | |
| 4189 | - return new DurableObjectNamespace(className, namespaceKey); | |
| 4190 | -} | |
| 4191 | -// A named class: SDKs sniff bindings by constructor name (workers-rs | |
| 4192 | -// EnvBinding requires `constructor.name === "DurableObjectNamespace"`). | |
| 4193 | -class DurableObjectNamespace { | |
| 4194 | - constructor(className, namespaceKey) { | |
| 4195 | - Object.defineProperty(this, "_className", { value: className }); | |
| 4196 | - Object.defineProperty(this, "_namespaceKey", { value: namespaceKey }); | |
| 4197 | - } | |
| 4198 | - idFromName(name) { | |
| 4199 | - name = String(name); | |
| 4200 | - return new DurableObjectId( | |
| 4201 | - this._className, __do_id(this._namespaceKey, "name", name), name, | |
| 4202 | - ); | |
| 4203 | - } | |
| 4204 | - idFromString(value) { | |
| 4205 | - return new DurableObjectId( | |
| 4206 | - this._className, __do_id(this._namespaceKey, "validate", String(value)), | |
| 4207 | - ); | |
| 4208 | - } | |
| 4209 | - newUniqueId(options = {}) { | |
| 4210 | - const jurisdiction = options == null ? undefined : options.jurisdiction; | |
| 4211 | - if (jurisdiction != null) | |
| 4212 | - throw new Error("Jurisdiction restrictions are not implemented"); | |
| 4213 | - return new DurableObjectId( | |
| 4214 | - this._className, __do_id(this._namespaceKey, "unique", ""), | |
| 4215 | - ); | |
| 4216 | - } | |
| 4217 | - jurisdiction(value) { | |
| 4218 | - if (value == null) return this; | |
| 4219 | - throw new Error("Jurisdiction restrictions are not implemented"); | |
| 4220 | - } | |
| 4221 | - getByName(name, options) { | |
| 4222 | - return this.get(this.idFromName(name), options); | |
| 4223 | - } | |
| 4224 | - get(id) { | |
| 4225 | - const className = this._className; | |
| 4226 | - if (!(id instanceof DurableObjectId) || id._className !== className) | |
| 4227 | - throw new TypeError("Durable Object ID is not valid for this namespace"); | |
| 4228 | - const scope = id._scope(); | |
| 4229 | - // Emulate production: the actor recovers its name only when it is | |
| 4230 | - // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is | |
| 4231 | - // undefined. The full name still seeds the routing hash, so | |
| 4232 | - // dispatch is unchanged. Short names skip the byte count (< 256 | |
| 4233 | - // chars is always <= 1020 bytes) to keep the hot path alloc-free. | |
| 4234 | - const nm = id.name; | |
| 4235 | - const dispatchName = nm === undefined ? undefined | |
| 4236 | - : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024 | |
| 4237 | - ? nm : undefined; | |
| 4238 | - if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName; | |
| 4239 | - // Fetch and native RPC use the same host routing/activation seam. | |
| 4240 | - // Never expose `.then`: a DO stub is not itself a promise. | |
| 4241 | - // `__celldDo` brands the stub so the RPC lift can send it as a | |
| 4242 | - // revivable marker rather than failing the clone; non-enumerable | |
| 4243 | - // so Object.keys(stub) stays Workerd's [id, name]. | |
| 4244 | - const target = { id, name: dispatchName }; | |
| 4245 | - Object.defineProperty(target, "__celldDo", { value: id }); | |
| 4246 | - const abortMarker = "__CELLD_ACTOR_ABORT__:"; | |
| 4247 | - const processExitMarker = "__CELLD_PROCESS_EXIT__:"; | |
| 4248 | - let brokenReason = null; | |
| 4249 | - const invoke = async (operation) => { | |
| 4250 | - if (brokenReason !== null) throw new Error(brokenReason); | |
| 4251 | - try { | |
| 4252 | - return await operation(); | |
| 4253 | - } catch (error) { | |
| 4254 | - const routingError = __durableObjectRoutingError(error); | |
| 4255 | - if (routingError !== null) throw routingError; | |
| 4256 | - const message = String(error && error.message || error); | |
| 4257 | - const marker = [abortMarker, processExitMarker] | |
| 4258 | - .find((candidate) => message.includes(candidate)); | |
| 4259 | - if (!marker) throw error; | |
| 4260 | - brokenReason = message.slice(message.indexOf(marker) + marker.length); | |
| 4261 | - throw new Error(brokenReason); | |
| 4262 | - } | |
| 4263 | - }; | |
| 4264 | - const doFetch = async (input, init) => { | |
| 4265 | - const req = new Request(input, init); | |
| 4266 | - const signal = req._signalForSubrequests; | |
| 4267 | - if (signal?.aborted) throw signal.reason; | |
| 4268 | - // A body already backed by a host stream forwards to the cell as its | |
| 4269 | - // stream id, so a proxied upload to a cell on this node costs a chunk | |
| 4270 | - // rather than the whole body (#156). The host keeps it a stream for a | |
| 4271 | - // local cell and collects it only to sign a cross-node frame. A held | |
| 4272 | - // body -- or a stream with no host id -- crosses as its bytes. | |
| 4273 | - const bodyStreamId = | |
| 4274 | - req._bodyBytes === null && req.body && req.body.__celldStreamId !== undefined | |
| 4275 | - ? req.body.__celldStreamId | |
| 4276 | - : undefined; | |
| 4277 | - const body_ = bodyStreamId !== undefined | |
| 4278 | - ? new Uint8Array() | |
| 4279 | - : req._bodyBytes === null | |
| 4280 | - ? await req._consume() | |
| 4281 | - : req._bodyBytes; | |
| 4282 | - if (bodyStreamId !== undefined) { | |
| 4283 | - // The cell reads this upload through the same host stream id, so the | |
| 4284 | - // Worker's wrapper must not also read it: lock it (a late read throws | |
| 4285 | - // instead of racing the cell over one host stream) and mark it used, | |
| 4286 | - // which is what awaiting the old _consume() did and what workerd | |
| 4287 | - // reports as request.bodyUsed after the forward. | |
| 4288 | - req.bodyUsed = true; | |
| 4289 | - req.body.getReader(); | |
| 4290 | - } | |
| 4291 | - // Forward the request's headers to the cell as JSON. When they were | |
| 4292 | - // never materialized -- a Worker that only routes to a cell reads | |
| 4293 | - // none -- pass the raw header string straight through, so the whole | |
| 4294 | - // dispatch never builds a Headers object on either side. | |
| 4295 | - // | |
| 4296 | - // Both branches now carry the same shape. The raw string is the | |
| 4297 | - // wire list the host handed in, so the materialized branch must send | |
| 4298 | - // the header list too, not the iterator; see the note on the | |
| 4299 | - // outbound `fetch`. Reading `.headers` on a forwarded request used | |
| 4300 | - // to change what the cell received. | |
| 4301 | - const headersJson = req._headersJson !== undefined | |
| 4302 | - ? req._headersJson | |
| 4303 | - : JSON.stringify(req.headers.__celldHeaderList); | |
| 4304 | - const r = JSON.parse(await invoke(() => { | |
| 4305 | - if (!signal) return __do_call( | |
| 4306 | - scope, dispatchName ?? null, req.url, req.method, body_, | |
| 4307 | - headersJson, bodyStreamId, | |
| 4308 | - ); | |
| 4309 | - return __awaitCancellableDoCall( | |
| 4310 | - __do_call_cancellable( | |
| 4311 | - scope, dispatchName ?? null, req.url, req.method, body_, | |
| 4312 | - headersJson, bodyStreamId, | |
| 4313 | - ), | |
| 4314 | - signal, | |
| 4315 | - ); | |
| 4316 | - })); | |
| 4317 | - const body = r.streamId !== undefined | |
| 4318 | - ? new CelldHttpBodyStream(r.streamId) | |
| 4319 | - : r.body !== undefined | |
| 4320 | - ? r.body | |
| 4321 | - : Uint8Array.from(r.bodyBytes || []); | |
| 4322 | - // An upgrade the cell answered with. The pair straddles two isolates, | |
| 4323 | - // so the client end cannot be the peer object itself -- it is a new | |
| 4324 | - // socket the host joins to the cell's on `accept()`. A caller that | |
| 4325 | - // returns this response instead of accepting keeps the direct route | |
| 4326 | - // `__wsTarget` already describes, and binds nothing. | |
| 4327 | - return new Response(body, { | |
| 4328 | - status: r.status, | |
| 4329 | - headers: r.headers, | |
| 4330 | - __wsTarget: r.wsTarget, | |
| 4331 | - webSocket: r.status === 101 && r.wsTarget | |
| 4332 | - ? new WebSocket(undefined, [], r.wsTarget) | |
| 4333 | - : undefined, | |
| 4334 | - }); | |
| 4335 | - }; | |
| 4336 | - const stub = new Proxy(target, { get: (_target, prop) => { | |
| 4337 | - if (prop === "then") return undefined; | |
| 4338 | - if (Reflect.has(_target, prop)) return Reflect.get(_target, prop); | |
| 4339 | - if (prop === "fetch") return doFetch; | |
| 4340 | - if (typeof prop !== "string") return undefined; | |
| 4341 | - if (__cell.compat.fetcherGetPutDelete && | |
| 4342 | - (prop === "get" || prop === "put" || prop === "delete")) | |
| 4343 | - return __fetcherHelper(doFetch, prop); | |
| 4344 | - // Every cell RPC goes out through the host, whichever node owns the | |
| 4345 | - // target. Same-process dispatch re-enters this isolate, where the | |
| 4346 | - // abort and exit markers revive; bytes that land elsewhere revive as | |
| 4347 | - // loud foreign stubs. | |
| 4348 | - return async (...args) => invoke( | |
| 4349 | - async () => __rpcDes(await __rpc_call( | |
| 4350 | - scope, dispatchName ?? null, prop, __rpcOut(args, true), | |
| 4351 | - )), | |
| 4352 | - ); | |
| 4353 | - }}); | |
| 4354 | - return stub; | |
| 4355 | - } | |
| 4356 | -} | |
| 4357 | -const __attachResponseRequestCancellation = ( | |
| 4358 | - response, | |
| 4359 | - requestController, | |
| 4360 | - wrapBody, | |
| 4361 | -) => { | |
| 4362 | - if (!(response instanceof Response) || | |
| 4363 | - response._bodyBytes !== null || | |
| 4364 | - response.body === null) { | |
| 4365 | - return; | |
| 4366 | - } | |
| 4367 | - const requestControllers = Array.isArray( | |
| 4368 | - response.__celldRequestControllers, | |
| 4369 | - ) | |
| 4370 | - ? response.__celldRequestControllers | |
| 4371 | - : [requestController]; | |
| 4372 | - if (requestControllers !== response.__celldRequestControllers) { | |
| 4373 | - Object.defineProperty(response, "__celldRequestControllers", { | |
| 4374 | - value: requestControllers, | |
| 4375 | - }); | |
| 4376 | - } else { | |
| 4377 | - requestControllers.push(requestController); | |
| 4378 | - } | |
| 4379 | - if (!wrapBody || response.__celldCancellationWrapped) return; | |
| 4380 | - const reader = response.body.getReader(); | |
| 4381 | - response.body = new ReadableStream({ | |
| 4382 | - async pull(controller) { | |
| 4383 | - const result = await reader.read(); | |
| 4384 | - if (result.done) controller.close(); | |
| 4385 | - else controller.enqueue(result.value); | |
| 4386 | - }, | |
| 4387 | - async cancel() { | |
| 4388 | - const reason = new Error("The client has disconnected"); | |
| 4389 | - for (const controller of requestControllers) { | |
| 4390 | - if (!controller.signal.aborted) controller.abort(reason); | |
| 4391 | - } | |
| 4392 | - try { | |
| 4393 | - await reader.cancel(reason); | |
| 4394 | - } catch {} | |
| 4395 | - }, | |
| 4396 | - }, { highWaterMark: 0 }); | |
| 4397 | - Object.defineProperty(response, "__celldCancellationWrapped", { | |
| 4398 | - value: true, | |
| 4399 | - }); | |
| 4400 | -}; | |
| 4401 | -// called on the owner node by the /__do/<scope> endpoint: run one object. | |
| 4402 | -// Returns the Response; Rust's read_response unwraps it (don't double-wrap). | |
| 4403 | -// A top-level (non-actor) request whose signal can be aborted by id, so a | |
| 4404 | -// disconnected HTTP or service-binding caller reaches the target's | |
| 4405 | -// `request.signal`. | |
| 4406 | -// A large body, or a body of unknown length, arrives as a stream id and | |
| 4407 | -// not as bytes. The handler then pulls the body off the socket as it | |
| 4408 | -// reads, so the whole body is never resident. `request.body` is a stream | |
| 4409 | -// in both cases. | |
| 4410 | -globalThis.__makeIncomingRequest = ( | |
| 4411 | - url, method, body, headersJson, streamId, | |
| 4412 | -) => __makeRequest( | |
| 4413 | - url, method, | |
| 4414 | - streamId === undefined ? body : new CelldHttpBodyStream(streamId), | |
| 4415 | - headersJson, undefined, true); | |
| 4416 | -globalThis.__dispatchTo = async ( | |
| 4417 | - scope, url, method, body, headersJson, requestId = null, bodyStreamId = null, | |
| 4418 | -) => { | |
| 4419 | - // A routed body that must not be collected crosses as a host stream id; the | |
| 4420 | - // handler here reads it in parts. A held body arrives as its bytes. | |
| 4421 | - if (bodyStreamId !== null) body = new CelldHttpBodyStream(bodyStreamId); | |
| 4422 | - // Request already allocates a default controller for an absent signal. | |
| 4423 | - // Retain that same allocation so a streamed response can report reader | |
| 4424 | - // cancellation after the handler has returned. | |
| 4425 | - const requestController = new AbortController(); | |
| 4426 | - if (requestId !== null) | |
| 4427 | - __incomingRequestSignals.set( | |
| 4428 | - String(requestId), requestController.signal); | |
| 4429 | - const actorEvent = __beginActorEvent(scope); | |
| 4430 | - try { | |
| 4431 | - const dispatch = (async () => { | |
| 4432 | - const inst = await _readyInstance(scope); | |
| 4433 | - return await __ctxRun(undefined, () => inst.fetch( | |
| 4434 | - __makeRequest( | |
| 4435 | - url, | |
| 4436 | - method, | |
| 4437 | - body, | |
| 4438 | - headersJson, | |
| 4439 | - requestController.signal, | |
| 4440 | - true, | |
| 4441 | - ))); | |
| 4442 | - })(); | |
| 4443 | - // The caller's abandonment reaches the target through | |
| 4444 | - // __do_call_cancel/__abortIncomingRequest, which aborts the fresh incoming | |
| 4445 | - // signal made above; the host dispatcher passes no caller signal here. | |
| 4446 | - const response = await dispatch; | |
| 4447 | - // Not wrapped: the host holds this response and gates it, and the caller | |
| 4448 | - // that would cancel the body reaches it through the routed channel's own | |
| 4449 | - // controller rather than this one. | |
| 4450 | - __attachResponseRequestCancellation(response, requestController, false); | |
| 4451 | - if (response instanceof Response && response.status === 101 && | |
| 4452 | - response.webSocket && !response.webSocket._target) { | |
| 4453 | - const socket = response.webSocket._peer; | |
| 4454 | - const target = { id: response.webSocket._id, scope }; | |
| 4455 | - response.webSocket._target = target; | |
| 4456 | - if (socket) { | |
| 4457 | - socket._target = target; | |
| 4458 | - if (!socket._hibernatable) | |
| 4459 | - __ws_accept_regular(socket._id, scope); | |
| 4460 | - __sockets.set(socket._id, socket); | |
| 4461 | - socket._flushPending(); | |
| 4462 | - } | |
| 4463 | - } | |
| 4464 | - return response; | |
| 4465 | - } finally { | |
| 4466 | - if (requestId !== null) | |
| 4467 | - __incomingRequestSignals.delete(String(requestId)); | |
| 4468 | - __endActorEvent(actorEvent); | |
| 4469 | - } | |
| 4470 | -}; | |
| 4471 | -const __rpcTargetMethod = async (scope, method) => { | |
| 4472 | - const inst = await _readyInstance(scope); | |
| 4473 | - if (!inst.__celldState._rpcOk) | |
| 4474 | - throw new TypeError( | |
| 4475 | - "The receiving Durable Object does not support RPC, because " + | |
| 4476 | - "its class was not declared with `extends DurableObject`. In " + | |
| 4477 | - "order to enable RPC, make sure your class extends the " + | |
| 4478 | - "special class `DurableObject`, which can be imported from " + | |
| 4479 | - "the module \"cloudflare:workers\"."); | |
| 4480 | - const fn = inst[method]; | |
| 4481 | - if (typeof fn !== "function") | |
| 4482 | - throw new TypeError(method + " is not a function"); | |
| 4483 | - return [inst, fn]; | |
| 4484 | -}; | |
| 4485 | -// The byte path always lifts stub-able values into the reply: the | |
| 4486 | -// markers carry the isolate token, so they revive only back in this | |
| 4487 | -// isolate (same-process routed dispatch re-enters it) and fail loudly | |
| 4488 | -// on use anywhere else. Callee exceptions cross in | |
| 4489 | -// the error envelope on every flavor. | |
| 4490 | -globalThis.__dispatchRpc = async (scope, method, args) => { | |
| 4491 | - const actorEvent = __beginActorEvent(scope); | |
| 4492 | - try { | |
| 4493 | - // A string is the legacy JSON flavor; bytes are V8 structured clone. | |
| 4494 | - // Answer in kind. | |
| 4495 | - if (typeof args === "string") { | |
| 4496 | - const [inst, fn] = await __rpcTargetMethod(scope, method); | |
| 4497 | - const result = await fn.apply(inst, JSON.parse(args)); | |
| 4498 | - return JSON.stringify(result) ?? "null"; | |
| 4499 | - } | |
| 4500 | - return await __ctxRun(undefined, () => (async () => { | |
| 4501 | - const decoded = __rpcDesArgs(args); | |
| 4502 | - try { | |
| 4503 | - return await __rpcRun(async () => { | |
| 4504 | - // A broken actor (JS-flavored ctx.abort) rejects every | |
| 4505 | - // later call with the reason. One gated field read. | |
| 4506 | - if (__brokenActors.size !== 0) { | |
| 4507 | - const broken = __brokenActors.get(scope); | |
| 4508 | - if (broken !== undefined) throw broken; | |
| 4509 | - } | |
| 4510 | - const [inst, fn] = await __rpcTargetMethod(scope, method); | |
| 4511 | - return fn.apply(inst, decoded.args); | |
| 4512 | - }, true); | |
| 4513 | - } finally { | |
| 4514 | - for (const handle of decoded.received) __disposeStub(handle); | |
| 4515 | - } | |
| 4516 | - })()); | |
| 4517 | - } finally { | |
| 4518 | - __endActorEvent(actorEvent); | |
| 4519 | - } | |
| 4520 | -}; | |
| 4521 | -// Invoke a method on a named WorkerEntrypoint. Instances are cached per | |
| 4522 | -// entrypoint: the class is stateless across calls the way a Worker is, | |
| 4523 | -// so re-constructing per call would only add allocation. | |
| 4524 | -const __entrypointInstances = new Map(); | |
| 4525 | -const __entrypointInstance = (name) => { | |
| 4526 | - const cls = __cell.entrypoints[name]; | |
| 4527 | - if (typeof cls !== "function") { | |
| 4528 | - // Workerd getExportedHandler(): distinguish a Durable Object class | |
| 4529 | - // misused as a stateless entrypoint from a name that resolves to | |
| 4530 | - // nothing. Error path only; both lookups are O(1). | |
| 4531 | - if (__cell.classes[name] !== undefined || __cell.doExports[name]) | |
| 4532 | - throw new TypeError( | |
| 4533 | - `The entrypoint name ${name} refers to a Durable Object ` + | |
| 4534 | - "class, but the incoming request is trying to invoke it as " + | |
| 4535 | - "a stateless worker."); | |
| 4536 | - throw new TypeError( | |
| 4537 | - `The entrypoint name ${name} was not found in this worker. ` + | |
| 4538 | - "Ensure the worker exports an entrypoint with that name."); | |
| 4539 | - } | |
| 4540 | - let inst = __entrypointInstances.get(name); | |
| 4541 | - if (inst === undefined) { | |
| 4542 | - // End the construction event immediately: ctx.waitUntil registers | |
| 4543 | - // into whichever event is current at call time, so leaving this | |
| 4544 | - // event on the stack would swallow every later registration in the | |
| 4545 | - // isolate. | |
| 4546 | - const ctx = __beginEvent(); | |
| 4547 | - try { | |
| 4548 | - inst = new cls(ctx, __cell.env); | |
| 4549 | - } finally { | |
| 4550 | - __endEvent(); | |
| 4551 | - } | |
| 4552 | - __entrypointInstances.set(name, inst); | |
| 4553 | - } | |
| 4554 | - return inst; | |
| 4555 | -}; | |
| 4556 | -// `env.NAME.fetch()` where NAME is bound with `entrypoint = "..."` goes | |
| 4557 | -// to that class's fetch, not the module's default export. A plain | |
| 4558 | -// object export (Workerd's non-class entrypoint) dispatches its | |
| 4559 | -// handler functions as fn(arg, env, ctx). | |
| 4560 | -const __dispatchEntrypointMethod = async (name, method, arg) => { | |
| 4561 | - const handler = __cell.objectEntrypoints[name]; | |
| 4562 | - if (handler !== undefined) { | |
| 4563 | - if (typeof handler[method] !== "function") | |
| 4564 | - throw new TypeError( | |
| 4565 | - `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); | |
| 4566 | - const ctx = __beginEvent(); | |
| 4567 | - try { | |
| 4568 | - return await __ctxRun(undefined, | |
| 4569 | - () => handler[method](arg, __cell.env, ctx)); | |
| 4570 | - } finally { | |
| 4571 | - __endEvent(); | |
| 4572 | - } | |
| 4573 | - } | |
| 4574 | - // A class entrypoint's methods get env and ctx from its constructor, | |
| 4575 | - // not as arguments. | |
| 4576 | - const inst = __entrypointInstance(name); | |
| 4577 | - if (typeof inst[method] !== "function") | |
| 4578 | - throw new TypeError( | |
| 4579 | - `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); | |
| 4580 | - return await __ctxRun(undefined, () => inst[method](arg)); | |
| 4581 | -}; | |
| 4582 | -// Invoke a handler inside the event frame that the host already opened. A | |
| 4583 | -// Queue dispatch uses this form because its host driver must receive and keep | |
| 4584 | -// driving the handler's waitUntil aggregate after the settlement is returned. | |
| 4585 | -const __dispatchEntrypointMethodInCurrentEvent = async (name, method, arg) => { | |
| 4586 | - const handler = __cell.objectEntrypoints[name]; | |
| 4587 | - if (handler !== undefined) { | |
| 4588 | - if (typeof handler[method] !== "function") | |
| 4589 | - throw new TypeError( | |
| 4590 | - `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); | |
| 4591 | - return await __ctxRun(undefined, | |
| 4592 | - () => handler[method](arg, __cell.env, __entrypointContext())); | |
| 4593 | - } | |
| 4594 | - const inst = __entrypointInstance(name); | |
| 4595 | - if (typeof inst[method] !== "function") | |
| 4596 | - throw new TypeError( | |
| 4597 | - `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); | |
| 4598 | - return await __ctxRun(undefined, () => inst[method](arg)); | |
| 4599 | -}; | |
| 4600 | -globalThis.__dispatchEntrypointFetch = (name, request) => | |
| 4601 | - __dispatchEntrypointMethod(name, "fetch", request); | |
| 4602 | -globalThis.__dispatchEntrypointScheduled = (name, ctrl) => | |
| 4603 | - __dispatchEntrypointMethod(name, "scheduled", ctrl); | |
| 4604 | -// A queue batch owns mutable settlement state only while its handler runs. | |
| 4605 | -// Keeping a batch alive after dispatch must not keep authority to settle its | |
| 4606 | -// lease, because that lease can have expired and been handed out again. | |
| 4607 | -globalThis.__dispatchEntrypointQueue = async (name, incoming) => { | |
| 4608 | - let active = true; | |
| 4609 | - let ackAll = false; | |
| 4610 | - const explicitAcks = new Set(); | |
| 4611 | - const retries = new Map(); | |
| 4612 | - const retryBatch = { retry: false, delaySeconds: undefined }; | |
| 4613 | - const checkActive = () => { | |
| 4614 | - if (!active) | |
| 4615 | - throw new Error("Queue event methods cannot be called after the handler returns."); | |
| 4616 | - }; | |
| 4617 | - const retryDelay = (options) => { | |
| 4618 | - const value = options?.delaySeconds; | |
| 4619 | - if (value === undefined) return undefined; | |
| 4620 | - if (!Number.isInteger(value) || value < -0x8000_0000 || value > 0x7fff_ffff) | |
| 4621 | - throw new TypeError("delaySeconds must be a 32-bit integer"); | |
| 4622 | - return value; | |
| 4623 | - }; | |
| 4624 | - const decode = (message) => { | |
| 4625 | - switch (message.contentType) { | |
| 4626 | - case "text": return new TextDecoder().decode(message.body); | |
| 4627 | - case "bytes": return message.body; | |
| 4628 | - case "json": return JSON.parse(new TextDecoder().decode(message.body)); | |
| 4629 | - case "v8": return __sc_decode(message.body); | |
| 4630 | - default: throw new TypeError(`Unknown queue content type: ${message.contentType}`); | |
| 4631 | - } | |
| 4632 | - }; | |
| 4633 | - const messages = incoming.messages.map((message) => ({ | |
| 4634 | - id: message.id, | |
| 4635 | - timestamp: new Date(message.timestamp), | |
| 4636 | - body: decode(message), | |
| 4637 | - attempts: message.attempts, | |
| 4638 | - ack() { | |
| 4639 | - checkActive(); | |
| 4640 | - if (ackAll || retryBatch.retry || retries.has(message.id)) return; | |
| 4641 | - explicitAcks.add(message.id); | |
| 4642 | - }, | |
| 4643 | - retry(options) { | |
| 4644 | - checkActive(); | |
| 4645 | - if (ackAll || explicitAcks.has(message.id)) return; | |
| 4646 | - const delaySeconds = retryDelay(options); | |
| 4647 | - if (delaySeconds !== undefined || !retries.has(message.id)) | |
| 4648 | - retries.set(message.id, delaySeconds); | |
| 4649 | - }, | |
| 4650 | - })); | |
| 4651 | - const oldest = incoming.metrics.oldestMessageTimestamp; | |
| 4652 | - const batch = { | |
| 4653 | - queue: incoming.queue, | |
| 4654 | - messages, | |
| 4655 | - metadata: { | |
| 4656 | - metrics: { | |
| 4657 | - backlogCount: incoming.metrics.backlogCount, | |
| 4658 | - backlogBytes: incoming.metrics.backlogBytes, | |
| 4659 | - oldestMessageTimestamp: oldest === undefined ? undefined : new Date(oldest), | |
| 4660 | - }, | |
| 4661 | - }, | |
| 4662 | - ackAll() { | |
| 4663 | - checkActive(); | |
| 4664 | - if (!retryBatch.retry) ackAll = true; | |
| 4665 | - }, | |
| 4666 | - retryAll(options) { | |
| 4667 | - checkActive(); | |
| 4668 | - if (ackAll) return; | |
| 4669 | - retryBatch.retry = true; | |
| 4670 | - const delaySeconds = retryDelay(options); | |
| 4671 | - if (delaySeconds !== undefined) retryBatch.delaySeconds = delaySeconds; | |
| 4672 | - }, | |
| 4673 | - }; | |
| 4674 | - let outcome = "ok"; | |
| 4675 | - let errorText; | |
| 4676 | - try { | |
| 4677 | - await __dispatchEntrypointMethodInCurrentEvent(name, "queue", batch); | |
| 4678 | - } catch (error) { | |
| 4679 | - // A handler exception retries the batch but keeps explicit acks that the | |
| 4680 | - // handler made before it threw. The caller needs both facts together. | |
| 4681 | - outcome = "exception"; | |
| 4682 | - try { | |
| 4683 | - errorText = String(error); | |
| 4684 | - } catch { | |
| 4685 | - errorText = "queue handler rejected"; | |
| 4686 | - } | |
| 4687 | - } finally { | |
| 4688 | - active = false; | |
| 4689 | - } | |
| 4690 | - return { | |
| 4691 | - outcome, | |
| 4692 | - error: errorText, | |
| 4693 | - ackAll, | |
| 4694 | - retryBatch, | |
| 4695 | - explicitAcks: [...explicitAcks], | |
| 4696 | - retryMessages: [...retries].map(([msgId, delaySeconds]) => ({ | |
| 4697 | - msgId, | |
| 4698 | - delaySeconds, | |
| 4699 | - })), | |
| 4700 | - }; | |
| 4701 | -}; | |
| 4702 | -// Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class | |
| 4703 | -// handler method is called as fn(arg, env, ctx), the client must send | |
| 4704 | -// exactly one argument, and the handler must not declare more than | |
| 4705 | -// (arg, env, ctx). The messages are Workerd's, verbatim. | |
| 4706 | -const __callObjectEntrypoint = (handler, method, args) => { | |
| 4707 | - const fn = handler[method]; | |
| 4708 | - if (typeof fn !== "function") | |
| 4709 | - throw new TypeError( | |
| 4710 | - 'The RPC receiver does not implement the method "' + method + | |
| 4711 | - '".'); | |
| 4712 | - if (fn.length > 3) | |
| 4713 | - throw new TypeError( | |
| 4714 | - 'Cannot call handler function "' + method + '" over RPC ' + | |
| 4715 | - "because it has the wrong number of arguments. A simple " + | |
| 4716 | - "function handler can only be called over RPC if it has " + | |
| 4717 | - "exactly the arguments (arg, env, ctx), where only the first " + | |
| 4718 | - "argument comes from the client. To support multi-argument " + | |
| 4719 | - "RPC functions, use class-based syntax (extending " + | |
| 4720 | - "WorkerEntrypoint) instead."); | |
| 4721 | - if (args.length !== 1) | |
| 4722 | - throw new TypeError( | |
| 4723 | - 'Attempted to call RPC function "' + method + '" with the ' + | |
| 4724 | - "wrong number of arguments. When calling a top-level handler " + | |
| 4725 | - "function that is not declared as part of a class, you must " + | |
| 4726 | - "always send exactly one argument. In order to support " + | |
| 4727 | - "variable numbers of arguments, the server must use " + | |
| 4728 | - "class-based syntax (extending WorkerEntrypoint) instead."); | |
| 4729 | - const ctx = { | |
| 4730 | - waitUntil: globalThis.__registerWaitUntil, | |
| 4731 | - passThroughOnException() {}, | |
| 4732 | - abort: __ctxAbortCurrent, | |
| 4733 | - props: __defaultProps, | |
| 4734 | - get exports() { return __ctxExports(); }, | |
| 4735 | - }; | |
| 4736 | - return fn.call(handler, args[0], __cell.env, ctx); | |
| 4737 | -}; | |
| 4738 | -// One entrypoint op (a call, or a property GET when argsSc is | |
| 4739 | -// null), inside a fresh request context — the callee owns stubs | |
| 4740 | -// revived from its params, and stubs it mints belong to it. | |
| 4741 | -const __entrypointOp = (name, path, argsSc, local, makeInst) => { | |
| 4742 | - const id = __nextCtxId++; | |
| 4743 | - return __ctxRun(id, () => (async () => { | |
| 4744 | - const decoded = argsSc === null ? null : __rpcDesArgs(argsSc); | |
| 4745 | - let drain = null; | |
| 4746 | - try { | |
| 4747 | - const reply = await __rpcRun(async () => { | |
| 4748 | - // The handler's synchronous part runs inside its own event so | |
| 4749 | - // ctx.waitUntil and the imported waitUntil have a target. The | |
| 4750 | - // event pops before the first await — the event stack is | |
| 4751 | - // strictly LIFO and an event held across an await would be | |
| 4752 | - // popped by whichever event settles next — and its registered | |
| 4753 | - // work drains before a plain reply (below). | |
| 4754 | - __beginEvent(); | |
| 4755 | - let result; | |
| 4756 | - try { | |
| 4757 | - const handler = __cell.objectEntrypoints[name]; | |
| 4758 | - if (handler !== undefined && makeInst === undefined) { | |
| 4759 | - // Simple-handler entrypoints expose single-method calls | |
| 4760 | - // only; property GETs and deeper paths are refused. | |
| 4761 | - if (argsSc === null || path.length !== 1) | |
| 4762 | - throw __rpcNoSuchMethod(path[0]); | |
| 4763 | - result = __callObjectEntrypoint( | |
| 4764 | - handler, path[0], decoded.args); | |
| 4765 | - } else { | |
| 4766 | - const inst = makeInst === undefined | |
| 4767 | - ? __entrypointInstance(name) : makeInst(); | |
| 4768 | - result = __rpcWalk(inst, path, | |
| 4769 | - decoded === null ? null : decoded.args, true); | |
| 4770 | - } | |
| 4771 | - } finally { | |
| 4772 | - drain = __endEvent(); | |
| 4773 | - } | |
| 4774 | - return await result; | |
| 4775 | - }, local); | |
| 4776 | - // Registered work drains before a plain reply. A | |
| 4777 | - // capability-bearing reply (tag 1) must not wait: a returned | |
| 4778 | - // stream's chunks may be produced by that very work, which | |
| 4779 | - // cannot finish until the caller pulls (returnReadableStream's | |
| 4780 | - // waitUntil writer would deadlock behind its own reply). | |
| 4781 | - if (reply[0] !== 1 && drain !== null) await drain; | |
| 4782 | - // ctx.abort() during the call supersedes its result; the raw | |
| 4783 | - // reason rejects the caller (same isolate — identity holds). | |
| 4784 | - if (__abortedCtxs.size !== 0) { | |
| 4785 | - const reason = __abortedCtxs.get(id); | |
| 4786 | - if (reason !== undefined) throw reason; | |
| 4787 | - } | |
| 4788 | - // A reply that exports no stubs (tag 0xff plain, tag 0 error) | |
| 4789 | - // leaves nothing rooting this context: tear it down now, so a | |
| 4790 | - // dup() the callee leaked reaches its disposal callback | |
| 4791 | - // promptly (Workerd tears the IoContext down at call end | |
| 4792 | - // unless returned capabilities hold it open). | |
| 4793 | - if (reply[0] !== 1) __ctxEnd(id); | |
| 4794 | - return reply; | |
| 4795 | - } finally { | |
| 4796 | - if (decoded !== null) | |
| 4797 | - for (const handle of decoded.received) __disposeStub(handle); | |
| 4798 | - } | |
| 4799 | -})()); | |
| 4800 | -}; | |
| 4801 | -// Cross-isolate and host callers still pass a single method name. | |
| 4802 | -globalThis.__dispatchEntrypointRpc = | |
| 4803 | - (name, path, argsSc, local = false) => __entrypointOp( | |
| 4804 | - name, typeof path === "string" ? [path] : path, argsSc, local, | |
| 4805 | - undefined); | |
| 4806 | -// WebSocket: the host holds the socket; these deliver events into the DO. | |
| 4807 | -// `ws` is a lightweight stub whose send/close route back to the host task | |
| 4808 | -// by wsId — so the isolate can be hibernated between messages. | |
| 4809 | -globalThis.__wsStub = (wsId) => ({ | |
| 4810 | - _hibernatable: true, | |
| 4811 | - send: (data) => { | |
| 4812 | - if (data instanceof ArrayBuffer) | |
| 4813 | - __ws_send_binary(wsId, new Uint8Array(data)); | |
| 4814 | - else if (ArrayBuffer.isView(data)) | |
| 4815 | - __ws_send_binary(wsId, | |
| 4816 | - new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); | |
| 4817 | - else | |
| 4818 | - __ws_send(wsId, String(data)); | |
| 4819 | - }, | |
| 4820 | - close: (code = 1000, reason = "") => __ws_close(wsId, code, reason), | |
| 4821 | -}); | |
| 4822 | -globalThis.__wsOpen = async (scope, wsId, protocol) => { | |
| 4823 | - const actorEvent = __beginActorEvent(scope); | |
| 4824 | - try { | |
| 4825 | - const inst = await _readyInstance(scope); | |
| 4826 | - const socket = inst.__celldState._socket(wsId); | |
| 4827 | - if (socket.readyState !== WebSocket.READY_STATE_CONNECTING) return; | |
| 4828 | - socket.protocol = protocol; | |
| 4829 | - socket.readyState = WebSocket.READY_STATE_OPEN; | |
| 4830 | - socket.dispatchEvent(new Event("open")); | |
| 4831 | - } finally { | |
| 4832 | - __endActorEvent(actorEvent); | |
| 4833 | - } | |
| 4834 | -}; | |
| 4835 | -globalThis.__wsMessage = async (scope, wsId, msg) => { | |
| 4836 | - const actorEvent = __beginActorEvent(scope); | |
| 4837 | - try { | |
| 4838 | - const inst = await _readyInstance(scope); | |
| 4839 | - const socket = inst.__celldState._socket(wsId); | |
| 4840 | - if (!socket._hibernatable && typeof socket._dispatchMessage === "function") | |
| 4841 | - socket._dispatchMessage(msg); | |
| 4842 | - else if (typeof inst.webSocketMessage === "function") | |
| 4843 | - await inst.webSocketMessage(socket, msg); | |
| 4844 | - } finally { | |
| 4845 | - __endActorEvent(actorEvent); | |
| 4846 | - } | |
| 4847 | -}; | |
| 4848 | -globalThis.__wsBinary = async (scope, wsId, data) => { | |
| 4849 | - const actorEvent = __beginActorEvent(scope); | |
| 4850 | - try { | |
| 4851 | - const inst = await _readyInstance(scope); | |
| 4852 | - const socket = inst.__celldState._socket(wsId); | |
| 4853 | - const bytes = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); | |
| 4854 | - if (!socket._hibernatable && typeof socket._dispatchMessage === "function") | |
| 4855 | - socket._dispatchMessage(bytes); | |
| 4856 | - else if (typeof inst.webSocketMessage === "function") | |
| 4857 | - await inst.webSocketMessage(socket, bytes); | |
| 4858 | - } finally { | |
| 4859 | - __endActorEvent(actorEvent); | |
| 4860 | - } | |
| 4861 | -}; | |
| 4862 | -globalThis.__wsClosed = async (scope, wsId, code, reason, wasClean) => { | |
| 4863 | - const actorEvent = __beginActorEvent(scope); | |
| 4864 | - try { | |
| 4865 | - const inst = await _readyInstance(scope); | |
| 4866 | - const socket = inst.__celldState._socket(wsId); | |
| 4867 | - if (!socket._hibernatable && typeof socket._dispatchClose === "function") | |
| 4868 | - socket._dispatchClose(code, reason, wasClean); | |
| 4869 | - else if (!wasClean && typeof inst.webSocketError === "function") | |
| 4870 | - // A hibernatable socket reports an abnormal closure through | |
| 4871 | - // webSocketError, which celld listed as a handler name and never | |
| 4872 | - // called. | |
| 4873 | - await inst.webSocketError( | |
| 4874 | - socket, | |
| 4875 | - new Error(reason ? `WebSocket closed abnormally: ${reason}` : "WebSocket closed abnormally"), | |
| 4876 | - ); | |
| 4877 | - else if (typeof inst.webSocketClose === "function") | |
| 4878 | - await inst.webSocketClose(socket, code, reason, wasClean); | |
| 4879 | - } finally { | |
| 4880 | - __endActorEvent(actorEvent); | |
| 4881 | - } | |
| 4882 | -}; | |
| 4883 | -// called by celld's scheduler when an alarm is due. Returns a promise. | |
| 4884 | -globalThis.__fireAlarm = async (scope, scheduledTime, retryCount) => { | |
| 4885 | - const actorEvent = __beginActorEvent(scope); | |
| 4886 | - try { | |
| 4887 | - const inst = await _readyInstance(scope); | |
| 4888 | - if (typeof inst.alarm !== "function") return; | |
| 4889 | - await inst.alarm({ scheduledTime, retryCount, isRetry: retryCount > 0 }); | |
| 4890 | - } finally { | |
| 4891 | - __endActorEvent(actorEvent); | |
| 4892 | - } | |
| 4893 | -}; | |
| 4894 | -// The reserved cron cell. It is not a user class: celld registers it under | |
| 4895 | -// `.cron` for every deployment that declares `triggers.crons`, and one cell | |
| 4896 | -// per script carries that script's whole schedule. Ownership CAS on that one | |
| 4897 | -// name is what makes a cron trigger fire once per fleet rather than once per | |
| 4898 | -// node -- the same arbiter an alarm already relies on, with nothing added. | |
| 4899 | -// | |
| 4900 | -// The schedule itself is never stored here. `__cell.crons` comes from the | |
| 4901 | -// deployment the cell is running under, so changing a cron expression takes | |
| 4902 | -// effect on the next activation and needs no migration of an armed alarm. | |
| 4903 | -class CelldCronSchedule { | |
| 4904 | - constructor(state) { | |
| 4905 | - this._state = state; | |
| 4906 | - // Failures within one occurrence. Held in memory on purpose: losing the | |
| 4907 | - // count to an eviction only makes the next retry sooner, and every retry | |
| 4908 | - // is capped at the next occurrence anyway, so it need not be durable. | |
| 4909 | - this._retry = 0; | |
| 4910 | - // What a pending retry owes: the occurrence, the expressions of it that | |
| 4911 | - // failed, and the deadline the retry was armed for. A retry deadline is a | |
| 4912 | - // backoff instant and not an occurrence, so nothing about it can be | |
| 4913 | - // recovered from the deadline itself -- without this record the wake | |
| 4914 | - // matches no expression, runs nothing, and drops the failed tick in | |
| 4915 | - // silence. Held in memory beside `_retry` and for the same reason: an | |
| 4916 | - // eviction costs the retry, never the next occurrence. | |
| 4917 | - this._owed = null; | |
| 4918 | - } | |
| 4919 | - // celld calls this once per node after a deployment loads, because a cron | |
| 4920 | - // cell has no client to wake it. Arming is idempotent -- the same schedule | |
| 4921 | - // and the same clock give the same answer -- so it does not matter which | |
| 4922 | - // node wins the cell. | |
| 4923 | - async fetch() { | |
| 4924 | - // A pending retry is a deadline this cell already owes, and re-arming | |
| 4925 | - // would move it to the next occurrence and lose the tick it owes with it. | |
| 4926 | - if (this._owed !== null) return new Response(null, { status: 204 }); | |
| 4927 | - const armed = await this._state.storage.getAlarm(); | |
| 4928 | - // An alarm already due is a tick that is late, not one that is wrong. | |
| 4929 | - // Leaving it alone is what makes a fleet that was down fire the missed | |
| 4930 | - // occurrence once, instead of skipping it by re-arming into the future. | |
| 4931 | - if (armed === null || armed > Date.now()) await this._arm(null, [], false); | |
| 4932 | - return new Response(null, { status: 204 }); | |
| 4933 | - } | |
| 4934 | - async alarm(info) { | |
| 4935 | - const crons = __cell.crons || []; | |
| 4936 | - // A retry wake carries the backoff instant as its deadline, so what to run | |
| 4937 | - // and what time to report both come from the record the failure left. Only | |
| 4938 | - // a deadline that is not a retry is an occurrence to match against. | |
| 4939 | - const owed = this._owed !== null && this._owed.armedFor === info.scheduledTime | |
| 4940 | - ? this._owed | |
| 4941 | - : null; | |
| 4942 | - const occurrence = owed === null ? info.scheduledTime : owed.at; | |
| 4943 | - // One deadline can belong to several expressions, and each is its own | |
| 4944 | - // invocation with its own controller.cron, as on Cloudflare. A retry | |
| 4945 | - // repeats only the expressions that failed, because the ones that | |
| 4946 | - // succeeded already ran for this occurrence. | |
| 4947 | - const due = owed === null | |
| 4948 | - ? __cron_plan(crons, info.scheduledTime, Date.now(), 0, false).matching | |
| 4949 | - : owed.indices; | |
| 4950 | - const failed = []; | |
| 4951 | - for (const index of due) { | |
| 4952 | - let noRetry = false; | |
| 4953 | - const controller = { | |
| 4954 | - // The occurrence, never the instant this attempt started, so a late | |
| 4955 | - // run and a retry both report the minute they were scheduled for. | |
| 4956 | - scheduledTime: occurrence, | |
| 4957 | - cron: crons[index], | |
| 4958 | - noRetry() { noRetry = true; }, | |
| 4959 | - }; | |
| 4960 | - const ctx = __beginEvent(); | |
| 4961 | - try { | |
| 4962 | - if (typeof __cell.selfScheduled !== "function") | |
| 4963 | - throw new Error( | |
| 4964 | - "a cron trigger needs the Worker to export a `scheduled` handler"); | |
| 4965 | - await __cell.selfScheduled(controller, __cell.env, ctx); | |
| 4966 | - } catch (error) { | |
| 4967 | - // Swallowed on purpose: this handler owns the re-arm below, so | |
| 4968 | - // throwing would hand the deadline to the generic alarm retry and | |
| 4969 | - // lose the next occurrence with it. | |
| 4970 | - console.error( | |
| 4971 | - `scheduled handler for cron ${JSON.stringify(crons[index])} failed:`, | |
| 4972 | - error); | |
| 4973 | - if (!noRetry) failed.push(index); | |
| 4974 | - } finally { | |
| 4975 | - __endEvent(); | |
| 4976 | - } | |
| 4977 | - } | |
| 4978 | - await this._arm(occurrence, failed, owed !== null); | |
| 4979 | - } | |
| 4980 | - // `occurrence` is the tick just handled, or null when the cell is only | |
| 4981 | - // arming, `failed` holds the expressions of it still owed, and `retried` | |
| 4982 | - // says the deadline just handled was a backoff rather than an occurrence. | |
| 4983 | - async _arm(occurrence, failed, retried) { | |
| 4984 | - const crons = __cell.crons || []; | |
| 4985 | - // The count is failures within one occurrence, so a fresh occurrence | |
| 4986 | - // starts at one however the last one ended. Carrying it across would | |
| 4987 | - // spend `alarm_retry`'s ceiling once and leave every later occurrence | |
| 4988 | - // with no retry at all, which is a budget for the schedule and not for | |
| 4989 | - // the tick. | |
| 4990 | - this._retry = failed.length ? (retried ? this._retry + 1 : 1) : 0; | |
| 4991 | - // A negative first argument means "arming only, nothing fired". | |
| 4992 | - const plan = __cron_plan(crons, -1, Date.now(), this._retry, failed.length > 0); | |
| 4993 | - // The next occurrence beats the backoff whenever it is sooner, and it then | |
| 4994 | - // cancels the retry rather than queueing behind it, so the record the | |
| 4995 | - // retry needed goes when the retry does. | |
| 4996 | - this._owed = plan.armIsRetry | |
| 4997 | - ? { at: occurrence, indices: failed, armedFor: plan.armAt } | |
| 4998 | - : null; | |
| 4999 | - // No expression matches again and nothing is owed: the deployment dropped | |
| 5000 | - // its crons, so the cell retires rather than waking forever. | |
| 5001 | - if (plan.armAt === null) await this._state.storage.deleteAlarm(); | |
| 5002 | - else await this._state.storage.setAlarm(plan.armAt); | |
| 5003 | - } | |
| 5004 | -} | |
| 5005 | -globalThis.__cell = { | |
| 5006 | - entrypoints: {}, | |
| 5007 | - objectEntrypoints: {}, | |
| 5008 | - doExports: {}, | |
| 5009 | - classes: { ".cron": CelldCronSchedule }, | |
| 5010 | - crons: [], | |
| 5011 | - workflows: {}, | |
| 5012 | - instances: {}, | |
| 5013 | - facetConfigs: {}, | |
| 5014 | - env: {}, | |
| 5015 | - idNames: {}, | |
| 5016 | - namespaceKeys: {}, | |
| 5017 | - node: "", | |
| 5018 | - deleteAllDeletesAlarm: false, | |
| 5019 | - compat: { jsRpc: false, fetcherGetPutDelete: false, queueJsonMessages: false }, | |
| 5020 | - makeNamespace, | |
| 5021 | - release: __cellRelease, | |
| 5022 | -}; | |
| 5023 | -// ---- KV ------------------------------------------------------------------ | |
| 5024 | -// A KV namespace is a cell of a runtime-supplied Durable Object class, so it | |
| 5025 | -// inherits ownership, fencing, LTX replication and durable acknowledgement | |
| 5026 | -// from the cell it already is. This half is the server; `__makeKvNamespace` | |
| 5027 | -// below is the client the binding hands to a Worker. | |
| 5028 | -// | |
| 5029 | -// Reads here are strongly consistent and the published contract is upstream's: | |
| 5030 | -// a value can be up to 60 seconds old. That gap is deliberate. A node-local | |
| 5031 | -// read cache is the obvious next optimisation and it would make reads | |
| 5032 | -// genuinely stale, and a freshness promise made now could not be withdrawn | |
| 5033 | -// then. Implement strong, promise weak. | |
| 5034 | -// | |
| 5035 | -// Storage is ordinary cell SQL rather than the KV surface, because a namespace | |
| 5036 | -// is read by ordered prefix scan and `list` is the operation that decides the | |
| 5037 | -// schema. `celld_logic::kv` owns every decision about a key, a deadline or a | |
| 5038 | -// limit; nothing here re-derives one. | |
| 5039 | - | |
| 5040 | -// Run one bounded reclamation transaction. A cell supplies only its ordered | |
| 5041 | -// candidate query and its per-row transition, so KV expiry and Queue retention | |
| 5042 | -// share the turn bound and the transaction shape without pretending their SQL | |
| 5043 | -// state machines are the same. | |
| 5044 | -const __cellSweepBatch = (storage, select, reclaim, limit) => { | |
| 5045 | - let processed = 0; | |
| 5046 | - storage.transactionSync(() => { | |
| 5047 | - const rows = select(limit); | |
| 5048 | - if (rows.length > limit) throw new Error("a cell sweep exceeded its row bound"); | |
| 5049 | - for (const row of rows) { | |
| 5050 | - reclaim(row); | |
| 5051 | - processed += 1; | |
| 5052 | - } | |
| 5053 | - }); | |
| 5054 | - return processed; | |
| 5055 | -}; | |
| 5056 | - | |
| 5057 | -const __KV_TABLE = "__kv"; | |
| 5058 | -const __KV_META_TABLE = "__kv_meta"; | |
| 5059 | - | |
| 5060 | -// Upstream's four content types. The wire form is what `get` returns for | |
| 5061 | -// `type: "text"`; the binding converts from there, so the cell stores bytes | |
| 5062 | -// and a tag and never a parsed value. | |
| 5063 | -const __kvError = (message) => new Error("KV_ERROR: " + String(message)); | |
| 5064 | - | |
| 5065 | -// One op for the whole large-value path, following `__d1_run`. Bytes cross as | |
| 5066 | -// a typed view in both directions. Encoding a 25 MiB value as a JSON number | |
| 5067 | -// array creates millions of heap objects and can crash an otherwise valid put. | |
| 5068 | -const __kvBlob = async (request, value) => { | |
| 5069 | - const reply = await __kv_blob(JSON.stringify(request), value); | |
| 5070 | - return reply instanceof Uint8Array | |
| 5071 | - ? { found: true, value: reply } | |
| 5072 | - : JSON.parse(reply); | |
| 5073 | -}; | |
| 5074 | - | |
| 5075 | -// The authenticated operator route still uses JSON for its control envelope. | |
| 5076 | -// A byte array is acceptable for an inline value, but a 25 MiB array creates | |
| 5077 | -// 25 million JavaScript numbers and exhausts the isolate. The raw base64 ops | |
| 5078 | -// accept typed views for this internal wire form; the public atob() and btoa() | |
| 5079 | -// wrappers keep their standard string-only behaviour. | |
| 5080 | -const __kvOperatorValue = (value) => { | |
| 5081 | - const bytes = value instanceof Uint8Array ? value : new Uint8Array(value); | |
| 5082 | - return bytes.byteLength > __kvLimits().maxInlineValueBytes | |
| 5083 | - ? { value: $$btoa(bytes), valueEncoding: "base64" } | |
| 5084 | - : { value: [...bytes] }; | |
| 5085 | -}; | |
| 5086 | - | |
| 5087 | -// Content addressing, so the same value written twice in one ownership epoch | |
| 5088 | -// stores once and a retry after an uncertain failure costs nothing. A later | |
| 5089 | -// epoch deliberately uses a different object. SHA-256 makes an accidental | |
| 5090 | -// collision infeasible. The host adds the active cell scope and epoch to the | |
| 5091 | -// object key, because one activation cannot prove another activation's live | |
| 5092 | -// set and therefore cannot safely collect from a shared digest prefix. | |
| 5093 | -const __kvDigest = async (bytes) => { | |
| 5094 | - const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); | |
| 5095 | - let out = ""; | |
| 5096 | - for (const byte of hash) out += byte.toString(16).padStart(2, "0"); | |
| 5097 | - return out; | |
| 5098 | -}; | |
| 5099 | - | |
| 5100 | -class __KvNamespaceCell { | |
| 5101 | - constructor(ctx) { | |
| 5102 | - this.ctx = ctx; | |
| 5103 | - this._ready = false; | |
| 5104 | - // Blob references written to the bucket whose row has not committed yet. A sweep | |
| 5105 | - // must spare these, or it collects bytes a put is about to reference. | |
| 5106 | - this._pending = new Set(); | |
| 5107 | - // Blob writes and the mark-and-sweep protocol share one per-cell queue. | |
| 5108 | - // The pending set is live state, not a snapshot that stays valid across an | |
| 5109 | - // await, so collection cannot overlap a put from its announcement through | |
| 5110 | - // its row commit. Other cells and ordinary reads stay independent. | |
| 5111 | - this._blobProtocolTail = Promise.resolve(); | |
| 5112 | - } | |
| 5113 | - | |
| 5114 | - async _withBlobProtocol(operation) { | |
| 5115 | - const previous = this._blobProtocolTail; | |
| 5116 | - let release; | |
| 5117 | - this._blobProtocolTail = new Promise((resolve) => { | |
| 5118 | - release = resolve; | |
| 5119 | - }); | |
| 5120 | - await previous; | |
| 5121 | - try { | |
| 5122 | - return await operation(); | |
| 5123 | - } finally { | |
| 5124 | - release(); | |
| 5125 | - } | |
| 5126 | - } | |
| 5127 | - | |
| 5128 | - // Schedule collection before a blob can leave the process or a row can drop | |
| 5129 | - // its reference. `setAlarm()` writes cell state, and the following bucket | |
| 5130 | - // egress waits on that write's output gate. A crash can therefore leave an | |
| 5131 | - // orphan only together with the durable wake that will collect it. | |
| 5132 | - async _armBlobSweep() { | |
| 5133 | - this._open().exec( | |
| 5134 | - `INSERT INTO ${__KV_META_TABLE} (name, value) VALUES ('blob-sweep-due', 1) | |
| 5135 | - ON CONFLICT(name) DO UPDATE SET value = excluded.value`, | |
| 5136 | - ); | |
| 5137 | - const now = Date.now(); | |
| 5138 | - const deadline = now + __kvLimits().blobSweepMs; | |
| 5139 | - const armed = await this.ctx.storage.getAlarm(); | |
| 5140 | - // During an alarm event, `getAlarm()` can still report the timestamp that | |
| 5141 | - // caused the current delivery. It is not a future wake and cannot cover a | |
| 5142 | - // reference removed by an event that interleaves with this one. | |
| 5143 | - if (armed === null || armed <= now || armed > deadline) { | |
| 5144 | - await this.ctx.storage.setAlarm(deadline); | |
| 5145 | - } | |
| 5146 | - } | |
| 5147 | - | |
| 5148 | - _blobSweepDue() { | |
| 5149 | - return this._open().exec( | |
| 5150 | - `SELECT 1 AS due FROM ${__KV_META_TABLE} | |
| 5151 | - WHERE name = 'blob-sweep-due' AND value = 1`, | |
| 5152 | - ).toArray().length > 0; | |
| 5153 | - } | |
| 5154 | - | |
| 5155 | - _clearBlobSweepDue() { | |
| 5156 | - this._open().exec( | |
| 5157 | - `DELETE FROM ${__KV_META_TABLE} WHERE name = 'blob-sweep-due'`, | |
| 5158 | - ); | |
| 5159 | - } | |
| 5160 | - | |
| 5161 | - // Created on first touch rather than at construction, so a namespace that is | |
| 5162 | - // only ever read costs no write, and an eviction that drops the isolate does | |
| 5163 | - // not need the table rebuilt before the cell can answer. | |
| 5164 | - _open() { | |
| 5165 | - if (this._ready) return this.ctx.storage.sql; | |
| 5166 | - const sql = this.ctx.storage.sql; | |
| 5167 | - // Recreate the first release's table before the normal open path. The | |
| 5168 | - // migration test then reaches the same `CREATE IF NOT EXISTS` boundary as | |
| 5169 | - // an upgraded cell and starts with a row it must preserve. | |
| 5170 | - if (__kvLimits().legacySchema) { | |
| 5171 | - sql.exec( | |
| 5172 | - `CREATE TABLE IF NOT EXISTS ${__KV_TABLE} ( | |
| 5173 | - name TEXT PRIMARY KEY, | |
| 5174 | - value BLOB, | |
| 5175 | - tag TEXT NOT NULL, | |
| 5176 | - metadata TEXT, | |
| 5177 | - expires_at INTEGER | |
| 5178 | - ) WITHOUT ROWID`, | |
| 5179 | - ); | |
| 5180 | - sql.exec( | |
| 5181 | - `INSERT OR IGNORE INTO ${__KV_TABLE} | |
| 5182 | - (name, value, tag, metadata, expires_at) | |
| 5183 | - VALUES ('before-upgrade', CAST('legacy' AS BLOB), 'text', NULL, NULL)`, | |
| 5184 | - ); | |
| 5185 | - } | |
| 5186 | - sql.exec( | |
| 5187 | - `CREATE TABLE IF NOT EXISTS ${__KV_TABLE} ( | |
| 5188 | - name TEXT PRIMARY KEY, | |
| 5189 | - value BLOB, | |
| 5190 | - blob_id TEXT, | |
| 5191 | - size INTEGER NOT NULL, | |
| 5192 | - tag TEXT NOT NULL, | |
| 5193 | - metadata TEXT, | |
| 5194 | - expires_at INTEGER | |
| 5195 | - ) WITHOUT ROWID`, | |
| 5196 | - ); | |
| 5197 | - // Inline KV shipped before `blob_id` and `size`. `CREATE IF NOT EXISTS` | |
| 5198 | - // does not change that table, so migrate each column independently. A | |
| 5199 | - // crash between the ALTER statements is safe because the next open reads | |
| 5200 | - // the surviving shape and resumes at the missing column. | |
| 5201 | - const columns = new Set( | |
| 5202 | - sql.exec(`PRAGMA table_info(${__KV_TABLE})`).toArray().map((row) => row.name), | |
| 5203 | - ); | |
| 5204 | - if (!columns.has("blob_id")) { | |
| 5205 | - sql.exec(`ALTER TABLE ${__KV_TABLE} ADD COLUMN blob_id TEXT`); | |
| 5206 | - } | |
| 5207 | - if (!columns.has("size")) { | |
| 5208 | - sql.exec( | |
| 5209 | - `ALTER TABLE ${__KV_TABLE} | |
| 5210 | - ADD COLUMN size INTEGER NOT NULL DEFAULT 0`, | |
| 5211 | - ); | |
| 5212 | - sql.exec(`UPDATE ${__KV_TABLE} SET size = LENGTH(value)`); | |
| 5213 | - } | |
| 5214 | - // `list` walks the primary key in order, so the only index worth carrying | |
| 5215 | - // is the sweeper's. Without it the sweep is a full scan of a namespace | |
| 5216 | - // whose whole point is being large. | |
| 5217 | - sql.exec( | |
| 5218 | - `CREATE INDEX IF NOT EXISTS ${__KV_TABLE}_expires | |
| 5219 | - ON ${__KV_TABLE} (expires_at) WHERE expires_at IS NOT NULL`, | |
| 5220 | - ); | |
| 5221 | - // The due bit is durable because the isolate that wrote a blob can die | |
| 5222 | - // before its row commit. In-memory state cannot schedule that orphan's | |
| 5223 | - // collector on the next owner. | |
| 5224 | - sql.exec( | |
| 5225 | - `CREATE TABLE IF NOT EXISTS ${__KV_META_TABLE} ( | |
| 5226 | - name TEXT PRIMARY KEY, | |
| 5227 | - value INTEGER NOT NULL | |
| 5228 | - ) WITHOUT ROWID`, | |
| 5229 | - ); | |
| 5230 | - this._ready = true; | |
| 5231 | - return sql; | |
| 5232 | - } | |
| 5233 | - | |
| 5234 | - // A key past its deadline is invisible from the instant it expires, not from | |
| 5235 | - // whenever the sweeper next runs. The read path filters and the sweep only | |
| 5236 | - // reclaims space, so the two can never disagree about which side of the | |
| 5237 | - // boundary a key is on. | |
| 5238 | - async __kvGet({ keys, withMetadata, withExpiration = false, now }) { | |
| 5239 | - const sql = this._open(); | |
| 5240 | - const out = []; | |
| 5241 | - for (const key of keys) { | |
| 5242 | - const row = sql.exec( | |
| 5243 | - `SELECT value, blob_id, tag, metadata, expires_at FROM ${__KV_TABLE} | |
| 5244 | - WHERE name = ? AND (expires_at IS NULL OR expires_at > ?)`, | |
| 5245 | - key, | |
| 5246 | - now, | |
| 5247 | - ).toArray()[0]; | |
| 5248 | - if (row === undefined) { | |
| 5249 | - out.push({ key, found: false }); | |
| 5250 | - continue; | |
| 5251 | - } | |
| 5252 | - let value = row.value; | |
| 5253 | - if (row.blob_id !== null && row.blob_id !== undefined) { | |
| 5254 | - const blob = await __kvBlob({ mode: "get", reference: row.blob_id }); | |
| 5255 | - // A row naming a blob the bucket does not hold is the failure the | |
| 5256 | - // commit order exists to prevent, so it is reported as itself rather | |
| 5257 | - // than as a missing key: an absent key and a broken one need different | |
| 5258 | - // answers from an operator. | |
| 5259 | - if (!blob.found) { | |
| 5260 | - throw __kvError( | |
| 5261 | - `the value for ${JSON.stringify(key)} is missing from the fleet ` + | |
| 5262 | - `bucket (blob ${row.blob_id})`, | |
| 5263 | - ); | |
| 5264 | - } | |
| 5265 | - value = new Uint8Array(blob.value); | |
| 5266 | - } | |
| 5267 | - const entry = { key, found: true, value, tag: row.tag }; | |
| 5268 | - if (withMetadata) entry.metadata = row.metadata ?? null; | |
| 5269 | - // These fields describe one row snapshot. The operator bulk export must | |
| 5270 | - // not combine a value from this read with an expiration from an earlier | |
| 5271 | - // listing when a concurrent put replaces the key between both calls. | |
| 5272 | - if (withExpiration) entry.expiration = row.expires_at ?? null; | |
| 5273 | - out.push(entry); | |
| 5274 | - } | |
| 5275 | - return out; | |
| 5276 | - } | |
| 5277 | - | |
| 5278 | - // One transaction for the whole batch, so a bulk put is all-or-nothing | |
| 5279 | - // rather than a prefix of itself. Upstream gives no such guarantee, and | |
| 5280 | - // giving a stronger one here costs nothing and cannot surprise a caller. | |
| 5281 | - // Blob first, row second. An orphan blob is bytes the collector reclaims; a | |
| 5282 | - // row naming a blob that was never written is a read that fails forever, and | |
| 5283 | - // no sweep repairs it. The opposite commit order can leave that dangling | |
| 5284 | - // row when a process stops between the two writes. | |
| 5285 | - // | |
| 5286 | - // The blob reference travels in `_pending` until the row commits, so a sweep that | |
| 5287 | - // runs mid-put does not collect bytes that are about to be referenced. That | |
| 5288 | - // costs the put and not the read -- the commit requires the blob, so a | |
| 5289 | - // collected blob means the commit cannot fire -- which is why the model's | |
| 5290 | - // tooth for it is an action property and not an invariant. | |
| 5291 | - async _store(value) { | |
| 5292 | - if (value.byteLength <= __kvLimits().maxInlineValueBytes) { | |
| 5293 | - return { value, blobId: null }; | |
| 5294 | - } | |
| 5295 | - const digest = await __kvDigest(value); | |
| 5296 | - await this._armBlobSweep(); | |
| 5297 | - // The host mints the reference from the epoch installed with this cell. | |
| 5298 | - // JavaScript never guesses that authority or recovers it after an await. | |
| 5299 | - const { reference } = await __kvBlob({ mode: "prepare", digest }); | |
| 5300 | - this._pending.add(reference); | |
| 5301 | - try { | |
| 5302 | - await __kvBlob({ mode: "put", reference }, value); | |
| 5303 | - // Force the collector race at its real seam. The alarm took its mark | |
| 5304 | - // snapshot before this put started and waits briefly after the put | |
| 5305 | - // announces itself. Without blob-protocol serialization, this write | |
| 5306 | - // lands during that wait and must stay here until the stale sweep runs. | |
| 5307 | - if ( | |
| 5308 | - __kvLimits().raceSweepPut && this._testSweepMarked && | |
| 5309 | - !this._testSweepFinished | |
| 5310 | - ) { | |
| 5311 | - await new Promise((resolve) => { | |
| 5312 | - this._testResumePut = resolve; | |
| 5313 | - }); | |
| 5314 | - } | |
| 5315 | - // The crash window the commit order exists for: the blob is in the | |
| 5316 | - // bucket and the row is not written yet. The failed operation no longer | |
| 5317 | - // protects the digest in memory, so the durable wake can reclaim it even | |
| 5318 | - // when this isolate remains resident. | |
| 5319 | - if (__kvLimits().failAfterBlobWrite) { | |
| 5320 | - throw __kvError("CELLD_TEST_KV_FAIL_AFTER_BLOB_WRITE"); | |
| 5321 | - } | |
| 5322 | - return { value: null, blobId: reference }; | |
| 5323 | - } catch (error) { | |
| 5324 | - this._pending.delete(reference); | |
| 5325 | - throw error; | |
| 5326 | - } | |
| 5327 | - } | |
| 5328 | - | |
| 5329 | - async __kvPut({ entries }) { | |
| 5330 | - if ( | |
| 5331 | - __kvLimits().raceSweepPut && | |
| 5332 | - entries.some((entry) => | |
| 5333 | - entry.value.byteLength > __kvLimits().maxInlineValueBytes | |
| 5334 | - ) | |
| 5335 | - ) { | |
| 5336 | - if (!this._testSweepMarked || this._testPutAttempted === undefined) { | |
| 5337 | - throw __kvError("the test blob sweep did not reach its mark snapshot"); | |
| 5338 | - } | |
| 5339 | - this._testPutAttempted(); | |
| 5340 | - this._testPutAttempted = undefined; | |
| 5341 | - } | |
| 5342 | - return this._withBlobProtocol(() => this._putLocked(entries)); | |
| 5343 | - } | |
| 5344 | - | |
| 5345 | - async _putLocked(entries) { | |
| 5346 | - const sql = this._open(); | |
| 5347 | - // An inline replacement can remove the final row reference to an old | |
| 5348 | - // blob, so arm before changing the row. A new large value also arms in | |
| 5349 | - // `_store`, before its own bucket write. | |
| 5350 | - const replacesBlob = entries.some((entry) => | |
| 5351 | - sql.exec( | |
| 5352 | - `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 5353 | - WHERE name = ? AND blob_id IS NOT NULL`, | |
| 5354 | - entry.key, | |
| 5355 | - ).toArray().length > 0 | |
| 5356 | - ); | |
| 5357 | - if (replacesBlob) await this._armBlobSweep(); | |
| 5358 | - const stored = []; | |
| 5359 | - try { | |
| 5360 | - for (const entry of entries) { | |
| 5361 | - stored.push({ entry, ...(await this._store(entry.value)) }); | |
| 5362 | - } | |
| 5363 | - this.ctx.storage.transactionSync(() => { | |
| 5364 | - for (const { entry, value, blobId } of stored) { | |
| 5365 | - sql.exec( | |
| 5366 | - `INSERT INTO ${__KV_TABLE} | |
| 5367 | - (name, value, blob_id, size, tag, metadata, expires_at) | |
| 5368 | - VALUES (?, ?, ?, ?, ?, ?, ?) | |
| 5369 | - ON CONFLICT(name) DO UPDATE SET | |
| 5370 | - value = excluded.value, | |
| 5371 | - blob_id = excluded.blob_id, | |
| 5372 | - size = excluded.size, | |
| 5373 | - tag = excluded.tag, | |
| 5374 | - metadata = excluded.metadata, | |
| 5375 | - expires_at = excluded.expires_at`, | |
| 5376 | - entry.key, | |
| 5377 | - value, | |
| 5378 | - blobId, | |
| 5379 | - entry.value.byteLength, | |
| 5380 | - entry.tag, | |
| 5381 | - entry.metadata ?? null, | |
| 5382 | - entry.expiresAt ?? null, | |
| 5383 | - ); | |
| 5384 | - } | |
| 5385 | - }); | |
| 5386 | - } finally { | |
| 5387 | - // A committed row protects the blob durably. A failed put protects | |
| 5388 | - // nothing, so it must not pin an orphan until this isolate is evicted. | |
| 5389 | - for (const { blobId } of stored) { | |
| 5390 | - if (blobId !== null) this._pending.delete(blobId); | |
| 5391 | - } | |
| 5392 | - } | |
| 5393 | - // Only when something in this batch can expire. A namespace of permanent | |
| 5394 | - // keys arms no alarm and wakes for nothing. | |
| 5395 | - if (entries.some((entry) => entry.expiresAt !== null && entry.expiresAt !== undefined)) { | |
| 5396 | - await this._rearm(); | |
| 5397 | - } | |
| 5398 | - } | |
| 5399 | - | |
| 5400 | - async __kvDelete({ keys }) { | |
| 5401 | - return this._withBlobProtocol(() => this._deleteLocked(keys)); | |
| 5402 | - } | |
| 5403 | - | |
| 5404 | - async _deleteLocked(keys) { | |
| 5405 | - const sql = this._open(); | |
| 5406 | - const removesBlob = keys.some((key) => | |
| 5407 | - sql.exec( | |
| 5408 | - `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 5409 | - WHERE name = ? AND blob_id IS NOT NULL`, | |
| 5410 | - key, | |
| 5411 | - ).toArray().length > 0 | |
| 5412 | - ); | |
| 5413 | - if (removesBlob) await this._armBlobSweep(); | |
| 5414 | - this.ctx.storage.transactionSync(() => { | |
| 5415 | - for (const key of keys) { | |
| 5416 | - sql.exec(`DELETE FROM ${__KV_TABLE} WHERE name = ?`, key); | |
| 5417 | - } | |
| 5418 | - }); | |
| 5419 | - } | |
| 5420 | - | |
| 5421 | - // Arm for the earliest deadline the table holds, or disarm when it holds | |
| 5422 | - // none. Asked from the row rather than held in memory, so the answer does | |
| 5423 | - // not depend on what this activation happens to remember -- an evicted cell | |
| 5424 | - // that wakes for an alarm re-derives the same deadline from the same rows. | |
| 5425 | - // | |
| 5426 | - // What carries the deadline across an eviction is the alarm itself, which is | |
| 5427 | - // durable cell state. This is *not* recomputed when a cell is merely opened, | |
| 5428 | - // so the one gap is a `_rearm` that throws after its put committed: the rows | |
| 5429 | - // are written, the caller sees an error, and nothing is armed until the next | |
| 5430 | - // put with a deadline. That costs space and never correctness, because the | |
| 5431 | - // read path filters an expired key whether or not it was reclaimed. | |
| 5432 | - async _rearm() { | |
| 5433 | - // A test that means to pin the read filter must be able to stop the sweep, | |
| 5434 | - // or it cannot tell which mechanism hid the key -- and a test that cannot | |
| 5435 | - // tell will pass when the filter is broken. This seam exists because that | |
| 5436 | - // is exactly what happened: the first version of the expiry test stayed | |
| 5437 | - // green with the filter removed. | |
| 5438 | - if (__kvLimits().sweepDisabled) return; | |
| 5439 | - const sql = this._open(); | |
| 5440 | - const row = sql.exec( | |
| 5441 | - `SELECT MIN(expires_at) AS next FROM ${__KV_TABLE} WHERE expires_at IS NOT NULL`, | |
| 5442 | - ).toArray()[0]; | |
| 5443 | - const next = row === undefined ? null : row.next; | |
| 5444 | - const blobDue = this._blobSweepDue(); | |
| 5445 | - if ((next === null || next === undefined) && !blobDue) { | |
| 5446 | - await this.ctx.storage.deleteAlarm(); | |
| 5447 | - return; | |
| 5448 | - } | |
| 5449 | - const now = Date.now(); | |
| 5450 | - const deadlines = []; | |
| 5451 | - // Never in the past: a deadline already due is swept on this wake, and | |
| 5452 | - // arming behind `now` would spin. | |
| 5453 | - if (next !== null && next !== undefined) { | |
| 5454 | - deadlines.push(Math.max(next, now + 1)); | |
| 5455 | - } | |
| 5456 | - if (blobDue) deadlines.push(now + __kvLimits().blobSweepMs); | |
| 5457 | - const deadline = Math.min(...deadlines); | |
| 5458 | - const armed = await this.ctx.storage.getAlarm(); | |
| 5459 | - if (armed === null || armed <= now || armed > deadline) { | |
| 5460 | - await this.ctx.storage.setAlarm(deadline); | |
| 5461 | - } | |
| 5462 | - } | |
| 5463 | - | |
| 5464 | - // Reclaiming space, never deciding visibility. A key is invisible from the | |
| 5465 | - // instant it expires because the read path filters, so a late sweep costs | |
| 5466 | - // storage and never correctness — which is what lets this be bounded and | |
| 5467 | - // re-armed rather than obliged to finish. | |
| 5468 | - // Every reference a row names, plus every reference a put has written and | |
| 5469 | - // not yet committed. The two go in one list because the bucket end cannot | |
| 5470 | - // tell them apart and does not need to: it only needs "do not delete these". | |
| 5471 | - _liveBlobs() { | |
| 5472 | - const rows = this._open().exec( | |
| 5473 | - `SELECT blob_id FROM ${__KV_TABLE} WHERE blob_id IS NOT NULL`, | |
| 5474 | - ).toArray(); | |
| 5475 | - return [...new Set([...rows.map((row) => row.blob_id), ...this._pending])]; | |
| 5476 | - } | |
| 5477 | - | |
| 5478 | - async alarm() { | |
| 5479 | - const removed = await this._withBlobProtocol(async () => { | |
| 5480 | - const now = Date.now(); | |
| 5481 | - // If expiry will remove a blob reference, persist the due bit and a | |
| 5482 | - // future wake before deleting the row. A crash later in this alarm then | |
| 5483 | - // leaves the next owner enough durable state to finish collection. | |
| 5484 | - const expiresBlob = this._open().exec( | |
| 5485 | - `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 5486 | - WHERE expires_at IS NOT NULL AND expires_at <= ? | |
| 5487 | - AND blob_id IS NOT NULL | |
| 5488 | - LIMIT ?`, | |
| 5489 | - now, | |
| 5490 | - __kvLimits().sweepBatchRows, | |
| 5491 | - ).toArray().length > 0; | |
| 5492 | - if (expiresBlob) await this._armBlobSweep(); | |
| 5493 | - | |
| 5494 | - const { removed } = this.__kvSweep({ | |
| 5495 | - now, | |
| 5496 | - limit: __kvLimits().sweepBatchRows, | |
| 5497 | - }); | |
| 5498 | - // The blob sweep runs after the row sweep, on the same wake, so a row | |
| 5499 | - // reclaimed above has already dropped its reference by the time the live | |
| 5500 | - // set is read. A durable due bit distinguishes a GC wake from an inline | |
| 5501 | - // expiry wake and survives isolate eviction or a failed bucket request. | |
| 5502 | - if (this._blobSweepDue() || __kvLimits().raceSweepPut) { | |
| 5503 | - const live = this._liveBlobs(); | |
| 5504 | - if (__kvLimits().raceSweepPut && !this._testSweepFinished) { | |
| 5505 | - const putAttempted = new Promise((resolve) => { | |
| 5506 | - this._testPutAttempted = resolve; | |
| 5507 | - }); | |
| 5508 | - this._testSweepMarked = true; | |
| 5509 | - await putAttempted; | |
| 5510 | - // The fixture bucket is local. This bounded pause lets an | |
| 5511 | - // unprotected put finish its blob write; a protected put is waiting | |
| 5512 | - // for this protocol lock and therefore cannot enter the window. | |
| 5513 | - await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 5514 | - } | |
| 5515 | - let swept = false; | |
| 5516 | - try { | |
| 5517 | - await __kvBlob({ mode: "sweep", live }); | |
| 5518 | - swept = true; | |
| 5519 | - } catch (error) { | |
| 5520 | - // Reclaiming space is not deciding visibility, so a bucket that | |
| 5521 | - // refuses a delete costs storage and never correctness. The next | |
| 5522 | - // wake tries again. | |
| 5523 | - console.error("kv blob sweep failed:", error); | |
| 5524 | - } finally { | |
| 5525 | - if (__kvLimits().raceSweepPut) { | |
| 5526 | - this._testSweepFinished = true; | |
| 5527 | - this._testResumePut?.(); | |
| 5528 | - this._testResumePut = undefined; | |
| 5529 | - } | |
| 5530 | - } | |
| 5531 | - if (swept) this._clearBlobSweepDue(); | |
| 5532 | - } | |
| 5533 | - return removed; | |
| 5534 | - }); | |
| 5535 | - // A full batch means there is more to reclaim, so come back promptly | |
| 5536 | - // rather than waiting for the next natural deadline. | |
| 5537 | - if (removed >= __kvLimits().sweepBatchRows) { | |
| 5538 | - await this.ctx.storage.setAlarm(Date.now() + 1); | |
| 5539 | - return; | |
| 5540 | - } | |
| 5541 | - await this._rearm(); | |
| 5542 | - } | |
| 5543 | - | |
| 5544 | - // Pagination resumes at `name > after`, never at an offset. A caller holds | |
| 5545 | - // no transaction across pages, so an offset would skip or repeat keys the | |
| 5546 | - // moment a concurrent writer inserted or deleted inside the prefix. | |
| 5547 | - // | |
| 5548 | - // One row beyond the limit is read to decide `list_complete`, and discarded. | |
| 5549 | - // Asking the database is the only honest answer: a page that happens to fill | |
| 5550 | - // exactly is indistinguishable from a page that ended. | |
| 5551 | - __kvList({ prefix, limit, after, now }) { | |
| 5552 | - const sql = this._open(); | |
| 5553 | - const pattern = `${prefix.replace(/([%_\\])/g, "\\$1")}%`; | |
| 5554 | - const rows = sql.exec( | |
| 5555 | - `SELECT name, metadata, expires_at FROM ${__KV_TABLE} | |
| 5556 | - WHERE name LIKE ? ESCAPE '\\' | |
| 5557 | - AND name > ? | |
| 5558 | - AND (expires_at IS NULL OR expires_at > ?) | |
| 5559 | - ORDER BY name | |
| 5560 | - LIMIT ?`, | |
| 5561 | - pattern, | |
| 5562 | - after ?? "", | |
| 5563 | - now, | |
| 5564 | - limit + 1, | |
| 5565 | - ).toArray(); | |
| 5566 | - const complete = rows.length <= limit; | |
| 5567 | - const page = complete ? rows : rows.slice(0, limit); | |
| 5568 | - return { | |
| 5569 | - keys: page.map((row) => ({ | |
| 5570 | - name: row.name, | |
| 5571 | - metadata: row.metadata ?? null, | |
| 5572 | - expiration: row.expires_at ?? null, | |
| 5573 | - })), | |
| 5574 | - complete, | |
| 5575 | - }; | |
| 5576 | - } | |
| 5577 | - | |
| 5578 | - // The operator's live key and byte counts. `size` stays in the row because | |
| 5579 | - // a bucket-backed value has a NULL inline `value`; `LENGTH(value)` would | |
| 5580 | - // report zero bytes for exactly the values whose size matters most. | |
| 5581 | - __kvMetrics({ now }) { | |
| 5582 | - const sql = this._open(); | |
| 5583 | - const row = sql.exec( | |
| 5584 | - `SELECT COUNT(*) AS count, | |
| 5585 | - COALESCE(SUM(size), 0) AS bytes | |
| 5586 | - FROM ${__KV_TABLE} | |
| 5587 | - WHERE expires_at IS NULL OR expires_at > ?`, | |
| 5588 | - now, | |
| 5589 | - ).toArray()[0]; | |
| 5590 | - return { count: row.count, bytes: row.bytes }; | |
| 5591 | - } | |
| 5592 | - | |
| 5593 | - // Reclaim what the read path already treats as gone. Bounded per call so a | |
| 5594 | - // namespace with a large expired population cannot hold the cell for an | |
| 5595 | - // unbounded time; the caller re-arms while there is more. | |
| 5596 | - __kvSweep({ now, limit }) { | |
| 5597 | - const sql = this._open(); | |
| 5598 | - const removed = __cellSweepBatch( | |
| 5599 | - this.ctx.storage, | |
| 5600 | - (bound) => sql.exec( | |
| 5601 | - `SELECT name FROM ${__KV_TABLE} | |
| 5602 | - WHERE expires_at IS NOT NULL AND expires_at <= ? | |
| 5603 | - ORDER BY expires_at | |
| 5604 | - LIMIT ?`, | |
| 5605 | - now, | |
| 5606 | - bound, | |
| 5607 | - ).toArray(), | |
| 5608 | - (row) => { | |
| 5609 | - sql.exec(`DELETE FROM ${__KV_TABLE} WHERE name = ?`, row.name); | |
| 5610 | - }, | |
| 5611 | - limit, | |
| 5612 | - ); | |
| 5613 | - return { removed }; | |
| 5614 | - } | |
| 5615 | - | |
| 5616 | - // The operator surface, reached only over `/runtime/`, which authenticates | |
| 5617 | - // with the fleet secret. `/do/` refuses every reserved class structurally, | |
| 5618 | - // so adding this handler does not put a namespace on an unauthenticated | |
| 5619 | - // route -- the trap d1.md decision 4 records paying for once, and the reason | |
| 5620 | - // that refusal is one question rather than one per class. | |
| 5621 | - // | |
| 5622 | - // Values cross this boundary as arrays of bytes rather than as text, because | |
| 5623 | - // a namespace holds bytes: a value written from a Worker as an ArrayBuffer | |
| 5624 | - // has no faithful string form, and `celld kv` must be able to read back | |
| 5625 | - // exactly what was written. | |
| 5626 | - async fetch(request) { | |
| 5627 | - let body; | |
| 5628 | - try { | |
| 5629 | - body = await request.json(); | |
| 5630 | - } catch { | |
| 5631 | - return Response.json({ error: "KV_ERROR: invalid request body" }, { status: 400 }); | |
| 5632 | - } | |
| 5633 | - const now = Date.now(); | |
| 5634 | - try { | |
| 5635 | - let result; | |
| 5636 | - switch (body.op) { | |
| 5637 | - case "get": { | |
| 5638 | - // Awaited: `__kvGet` resolves a bucket-backed value, so it is | |
| 5639 | - // async. Destructuring the promise instead threw "object is not | |
| 5640 | - // iterable" on every operator read, and only here -- the binding | |
| 5641 | - // reaches the same method over RPC, which awaits for it. | |
| 5642 | - const [row] = await this.__kvGet({ | |
| 5643 | - keys: [String(body.key)], | |
| 5644 | - withMetadata: true, | |
| 5645 | - withExpiration: true, | |
| 5646 | - now, | |
| 5647 | - }); | |
| 5648 | - result = row.found | |
| 5649 | - ? { | |
| 5650 | - found: true, | |
| 5651 | - ...__kvOperatorValue(row.value), | |
| 5652 | - tag: row.tag, | |
| 5653 | - metadata: row.metadata ?? null, | |
| 5654 | - expiration: row.expiration, | |
| 5655 | - } | |
| 5656 | - : { found: false }; | |
| 5657 | - break; | |
| 5658 | - } | |
| 5659 | - case "put": | |
| 5660 | - case "put-base64": { | |
| 5661 | - // Validated here, through the same helpers the binding calls, so a | |
| 5662 | - // key written by `celld kv` is a key the binding could have written. | |
| 5663 | - // The operator route used to arrive pre-validated by the CLI, which | |
| 5664 | - // put the same bound in two processes -- and they disagreed the first | |
| 5665 | - // time a test shortened one of them. | |
| 5666 | - const key = String(body.key); | |
| 5667 | - __kvCheckKey(key); | |
| 5668 | - const value = body.op === "put-base64" | |
| 5669 | - ? $$atob(String(body.value), true) | |
| 5670 | - : new Uint8Array(body.value); | |
| 5671 | - __kvCheckValue(value.byteLength); | |
| 5672 | - const metadata = body.metadata === undefined ? null : body.metadata; | |
| 5673 | - if (metadata !== null) __kvCheckMetadata(metadata); | |
| 5674 | - // Resolved from the cell's clock, not the caller's, because that is | |
| 5675 | - // the clock the read filter and the sweeper compare against. | |
| 5676 | - const expiresAt = __kvExpiryAt(now, body.expiration, body.expirationTtl); | |
| 5677 | - await this.__kvPut({ | |
| 5678 | - entries: [{ | |
| 5679 | - key, | |
| 5680 | - value, | |
| 5681 | - tag: String(body.tag ?? __KV_TAG_BYTES), | |
| 5682 | - metadata, | |
| 5683 | - expiresAt, | |
| 5684 | - }], | |
| 5685 | - }); | |
| 5686 | - result = { ok: true }; | |
| 5687 | - break; | |
| 5688 | - } | |
| 5689 | - case "delete": | |
| 5690 | - for (const key of body.keys) __kvCheckKey(String(key)); | |
| 5691 | - await this.__kvDelete({ keys: body.keys.map(String) }); | |
| 5692 | - result = { ok: true }; | |
| 5693 | - break; | |
| 5694 | - case "list": | |
| 5695 | - result = this.__kvList({ | |
| 5696 | - prefix: String(body.prefix ?? ""), | |
| 5697 | - limit: Number(body.limit), | |
| 5698 | - after: String(body.after ?? ""), | |
| 5699 | - now, | |
| 5700 | - }); | |
| 5701 | - break; | |
| 5702 | - // What `celld kv info` reports. `stored` counts every row and `live` | |
| 5703 | - // counts only what a read would return, so the difference is exactly | |
| 5704 | - // the population the sweeper still owes -- which is the one number | |
| 5705 | - // that makes reclamation observable from outside the cell. | |
| 5706 | - case "info": { | |
| 5707 | - const live = this.__kvMetrics({ now }); | |
| 5708 | - const total = this._open().exec( | |
| 5709 | - `SELECT COUNT(*) AS count FROM ${__KV_TABLE}`, | |
| 5710 | - ).toArray()[0]; | |
| 5711 | - result = { live: live.count, bytes: live.bytes, stored: total.count }; | |
| 5712 | - break; | |
| 5713 | - } | |
| 5714 | - default: | |
| 5715 | - return Response.json( | |
| 5716 | - { error: `KV_ERROR: unknown operation ${JSON.stringify(body.op)}` }, | |
| 5717 | - { status: 400 }, | |
| 5718 | - ); | |
| 5719 | - } | |
| 5720 | - return Response.json({ result }); | |
| 5721 | - } catch (error) { | |
| 5722 | - return Response.json( | |
| 5723 | - { error: String(error && error.message || error) }, | |
| 5724 | - { status: 400 }, | |
| 5725 | - ); | |
| 5726 | - } | |
| 5727 | - } | |
| 5728 | -} | |
| 5729 | - | |
| 5730 | -__cell.classes.__KvNamespace = __KvNamespaceCell; | |
| 5731 | -// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class is | |
| 5732 | -// the runtime's own, so grant it here rather than making every KV user set a | |
| 5733 | -// compatibility flag to reach a namespace. | |
| 5734 | -__cell.doExports.__KvNamespace = true; | |
| 5735 | - | |
| 5736 | -// The client half. | |
| 5737 | -// | |
| 5738 | -// Every number below is injected from `celld_logic::kv` as `__cell.kvLimits` | |
| 5739 | -// rather than written here, so the binding, `celld kv` and deploy-time | |
| 5740 | -// validation cannot disagree about what a valid key is. No new host op: D1 set | |
| 5741 | -// the bar at one and Workflows came in under it, and a limit is data rather | |
| 5742 | -// than a decision, so shipping the values is enough. What stays in JS is the | |
| 5743 | -// presentation -- the error text is the binding's published contract, in | |
| 5744 | -// upstream's `KV <OP> failed:` shape, and belongs beside the calls that raise | |
| 5745 | -// it. | |
| 5746 | -// | |
| 5747 | -// The cursor codec is the one thing that must byte-match Rust's, and it is | |
| 5748 | -// plain hex: a total function with a single right answer, which two correct | |
| 5749 | -// implementations cannot disagree about. A policy would be a different matter | |
| 5750 | -// and none is duplicated here. | |
| 5751 | -const __kvLimits = () => __cell.kvLimits; | |
| 5752 | - | |
| 5753 | -const __kvCheckKey = (key) => { | |
| 5754 | - if (key.length === 0) throw __kvError("a key must not be empty"); | |
| 5755 | - const bytes = __kvEncoder.encode(key).byteLength; | |
| 5756 | - if (bytes > __kvLimits().maxKeyBytes) { | |
| 5757 | - throw __kvError( | |
| 5758 | - `a key is at most ${__kvLimits().maxKeyBytes} bytes, got ${bytes}`, | |
| 5759 | - ); | |
| 5760 | - } | |
| 5761 | -}; | |
| 5762 | - | |
| 5763 | -// A TTL becomes an absolute deadline here, once, at the call. Resolving it | |
| 5764 | -// again later against a newer clock would extend the life of the key every | |
| 5765 | -// time anything re-read the row -- the reason a workflow persists a sleep | |
| 5766 | -// deadline and not its duration. | |
| 5767 | -const __kvCheckValue = (size) => { | |
| 5768 | - // Upstream's bound, and now the only one. A value above the inline bound is | |
| 5769 | - // no longer refused: it goes to the fleet bucket, which is the split | |
| 5770 | - // Cloudflare's own KV rearchitecture made and for the same reason — a cell | |
| 5771 | - // replicates every write as LTX, so an inline value is paid for twice. | |
| 5772 | - if (size > __kvLimits().maxValueBytes) { | |
| 5773 | - throw __kvError(`a value is at most ${__kvLimits().maxValueBytes} bytes, got ${size}`); | |
| 5774 | - } | |
| 5775 | -}; | |
| 5776 | - | |
| 5777 | -const __kvCheckMetadata = (metadata) => { | |
| 5778 | - const bytes = __kvEncoder.encode(metadata).byteLength; | |
| 5779 | - if (bytes > __kvLimits().maxMetadataBytes) { | |
| 5780 | - throw __kvError( | |
| 5781 | - `metadata is at most ${__kvLimits().maxMetadataBytes} bytes, got ${bytes}`, | |
| 5782 | - ); | |
| 5783 | - } | |
| 5784 | -}; | |
| 5785 | - | |
| 5786 | -const __kvExpiryAt = (now, expiration, expirationTtl) => { | |
| 5787 | - if (expirationTtl !== undefined && expirationTtl !== null) { | |
| 5788 | - const ms = Math.floor(Number(expirationTtl) * 1000); | |
| 5789 | - if (!Number.isFinite(ms) || ms < __kvLimits().minExpirationTtlMs) { | |
| 5790 | - throw __kvError( | |
| 5791 | - `expirationTtl is at least ${__kvLimits().minExpirationTtlMs / 1000} seconds`, | |
| 5792 | - ); | |
| 5793 | - } | |
| 5794 | - return now + ms; | |
| 5795 | - } | |
| 5796 | - if (expiration !== undefined && expiration !== null) { | |
| 5797 | - const at = Math.floor(Number(expiration) * 1000); | |
| 5798 | - if (!Number.isFinite(at) || at <= now) { | |
| 5799 | - throw __kvError(`expiration ${expiration} is in the past`); | |
| 5800 | - } | |
| 5801 | - return at; | |
| 5802 | - } | |
| 5803 | - return null; | |
| 5804 | -}; | |
| 5805 | - | |
| 5806 | -const __kvCursor = { | |
| 5807 | - encode(key) { | |
| 5808 | - let out = ""; | |
| 5809 | - for (const byte of __kvEncoder.encode(key)) { | |
| 5810 | - out += byte.toString(16).padStart(2, "0"); | |
| 5811 | - } | |
| 5812 | - return out; | |
| 5813 | - }, | |
| 5814 | - decode(cursor) { | |
| 5815 | - // A malformed cursor is refused, never read as "start from the | |
| 5816 | - // beginning": that would hand a paginating caller its first page a second | |
| 5817 | - // time and call it progress. | |
| 5818 | - if (cursor.length % 2 !== 0 || /[^0-9a-f]/.test(cursor)) { | |
| 5819 | - throw __kvError("the list cursor is malformed"); | |
| 5820 | - } | |
| 5821 | - const bytes = new Uint8Array(cursor.length / 2); | |
| 5822 | - for (let at = 0; at < bytes.length; at += 1) { | |
| 5823 | - bytes[at] = Number.parseInt(cursor.slice(at * 2, at * 2 + 2), 16); | |
| 5824 | - } | |
| 5825 | - return __kvDecoder.decode(bytes); | |
| 5826 | - }, | |
| 5827 | -}; | |
| 5828 | - | |
| 5829 | -const __kvListLimit = (requested) => { | |
| 5830 | - const max = __kvLimits().maxListLimit; | |
| 5831 | - if (requested === undefined || requested === null) return max; | |
| 5832 | - const limit = Math.floor(Number(requested)); | |
| 5833 | - // Zero would be a page that never ends. | |
| 5834 | - if (!Number.isFinite(limit) || limit <= 0) return max; | |
| 5835 | - return Math.min(limit, max); | |
| 5836 | -}; | |
| 5837 | - | |
| 5838 | -// Upstream's four content types, and what each one means on the way in and out. | |
| 5839 | -const __KV_TAG_TEXT = "text"; | |
| 5840 | -const __KV_TAG_BYTES = "bytes"; | |
| 5841 | - | |
| 5842 | -const __kvEncoder = new TextEncoder(); | |
| 5843 | -const __kvDecoder = new TextDecoder(); | |
| 5844 | - | |
| 5845 | -// A value becomes bytes plus a tag, once, at the public boundary. Storing the | |
| 5846 | -// tag is what lets `get(key, "text")` and `get(key)` answer differently from | |
| 5847 | -// the same row without the cell parsing anything. | |
| 5848 | -const __kvEncodeValue = (value) => { | |
| 5849 | - if (typeof value === "string") { | |
| 5850 | - return { value: __kvEncoder.encode(value), tag: __KV_TAG_TEXT }; | |
| 5851 | - } | |
| 5852 | - if (value instanceof ArrayBuffer) { | |
| 5853 | - return { value: new Uint8Array(value.slice(0)), tag: __KV_TAG_BYTES }; | |
| 5854 | - } | |
| 5855 | - if (ArrayBuffer.isView(value)) { | |
| 5856 | - // Copied, not referenced. `sendBatch`'s resizable-ArrayBuffer regression | |
| 5857 | - // upstream is the same hazard: a caller may resize or reuse the buffer | |
| 5858 | - // between this call and the write, and a shallow view would then read | |
| 5859 | - // decommitted pages. | |
| 5860 | - return { | |
| 5861 | - value: new Uint8Array( | |
| 5862 | - value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), | |
| 5863 | - ), | |
| 5864 | - tag: __KV_TAG_BYTES, | |
| 5865 | - }; | |
| 5866 | - } | |
| 5867 | - throw __kvError( | |
| 5868 | - "a KV value must be a string, an ArrayBuffer, or a typed array", | |
| 5869 | - ); | |
| 5870 | -}; | |
| 5871 | - | |
| 5872 | -const __kvDecodeValue = (bytes, tag, type) => { | |
| 5873 | - const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); | |
| 5874 | - switch (type) { | |
| 5875 | - case "arrayBuffer": | |
| 5876 | - return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength); | |
| 5877 | - case "json": | |
| 5878 | - return JSON.parse(__kvDecoder.decode(view)); | |
| 5879 | - case "stream": | |
| 5880 | - return new Response(view).body; | |
| 5881 | - case "text": | |
| 5882 | - default: | |
| 5883 | - // A value written as bytes still decodes as text when asked for text, | |
| 5884 | - // which is upstream's behaviour and the reason the tag is advisory | |
| 5885 | - // rather than a type check. | |
| 5886 | - return __kvDecoder.decode(view); | |
| 5887 | - } | |
| 5888 | -}; | |
| 5889 | - | |
| 5890 | -const __kvReadOptions = (options) => { | |
| 5891 | - if (typeof options === "string") return { type: options }; | |
| 5892 | - if (options === null || options === undefined) return { type: "text" }; | |
| 5893 | - return { type: options.type ?? "text", cacheTtl: options.cacheTtl }; | |
| 5894 | -}; | |
| 5895 | - | |
| 5896 | -class KvNamespace { | |
| 5897 | - constructor(id, cellName) { | |
| 5898 | - Object.defineProperty(this, "_id", { value: id }); | |
| 5899 | - Object.defineProperty(this, "_cellName", { value: cellName }); | |
| 5900 | - } | |
| 5901 | - | |
| 5902 | - // Resolved per call rather than cached: a cell can move between calls, and | |
| 5903 | - // `getByName` costs what the Durable Object path already pays. | |
| 5904 | - get _stub() { | |
| 5905 | - return __cell.makeNamespace("__KvNamespace").getByName(this._cellName); | |
| 5906 | - } | |
| 5907 | - | |
| 5908 | - async _read(keys, options, withMetadata) { | |
| 5909 | - const { type } = __kvReadOptions(options); | |
| 5910 | - for (const key of keys) __kvCheckKey(key); | |
| 5911 | - const rows = await this._stub.__kvGet({ | |
| 5912 | - keys, | |
| 5913 | - withMetadata, | |
| 5914 | - now: Date.now(), | |
| 5915 | - }); | |
| 5916 | - return rows.map((row) => { | |
| 5917 | - if (!row.found) return { key: row.key, value: null, metadata: null }; | |
| 5918 | - return { | |
| 5919 | - key: row.key, | |
| 5920 | - value: __kvDecodeValue(row.value, row.tag, type), | |
| 5921 | - metadata: row.metadata === null || row.metadata === undefined | |
| 5922 | - ? null | |
| 5923 | - : JSON.parse(row.metadata), | |
| 5924 | - }; | |
| 5925 | - }); | |
| 5926 | - } | |
| 5927 | - | |
| 5928 | - // `get(key)` answers a value; `get([keys])` answers a Map with a null hole | |
| 5929 | - // for a key that is not there. Upstream's bulk form is a Map and not an | |
| 5930 | - // object, which matters: an object would collide a key named `__proto__` | |
| 5931 | - // with the prototype chain. | |
| 5932 | - async get(key, options) { | |
| 5933 | - if (Array.isArray(key)) { | |
| 5934 | - const rows = await this._read(__kvBulkKeys(key), options, false); | |
| 5935 | - return new Map(rows.map((row) => [row.key, row.value])); | |
| 5936 | - } | |
| 5937 | - const [row] = await this._read([String(key)], options, false); | |
| 5938 | - return row.value; | |
| 5939 | - } | |
| 5940 | - | |
| 5941 | - async getWithMetadata(key, options) { | |
| 5942 | - if (Array.isArray(key)) { | |
| 5943 | - const rows = await this._read(__kvBulkKeys(key), options, true); | |
| 5944 | - return new Map( | |
| 5945 | - rows.map((row) => [row.key, { value: row.value, metadata: row.metadata }]), | |
| 5946 | - ); | |
| 5947 | - } | |
| 5948 | - const [row] = await this._read([String(key)], options, true); | |
| 5949 | - return { | |
| 5950 | - value: row.value, | |
| 5951 | - metadata: row.metadata, | |
| 5952 | - // Null, and honestly so: celld has no read cache, and reporting a HIT | |
| 5953 | - // from a runtime that never cached anything would be a lie in a field | |
| 5954 | - // applications read. | |
| 5955 | - cacheStatus: null, | |
| 5956 | - }; | |
| 5957 | - } | |
| 5958 | - | |
| 5959 | - async put(key, value, options) { | |
| 5960 | - const name = String(key); | |
| 5961 | - __kvCheckKey(name); | |
| 5962 | - const encoded = __kvEncodeValue(value); | |
| 5963 | - __kvCheckValue(encoded.value.byteLength); | |
| 5964 | - const metadata = options && options.metadata !== undefined | |
| 5965 | - ? JSON.stringify(options.metadata) | |
| 5966 | - : null; | |
| 5967 | - if (metadata !== null) __kvCheckMetadata(metadata); | |
| 5968 | - const expiresAt = __kvExpiryAt( | |
| 5969 | - Date.now(), | |
| 5970 | - options && options.expiration, | |
| 5971 | - options && options.expirationTtl, | |
| 5972 | - ); | |
| 5973 | - await this._stub.__kvPut({ | |
| 5974 | - entries: [{ key: name, value: encoded.value, tag: encoded.tag, metadata, expiresAt }], | |
| 5975 | - }); | |
| 5976 | - } | |
| 5977 | - | |
| 5978 | - async delete(key) { | |
| 5979 | - const name = String(key); | |
| 5980 | - __kvCheckKey(name); | |
| 5981 | - await this._stub.__kvDelete({ keys: [name] }); | |
| 5982 | - } | |
| 5983 | - | |
| 5984 | - // Upstream takes one key or an array, and caps the array at the same 100 a | |
| 5985 | - // bulk get takes. | |
| 5986 | - async deleteBulk(keys) { | |
| 5987 | - const names = Array.isArray(keys) ? __kvBulkKeys(keys) : [String(keys)]; | |
| 5988 | - for (const name of names) __kvCheckKey(name); | |
| 5989 | - await this._stub.__kvDelete({ keys: names }); | |
| 5990 | - } | |
| 5991 | - | |
| 5992 | - async list(options) { | |
| 5993 | - const prefix = options && options.prefix ? String(options.prefix) : ""; | |
| 5994 | - const limit = __kvListLimit(options && options.limit); | |
| 5995 | - const after = options && options.cursor ? __kvCursor.decode(String(options.cursor)) : ""; | |
| 5996 | - const page = await this._stub.__kvList({ prefix, limit, after, now: Date.now() }); | |
| 5997 | - const keys = page.keys.map((entry) => { | |
| 5998 | - const key = { name: entry.name }; | |
| 5999 | - if (entry.metadata !== null) key.metadata = JSON.parse(entry.metadata); | |
| 6000 | - // Upstream reports an expiration in seconds. | |
| 6001 | - if (entry.expiration !== null) key.expiration = Math.floor(entry.expiration / 1000); | |
| 6002 | - return key; | |
| 6003 | - }); | |
| 6004 | - if (page.complete) return { keys, list_complete: true, cacheStatus: null }; | |
| 6005 | - return { | |
| 6006 | - keys, | |
| 6007 | - list_complete: false, | |
| 6008 | - cursor: __kvCursor.encode(keys[keys.length - 1].name), | |
| 6009 | - cacheStatus: null, | |
| 6010 | - }; | |
| 6011 | - } | |
| 6012 | -} | |
| 6013 | - | |
| 6014 | -// The bulk ceiling belongs to the binding, and a CLI chunks beneath it rather | |
| 6015 | -// than inheriting it. An empty array is refused because upstream refuses it: | |
| 6016 | -// answering an empty Map would look like "none of these keys exist". | |
| 6017 | -const __kvBulkKeys = (keys) => { | |
| 6018 | - if (keys.length === 0) throw __kvError("a bulk get needs at least one key"); | |
| 6019 | - if (keys.length > __kvLimits().maxBulkKeys) { | |
| 6020 | - throw __kvError( | |
| 6021 | - `a bulk get takes at most ${__kvLimits().maxBulkKeys} keys, got ${keys.length}`, | |
| 6022 | - ); | |
| 6023 | - } | |
| 6024 | - return keys.map(String); | |
| 6025 | -}; | |
| 6026 | - | |
| 6027 | -globalThis.__makeKvNamespace = (id, cellName) => new KvNamespace(id, cellName); | |
| 6028 | - | |
| 6029 | -// ---- Queues -------------------------------------------------------------- | |
| 6030 | -// A Queue is one runtime-supplied Durable Object. The producer binding writes | |
| 6031 | -// bytes and a content tag through RPC, and the cell owns the durable order, | |
| 6032 | -// deadlines, leases, and alarms. `celld_logic::queue` owns every transition | |
| 6033 | -// that can invalidate a lease or choose a deadline; this code supplies SQL and | |
| 6034 | -// the Cloudflare-compatible presentation. | |
| 6035 | - | |
| 6036 | -const __QUEUE_MESSAGES = "__queue_messages"; | |
| 6037 | -const __QUEUE_META = "__queue_meta"; | |
| 6038 | -const __QUEUE_STATS = "__queue_stats"; | |
| 6039 | -const __QUEUE_TRANSFER_RECEIPTS = "__queue_transfer_receipts"; | |
| 6040 | -const __queueEncoder = new TextEncoder(); | |
| 6041 | - | |
| 6042 | -// Independent send() calls share the same economics as sendBatch() without | |
| 6043 | -// changing the public promise boundary. The first call opens a four-millisecond | |
| 6044 | -// owner-local group by default; later cell events append their already-copied | |
| 6045 | -// entries, and park on their own promise. One event commits the bounded group, | |
| 6046 | -// and every response still trails that commit through the ordinary output | |
| 6047 | -// gate. The three caps bound heap retention and keep the persisted transaction | |
| 6048 | -// inside the public sendBatch limits. | |
| 6049 | -const __QUEUE_PRODUCER_GROUP_CALLS = 64; | |
| 6050 | -const __QUEUE_PRODUCER_GROUP_MESSAGES = 100; | |
| 6051 | -const __QUEUE_PRODUCER_GROUP_BYTES = 256_000; | |
| 6052 | - | |
| 6053 | -const __queueError = (message) => new Error("QUEUE_ERROR: " + String(message)); | |
| 6054 | -// A Queue message id is a UUIDv7 (RFC 9562): 48 bits of enqueue time, a | |
| 6055 | -// 12-bit sequence inside that millisecond, and 62 random bits. It keeps the | |
| 6056 | -// UUID shape a consumer can parse, and it sorts in enqueue order, so the | |
| 6057 | -// UNIQUE index on `id` appends. A random v4 id made every grouped send | |
| 6058 | -// transaction dirty one index leaf per message (about 1.6 WAL frames per | |
| 6059 | -// 64-byte message) and turned every passive checkpoint into a random write | |
| 6060 | -// across the whole backlog, which is what made a deep Queue's checkpoint | |
| 6061 | -// cost grow with its backlog. The sequence never moves backwards inside one | |
| 6062 | -// process, so a clock step only widens the gap between consecutive ids. | |
| 6063 | -let __queueIdMs = 0; | |
| 6064 | -let __queueIdSeq = 0; | |
| 6065 | -function __queueMessageId(now) { | |
| 6066 | - if (now > __queueIdMs) { | |
| 6067 | - __queueIdMs = now; | |
| 6068 | - __queueIdSeq = 0; | |
| 6069 | - } else { | |
| 6070 | - __queueIdSeq += 1; | |
| 6071 | - if (__queueIdSeq > 0xfff) { | |
| 6072 | - __queueIdMs += 1; | |
| 6073 | - __queueIdSeq = 0; | |
| 6074 | - } | |
| 6075 | - } | |
| 6076 | - const bytes = new Uint8Array(16); | |
| 6077 | - crypto.getRandomValues(bytes); | |
| 6078 | - const ms = __queueIdMs; | |
| 6079 | - bytes[0] = Math.floor(ms / 0x10000000000) & 0xff; | |
| 6080 | - bytes[1] = Math.floor(ms / 0x100000000) & 0xff; | |
| 6081 | - bytes[2] = (ms >>> 24) & 0xff; | |
| 6082 | - bytes[3] = (ms >>> 16) & 0xff; | |
| 6083 | - bytes[4] = (ms >>> 8) & 0xff; | |
| 6084 | - bytes[5] = ms & 0xff; | |
| 6085 | - bytes[6] = 0x70 | (__queueIdSeq >> 8); | |
| 6086 | - bytes[7] = __queueIdSeq & 0xff; | |
| 6087 | - bytes[8] = (bytes[8] & 0x3f) | 0x80; | |
| 6088 | - let hex = ""; | |
| 6089 | - for (let i = 0; i < 16; i++) hex += bytes[i].toString(16).padStart(2, "0"); | |
| 6090 | - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${ | |
| 6091 | - hex.slice(16, 20) | |
| 6092 | - }-${hex.slice(20)}`; | |
| 6093 | -} | |
| 6094 | -const __queueLimits = () => __cell.queueLimits; | |
| 6095 | -const __queuePolicy = (request) => | |
| 6096 | - JSON.parse(__queue_policy(JSON.stringify(request))); | |
| 6097 | - | |
| 6098 | -const __queueDelay = (value, fallback = 0) => { | |
| 6099 | - if (value === undefined || value === null) return fallback; | |
| 6100 | - const seconds = Number(value); | |
| 6101 | - if (!Number.isInteger(seconds) || seconds < 0 || | |
| 6102 | - seconds > __queueLimits().maxDelaySeconds) { | |
| 6103 | - throw __queueError( | |
| 6104 | - `delaySeconds must be an integer from 0 to ${__queueLimits().maxDelaySeconds}`, | |
| 6105 | - ); | |
| 6106 | - } | |
| 6107 | - return seconds; | |
| 6108 | -}; | |
| 6109 | - | |
| 6110 | -const __queueBytes = (value) => { | |
| 6111 | - if (value instanceof ArrayBuffer) { | |
| 6112 | - return new Uint8Array(value.slice(0)); | |
| 6113 | - } | |
| 6114 | - if (ArrayBuffer.isView(value)) { | |
| 6115 | - return new Uint8Array( | |
| 6116 | - value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), | |
| 6117 | - ); | |
| 6118 | - } | |
| 6119 | - throw __queueError("a bytes message must be an ArrayBuffer or a typed array"); | |
| 6120 | -}; | |
| 6121 | - | |
| 6122 | -// Encode before entering the cell. The copy makes `sendBatch()` immune to a | |
| 6123 | -// caller resizing or reusing a backing buffer while the durable write awaits. | |
| 6124 | -const __queueEncode = (body, requestedType) => { | |
| 6125 | - const contentType = requestedType ?? | |
| 6126 | - (__cell.compat.queueJsonMessages ? "json" : "v8"); | |
| 6127 | - let bytes; | |
| 6128 | - switch (contentType) { | |
| 6129 | - case "text": | |
| 6130 | - bytes = __queueEncoder.encode(String(body)); | |
| 6131 | - break; | |
| 6132 | - case "bytes": | |
| 6133 | - bytes = __queueBytes(body); | |
| 6134 | - break; | |
| 6135 | - case "json": { | |
| 6136 | - let json; | |
| 6137 | - try { | |
| 6138 | - json = JSON.stringify(body); | |
| 6139 | - } catch (error) { | |
| 6140 | - throw __queueError("the JSON message body cannot be serialized", error); | |
| 6141 | - } | |
| 6142 | - if (json === undefined) { | |
| 6143 | - throw __queueError("the JSON message body cannot be undefined"); | |
| 6144 | - } | |
| 6145 | - bytes = __queueEncoder.encode(json); | |
| 6146 | - break; | |
| 6147 | - } | |
| 6148 | - case "v8": | |
| 6149 | - try { | |
| 6150 | - bytes = __sc_encode(body); | |
| 6151 | - } catch (error) { | |
| 6152 | - throw __queueError("the message body cannot be cloned", error); | |
| 6153 | - } | |
| 6154 | - break; | |
| 6155 | - default: | |
| 6156 | - throw __queueError( | |
| 6157 | - `contentType must be "text", "bytes", "json", or "v8", got ${JSON.stringify(contentType)}`, | |
| 6158 | - ); | |
| 6159 | - } | |
| 6160 | - if (bytes.byteLength > __queueLimits().maxMessageBytes) { | |
| 6161 | - throw __queueError( | |
| 6162 | - `a message is at most ${__queueLimits().maxMessageBytes} bytes, got ${bytes.byteLength}`, | |
| 6163 | - ); | |
| 6164 | - } | |
| 6165 | - return { body: bytes, contentType, size: bytes.byteLength }; | |
| 6166 | -}; | |
| 6167 | - | |
| 6168 | -// A lease-scoped read must seek, not walk the backlog. The plan is the only | |
| 6169 | -// evidence that says which, and it is cheap to ask for, so a gated test seam | |
| 6170 | -// reads it from the shipped query rather than from a copy that can drift. | |
| 6171 | -const __queueReportLeaseLookupPlan = (sql, query, leaseId) => { | |
| 6172 | - if (typeof __test_queue_lease_lookup_plan !== "function") return; | |
| 6173 | - const plan = sql.exec(`EXPLAIN QUERY PLAN ${query}`, leaseId) | |
| 6174 | - .toArray() | |
| 6175 | - .map((row) => row.detail) | |
| 6176 | - .join("; "); | |
| 6177 | - __test_queue_lease_lookup_plan(plan); | |
| 6178 | -}; | |
| 6179 | - | |
| 6180 | -const __queueMetricsView = (metrics) => ({ | |
| 6181 | - backlogCount: metrics.backlogCount, | |
| 6182 | - backlogBytes: metrics.backlogBytes, | |
| 6183 | - oldestMessageTimestamp: metrics.oldestMessageTimestamp === null || | |
| 6184 | - metrics.oldestMessageTimestamp === undefined | |
| 6185 | - ? undefined | |
| 6186 | - : new Date(metrics.oldestMessageTimestamp), | |
| 6187 | -}); | |
| 6188 | - | |
| 6189 | -class __QueueCell { | |
| 6190 | - constructor(ctx) { | |
| 6191 | - this.ctx = ctx; | |
| 6192 | - this.queue = ctx.id.name; | |
| 6193 | - this._ready = false; | |
| 6194 | - this._producerGroup = null; | |
| 6195 | - } | |
| 6196 | - | |
| 6197 | - _open() { | |
| 6198 | - if (this._ready) return this.ctx.storage.sql; | |
| 6199 | - const sql = this.ctx.storage.sql; | |
| 6200 | - sql.exec( | |
| 6201 | - `CREATE TABLE IF NOT EXISTS ${__QUEUE_MESSAGES} ( | |
| 6202 | - seq INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 6203 | - id TEXT NOT NULL UNIQUE, | |
| 6204 | - body BLOB NOT NULL, | |
| 6205 | - content_type TEXT NOT NULL, | |
| 6206 | - size INTEGER NOT NULL, | |
| 6207 | - enqueued_at INTEGER NOT NULL, | |
| 6208 | - visible_at INTEGER NOT NULL, | |
| 6209 | - attempts INTEGER NOT NULL DEFAULT 0, | |
| 6210 | - lease_id TEXT, | |
| 6211 | - lease_generation INTEGER NOT NULL DEFAULT 0, | |
| 6212 | - leased_until INTEGER, | |
| 6213 | - purge_on_settle INTEGER NOT NULL DEFAULT 0, | |
| 6214 | - dlq_target TEXT, | |
| 6215 | - dlq_transfer_id TEXT, | |
| 6216 | - transfer_kind TEXT, | |
| 6217 | - dead_letter_source TEXT, | |
| 6218 | - CHECK ((dlq_target IS NULL AND transfer_kind IS NULL) | |
| 6219 | - OR (dlq_target IS NOT NULL | |
| 6220 | - AND transfer_kind IN ('dead-letter', 'redrive'))) | |
| 6221 | - )`, | |
| 6222 | - ); | |
| 6223 | - sql.exec( | |
| 6224 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_visible | |
| 6225 | - ON ${__QUEUE_MESSAGES} (visible_at, seq)`, | |
| 6226 | - ); | |
| 6227 | - // Rearming is on every producer acknowledgement and settlement. Each | |
| 6228 | - // scheduling lookup must therefore stop at one deadline or one batch; | |
| 6229 | - // an aggregate over the backlog makes a large Queue quadratic to fill. | |
| 6230 | - sql.exec( | |
| 6231 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_ready | |
| 6232 | - ON ${__QUEUE_MESSAGES} (visible_at, seq) | |
| 6233 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6234 | - AND lease_id IS NULL`, | |
| 6235 | - ); | |
| 6236 | - sql.exec( | |
| 6237 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_enqueued | |
| 6238 | - ON ${__QUEUE_MESSAGES} (enqueued_at, seq)`, | |
| 6239 | - ); | |
| 6240 | - sql.exec( | |
| 6241 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_retained | |
| 6242 | - ON ${__QUEUE_MESSAGES} (enqueued_at, seq) | |
| 6243 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL`, | |
| 6244 | - ); | |
| 6245 | - sql.exec( | |
| 6246 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease | |
| 6247 | - ON ${__QUEUE_MESSAGES} (leased_until, seq) | |
| 6248 | - WHERE lease_id IS NOT NULL`, | |
| 6249 | - ); | |
| 6250 | - sql.exec( | |
| 6251 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_moving | |
| 6252 | - ON ${__QUEUE_MESSAGES} (seq) | |
| 6253 | - WHERE dlq_target IS NOT NULL`, | |
| 6254 | - ); | |
| 6255 | - // Dispatch and settlement both select a whole batch by its lease. Without | |
| 6256 | - // this index SQLite answers them by walking every row: the dispatch | |
| 6257 | - // readback scans `_visible` and the settlement scan walks the table, so | |
| 6258 | - // each delivered batch costs two passes over the backlog. The `_lease` | |
| 6259 | - // index cannot serve them because it is keyed on `leased_until`. | |
| 6260 | - // The partial predicate keeps only leased rows, which `max_concurrency` | |
| 6261 | - // times `max_batch_size` bounds, and an inserted message has a null | |
| 6262 | - // `lease_id`, so `send` pays nothing for it. | |
| 6263 | - sql.exec( | |
| 6264 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease_batch | |
| 6265 | - ON ${__QUEUE_MESSAGES} (lease_id, visible_at, seq) | |
| 6266 | - WHERE lease_id IS NOT NULL`, | |
| 6267 | - ); | |
| 6268 | - // The live-row index catches an impossible duplicate while a received | |
| 6269 | - // message remains queued. The receipt below is the durable deduplication | |
| 6270 | - // record after a consumer or purge removes that message. | |
| 6271 | - sql.exec( | |
| 6272 | - `CREATE UNIQUE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_dlq_transfer | |
| 6273 | - ON ${__QUEUE_MESSAGES} (dlq_transfer_id) | |
| 6274 | - WHERE dlq_transfer_id IS NOT NULL AND dlq_target IS NULL`, | |
| 6275 | - ); | |
| 6276 | - sql.exec( | |
| 6277 | - `CREATE TABLE IF NOT EXISTS ${__QUEUE_META} ( | |
| 6278 | - name TEXT PRIMARY KEY, | |
| 6279 | - value TEXT NOT NULL | |
| 6280 | - ) WITHOUT ROWID`, | |
| 6281 | - ); | |
| 6282 | - // The producer result and operator metrics are on hot paths. SQLite | |
| 6283 | - // triggers keep the three values in the same transaction as every row | |
| 6284 | - // transition, so a caller cannot observe a new message with old totals. | |
| 6285 | - sql.exec( | |
| 6286 | - `CREATE TABLE IF NOT EXISTS ${__QUEUE_STATS} ( | |
| 6287 | - id INTEGER PRIMARY KEY CHECK (id = 1), | |
| 6288 | - stored_count INTEGER NOT NULL, | |
| 6289 | - backlog_count INTEGER NOT NULL, | |
| 6290 | - backlog_bytes INTEGER NOT NULL, | |
| 6291 | - oldest_message_timestamp INTEGER | |
| 6292 | - )`, | |
| 6293 | - ); | |
| 6294 | - sql.exec( | |
| 6295 | - `INSERT INTO ${__QUEUE_STATS} | |
| 6296 | - (id, stored_count, backlog_count, backlog_bytes, | |
| 6297 | - oldest_message_timestamp) | |
| 6298 | - SELECT 1, | |
| 6299 | - COUNT(*), | |
| 6300 | - COALESCE(SUM(purge_on_settle = 0), 0), | |
| 6301 | - COALESCE(SUM(CASE WHEN purge_on_settle = 0 THEN size ELSE 0 END), 0), | |
| 6302 | - MIN(CASE WHEN purge_on_settle = 0 THEN enqueued_at END) | |
| 6303 | - FROM ${__QUEUE_MESSAGES} | |
| 6304 | - WHERE true | |
| 6305 | - ON CONFLICT(id) DO NOTHING`, | |
| 6306 | - ); | |
| 6307 | - sql.exec( | |
| 6308 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_insert | |
| 6309 | - AFTER INSERT ON ${__QUEUE_MESSAGES} | |
| 6310 | - BEGIN | |
| 6311 | - UPDATE ${__QUEUE_STATS} | |
| 6312 | - SET stored_count = stored_count + 1 | |
| 6313 | - WHERE id = 1; | |
| 6314 | - END`, | |
| 6315 | - ); | |
| 6316 | - sql.exec( | |
| 6317 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_delete | |
| 6318 | - AFTER DELETE ON ${__QUEUE_MESSAGES} | |
| 6319 | - BEGIN | |
| 6320 | - UPDATE ${__QUEUE_STATS} | |
| 6321 | - SET stored_count = stored_count - 1 | |
| 6322 | - WHERE id = 1; | |
| 6323 | - END`, | |
| 6324 | - ); | |
| 6325 | - sql.exec( | |
| 6326 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_insert | |
| 6327 | - AFTER INSERT ON ${__QUEUE_MESSAGES} | |
| 6328 | - WHEN new.purge_on_settle = 0 | |
| 6329 | - BEGIN | |
| 6330 | - UPDATE ${__QUEUE_STATS} | |
| 6331 | - SET backlog_count = backlog_count + 1, | |
| 6332 | - backlog_bytes = backlog_bytes + new.size, | |
| 6333 | - oldest_message_timestamp = CASE | |
| 6334 | - WHEN oldest_message_timestamp IS NULL | |
| 6335 | - OR new.enqueued_at < oldest_message_timestamp | |
| 6336 | - THEN new.enqueued_at ELSE oldest_message_timestamp END | |
| 6337 | - WHERE id = 1; | |
| 6338 | - END`, | |
| 6339 | - ); | |
| 6340 | - sql.exec( | |
| 6341 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_delete | |
| 6342 | - AFTER DELETE ON ${__QUEUE_MESSAGES} | |
| 6343 | - WHEN old.purge_on_settle = 0 | |
| 6344 | - BEGIN | |
| 6345 | - UPDATE ${__QUEUE_STATS} | |
| 6346 | - SET backlog_count = backlog_count - 1, | |
| 6347 | - backlog_bytes = backlog_bytes - old.size, | |
| 6348 | - oldest_message_timestamp = CASE | |
| 6349 | - WHEN backlog_count <= 1 THEN NULL | |
| 6350 | - WHEN oldest_message_timestamp = old.enqueued_at | |
| 6351 | - THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} | |
| 6352 | - WHERE purge_on_settle = 0) | |
| 6353 | - ELSE oldest_message_timestamp END | |
| 6354 | - WHERE id = 1; | |
| 6355 | - END`, | |
| 6356 | - ); | |
| 6357 | - sql.exec( | |
| 6358 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_exclude | |
| 6359 | - AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} | |
| 6360 | - WHEN old.purge_on_settle = 0 AND new.purge_on_settle != 0 | |
| 6361 | - BEGIN | |
| 6362 | - UPDATE ${__QUEUE_STATS} | |
| 6363 | - SET backlog_count = backlog_count - 1, | |
| 6364 | - backlog_bytes = backlog_bytes - old.size, | |
| 6365 | - oldest_message_timestamp = CASE | |
| 6366 | - WHEN backlog_count <= 1 THEN NULL | |
| 6367 | - WHEN oldest_message_timestamp = old.enqueued_at | |
| 6368 | - THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} | |
| 6369 | - WHERE purge_on_settle = 0) | |
| 6370 | - ELSE oldest_message_timestamp END | |
| 6371 | - WHERE id = 1; | |
| 6372 | - END`, | |
| 6373 | - ); | |
| 6374 | - sql.exec( | |
| 6375 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_include | |
| 6376 | - AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} | |
| 6377 | - WHEN old.purge_on_settle != 0 AND new.purge_on_settle = 0 | |
| 6378 | - BEGIN | |
| 6379 | - UPDATE ${__QUEUE_STATS} | |
| 6380 | - SET backlog_count = backlog_count + 1, | |
| 6381 | - backlog_bytes = backlog_bytes + new.size, | |
| 6382 | - oldest_message_timestamp = CASE | |
| 6383 | - WHEN oldest_message_timestamp IS NULL | |
| 6384 | - OR new.enqueued_at < oldest_message_timestamp | |
| 6385 | - THEN new.enqueued_at ELSE oldest_message_timestamp END | |
| 6386 | - WHERE id = 1; | |
| 6387 | - END`, | |
| 6388 | - ); | |
| 6389 | - sql.exec( | |
| 6390 | - `CREATE TABLE IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS} ( | |
| 6391 | - transfer_id TEXT PRIMARY KEY, | |
| 6392 | - message_id TEXT NOT NULL, | |
| 6393 | - dead_letter_source TEXT, | |
| 6394 | - expires_at INTEGER NOT NULL | |
| 6395 | - ) WITHOUT ROWID`, | |
| 6396 | - ); | |
| 6397 | - sql.exec( | |
| 6398 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS}_expires | |
| 6399 | - ON ${__QUEUE_TRANSFER_RECEIPTS} (expires_at, transfer_id)`, | |
| 6400 | - ); | |
| 6401 | - this._ready = true; | |
| 6402 | - return sql; | |
| 6403 | - } | |
| 6404 | - | |
| 6405 | - _meta(name) { | |
| 6406 | - return this._open().exec( | |
| 6407 | - `SELECT value FROM ${__QUEUE_META} WHERE name = ?`, name, | |
| 6408 | - ).toArray()[0]?.value; | |
| 6409 | - } | |
| 6410 | - | |
| 6411 | - _setMeta(name, value) { | |
| 6412 | - if (value === null || value === undefined) { | |
| 6413 | - this._open().exec(`DELETE FROM ${__QUEUE_META} WHERE name = ?`, name); | |
| 6414 | - return; | |
| 6415 | - } | |
| 6416 | - this._open().exec( | |
| 6417 | - `INSERT INTO ${__QUEUE_META} (name, value) VALUES (?, ?) | |
| 6418 | - ON CONFLICT(name) DO UPDATE SET value = excluded.value`, | |
| 6419 | - name, | |
| 6420 | - String(value), | |
| 6421 | - ); | |
| 6422 | - } | |
| 6423 | - | |
| 6424 | - _paused() { | |
| 6425 | - return this._meta("paused") === "1"; | |
| 6426 | - } | |
| 6427 | - | |
| 6428 | - _metrics(now = Date.now(), waitingOnly = false) { | |
| 6429 | - const expiresBefore = now - __queueLimits().retentionMs; | |
| 6430 | - const sql = this._open(); | |
| 6431 | - const stats = sql.exec( | |
| 6432 | - `SELECT backlog_count, backlog_bytes, oldest_message_timestamp | |
| 6433 | - FROM ${__QUEUE_STATS} WHERE id = 1`, | |
| 6434 | - ).toArray()[0]; | |
| 6435 | - // Retention is a clock transition, not a row transition. Until the | |
| 6436 | - // bounded sweep catches up, use the exact query only at that boundary; | |
| 6437 | - // the normal hot path remains one materialized row at every depth. | |
| 6438 | - if (stats.oldest_message_timestamp !== null && | |
| 6439 | - stats.oldest_message_timestamp <= expiresBefore) { | |
| 6440 | - const row = sql.exec( | |
| 6441 | - `SELECT COUNT(*) AS backlog_count, | |
| 6442 | - COALESCE(SUM(size), 0) AS backlog_bytes, | |
| 6443 | - MIN(enqueued_at) AS oldest_message_timestamp | |
| 6444 | - FROM ${__QUEUE_MESSAGES} | |
| 6445 | - WHERE purge_on_settle = 0 AND enqueued_at > ? | |
| 6446 | - AND (? = 0 OR (lease_id IS NULL AND dlq_target IS NULL | |
| 6447 | - AND visible_at <= ?))`, | |
| 6448 | - expiresBefore, | |
| 6449 | - waitingOnly ? 1 : 0, | |
| 6450 | - now, | |
| 6451 | - ).toArray()[0]; | |
| 6452 | - return { | |
| 6453 | - backlogCount: row.backlog_count, | |
| 6454 | - backlogBytes: row.backlog_bytes, | |
| 6455 | - oldestMessageTimestamp: row.oldest_message_timestamp ?? null, | |
| 6456 | - }; | |
| 6457 | - } | |
| 6458 | - if (!waitingOnly) { | |
| 6459 | - if (typeof __test_queue_metrics_materialized === "function") { | |
| 6460 | - __test_queue_metrics_materialized(); | |
| 6461 | - } | |
| 6462 | - return { | |
| 6463 | - backlogCount: stats.backlog_count, | |
| 6464 | - backlogBytes: stats.backlog_bytes, | |
| 6465 | - oldestMessageTimestamp: stats.oldest_message_timestamp ?? null, | |
| 6466 | - }; | |
| 6467 | - } | |
| 6468 | - const blocked = sql.exec( | |
| 6469 | - `SELECT COALESCE(SUM(blocked_count), 0) AS blocked_count, | |
| 6470 | - COALESCE(SUM(blocked_bytes), 0) AS blocked_bytes | |
| 6471 | - FROM ( | |
| 6472 | - SELECT COUNT(*) AS blocked_count, | |
| 6473 | - COALESCE(SUM(size), 0) AS blocked_bytes | |
| 6474 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 6475 | - WHERE purge_on_settle = 0 AND lease_id IS NOT NULL | |
| 6476 | - UNION ALL | |
| 6477 | - SELECT COUNT(*) AS blocked_count, | |
| 6478 | - COALESCE(SUM(size), 0) AS blocked_bytes | |
| 6479 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving | |
| 6480 | - WHERE purge_on_settle = 0 AND dlq_target IS NOT NULL | |
| 6481 | - UNION ALL | |
| 6482 | - SELECT COUNT(*) AS blocked_count, | |
| 6483 | - COALESCE(SUM(size), 0) AS blocked_bytes | |
| 6484 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 6485 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6486 | - AND lease_id IS NULL AND visible_at > ? | |
| 6487 | - )`, | |
| 6488 | - now, | |
| 6489 | - ).toArray()[0]; | |
| 6490 | - const unleasedOldest = sql.exec( | |
| 6491 | - `SELECT enqueued_at | |
| 6492 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained | |
| 6493 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6494 | - AND lease_id IS NULL AND visible_at <= ? | |
| 6495 | - ORDER BY enqueued_at, seq | |
| 6496 | - LIMIT 1`, | |
| 6497 | - now, | |
| 6498 | - ).toArray()[0]?.enqueued_at ?? null; | |
| 6499 | - return { | |
| 6500 | - backlogCount: stats.backlog_count - blocked.blocked_count, | |
| 6501 | - backlogBytes: stats.backlog_bytes - blocked.blocked_bytes, | |
| 6502 | - oldestMessageTimestamp: unleasedOldest, | |
| 6503 | - }; | |
| 6504 | - } | |
| 6505 | - | |
| 6506 | - async _rearm(now = Date.now(), waitForWake = false) { | |
| 6507 | - const sql = this._open(); | |
| 6508 | - const consumer = __cell.queueConsumers?.[this.queue]; | |
| 6509 | - const paused = this._paused(); | |
| 6510 | - const active = sql.exec( | |
| 6511 | - `SELECT COUNT(DISTINCT lease_id) AS count | |
| 6512 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 6513 | - WHERE lease_id IS NOT NULL AND leased_until > ?`, | |
| 6514 | - now, | |
| 6515 | - ).toArray()[0].count; | |
| 6516 | - const concurrency = consumer | |
| 6517 | - ? consumer.maxConcurrency ?? __queueLimits().maxConcurrency | |
| 6518 | - : 0; | |
| 6519 | - const hasCapacity = !paused && consumer !== undefined && __queuePolicy({ | |
| 6520 | - op: "capacity", | |
| 6521 | - active, | |
| 6522 | - maximum: concurrency, | |
| 6523 | - }); | |
| 6524 | - // We need only enough ready rows to distinguish a partial batch from a | |
| 6525 | - // full one. The two indexed arms cover a new row and an expired lease, | |
| 6526 | - // and the outer LIMIT keeps the work independent of backlog depth. | |
| 6527 | - let ready = []; | |
| 6528 | - if (hasCapacity) { | |
| 6529 | - const visibleReady = sql.exec( | |
| 6530 | - `SELECT visible_at AS ready_at, seq | |
| 6531 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 6532 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6533 | - AND lease_id IS NULL AND visible_at <= ? | |
| 6534 | - ORDER BY visible_at, seq | |
| 6535 | - LIMIT ?`, | |
| 6536 | - now, | |
| 6537 | - consumer.maxBatchSize, | |
| 6538 | - ).toArray(); | |
| 6539 | - const expiredReady = sql.exec( | |
| 6540 | - `SELECT leased_until AS ready_at, seq | |
| 6541 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 6542 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6543 | - AND lease_id IS NOT NULL AND leased_until <= ? | |
| 6544 | - ORDER BY leased_until, seq | |
| 6545 | - LIMIT ?`, | |
| 6546 | - now, | |
| 6547 | - consumer.maxBatchSize, | |
| 6548 | - ).toArray(); | |
| 6549 | - ready = [...visibleReady, ...expiredReady] | |
| 6550 | - .sort((left, right) => left.ready_at - right.ready_at || left.seq - right.seq) | |
| 6551 | - .slice(0, consumer.maxBatchSize); | |
| 6552 | - } | |
| 6553 | - if (typeof __test_queue_rearm_bounded === "function") { | |
| 6554 | - __test_queue_rearm_bounded( | |
| 6555 | - ready.length <= (consumer?.maxBatchSize ?? 0), | |
| 6556 | - ready.length > 0, | |
| 6557 | - ); | |
| 6558 | - } | |
| 6559 | - const earliestVisible = hasCapacity | |
| 6560 | - ? sql.exec( | |
| 6561 | - `SELECT visible_at | |
| 6562 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 6563 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6564 | - AND lease_id IS NULL AND visible_at > ? | |
| 6565 | - ORDER BY visible_at, seq | |
| 6566 | - LIMIT 1`, | |
| 6567 | - now, | |
| 6568 | - ).toArray()[0]?.visible_at ?? null | |
| 6569 | - : null; | |
| 6570 | - const earliestLeaseExpiry = paused | |
| 6571 | - ? null | |
| 6572 | - : sql.exec( | |
| 6573 | - `SELECT leased_until | |
| 6574 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 6575 | - WHERE lease_id IS NOT NULL | |
| 6576 | - ORDER BY leased_until | |
| 6577 | - LIMIT 1`, | |
| 6578 | - ).toArray()[0]?.leased_until ?? null; | |
| 6579 | - const nextSweep = sql.exec( | |
| 6580 | - `SELECT enqueued_at + ? AS next_sweep | |
| 6581 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained | |
| 6582 | - WHERE dlq_target IS NULL AND purge_on_settle = 0 | |
| 6583 | - ORDER BY enqueued_at, seq | |
| 6584 | - LIMIT 1`, | |
| 6585 | - __queueLimits().retentionMs, | |
| 6586 | - ).toArray()[0]?.next_sweep ?? null; | |
| 6587 | - const dlqPending = sql.exec( | |
| 6588 | - `SELECT 1 AS pending | |
| 6589 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving | |
| 6590 | - WHERE dlq_target IS NOT NULL | |
| 6591 | - LIMIT 1`, | |
| 6592 | - ).toArray().length !== 0; | |
| 6593 | - const receiptSweep = sql.exec( | |
| 6594 | - `SELECT expires_at AS next_sweep | |
| 6595 | - FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 6596 | - ORDER BY expires_at, transfer_id | |
| 6597 | - LIMIT 1`, | |
| 6598 | - ).toArray()[0]?.next_sweep ?? null; | |
| 6599 | - // A queue without an attached consumer only wakes to reclaim retention. | |
| 6600 | - // Consumer attachment will nudge the cell when the fleet catalog gains a | |
| 6601 | - // registration; spinning on an already-visible row cannot make progress. | |
| 6602 | - let batchDeadline = null; | |
| 6603 | - if (ready.length > 0) { | |
| 6604 | - batchDeadline = ready.length >= consumer.maxBatchSize | |
| 6605 | - ? now | |
| 6606 | - : ready[0].ready_at + consumer.maxBatchTimeoutMs; | |
| 6607 | - } | |
| 6608 | - if (dlqPending) { | |
| 6609 | - batchDeadline = batchDeadline === null ? now : Math.min(batchDeadline, now); | |
| 6610 | - } | |
| 6611 | - const sweepDeadlines = [nextSweep, receiptSweep] | |
| 6612 | - .filter((deadline) => deadline !== null && deadline !== undefined); | |
| 6613 | - const armAt = __queuePolicy({ | |
| 6614 | - op: "rearm", | |
| 6615 | - now, | |
| 6616 | - batchDeadline, | |
| 6617 | - earliestVisible, | |
| 6618 | - // A live handler can settle after delivery pauses. Do not reclaim its | |
| 6619 | - // lease while paused; resume re-arms the expired deadline immediately | |
| 6620 | - // and only then can a new generation replace it. | |
| 6621 | - earliestLeaseExpiry, | |
| 6622 | - nextSweep: sweepDeadlines.length === 0 ? null : Math.min(...sweepDeadlines), | |
| 6623 | - }); | |
| 6624 | - if (armAt !== null && !Number.isFinite(armAt)) { | |
| 6625 | - throw __queueError("the Queue sweep deadline is invalid"); | |
| 6626 | - } | |
| 6627 | - if (armAt === null) await this.ctx.storage.deleteAlarm(); | |
| 6628 | - else if (waitForWake) { | |
| 6629 | - await __queue_alarm_set_wait(this.ctx.storage._scope, armAt); | |
| 6630 | - } else await this.ctx.storage.setAlarm(armAt); | |
| 6631 | - } | |
| 6632 | - | |
| 6633 | - _newProducerGroup() { | |
| 6634 | - const group = { | |
| 6635 | - calls: [], | |
| 6636 | - entries: [], | |
| 6637 | - bytes: 0, | |
| 6638 | - flushing: false, | |
| 6639 | - timer: null, | |
| 6640 | - }; | |
| 6641 | - this._producerGroup = group; | |
| 6642 | - group.timer = setTimeout(() => { | |
| 6643 | - void this._flushProducerGroup(group); | |
| 6644 | - }, __queueLimits().producerGroupMs); | |
| 6645 | - return group; | |
| 6646 | - } | |
| 6647 | - | |
| 6648 | - async _flushProducerGroup(group) { | |
| 6649 | - if (group.flushing) return; | |
| 6650 | - group.flushing = true; | |
| 6651 | - if (this._producerGroup === group) this._producerGroup = null; | |
| 6652 | - if (group.timer !== null) { | |
| 6653 | - clearTimeout(group.timer); | |
| 6654 | - group.timer = null; | |
| 6655 | - } | |
| 6656 | - | |
| 6657 | - const now = Date.now(); | |
| 6658 | - try { | |
| 6659 | - const sql = this._open(); | |
| 6660 | - this.ctx.storage.transactionSync(() => { | |
| 6661 | - for (const entry of group.entries) { | |
| 6662 | - sql.exec( | |
| 6663 | - `INSERT INTO ${__QUEUE_MESSAGES} | |
| 6664 | - (id, body, content_type, size, enqueued_at, visible_at) | |
| 6665 | - VALUES (?, ?, ?, ?, ?, ?)`, | |
| 6666 | - __queueMessageId(now), | |
| 6667 | - entry.body, | |
| 6668 | - entry.contentType, | |
| 6669 | - entry.size, | |
| 6670 | - now, | |
| 6671 | - now + entry.delaySeconds * 1000, | |
| 6672 | - ); | |
| 6673 | - } | |
| 6674 | - }); | |
| 6675 | - await this._rearm(now, true); | |
| 6676 | - const metrics = this._metrics(now); | |
| 6677 | - if (typeof __test_queue_producer_group === "function") { | |
| 6678 | - __test_queue_producer_group(group.calls.length, group.entries.length); | |
| 6679 | - } | |
| 6680 | - for (const call of group.calls) call.resolve(metrics); | |
| 6681 | - } catch (error) { | |
| 6682 | - for (const call of group.calls) call.reject(error); | |
| 6683 | - } | |
| 6684 | - } | |
| 6685 | - | |
| 6686 | - __queueSend({ entries }) { | |
| 6687 | - const bytes = entries.reduce((total, entry) => total + entry.size, 0); | |
| 6688 | - return new Promise((resolve, reject) => { | |
| 6689 | - let group = this._producerGroup; | |
| 6690 | - if (group !== null && | |
| 6691 | - (group.calls.length + 1 > __QUEUE_PRODUCER_GROUP_CALLS || | |
| 6692 | - group.entries.length + entries.length > __QUEUE_PRODUCER_GROUP_MESSAGES || | |
| 6693 | - group.bytes + bytes > __QUEUE_PRODUCER_GROUP_BYTES)) { | |
| 6694 | - void this._flushProducerGroup(group); | |
| 6695 | - group = null; | |
| 6696 | - } | |
| 6697 | - if (group === null) group = this._newProducerGroup(); | |
| 6698 | - group.calls.push({ resolve, reject }); | |
| 6699 | - group.entries.push(...entries); | |
| 6700 | - group.bytes += bytes; | |
| 6701 | - if (group.calls.length === __QUEUE_PRODUCER_GROUP_CALLS || | |
| 6702 | - group.entries.length === __QUEUE_PRODUCER_GROUP_MESSAGES || | |
| 6703 | - group.bytes === __QUEUE_PRODUCER_GROUP_BYTES) { | |
| 6704 | - void this._flushProducerGroup(group); | |
| 6705 | - } | |
| 6706 | - }); | |
| 6707 | - } | |
| 6708 | - | |
| 6709 | - __queueMetrics() { | |
| 6710 | - return this._metrics(); | |
| 6711 | - } | |
| 6712 | - | |
| 6713 | - // Retention decides visibility through `_metrics` immediately, while this | |
| 6714 | - // bounded sweep only reclaims space. A live lease is marked instead of | |
| 6715 | - // deleted, so its handler can finish but settlement or expiry removes it | |
| 6716 | - // without a redelivery. | |
| 6717 | - _sweep(now) { | |
| 6718 | - const sql = this._open(); | |
| 6719 | - const cutoff = now - __queueLimits().retentionMs; | |
| 6720 | - const messages = __cellSweepBatch( | |
| 6721 | - this.ctx.storage, | |
| 6722 | - (limit) => sql.exec( | |
| 6723 | - `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} | |
| 6724 | - WHERE enqueued_at <= ? | |
| 6725 | - AND (purge_on_settle = 0 | |
| 6726 | - OR lease_id IS NULL OR leased_until <= ?) | |
| 6727 | - ORDER BY enqueued_at, seq | |
| 6728 | - LIMIT ?`, | |
| 6729 | - cutoff, | |
| 6730 | - now, | |
| 6731 | - limit, | |
| 6732 | - ).toArray(), | |
| 6733 | - (row) => { | |
| 6734 | - if (row.lease_id !== null && row.leased_until > now) { | |
| 6735 | - sql.exec( | |
| 6736 | - `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 WHERE seq = ?`, | |
| 6737 | - row.seq, | |
| 6738 | - ); | |
| 6739 | - } else { | |
| 6740 | - sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); | |
| 6741 | - } | |
| 6742 | - }, | |
| 6743 | - __queueLimits().sweepBatchRows, | |
| 6744 | - ); | |
| 6745 | - const remaining = __queueLimits().sweepBatchRows - messages; | |
| 6746 | - if (remaining === 0) return messages; | |
| 6747 | - const receipts = __cellSweepBatch( | |
| 6748 | - this.ctx.storage, | |
| 6749 | - (limit) => sql.exec( | |
| 6750 | - `SELECT transfer_id FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 6751 | - WHERE expires_at <= ? | |
| 6752 | - ORDER BY expires_at, transfer_id | |
| 6753 | - LIMIT ?`, | |
| 6754 | - now, | |
| 6755 | - limit, | |
| 6756 | - ).toArray(), | |
| 6757 | - (row) => { | |
| 6758 | - sql.exec( | |
| 6759 | - `DELETE FROM ${__QUEUE_TRANSFER_RECEIPTS} WHERE transfer_id = ?`, | |
| 6760 | - row.transfer_id, | |
| 6761 | - ); | |
| 6762 | - }, | |
| 6763 | - remaining, | |
| 6764 | - ); | |
| 6765 | - return messages + receipts; | |
| 6766 | - } | |
| 6767 | - | |
| 6768 | - _candidateRows(now, limit) { | |
| 6769 | - return this._open().exec( | |
| 6770 | - `SELECT seq, id, body, content_type, size, enqueued_at, visible_at, | |
| 6771 | - attempts, lease_id, lease_generation, leased_until, | |
| 6772 | - purge_on_settle | |
| 6773 | - FROM ${__QUEUE_MESSAGES} | |
| 6774 | - WHERE dlq_target IS NULL AND ((purge_on_settle = 1 | |
| 6775 | - AND (lease_id IS NULL OR leased_until <= ?)) | |
| 6776 | - OR (purge_on_settle = 0 AND visible_at <= ? | |
| 6777 | - AND (lease_id IS NULL OR leased_until <= ?))) | |
| 6778 | - ORDER BY visible_at, seq | |
| 6779 | - LIMIT ?`, | |
| 6780 | - now, | |
| 6781 | - now, | |
| 6782 | - now, | |
| 6783 | - limit, | |
| 6784 | - ).toArray(); | |
| 6785 | - } | |
| 6786 | - | |
| 6787 | - async _leaseBatch(now, consumer) { | |
| 6788 | - const sql = this._open(); | |
| 6789 | - const active = sql.exec( | |
| 6790 | - `SELECT COUNT(DISTINCT lease_id) AS count | |
| 6791 | - FROM ${__QUEUE_MESSAGES} | |
| 6792 | - WHERE lease_id IS NOT NULL AND leased_until > ?`, | |
| 6793 | - now, | |
| 6794 | - ).toArray()[0].count; | |
| 6795 | - const concurrency = consumer.maxConcurrency ?? __queueLimits().maxConcurrency; | |
| 6796 | - if (!__queuePolicy({ op: "capacity", active, maximum: concurrency })) return null; | |
| 6797 | - | |
| 6798 | - // Read extra rows so expired purge markers cannot hide a deliverable | |
| 6799 | - // batch. Policy chooses at most `maxBatchSize` rows and returns every | |
| 6800 | - // purge deletion that precedes them in this bounded scan. | |
| 6801 | - const rows = this._candidateRows(now, consumer.maxBatchSize + 256); | |
| 6802 | - const deliverable = rows.filter((row) => row.purge_on_settle === 0); | |
| 6803 | - if (deliverable.length === 0) { | |
| 6804 | - if (rows.length > 0) { | |
| 6805 | - this.ctx.storage.transactionSync(() => { | |
| 6806 | - for (const row of rows) { | |
| 6807 | - sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); | |
| 6808 | - } | |
| 6809 | - }); | |
| 6810 | - } | |
| 6811 | - return null; | |
| 6812 | - } | |
| 6813 | - const readySince = Math.min(...deliverable.map((row) => | |
| 6814 | - row.lease_id === null ? row.visible_at : row.leased_until | |
| 6815 | - )); | |
| 6816 | - if (deliverable.length < consumer.maxBatchSize && | |
| 6817 | - readySince + consumer.maxBatchTimeoutMs > now) { | |
| 6818 | - return null; | |
| 6819 | - } | |
| 6820 | - | |
| 6821 | - const plan = __queuePolicy({ | |
| 6822 | - op: "batch", | |
| 6823 | - now, | |
| 6824 | - maxBatchSize: consumer.maxBatchSize, | |
| 6825 | - rows: rows.map((row) => ({ | |
| 6826 | - seq: row.seq, | |
| 6827 | - visibleAt: row.visible_at, | |
| 6828 | - leaseGeneration: String(row.lease_generation), | |
| 6829 | - leasedUntil: row.leased_until, | |
| 6830 | - purgeOnSettle: row.purge_on_settle !== 0, | |
| 6831 | - })), | |
| 6832 | - }); | |
| 6833 | - if (plan.leases.length === 0 && plan.deletePurged.length === 0) return null; | |
| 6834 | - const rowBySeq = new Map(rows.map((row) => [row.seq, row])); | |
| 6835 | - const reclaimed = plan.leases.filter((lease) => lease.reclaimed); | |
| 6836 | - const expiryPolicy = __queuePolicy({ | |
| 6837 | - op: "expiry", | |
| 6838 | - now, | |
| 6839 | - entries: reclaimed.map((lease) => { | |
| 6840 | - const row = rowBySeq.get(lease.seq); | |
| 6841 | - return { | |
| 6842 | - priorFailures: row.attempts, | |
| 6843 | - maxRetries: consumer.maxRetries, | |
| 6844 | - configuredSeconds: consumer.retryDelaySeconds ?? null, | |
| 6845 | - purgeOnSettle: row.purge_on_settle !== 0, | |
| 6846 | - }; | |
| 6847 | - }), | |
| 6848 | - }); | |
| 6849 | - const expiryBySeq = new Map( | |
| 6850 | - reclaimed.map((lease, index) => [lease.seq, expiryPolicy[index]]), | |
| 6851 | - ); | |
| 6852 | - const installs = plan.leases.filter((lease) => { | |
| 6853 | - const expiry = expiryBySeq.get(lease.seq); | |
| 6854 | - return expiry === undefined || | |
| 6855 | - (expiry.action.kind === "retry" && expiry.action.at <= now); | |
| 6856 | - }); | |
| 6857 | - const exhaustedTransfers = new Map( | |
| 6858 | - reclaimed | |
| 6859 | - .filter((lease) => | |
| 6860 | - expiryBySeq.get(lease.seq).action.kind === "exhausted" && | |
| 6861 | - consumer.deadLetterQueue !== undefined | |
| 6862 | - ) | |
| 6863 | - .map((lease) => [lease.seq, crypto.randomUUID()]), | |
| 6864 | - ); | |
| 6865 | - const leaseId = crypto.randomUUID(); | |
| 6866 | - const leasedUntil = Math.min( | |
| 6867 | - Number.MAX_SAFE_INTEGER, | |
| 6868 | - now + __cell.queueLeaseDurationMs, | |
| 6869 | - ); | |
| 6870 | - this.ctx.storage.transactionSync(() => { | |
| 6871 | - for (const seq of plan.deletePurged) { | |
| 6872 | - sql.exec( | |
| 6873 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 6874 | - WHERE seq = ? AND purge_on_settle = 1 | |
| 6875 | - AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 6876 | - seq, | |
| 6877 | - now, | |
| 6878 | - ); | |
| 6879 | - } | |
| 6880 | - for (const lease of reclaimed) { | |
| 6881 | - const expiry = expiryBySeq.get(lease.seq); | |
| 6882 | - if (expiry.action.kind === "delete-purged") { | |
| 6883 | - sql.exec( | |
| 6884 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 6885 | - WHERE seq = ? AND leased_until <= ?`, | |
| 6886 | - lease.seq, | |
| 6887 | - now, | |
| 6888 | - ); | |
| 6889 | - } else if (expiry.action.kind === "exhausted") { | |
| 6890 | - if (consumer.deadLetterQueue === undefined) { | |
| 6891 | - sql.exec( | |
| 6892 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 6893 | - WHERE seq = ? AND leased_until <= ?`, | |
| 6894 | - lease.seq, | |
| 6895 | - now, | |
| 6896 | - ); | |
| 6897 | - } else { | |
| 6898 | - sql.exec( | |
| 6899 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 6900 | - SET attempts = ?, lease_id = NULL, leased_until = NULL, | |
| 6901 | - dlq_target = ?, dlq_transfer_id = ?, | |
| 6902 | - transfer_kind = 'dead-letter' | |
| 6903 | - WHERE seq = ? AND leased_until <= ?`, | |
| 6904 | - expiry.attempt, | |
| 6905 | - consumer.deadLetterQueue, | |
| 6906 | - exhaustedTransfers.get(lease.seq), | |
| 6907 | - lease.seq, | |
| 6908 | - now, | |
| 6909 | - ); | |
| 6910 | - } | |
| 6911 | - } else if (expiry.action.at > now) { | |
| 6912 | - sql.exec( | |
| 6913 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 6914 | - SET attempts = ?, visible_at = ?, lease_id = NULL, | |
| 6915 | - leased_until = NULL | |
| 6916 | - WHERE seq = ? AND leased_until <= ?`, | |
| 6917 | - expiry.attempt, | |
| 6918 | - expiry.action.at, | |
| 6919 | - lease.seq, | |
| 6920 | - now, | |
| 6921 | - ); | |
| 6922 | - } | |
| 6923 | - } | |
| 6924 | - for (const lease of installs) { | |
| 6925 | - const generation = Number(lease.generation); | |
| 6926 | - if (!Number.isSafeInteger(generation)) { | |
| 6927 | - throw __queueError(`message ${lease.seq} exhausted its safe lease generation`); | |
| 6928 | - } | |
| 6929 | - sql.exec( | |
| 6930 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 6931 | - SET lease_id = ?, lease_generation = ?, leased_until = ?, | |
| 6932 | - attempts = attempts + ? | |
| 6933 | - WHERE seq = ? AND lease_generation = ? | |
| 6934 | - AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 6935 | - leaseId, | |
| 6936 | - generation, | |
| 6937 | - leasedUntil, | |
| 6938 | - lease.reclaimed ? 1 : 0, | |
| 6939 | - lease.seq, | |
| 6940 | - generation - 1, | |
| 6941 | - now, | |
| 6942 | - ); | |
| 6943 | - } | |
| 6944 | - }); | |
| 6945 | - if (installs.length === 0) return null; | |
| 6946 | - const leasedQuery = | |
| 6947 | - `SELECT seq, id, body, content_type, enqueued_at, attempts, | |
| 6948 | - lease_generation | |
| 6949 | - FROM ${__QUEUE_MESSAGES} | |
| 6950 | - WHERE lease_id = ? | |
| 6951 | - ORDER BY visible_at, seq`; | |
| 6952 | - __queueReportLeaseLookupPlan(sql, leasedQuery, leaseId); | |
| 6953 | - const leased = sql.exec(leasedQuery, leaseId).toArray(); | |
| 6954 | - if (leased.length !== installs.length) { | |
| 6955 | - throw __queueError("the Queue lease transaction changed fewer rows than its plan"); | |
| 6956 | - } | |
| 6957 | - return { | |
| 6958 | - leaseId, | |
| 6959 | - leases: leased.map((row) => ({ | |
| 6960 | - message_id: row.id, | |
| 6961 | - seq: row.seq, | |
| 6962 | - generation: row.lease_generation, | |
| 6963 | - })), | |
| 6964 | - messages: leased.map((row) => ({ | |
| 6965 | - id: row.id, | |
| 6966 | - timestampMs: row.enqueued_at, | |
| 6967 | - // SQLite answers a BLOB as an ArrayBuffer. The raw base64 op accepts | |
| 6968 | - // typed views, so normalize here; otherwise it encodes the text | |
| 6969 | - // "[object ArrayBuffer]" and every consumer decoder sees corrupt data. | |
| 6970 | - bodyBase64: $$btoa( | |
| 6971 | - row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), | |
| 6972 | - ), | |
| 6973 | - contentType: row.content_type, | |
| 6974 | - attempts: row.attempts + 1, | |
| 6975 | - })), | |
| 6976 | - // Miniflare removes every dispatched batch from its backlog before it | |
| 6977 | - // invokes the consumer. Exclude every lease here for the same contract; | |
| 6978 | - // the operator aggregate still includes durable in-flight messages. | |
| 6979 | - metrics: this._metrics(now, true), | |
| 6980 | - }; | |
| 6981 | - } | |
| 6982 | - | |
| 6983 | - // The target deduplicates the stable transfer identity. The source can | |
| 6984 | - // therefore repeat this call after a stop between the target commit and the | |
| 6985 | - // source delete without creating a second message. | |
| 6986 | - async __queueDlqAcceptBatch({ transfers }) { | |
| 6987 | - if (!Array.isArray(transfers) || transfers.length === 0 || | |
| 6988 | - transfers.length > __queueLimits().maxBatchMessages) { | |
| 6989 | - throw __queueError("a Queue transfer batch has an invalid size"); | |
| 6990 | - } | |
| 6991 | - for (const transfer of transfers) { | |
| 6992 | - if (transfer.deadLetterSource !== null && | |
| 6993 | - typeof transfer.deadLetterSource !== "string") { | |
| 6994 | - throw __queueError("a Queue transfer has an invalid dead-letter source"); | |
| 6995 | - } | |
| 6996 | - } | |
| 6997 | - const now = Date.now(); | |
| 6998 | - const sql = this._open(); | |
| 6999 | - this.ctx.storage.transactionSync(() => { | |
| 7000 | - for (const { transferId, entry, deadLetterSource } of transfers) { | |
| 7001 | - const accepted = sql.exec( | |
| 7002 | - `SELECT message_id, dead_letter_source | |
| 7003 | - FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7004 | - WHERE transfer_id = ?`, | |
| 7005 | - transferId, | |
| 7006 | - ).toArray()[0]; | |
| 7007 | - if (accepted !== undefined && (accepted.message_id !== entry.id || | |
| 7008 | - accepted.dead_letter_source !== deadLetterSource)) { | |
| 7009 | - throw __queueError("a DLQ transfer collided with another message identity"); | |
| 7010 | - } | |
| 7011 | - if (accepted !== undefined) continue; | |
| 7012 | - sql.exec( | |
| 7013 | - `INSERT INTO ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7014 | - (transfer_id, message_id, dead_letter_source, expires_at) | |
| 7015 | - VALUES (?, ?, ?, ?)`, | |
| 7016 | - transferId, | |
| 7017 | - entry.id, | |
| 7018 | - deadLetterSource, | |
| 7019 | - now + __queueLimits().retentionMs, | |
| 7020 | - ); | |
| 7021 | - sql.exec( | |
| 7022 | - `INSERT INTO ${__QUEUE_MESSAGES} | |
| 7023 | - (id, body, content_type, size, enqueued_at, visible_at, | |
| 7024 | - attempts, dlq_transfer_id, dead_letter_source) | |
| 7025 | - VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)`, | |
| 7026 | - entry.id, | |
| 7027 | - entry.body, | |
| 7028 | - entry.contentType, | |
| 7029 | - entry.size, | |
| 7030 | - now, | |
| 7031 | - now, | |
| 7032 | - transferId, | |
| 7033 | - deadLetterSource, | |
| 7034 | - ); | |
| 7035 | - } | |
| 7036 | - }); | |
| 7037 | - await this._rearm(now); | |
| 7038 | - return this._metrics(now); | |
| 7039 | - } | |
| 7040 | - | |
| 7041 | - async _driveDlq(limit = 100) { | |
| 7042 | - const now = Date.now(); | |
| 7043 | - const pending = this._open().exec( | |
| 7044 | - `SELECT seq, id, body, content_type, size, dlq_target, dlq_transfer_id, | |
| 7045 | - transfer_kind | |
| 7046 | - FROM ${__QUEUE_MESSAGES} | |
| 7047 | - WHERE dlq_target IS NOT NULL | |
| 7048 | - AND enqueued_at > ? | |
| 7049 | - ORDER BY seq | |
| 7050 | - LIMIT ?`, | |
| 7051 | - now - __queueLimits().retentionMs, | |
| 7052 | - limit, | |
| 7053 | - ).toArray(); | |
| 7054 | - const groups = new Map(); | |
| 7055 | - for (const row of pending) { | |
| 7056 | - let group = groups.get(row.dlq_target); | |
| 7057 | - if (group === undefined) groups.set(row.dlq_target, group = []); | |
| 7058 | - group.push(row); | |
| 7059 | - } | |
| 7060 | - for (const [targetName, rows] of groups) { | |
| 7061 | - const target = __cell.makeNamespace("__Queue").getByName(targetName); | |
| 7062 | - await target.__queueDlqAcceptBatch({ | |
| 7063 | - transfers: rows.map((row) => ({ | |
| 7064 | - transferId: row.dlq_transfer_id, | |
| 7065 | - // A dead-letter transfer records where redrive returns the message. | |
| 7066 | - // A redrive returns it to ordinary queue state, so the source marker | |
| 7067 | - // must not follow it and make a later redrive bounce it backwards. | |
| 7068 | - deadLetterSource: row.transfer_kind === "dead-letter" ? this.queue : null, | |
| 7069 | - entry: { | |
| 7070 | - id: row.id, | |
| 7071 | - body: row.body, | |
| 7072 | - contentType: row.content_type, | |
| 7073 | - size: row.size, | |
| 7074 | - }, | |
| 7075 | - })), | |
| 7076 | - }); | |
| 7077 | - if (typeof __test_queue_dlq_accepted === "function") { | |
| 7078 | - __test_queue_dlq_accepted(); | |
| 7079 | - } | |
| 7080 | - // The target committed every receipt before this reply. Delete the | |
| 7081 | - // corresponding source marks together; a stop before this transaction | |
| 7082 | - // leaves the whole group replayable through those stable receipts. | |
| 7083 | - this.ctx.storage.transactionSync(() => { | |
| 7084 | - for (const row of rows) { | |
| 7085 | - this._open().exec( | |
| 7086 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7087 | - WHERE seq = ? AND dlq_target = ? AND dlq_transfer_id = ? | |
| 7088 | - AND transfer_kind = ?`, | |
| 7089 | - row.seq, | |
| 7090 | - row.dlq_target, | |
| 7091 | - row.dlq_transfer_id, | |
| 7092 | - row.transfer_kind, | |
| 7093 | - ); | |
| 7094 | - } | |
| 7095 | - }); | |
| 7096 | - } | |
| 7097 | - return pending.length; | |
| 7098 | - } | |
| 7099 | - | |
| 7100 | - async alarm() { | |
| 7101 | - const now = Date.now(); | |
| 7102 | - try { | |
| 7103 | - await this._driveDlq(); | |
| 7104 | - } catch (error) { | |
| 7105 | - // The durable source mark is the retry record. An alarm stays armed at | |
| 7106 | - // `now`, and the target's transfer identity makes a replay idempotent. | |
| 7107 | - console.error("Queue DLQ transfer failed:", error); | |
| 7108 | - } | |
| 7109 | - const swept = this._sweep(now); | |
| 7110 | - const consumer = this._paused() | |
| 7111 | - ? undefined | |
| 7112 | - : __cell.queueConsumers?.[this.queue]; | |
| 7113 | - // Install every lease that the configured concurrency admits before the | |
| 7114 | - // first consumer can settle. One lease per alarm serialized full batches | |
| 7115 | - // because the next alarm depended on a later scheduler turn, so a queue | |
| 7116 | - // with maxConcurrency > 1 still used only one handler under backlog. | |
| 7117 | - // `_leaseBatch` counts the durable lease IDs on every iteration, which | |
| 7118 | - // makes the configured concurrency the structural bound for this loop. | |
| 7119 | - const batches = []; | |
| 7120 | - if (consumer !== undefined) { | |
| 7121 | - while (true) { | |
| 7122 | - const batch = await this._leaseBatch(now, consumer); | |
| 7123 | - if (batch === null) break; | |
| 7124 | - batches.push(batch); | |
| 7125 | - } | |
| 7126 | - } | |
| 7127 | - try { | |
| 7128 | - // `_leaseBatch` can exhaust an expired lease and create a new durable | |
| 7129 | - // DLQ mark. Drive that mark in the same wake; the first call above is | |
| 7130 | - // for a mark recovered from an earlier stopped process. | |
| 7131 | - await this._driveDlq(); | |
| 7132 | - } catch (error) { | |
| 7133 | - console.error("Queue DLQ transfer failed:", error); | |
| 7134 | - } | |
| 7135 | - await this._rearm(now); | |
| 7136 | - if (swept >= __queueLimits().sweepBatchRows && batches.length === 0) { | |
| 7137 | - await this.ctx.storage.setAlarm(now + 1); | |
| 7138 | - return; | |
| 7139 | - } | |
| 7140 | - for (const batch of batches) { | |
| 7141 | - // This await covers only the output-gated handoff to the host. The | |
| 7142 | - // consumer runs after this alarm returns, and settlement comes back as | |
| 7143 | - // an independent cell event. All admitted leases are durable before the | |
| 7144 | - // first handoff, so a fast settlement cannot make this turn exceed the | |
| 7145 | - // configured concurrency. | |
| 7146 | - await __queue_dispatch( | |
| 7147 | - consumer.script, | |
| 7148 | - this.queue, | |
| 7149 | - JSON.stringify(batch), | |
| 7150 | - ); | |
| 7151 | - } | |
| 7152 | - } | |
| 7153 | - | |
| 7154 | - _matchingLease(body) { | |
| 7155 | - if (typeof body.leaseId !== "string" || !Array.isArray(body.leases)) return null; | |
| 7156 | - const matchQuery = | |
| 7157 | - `SELECT seq, id, attempts, lease_generation, purge_on_settle | |
| 7158 | - FROM ${__QUEUE_MESSAGES} | |
| 7159 | - WHERE lease_id = ? | |
| 7160 | - ORDER BY seq`; | |
| 7161 | - __queueReportLeaseLookupPlan(this._open(), matchQuery, body.leaseId); | |
| 7162 | - const rows = this._open().exec(matchQuery, body.leaseId).toArray(); | |
| 7163 | - for (const lease of body.leases) { | |
| 7164 | - if (typeof lease?.message_id !== "string" || | |
| 7165 | - !Number.isSafeInteger(lease.seq) || | |
| 7166 | - !Number.isSafeInteger(lease.generation)) return null; | |
| 7167 | - } | |
| 7168 | - const matches = __queuePolicy({ | |
| 7169 | - op: "settlement", | |
| 7170 | - current: rows.map((row) => ({ | |
| 7171 | - seq: String(row.seq), | |
| 7172 | - messageId: row.id, | |
| 7173 | - generation: String(row.lease_generation), | |
| 7174 | - })), | |
| 7175 | - submitted: body.leases.map((lease) => ({ | |
| 7176 | - seq: String(lease.seq), | |
| 7177 | - messageId: lease.message_id, | |
| 7178 | - generation: String(lease.generation), | |
| 7179 | - })), | |
| 7180 | - }); | |
| 7181 | - return matches ? rows : null; | |
| 7182 | - } | |
| 7183 | - | |
| 7184 | - async _settle(body) { | |
| 7185 | - const rows = this._matchingLease(body); | |
| 7186 | - if (rows === null) return false; | |
| 7187 | - const consumer = __cell.queueConsumers?.[this.queue]; | |
| 7188 | - if (consumer === undefined) return false; | |
| 7189 | - const explicitAcks = new Set(body.explicitAcks ?? []); | |
| 7190 | - const retryMessages = new Map( | |
| 7191 | - (body.retryMessages ?? []).map((retry) => [retry.msgId, retry.delaySeconds]), | |
| 7192 | - ); | |
| 7193 | - const retryBatch = body.retryBatch?.retry === true; | |
| 7194 | - const batchDelay = body.retryBatch?.delaySeconds; | |
| 7195 | - const exception = body.outcome === "exception"; | |
| 7196 | - // An explicit ack-all survives a later handler exception, so it must | |
| 7197 | - // override every batch-level and message-level retry signal. | |
| 7198 | - const ackAll = body.ackAll === true; | |
| 7199 | - const decisions = rows.map((row) => { | |
| 7200 | - const retry = !ackAll && !explicitAcks.has(row.id) && ( | |
| 7201 | - retryMessages.has(row.id) || retryBatch || exception | |
| 7202 | - ); | |
| 7203 | - return { row, retry }; | |
| 7204 | - }); | |
| 7205 | - const retrying = decisions.filter((decision) => | |
| 7206 | - decision.retry && decision.row.purge_on_settle === 0 | |
| 7207 | - ); | |
| 7208 | - const retryPolicy = __queuePolicy({ | |
| 7209 | - op: "retries", | |
| 7210 | - now: Date.now(), | |
| 7211 | - entries: retrying.map(({ row }) => ({ | |
| 7212 | - attempt: row.attempts + 1, | |
| 7213 | - maxRetries: consumer.maxRetries, | |
| 7214 | - explicitSeconds: retryMessages.has(row.id) | |
| 7215 | - ? retryMessages.get(row.id) | |
| 7216 | - : retryBatch ? batchDelay : null, | |
| 7217 | - configuredSeconds: consumer.retryDelaySeconds ?? null, | |
| 7218 | - })), | |
| 7219 | - }); | |
| 7220 | - const retryById = new Map( | |
| 7221 | - retrying.map(({ row }, index) => [row.id, retryPolicy[index]]), | |
| 7222 | - ); | |
| 7223 | - const dlqTransferById = new Map( | |
| 7224 | - retrying | |
| 7225 | - .filter(({ row }) => | |
| 7226 | - retryById.get(row.id).exhausted && consumer.deadLetterQueue !== undefined | |
| 7227 | - ) | |
| 7228 | - .map(({ row }) => [row.id, crypto.randomUUID()]), | |
| 7229 | - ); | |
| 7230 | - const sql = this._open(); | |
| 7231 | - this.ctx.storage.transactionSync(() => { | |
| 7232 | - for (const { row, retry } of decisions) { | |
| 7233 | - const policy = retryById.get(row.id); | |
| 7234 | - if (row.purge_on_settle !== 0 || !retry || | |
| 7235 | - (policy.exhausted && consumer.deadLetterQueue === undefined)) { | |
| 7236 | - sql.exec( | |
| 7237 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7238 | - WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 7239 | - row.seq, | |
| 7240 | - body.leaseId, | |
| 7241 | - row.lease_generation, | |
| 7242 | - ); | |
| 7243 | - continue; | |
| 7244 | - } | |
| 7245 | - if (policy.exhausted) { | |
| 7246 | - sql.exec( | |
| 7247 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 7248 | - SET attempts = attempts + 1, lease_id = NULL, | |
| 7249 | - leased_until = NULL, dlq_target = ?, dlq_transfer_id = ?, | |
| 7250 | - transfer_kind = 'dead-letter' | |
| 7251 | - WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 7252 | - consumer.deadLetterQueue, | |
| 7253 | - dlqTransferById.get(row.id), | |
| 7254 | - row.seq, | |
| 7255 | - body.leaseId, | |
| 7256 | - row.lease_generation, | |
| 7257 | - ); | |
| 7258 | - continue; | |
| 7259 | - } | |
| 7260 | - sql.exec( | |
| 7261 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 7262 | - SET attempts = attempts + 1, visible_at = ?, | |
| 7263 | - lease_id = NULL, leased_until = NULL | |
| 7264 | - WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 7265 | - policy.at, | |
| 7266 | - row.seq, | |
| 7267 | - body.leaseId, | |
| 7268 | - row.lease_generation, | |
| 7269 | - ); | |
| 7270 | - } | |
| 7271 | - }); | |
| 7272 | - try { | |
| 7273 | - await this._driveDlq(); | |
| 7274 | - } catch (error) { | |
| 7275 | - // Settlement is durable once the source mark commits. A failed transfer | |
| 7276 | - // is alarm work now, not a reason to put the message back in delivery. | |
| 7277 | - console.error("Queue DLQ transfer deferred:", error); | |
| 7278 | - } | |
| 7279 | - await this._rearm(); | |
| 7280 | - return true; | |
| 7281 | - } | |
| 7282 | - | |
| 7283 | - async _purge() { | |
| 7284 | - const now = Date.now(); | |
| 7285 | - const sql = this._open(); | |
| 7286 | - let deleted = 0; | |
| 7287 | - let leased = 0; | |
| 7288 | - this.ctx.storage.transactionSync(() => { | |
| 7289 | - let after = 0; | |
| 7290 | - while (true) { | |
| 7291 | - // Purge is necessarily proportional to the stored backlog, but its | |
| 7292 | - // policy envelope stays bounded instead of materializing the Queue in | |
| 7293 | - // V8 or Rust. One SQLite transaction keeps the visibility change | |
| 7294 | - // atomic across all chunks. | |
| 7295 | - const rows = sql.exec( | |
| 7296 | - `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} | |
| 7297 | - WHERE seq > ? | |
| 7298 | - ORDER BY seq | |
| 7299 | - LIMIT 256`, | |
| 7300 | - after, | |
| 7301 | - ).toArray(); | |
| 7302 | - if (rows.length === 0) break; | |
| 7303 | - after = rows[rows.length - 1].seq; | |
| 7304 | - const plan = __queuePolicy({ | |
| 7305 | - op: "purge", | |
| 7306 | - now, | |
| 7307 | - rows: rows.map((row) => ({ | |
| 7308 | - seq: String(row.seq), | |
| 7309 | - leaseIdPresent: row.lease_id !== null, | |
| 7310 | - leasedUntil: row.leased_until, | |
| 7311 | - })), | |
| 7312 | - }); | |
| 7313 | - for (const seq of plan.delete) { | |
| 7314 | - sql.exec( | |
| 7315 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7316 | - WHERE seq = ? | |
| 7317 | - AND (lease_id IS NULL OR leased_until IS NULL OR leased_until <= ?)`, | |
| 7318 | - Number(seq), | |
| 7319 | - now, | |
| 7320 | - ); | |
| 7321 | - deleted += 1; | |
| 7322 | - } | |
| 7323 | - for (const seq of plan.markForSettle) { | |
| 7324 | - sql.exec( | |
| 7325 | - `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 | |
| 7326 | - WHERE seq = ? AND lease_id IS NOT NULL AND leased_until > ?`, | |
| 7327 | - Number(seq), | |
| 7328 | - now, | |
| 7329 | - ); | |
| 7330 | - leased += 1; | |
| 7331 | - } | |
| 7332 | - } | |
| 7333 | - }); | |
| 7334 | - await this._rearm(now); | |
| 7335 | - return { deleted, leased, metrics: this._metrics(now) }; | |
| 7336 | - } | |
| 7337 | - | |
| 7338 | - async _setPaused(paused) { | |
| 7339 | - this._setMeta("paused", paused ? "1" : null); | |
| 7340 | - await this._rearm(); | |
| 7341 | - return { paused, ...this._metrics() }; | |
| 7342 | - } | |
| 7343 | - | |
| 7344 | - _operatorLimit(value, fallback) { | |
| 7345 | - const limit = value ?? fallback; | |
| 7346 | - if (!Number.isInteger(limit) || limit < 1 || limit > 100) { | |
| 7347 | - throw __queueError("limit must be an integer from 1 through 100"); | |
| 7348 | - } | |
| 7349 | - return limit; | |
| 7350 | - } | |
| 7351 | - | |
| 7352 | - _peek(limit) { | |
| 7353 | - const now = Date.now(); | |
| 7354 | - const cutoff = now - __queueLimits().retentionMs; | |
| 7355 | - const rows = this._open().exec( | |
| 7356 | - `SELECT id, body, content_type, size, enqueued_at, visible_at, attempts, | |
| 7357 | - lease_id, leased_until, purge_on_settle, dlq_target, | |
| 7358 | - dead_letter_source | |
| 7359 | - FROM ${__QUEUE_MESSAGES} | |
| 7360 | - WHERE enqueued_at > ? | |
| 7361 | - ORDER BY visible_at, seq | |
| 7362 | - LIMIT ?`, | |
| 7363 | - cutoff, | |
| 7364 | - limit, | |
| 7365 | - ).toArray(); | |
| 7366 | - return { | |
| 7367 | - messages: rows.map((row) => ({ | |
| 7368 | - id: row.id, | |
| 7369 | - bodyBase64: $$btoa( | |
| 7370 | - row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), | |
| 7371 | - ), | |
| 7372 | - contentType: row.content_type, | |
| 7373 | - size: row.size, | |
| 7374 | - enqueuedAt: row.enqueued_at, | |
| 7375 | - visibleAt: row.visible_at, | |
| 7376 | - attempts: row.attempts, | |
| 7377 | - state: row.dlq_target !== null | |
| 7378 | - ? "moving" | |
| 7379 | - : row.purge_on_settle !== 0 | |
| 7380 | - ? "purging" | |
| 7381 | - : row.lease_id !== null && row.leased_until > now | |
| 7382 | - ? "leased" | |
| 7383 | - : row.visible_at <= now | |
| 7384 | - ? "visible" | |
| 7385 | - : "delayed", | |
| 7386 | - leasedUntil: row.lease_id !== null && row.leased_until > now | |
| 7387 | - ? row.leased_until | |
| 7388 | - : null, | |
| 7389 | - transferTarget: row.dlq_target, | |
| 7390 | - deadLetterSource: row.dead_letter_source, | |
| 7391 | - })), | |
| 7392 | - }; | |
| 7393 | - } | |
| 7394 | - | |
| 7395 | - async _redrive(limit) { | |
| 7396 | - // Finish an interrupted move before selecting more work. A transfer mark | |
| 7397 | - // is durable, so selecting it a second time would invent another identity | |
| 7398 | - // where replaying the existing identity is sufficient. | |
| 7399 | - await this._driveDlq(100); | |
| 7400 | - const now = Date.now(); | |
| 7401 | - const cutoff = now - __queueLimits().retentionMs; | |
| 7402 | - const candidates = this._open().exec( | |
| 7403 | - `SELECT seq, dead_letter_source | |
| 7404 | - FROM ${__QUEUE_MESSAGES} | |
| 7405 | - WHERE dead_letter_source IS NOT NULL | |
| 7406 | - AND dlq_target IS NULL | |
| 7407 | - AND purge_on_settle = 0 | |
| 7408 | - AND enqueued_at > ? | |
| 7409 | - AND (lease_id IS NULL OR leased_until <= ?) | |
| 7410 | - ORDER BY visible_at, seq | |
| 7411 | - LIMIT ?`, | |
| 7412 | - cutoff, | |
| 7413 | - now, | |
| 7414 | - limit, | |
| 7415 | - ).toArray(); | |
| 7416 | - const transfers = candidates.map((row) => ({ | |
| 7417 | - ...row, | |
| 7418 | - transferId: crypto.randomUUID(), | |
| 7419 | - })); | |
| 7420 | - this.ctx.storage.transactionSync(() => { | |
| 7421 | - for (const transfer of transfers) { | |
| 7422 | - this._open().exec( | |
| 7423 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 7424 | - SET dlq_target = ?, dlq_transfer_id = ?, transfer_kind = 'redrive', | |
| 7425 | - lease_id = NULL, leased_until = NULL | |
| 7426 | - WHERE seq = ? AND dead_letter_source = ? AND dlq_target IS NULL | |
| 7427 | - AND purge_on_settle = 0 | |
| 7428 | - AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 7429 | - transfer.dead_letter_source, | |
| 7430 | - transfer.transferId, | |
| 7431 | - transfer.seq, | |
| 7432 | - transfer.dead_letter_source, | |
| 7433 | - now, | |
| 7434 | - ); | |
| 7435 | - } | |
| 7436 | - }); | |
| 7437 | - // Arm before the cross-cell call. If the process stops after the durable | |
| 7438 | - // mark, the alarm replays the same transfer identity. | |
| 7439 | - await this._rearm(now); | |
| 7440 | - await this._driveDlq(100); | |
| 7441 | - await this._rearm(); | |
| 7442 | - return { redriven: transfers.length, metrics: this._metrics() }; | |
| 7443 | - } | |
| 7444 | - | |
| 7445 | - async fetch(request) { | |
| 7446 | - const path = new URL(request.url).pathname; | |
| 7447 | - if (request.method !== "POST") { | |
| 7448 | - return new Response("Queue route not found", { status: 404 }); | |
| 7449 | - } | |
| 7450 | - let body; | |
| 7451 | - try { | |
| 7452 | - body = await request.json(); | |
| 7453 | - } catch { | |
| 7454 | - return new Response("invalid Queue request", { status: 400 }); | |
| 7455 | - } | |
| 7456 | - try { | |
| 7457 | - if (path === "/__qSettle") { | |
| 7458 | - return await this._settle(body) | |
| 7459 | - ? new Response(null, { status: 204 }) | |
| 7460 | - : new Response("stale Queue settlement", { status: 409 }); | |
| 7461 | - } | |
| 7462 | - if (body.op === "info") { | |
| 7463 | - const metrics = this._metrics(); | |
| 7464 | - const stored = this._open().exec( | |
| 7465 | - `SELECT stored_count FROM ${__QUEUE_STATS} WHERE id = 1`, | |
| 7466 | - ).toArray()[0].stored_count; | |
| 7467 | - return Response.json({ result: { ...metrics, stored, paused: this._paused() } }); | |
| 7468 | - } | |
| 7469 | - if (body.op === "purge") { | |
| 7470 | - return Response.json({ result: await this._purge() }); | |
| 7471 | - } | |
| 7472 | - if (body.op === "pause") { | |
| 7473 | - return Response.json({ result: await this._setPaused(true) }); | |
| 7474 | - } | |
| 7475 | - if (body.op === "resume") { | |
| 7476 | - return Response.json({ result: await this._setPaused(false) }); | |
| 7477 | - } | |
| 7478 | - if (body.op === "peek") { | |
| 7479 | - return Response.json({ | |
| 7480 | - result: this._peek(this._operatorLimit(body.limit, 10)), | |
| 7481 | - }); | |
| 7482 | - } | |
| 7483 | - if (body.op === "redrive") { | |
| 7484 | - return Response.json({ | |
| 7485 | - result: await this._redrive(this._operatorLimit(body.limit, 100)), | |
| 7486 | - }); | |
| 7487 | - } | |
| 7488 | - return Response.json( | |
| 7489 | - { error: `QUEUE_ERROR: unknown operation ${JSON.stringify(body.op)}` }, | |
| 7490 | - { status: 400 }, | |
| 7491 | - ); | |
| 7492 | - } catch (error) { | |
| 7493 | - return Response.json( | |
| 7494 | - { error: String(error?.message ?? error) }, | |
| 7495 | - { status: 400 }, | |
| 7496 | - ); | |
| 7497 | - } | |
| 7498 | - } | |
| 7499 | -} | |
| 7500 | - | |
| 7501 | -__cell.classes.__Queue = __QueueCell; | |
| 7502 | -__cell.doExports.__Queue = true; | |
| 7503 | - | |
| 7504 | -class Queue { | |
| 7505 | - constructor(queue, cellName, deliveryDelay) { | |
| 7506 | - Object.defineProperties(this, { | |
| 7507 | - _queue: { value: queue }, | |
| 7508 | - _cellName: { value: cellName }, | |
| 7509 | - _deliveryDelay: { value: deliveryDelay }, | |
| 7510 | - }); | |
| 7511 | - } | |
| 7512 | - | |
| 7513 | - get _stub() { | |
| 7514 | - return __cell.makeNamespace("__Queue").getByName(this._cellName); | |
| 7515 | - } | |
| 7516 | - | |
| 7517 | - async _send(entries) { | |
| 7518 | - const metrics = await this._stub.__queueSend({ entries }); | |
| 7519 | - return { metadata: { metrics: __queueMetricsView(metrics) } }; | |
| 7520 | - } | |
| 7521 | - | |
| 7522 | - send(body, options = {}) { | |
| 7523 | - const encoded = __queueEncode(body, options.contentType); | |
| 7524 | - return this._send([{ | |
| 7525 | - ...encoded, | |
| 7526 | - delaySeconds: __queueDelay(options.delaySeconds, this._deliveryDelay), | |
| 7527 | - }]); | |
| 7528 | - } | |
| 7529 | - | |
| 7530 | - sendBatch(messages, options = {}) { | |
| 7531 | - if (messages === null || messages === undefined || | |
| 7532 | - typeof messages[Symbol.iterator] !== "function") { | |
| 7533 | - throw __queueError("sendBatch() needs an iterable of messages"); | |
| 7534 | - } | |
| 7535 | - const entries = []; | |
| 7536 | - let bytes = 0; | |
| 7537 | - const batchDelay = __queueDelay(options.delaySeconds, this._deliveryDelay); | |
| 7538 | - for (const message of messages) { | |
| 7539 | - if (entries.length >= __queueLimits().maxBatchMessages) { | |
| 7540 | - throw __queueError( | |
| 7541 | - `a batch has at most ${__queueLimits().maxBatchMessages} messages`, | |
| 7542 | - ); | |
| 7543 | - } | |
| 7544 | - if (message === null || typeof message !== "object" || !("body" in message)) { | |
| 7545 | - throw __queueError("each batch entry needs a body"); | |
| 7546 | - } | |
| 7547 | - const encoded = __queueEncode(message.body, message.contentType); | |
| 7548 | - bytes += encoded.size; | |
| 7549 | - if (bytes > __queueLimits().maxBatchBytes) { | |
| 7550 | - throw __queueError( | |
| 7551 | - `a batch is at most ${__queueLimits().maxBatchBytes} bytes, got ${bytes}`, | |
| 7552 | - ); | |
| 7553 | - } | |
| 7554 | - entries.push({ | |
| 7555 | - ...encoded, | |
| 7556 | - delaySeconds: __queueDelay(message.delaySeconds, batchDelay), | |
| 7557 | - }); | |
| 7558 | - } | |
| 7559 | - if (entries.length === 0) { | |
| 7560 | - throw __queueError("sendBatch() needs at least one message"); | |
| 7561 | - } | |
| 7562 | - return this._send(entries); | |
| 7563 | - } | |
| 7564 | - | |
| 7565 | - async metrics() { | |
| 7566 | - return __queueMetricsView(await this._stub.__queueMetrics()); | |
| 7567 | - } | |
| 7568 | -} | |
| 7569 | - | |
| 7570 | -globalThis.__makeQueue = (queue, cellName, deliveryDelay) => | |
| 7571 | - new Queue(queue, cellName, deliveryDelay); | |
| 7572 | - | |
| 7573 | -// ---- D1 ----------------------------------------------------------------- | |
| 7574 | -// A D1 database is a cell of a runtime-supplied Durable Object class, so it | |
| 7575 | -// inherits ownership, fencing, LTX replication, RPO=0 acknowledgement and | |
| 7576 | -// pressure shedding from the cell it already is. This half is the server; | |
| 7577 | -// `__makeD1Database` below is the client the binding hands to a Worker. | |
| 7578 | -// | |
| 7579 | -// Everything SQL goes through the one `__d1_run` op. The engine owns the | |
| 7580 | -// statement walk, the row and byte caps, and the meta snapshot, all inside | |
| 7581 | -// one execution — the previous shape assembled these from the general | |
| 7582 | -// SqlStorage ops, and every seam between them was a contract only convention | |
| 7583 | -// enforced. | |
| 7584 | - | |
| 7585 | -// The error families applications match on. A message that already carries | |
| 7586 | -// one must pass through unwrapped: wrapping again would bury the family the | |
| 7587 | -// application is matching under a second D1_ERROR prefix. | |
| 7588 | -const __d1IsFamilyError = (message) => | |
| 7589 | - /^D1_([A-Z]+_)*(ERROR|NOTFOUND): /.test(String(message)); | |
| 7590 | - | |
| 7591 | -const __d1Error = (message, cause) => { | |
| 7592 | - const error = new Error("D1_ERROR: " + String(message)); | |
| 7593 | - error.cause = cause !== undefined ? cause : new Error(String(message)); | |
| 7594 | - return error; | |
| 7595 | -}; | |
| 7596 | - | |
| 7597 | -// A typed refusal from the engine: `{family, message}` becomes the Error the | |
| 7598 | -// application sees, with `.cause` carrying the bare message as upstream does. | |
| 7599 | -const __d1Failure = (failure) => { | |
| 7600 | - const error = new Error(failure.family + ": " + failure.message); | |
| 7601 | - error.cause = new Error(failure.message); | |
| 7602 | - return error; | |
| 7603 | -}; | |
| 7604 | - | |
| 7605 | -const __d1Run = (scope, request) => { | |
| 7606 | - const response = JSON.parse(__d1_run(scope, JSON.stringify(request))); | |
| 7607 | - if (response.error) throw __d1Failure(response.error); | |
| 7608 | - return response.ok; | |
| 7609 | -}; | |
| 7610 | - | |
| 7611 | -class __D1DatabaseCell { | |
| 7612 | - constructor(ctx) { | |
| 7613 | - this.ctx = ctx; | |
| 7614 | - } | |
| 7615 | - // Takes an array so that `batch()` can ride this same method, and the | |
| 7616 | - // same turn, when it lands. | |
| 7617 | - __d1Query(statements) { | |
| 7618 | - const scope = this.ctx.storage.sql._scope; | |
| 7619 | - return statements.map((statement) => | |
| 7620 | - __d1Run(scope, { | |
| 7621 | - mode: "prepared", | |
| 7622 | - sql: String(statement.sql), | |
| 7623 | - params: statement.params || [], | |
| 7624 | - first: !!statement.first, | |
| 7625 | - }) | |
| 7626 | - ); | |
| 7627 | - } | |
| 7628 | - __d1Batch(statements) { | |
| 7629 | - return __d1Run(this.ctx.storage.sql._scope, { | |
| 7630 | - mode: "batch", | |
| 7631 | - statements: statements.map((statement) => ({ | |
| 7632 | - sql: String(statement.sql), | |
| 7633 | - params: statement.params || [], | |
| 7634 | - })), | |
| 7635 | - }); | |
| 7636 | - } | |
| 7637 | - // The CLI's way in. `celld d1` signs each request with the fleet secret | |
| 7638 | - // and sends it to a live node's `/runtime/<scope>` route, which verifies the | |
| 7639 | - // signature and then forwards to the owner over the same dispatch `/do/` | |
| 7640 | - // uses — so the CLI needs no ownership logic and the database is reached | |
| 7641 | - // the way a Worker reaches it. The unauthenticated `/do/` route refuses a | |
| 7642 | - // D1 scope outright: this cell answers arbitrary SQL, and its scope is an | |
| 7643 | - // HMAC over names that sit in the project's config, so the scope itself | |
| 7644 | - // is no secret. | |
| 7645 | - async fetch(request) { | |
| 7646 | - let body; | |
| 7647 | - try { | |
| 7648 | - body = await request.json(); | |
| 7649 | - } catch { | |
| 7650 | - return Response.json({ error: "D1_ERROR: invalid request body" }, { status: 400 }); | |
| 7651 | - } | |
| 7652 | - try { | |
| 7653 | - let result; | |
| 7654 | - if (body.migrate !== undefined) { | |
| 7655 | - result = this.__d1Migrate( | |
| 7656 | - String(body.migrate.name), | |
| 7657 | - String(body.migrate.sql), | |
| 7658 | - String(body.migrate.table || "d1_migrations"), | |
| 7659 | - ); | |
| 7660 | - } else if (body.exec !== undefined) { | |
| 7661 | - // The CLI asks for rows; the Worker binding's exec() never does. | |
| 7662 | - result = __d1Run(this.ctx.storage.sql._scope, { | |
| 7663 | - mode: "exec", | |
| 7664 | - sql: String(body.exec.sql), | |
| 7665 | - rows: !!body.exec.rows, | |
| 7666 | - }); | |
| 7667 | - } else { | |
| 7668 | - result = this.__d1Query(body.statements || []); | |
| 7669 | - } | |
| 7670 | - return Response.json({ result }); | |
| 7671 | - } catch (error) { | |
| 7672 | - return Response.json({ error: String(error && error.message || error) }, { status: 400 }); | |
| 7673 | - } | |
| 7674 | - } | |
| 7675 | - __d1Exec(source) { | |
| 7676 | - const result = __d1Run(this.ctx.storage.sql._scope, { | |
| 7677 | - mode: "exec", | |
| 7678 | - sql: String(source), | |
| 7679 | - rows: false, | |
| 7680 | - }); | |
| 7681 | - return { count: result.count, duration: result.duration }; | |
| 7682 | - } | |
| 7683 | - // Apply one migration and record it. The engine runs the file, the | |
| 7684 | - // bookkeeping insert (the name is a bound parameter, so a file name never | |
| 7685 | - // reaches SQL text) and the BEGIN IMMEDIATE .. COMMIT bracket in one | |
| 7686 | - // request, so a migration that fails part-way rolls back whole and the | |
| 7687 | - // operator fixes the file and re-runs. Without the transaction the | |
| 7688 | - // statements that DID land are exactly the ones a re-run trips over. | |
| 7689 | - __d1Migrate(name, source, table) { | |
| 7690 | - return __d1Run(this.ctx.storage.sql._scope, { | |
| 7691 | - mode: "migrate", | |
| 7692 | - name, | |
| 7693 | - sql: source, | |
| 7694 | - table, | |
| 7695 | - }); | |
| 7696 | - } | |
| 7697 | -} | |
| 7698 | - | |
| 7699 | -__cell.classes.__D1Database = __D1DatabaseCell; | |
| 7700 | -// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class | |
| 7701 | -// is the runtime's own, so grant it here instead of making every D1 user set | |
| 7702 | -// a compatibility flag to reach their database. | |
| 7703 | -__cell.doExports.__D1Database = true; | |
| 7704 | - | |
| 7705 | -// Validate and encode bind values once, at the public boundary, exactly as | |
| 7706 | -// upstream does (workerd d1-api.ts). Byte-shaped values become byte arrays — | |
| 7707 | -// the wire format for a BLOB bind — and anything unsupported throws | |
| 7708 | -// D1_TYPE_ERROR here, before any SQL runs. The first version deferred this | |
| 7709 | -// to a JSON round-trip whose fallthrough was SQL NULL, so a Uint8Array bind | |
| 7710 | -// stored NULL and nothing said so. | |
| 7711 | -const __d1BindValue = (value) => { | |
| 7712 | - const kind = typeof value; | |
| 7713 | - if (kind === "number") { | |
| 7714 | - // A non-finite number has no JSON form, so it crosses as null and | |
| 7715 | - // stores SQL NULL. Upstream does the same (bind(NaN) selects typeof | |
| 7716 | - // "null"); making it explicit here turns the conversion from an | |
| 7717 | - // accident of JSON.stringify into a pinned decision. | |
| 7718 | - return Number.isFinite(value) ? value : null; | |
| 7719 | - } | |
| 7720 | - if (kind === "string") return value; | |
| 7721 | - if (kind === "boolean") return value ? 1 : 0; | |
| 7722 | - if (kind === "object") { | |
| 7723 | - if (value === null) return value; | |
| 7724 | - if ( | |
| 7725 | - Array.isArray(value) && | |
| 7726 | - value.every((byte) => typeof byte === "number" && byte >= 0 && byte < 256) | |
| 7727 | - ) { | |
| 7728 | - return value; | |
| 7729 | - } | |
| 7730 | - if (value instanceof ArrayBuffer) { | |
| 7731 | - return Array.from(new Uint8Array(value)); | |
| 7732 | - } | |
| 7733 | - // A typed view binds its ELEMENT values, each truncated to a byte — | |
| 7734 | - // Int8Array([-1]) stores 0xff, Float32Array([1.5]) stores 0x01 — not | |
| 7735 | - // its underlying byte window, so Uint16Array([65, 66]) stores 2 bytes | |
| 7736 | - // and not 4. Upstream behaves this way (verified against workerd's D1; | |
| 7737 | - // the differential suite pins it), and the bare Array.from that | |
| 7738 | - // preceded this produced elements the engine then refused as bytes. | |
| 7739 | - if (ArrayBuffer.isView(value)) return Array.from(Uint8Array.from(value)); | |
| 7740 | - } | |
| 7741 | - const error = new Error( | |
| 7742 | - `D1_TYPE_ERROR: Type '${kind}' not supported for value '${value}'`, | |
| 7743 | - ); | |
| 7744 | - error.cause = new Error(`Type '${kind}' not supported for value '${value}'`); | |
| 7745 | - throw error; | |
| 7746 | -}; | |
| 7747 | - | |
| 7748 | -class D1PreparedStatement { | |
| 7749 | - constructor(database, sql, params) { | |
| 7750 | - Object.defineProperty(this, "_database", { value: database }); | |
| 7751 | - Object.defineProperty(this, "_sql", { value: sql }); | |
| 7752 | - Object.defineProperty(this, "_params", { value: params }); | |
| 7753 | - } | |
| 7754 | - bind(...values) { | |
| 7755 | - return new D1PreparedStatement( | |
| 7756 | - this._database, | |
| 7757 | - this._sql, | |
| 7758 | - values.map(__d1BindValue), | |
| 7759 | - ); | |
| 7760 | - } | |
| 7761 | - async _run(first) { | |
| 7762 | - const results = await this._database._query([ | |
| 7763 | - { sql: this._sql, params: this._params, first }, | |
| 7764 | - ]); | |
| 7765 | - return results[0]; | |
| 7766 | - } | |
| 7767 | - async all() { | |
| 7768 | - const result = await this._run(); | |
| 7769 | - return { | |
| 7770 | - success: true, | |
| 7771 | - meta: result.meta, | |
| 7772 | - results: result.rows.map((row) => __d1Shape(result.columns, row)), | |
| 7773 | - }; | |
| 7774 | - } | |
| 7775 | - async run() { | |
| 7776 | - return await this.all(); | |
| 7777 | - } | |
| 7778 | - async first(column) { | |
| 7779 | - // `first: true` keeps one row on the cell side, so only that row crosses | |
| 7780 | - // the isolate boundary and the row cap cannot fire for a first(). | |
| 7781 | - const result = await this._run(true); | |
| 7782 | - if (result.rows.length === 0) return null; | |
| 7783 | - const row = __d1Shape(result.columns, result.rows[0]); | |
| 7784 | - if (column === undefined) return row; | |
| 7785 | - // The check runs on the shaped object, as upstream's does, so a column | |
| 7786 | - // named like an Object.prototype member behaves the same here as there. | |
| 7787 | - if (row[column] === undefined) { | |
| 7788 | - const error = new Error( | |
| 7789 | - `D1_COLUMN_NOTFOUND: Column not found (${column})`, | |
| 7790 | - ); | |
| 7791 | - error.cause = new Error("Column not found"); | |
| 7792 | - throw error; | |
| 7793 | - } | |
| 7794 | - return row[column]; | |
| 7795 | - } | |
| 7796 | - async raw(options) { | |
| 7797 | - const result = await this._run(); | |
| 7798 | - return options && options.columnNames | |
| 7799 | - ? [result.columns, ...result.rows] | |
| 7800 | - : result.rows; | |
| 7801 | - } | |
| 7802 | -} | |
| 7803 | - | |
| 7804 | -// Object.fromEntries, not property assignment: assigning to a column named | |
| 7805 | -// `__proto__` would walk the prototype chain and silently drop the value, | |
| 7806 | -// while fromEntries defines an own property whatever the name. | |
| 7807 | -const __d1Shape = (columns, row) => | |
| 7808 | - Object.fromEntries(row.map((value, index) => [columns[index], value])); | |
| 7809 | - | |
| 7810 | -const __d1PublicResult = (result) => ({ | |
| 7811 | - success: true, | |
| 7812 | - meta: result.meta, | |
| 7813 | - results: result.rows.map((row) => __d1Shape(result.columns, row)), | |
| 7814 | -}); | |
| 7815 | - | |
| 7816 | -// celld has one primary and no replicas, so every completed query satisfies | |
| 7817 | -// every earlier session constraint. One stable opaque token states that fact | |
| 7818 | -// without pretending an isolate-local counter is a durable database position. | |
| 7819 | -const __d1PrimaryBookmark = "celld:primary"; | |
| 7820 | - | |
| 7821 | -class D1DatabaseSession { | |
| 7822 | - constructor(database, constraintOrBookmark) { | |
| 7823 | - Object.defineProperty(this, "_database", { value: database }); | |
| 7824 | - const value = constraintOrBookmark == null | |
| 7825 | - ? "first-unconstrained" | |
| 7826 | - : String(constraintOrBookmark).trim(); | |
| 7827 | - if (!value) { | |
| 7828 | - throw new Error("D1_SESSION_ERROR: invalid bookmark or constraint"); | |
| 7829 | - } | |
| 7830 | - Object.defineProperty(this, "_bookmark", { | |
| 7831 | - value: value === "first-primary" || value === "first-unconstrained" ? null : value, | |
| 7832 | - writable: true, | |
| 7833 | - }); | |
| 7834 | - } | |
| 7835 | - _advanceBookmark() { | |
| 7836 | - this._bookmark = __d1PrimaryBookmark; | |
| 7837 | - } | |
| 7838 | - async _query(statements) { | |
| 7839 | - const results = await this._database._query(statements); | |
| 7840 | - this._advanceBookmark(); | |
| 7841 | - return results; | |
| 7842 | - } | |
| 7843 | - prepare(sql) { | |
| 7844 | - return new D1PreparedStatement(this, String(sql), []); | |
| 7845 | - } | |
| 7846 | - async batch(statements) { | |
| 7847 | - const results = await this._database._batch(statements); | |
| 7848 | - this._advanceBookmark(); | |
| 7849 | - return results; | |
| 7850 | - } | |
| 7851 | - getBookmark() { | |
| 7852 | - return this._bookmark; | |
| 7853 | - } | |
| 7854 | -} | |
| 7855 | - | |
| 7856 | -// Named so SDKs that sniff a binding by `constructor.name` recognise it. | |
| 7857 | -class D1Database { | |
| 7858 | - constructor(databaseName) { | |
| 7859 | - Object.defineProperty(this, "_databaseName", { value: databaseName }); | |
| 7860 | - } | |
| 7861 | - // Resolved per call rather than cached: a cell can move between calls, and | |
| 7862 | - // `getByName` is the same cost the Durable Object path already pays. | |
| 7863 | - get _stub() { | |
| 7864 | - return __cell.makeNamespace("__D1Database").getByName(this._databaseName); | |
| 7865 | - } | |
| 7866 | - async _query(statements) { | |
| 7867 | - try { | |
| 7868 | - return await this._stub.__d1Query(statements); | |
| 7869 | - } catch (error) { | |
| 7870 | - if (__d1IsFamilyError(error && error.message)) throw error; | |
| 7871 | - throw __d1Error(String(error && error.message || error), error); | |
| 7872 | - } | |
| 7873 | - } | |
| 7874 | - async _batch(statements) { | |
| 7875 | - try { | |
| 7876 | - const encoded = statements.map((statement) => ({ | |
| 7877 | - sql: statement._sql, | |
| 7878 | - params: statement._params, | |
| 7879 | - })); | |
| 7880 | - const results = await this._stub.__d1Batch(encoded); | |
| 7881 | - return results.map(__d1PublicResult); | |
| 7882 | - } catch (error) { | |
| 7883 | - if (__d1IsFamilyError(error && error.message)) throw error; | |
| 7884 | - throw __d1Error(String(error && error.message || error), error); | |
| 7885 | - } | |
| 7886 | - } | |
| 7887 | - prepare(sql) { | |
| 7888 | - return new D1PreparedStatement(this, String(sql), []); | |
| 7889 | - } | |
| 7890 | - async exec(sql) { | |
| 7891 | - try { | |
| 7892 | - return await this._stub.__d1Exec(String(sql)); | |
| 7893 | - } catch (error) { | |
| 7894 | - if (__d1IsFamilyError(error && error.message)) throw error; | |
| 7895 | - throw __d1Error(String(error && error.message || error), error); | |
| 7896 | - } | |
| 7897 | - } | |
| 7898 | - async batch(statements) { | |
| 7899 | - return await this._batch(statements); | |
| 7900 | - } | |
| 7901 | - withSession(constraintOrBookmark) { | |
| 7902 | - return new D1DatabaseSession(this, constraintOrBookmark); | |
| 7903 | - } | |
| 7904 | - async dump() { | |
| 7905 | - throw __d1Error( | |
| 7906 | - "dump() is not implemented in celld; the database is a SQLite file in " + | |
| 7907 | - "your own bucket", | |
| 7908 | - ); | |
| 7909 | - } | |
| 7910 | -} | |
| 7911 | - | |
| 7912 | -globalThis.__makeD1Database = (databaseName) => new D1Database(databaseName); | |
| 7913 | -// ---- Workflows ---------------------------------------------------------- | |
| 7914 | -// A workflow instance is one cell of the runtime-supplied `__Workflow` class, | |
| 7915 | -// named `<workflow_name>/<instance_id>` through getByName, so it inherits | |
| 7916 | -// ownership, fencing, LTX replication and the output gate from the cell it | |
| 7917 | -// already is. Execution is replay: `run()` re-executes from the top on every | |
| 7918 | -// resume and only steps are memoized, in `ctx.storage` KV under `__wf.*`. | |
| 7919 | -// This half is the server; `__makeWorkflow` below is the client the binding | |
| 7920 | -// hands to a Worker. The public contract is in docs/cloudflare-compat.md. | |
| 7921 | - | |
| 7922 | -// Upstream's limit for a step return, an event payload, and the params. The | |
| 7923 | -// error is distinct and names the step, because "too large" and "the isolate | |
| 7924 | -// died" must not read the same (the D1 row-cap precedent). | |
| 7925 | -const __WF_VALUE_CAP = 1 << 20; | |
| 7926 | -// Workflow names, instance ids, and event types all share this charset. | |
| 7927 | -// `/` is outside it, which is what makes the `<name>/<id>` cell-name join | |
| 7928 | -// unambiguous. | |
| 7929 | -const __WF_NAME_RE = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/; | |
| 7930 | -const __wfError = (message) => new Error("WORKFLOW_ERROR: " + message); | |
| 7931 | -// The suspension primitive: a blocked step returns a promise that never | |
| 7932 | -// settles in this invocation, so user code simply stops progressing. A | |
| 7933 | -// sentinel thrown through user code was rejected because `Promise.all` in | |
| 7934 | -// `run()` would observe it as a rejection and user try/catch would eat it. | |
| 7935 | -const __wfNever = new Promise(() => {}); | |
| 7936 | -const __wfTerminal = (status) => | |
| 7937 | - status === "complete" || status === "errored" || status === "terminated"; | |
| 7938 | -// Upstream's hard bounds: 10,000 retries per step, 365 days for any sleep or | |
| 7939 | -// event wait, one second under a waitForEvent timeout. Enforced loudly at the | |
| 7940 | -// call site -- a config outside them would otherwise misbehave only after | |
| 7941 | -// the instance is minutes or days into its run. | |
| 7942 | -const __WF_RETRY_LIMIT_CAP = 10000; | |
| 7943 | -const __WF_STEP_NAME_LIMIT = 256; | |
| 7944 | -const __WF_MAX_WAIT_MS = 365 * 86400000; | |
| 7945 | -const __WF_MIN_EVENT_TIMEOUT_MS = 1000; | |
| 7946 | -// How long run() can stay pending on non-step work while no step runs and | |
| 7947 | -// none is blocked before the instance fails. Upstream permits un-stepped | |
| 7948 | -// awaits between steps (they are merely non-durable), so erroring at the | |
| 7949 | -// first quiescent macrotask would kill any run() whose external await | |
| 7950 | -// outlives one turn of the loop. Sixty seconds is long enough for any | |
| 7951 | -// sane un-stepped await and short enough that a truly never-settling | |
| 7952 | -// promise fails the instance instead of wedging the alarm handler. | |
| 7953 | -const __WF_STALL_GRACE_MS = 60000; | |
| 7954 | -const __WF_UNITS = { | |
| 7955 | - second: 1000, | |
| 7956 | - minute: 60000, | |
| 7957 | - hour: 3600000, | |
| 7958 | - day: 86400000, | |
| 7959 | - week: 604800000, | |
| 7960 | - // Upstream does not document its month/year arithmetic; fixed 30/365-day | |
| 7961 | - // units are used so one expression cannot mean two durations depending on | |
| 7962 | - // when it runs. | |
| 7963 | - month: 30 * 86400000, | |
| 7964 | - year: 365 * 86400000, | |
| 7965 | -}; | |
| 7966 | -const __wfDuration = (value, what) => { | |
| 7967 | - if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value; | |
| 7968 | - if (typeof value !== "string") { | |
| 7969 | - throw __wfError( | |
| 7970 | - `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + | |
| 7971 | - 'or "<n> <second|minute|hour|day|week|month|year>[s]"', | |
| 7972 | - ); | |
| 7973 | - } | |
| 7974 | - const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week|month|year)s?\s*$/ | |
| 7975 | - .exec(value); | |
| 7976 | - if (!match) { | |
| 7977 | - throw __wfError( | |
| 7978 | - `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + | |
| 7979 | - 'or "<n> <second|minute|hour|day|week|month|year>[s]"', | |
| 7980 | - ); | |
| 7981 | - } | |
| 7982 | - return Number(match[1]) * __WF_UNITS[match[2]]; | |
| 7983 | -}; | |
| 7984 | -const __wfOwnObject = (value) => | |
| 7985 | - value !== null && typeof value === "object" && !Array.isArray(value); | |
| 7986 | -const __wfUnknownKey = (value, allowed) => | |
| 7987 | - Object.keys(value).find((key) => !allowed.includes(key)); | |
| 7988 | -const __wfStepName = (name) => { | |
| 7989 | - // The pinned workers-sdk validator has no minimum length. An empty name is | |
| 7990 | - // therefore valid, although rejecting it looks safer at first glance. A | |
| 7991 | - // non-empty check made celld reject Worker code that the upstream runtime | |
| 7992 | - // accepts, so keep only the upstream length and control-character bounds. | |
| 7993 | - if ( | |
| 7994 | - typeof name !== "string" || name.length > __WF_STEP_NAME_LIMIT || | |
| 7995 | - /[\x00-\x1f]/.test(name) | |
| 7996 | - ) { | |
| 7997 | - throw __wfError( | |
| 7998 | - `invalid step name ${JSON.stringify(name)}: use at most ` + | |
| 7999 | - `${__WF_STEP_NAME_LIMIT} characters and no control characters`, | |
| 8000 | - ); | |
| 8001 | - } | |
| 8002 | -}; | |
| 8003 | -const __wfEventType = (type) => { | |
| 8004 | - if (typeof type !== "string" || type.length > 100 || !__WF_NAME_RE.test(type)) { | |
| 8005 | - throw __wfError( | |
| 8006 | - `invalid event type ${JSON.stringify(type)}: use at most 100 letters, ` + | |
| 8007 | - "digits, hyphens, or underscores", | |
| 8008 | - ); | |
| 8009 | - } | |
| 8010 | -}; | |
| 8011 | -const __wfSleepDuration = (duration, name) => { | |
| 8012 | - const durationMs = __wfDuration( | |
| 8013 | - duration, | |
| 8014 | - `the duration of sleep ${JSON.stringify(name)}`, | |
| 8015 | - ); | |
| 8016 | - if (durationMs > __WF_MAX_WAIT_MS) { | |
| 8017 | - throw __wfError( | |
| 8018 | - `sleep ${JSON.stringify(name)} is ${durationMs} ms, above the upstream ` + | |
| 8019 | - "limit of 365 days", | |
| 8020 | - ); | |
| 8021 | - } | |
| 8022 | - return durationMs; | |
| 8023 | -}; | |
| 8024 | -const __wfSleepUntil = (timestamp, name) => { | |
| 8025 | - const at = timestamp instanceof Date ? timestamp.getTime() : timestamp; | |
| 8026 | - if (typeof at !== "number" || !Number.isFinite(at)) { | |
| 8027 | - throw __wfError( | |
| 8028 | - `invalid sleepUntil timestamp for ${JSON.stringify(name)}: use a Date ` + | |
| 8029 | - "or a UNIX timestamp in milliseconds", | |
| 8030 | - ); | |
| 8031 | - } | |
| 8032 | - const delay = at - Date.now(); | |
| 8033 | - if (delay > __WF_MAX_WAIT_MS) { | |
| 8034 | - throw __wfError( | |
| 8035 | - `sleepUntil ${JSON.stringify(name)} is ${delay} ms away, above the ` + | |
| 8036 | - "upstream limit of 365 days", | |
| 8037 | - ); | |
| 8038 | - } | |
| 8039 | - return at; | |
| 8040 | -}; | |
| 8041 | -const __wfWaitOptions = (options, name) => { | |
| 8042 | - if (!__wfOwnObject(options)) { | |
| 8043 | - throw __wfError(`invalid waitForEvent options for ${JSON.stringify(name)}`); | |
| 8044 | - } | |
| 8045 | - __wfEventType(options.type); | |
| 8046 | - const timeout = options.timeout ?? "24 hours"; | |
| 8047 | - const timeoutMs = __wfDuration( | |
| 8048 | - timeout, | |
| 8049 | - `the timeout of waitForEvent ${JSON.stringify(name)}`, | |
| 8050 | - ); | |
| 8051 | - if (timeoutMs < __WF_MIN_EVENT_TIMEOUT_MS || timeoutMs > __WF_MAX_WAIT_MS) { | |
| 8052 | - throw __wfError( | |
| 8053 | - `the timeout of waitForEvent ${JSON.stringify(name)} is ${timeoutMs} ms; ` + | |
| 8054 | - "upstream allows 1 second to 365 days", | |
| 8055 | - ); | |
| 8056 | - } | |
| 8057 | - return { type: options.type, timeout, timeoutMs }; | |
| 8058 | -}; | |
| 8059 | -const __wfEventOptions = (options) => { | |
| 8060 | - if (!__wfOwnObject(options)) { | |
| 8061 | - throw __wfError("sendEvent() needs an event object"); | |
| 8062 | - } | |
| 8063 | - __wfEventType(options.type); | |
| 8064 | - if (options.payload !== undefined) __wfCheckValue(options.payload, "the event payload"); | |
| 8065 | - return { type: options.type, payload: options.payload }; | |
| 8066 | -}; | |
| 8067 | -const __wfRestartOptions = (options) => { | |
| 8068 | - if (options === undefined) return {}; | |
| 8069 | - if (!__wfOwnObject(options)) { | |
| 8070 | - throw __wfError("restart() options must be an object"); | |
| 8071 | - } | |
| 8072 | - const unknown = __wfUnknownKey(options, ["from"]); | |
| 8073 | - if (unknown !== undefined) { | |
| 8074 | - throw __wfError(`restart() has an unknown option ${JSON.stringify(unknown)}`); | |
| 8075 | - } | |
| 8076 | - if (options.from === undefined) return {}; | |
| 8077 | - const from = options.from; | |
| 8078 | - if (!__wfOwnObject(from)) { | |
| 8079 | - throw __wfError("restart() option from must be an object"); | |
| 8080 | - } | |
| 8081 | - const fromUnknown = __wfUnknownKey(from, ["name", "count", "type"]); | |
| 8082 | - if (fromUnknown !== undefined) { | |
| 8083 | - throw __wfError( | |
| 8084 | - `restart() option from has an unknown field ${JSON.stringify(fromUnknown)}`, | |
| 8085 | - ); | |
| 8086 | - } | |
| 8087 | - __wfStepName(from.name); | |
| 8088 | - const count = from.count ?? 1; | |
| 8089 | - if (!Number.isInteger(count) || count < 1) { | |
| 8090 | - throw __wfError("restart() option from.count must be a positive integer"); | |
| 8091 | - } | |
| 8092 | - const type = from.type ?? "do"; | |
| 8093 | - if (!["do", "sleep", "waitForEvent"].includes(type)) { | |
| 8094 | - throw __wfError( | |
| 8095 | - 'restart() option from.type must be "do", "sleep", or "waitForEvent"', | |
| 8096 | - ); | |
| 8097 | - } | |
| 8098 | - return { from: { name: from.name, count, type } }; | |
| 8099 | -}; | |
| 8100 | -const __wfStepConfig = (config, name) => { | |
| 8101 | - if (!__wfOwnObject(config)) { | |
| 8102 | - throw __wfError(`invalid config for step ${JSON.stringify(name)}: use an object`); | |
| 8103 | - } | |
| 8104 | - let unknown = __wfUnknownKey(config, ["retries", "timeout", "sensitive"]); | |
| 8105 | - if (unknown !== undefined) { | |
| 8106 | - throw __wfError( | |
| 8107 | - `invalid config for step ${JSON.stringify(name)}: unknown option ` + | |
| 8108 | - JSON.stringify(unknown), | |
| 8109 | - ); | |
| 8110 | - } | |
| 8111 | - const retries = config.retries; | |
| 8112 | - if (retries !== undefined) { | |
| 8113 | - if (!__wfOwnObject(retries)) { | |
| 8114 | - throw __wfError(`invalid retries config for step ${JSON.stringify(name)}`); | |
| 8115 | - } | |
| 8116 | - unknown = __wfUnknownKey(retries, ["limit", "delay", "backoff"]); | |
| 8117 | - if (unknown !== undefined) { | |
| 8118 | - throw __wfError( | |
| 8119 | - `invalid retries config for step ${JSON.stringify(name)}: unknown option ` + | |
| 8120 | - JSON.stringify(unknown), | |
| 8121 | - ); | |
| 8122 | - } | |
| 8123 | - if ( | |
| 8124 | - typeof retries.limit !== "number" || !Number.isFinite(retries.limit) || | |
| 8125 | - retries.limit < 0 | |
| 8126 | - ) { | |
| 8127 | - throw __wfError( | |
| 8128 | - `invalid retries config for step ${JSON.stringify(name)}: ` + | |
| 8129 | - "limit must be a non-negative number", | |
| 8130 | - ); | |
| 8131 | - } | |
| 8132 | - if (retries.limit > __WF_RETRY_LIMIT_CAP) { | |
| 8133 | - throw __wfError( | |
| 8134 | - `invalid retries config for step ${JSON.stringify(name)}: limit is above ` + | |
| 8135 | - String(__WF_RETRY_LIMIT_CAP), | |
| 8136 | - ); | |
| 8137 | - } | |
| 8138 | - if (typeof retries.delay !== "function") { | |
| 8139 | - __wfDuration(retries.delay, `the retries config delay of step ${JSON.stringify(name)}`); | |
| 8140 | - } | |
| 8141 | - if ( | |
| 8142 | - retries.backoff !== undefined && | |
| 8143 | - !["constant", "linear", "exponential"].includes(retries.backoff) | |
| 8144 | - ) { | |
| 8145 | - throw __wfError( | |
| 8146 | - `invalid retries config for step ${JSON.stringify(name)}: ` + | |
| 8147 | - "backoff must be constant, linear, or exponential", | |
| 8148 | - ); | |
| 8149 | - } | |
| 8150 | - } | |
| 8151 | - if (config.timeout !== undefined) { | |
| 8152 | - const timeout = __wfDuration( | |
| 8153 | - config.timeout, | |
| 8154 | - `the config timeout of step ${JSON.stringify(name)}`, | |
| 8155 | - ); | |
| 8156 | - if (timeout === 0) { | |
| 8157 | - throw __wfError( | |
| 8158 | - `invalid config timeout for step ${JSON.stringify(name)}: use a value above zero`, | |
| 8159 | - ); | |
| 8160 | - } | |
| 8161 | - } | |
| 8162 | - if (config.sensitive !== undefined && config.sensitive !== "output") { | |
| 8163 | - throw __wfError( | |
| 8164 | - `invalid config sensitive value for step ${JSON.stringify(name)}: use "output"`, | |
| 8165 | - ); | |
| 8166 | - } | |
| 8167 | - return { | |
| 8168 | - ...config, | |
| 8169 | - ...(retries === undefined ? {} : { retries: { ...retries } }), | |
| 8170 | - }; | |
| 8171 | -}; | |
| 8172 | -// Serialization is checked with the same encoder storage and RPC use, so a | |
| 8173 | -// value that passes here cannot fail later at the isolate boundary. The | |
| 8174 | -// thrown errors are permanent: retrying cannot make a value cloneable or | |
| 8175 | -// shrink it. | |
| 8176 | -const __wfEncodeValue = (value, what) => { | |
| 8177 | - try { | |
| 8178 | - return __sc_encode(value); | |
| 8179 | - } catch (error) { | |
| 8180 | - const failure = __wfError( | |
| 8181 | - `${what} is not serializable: ${String(error && error.message || error)}. ` + | |
| 8182 | - "It must survive structured clone; a ReadableStream return is not implemented in celld.", | |
| 8183 | - ); | |
| 8184 | - failure.__wfPermanent = true; | |
| 8185 | - throw failure; | |
| 8186 | - } | |
| 8187 | -}; | |
| 8188 | -const __wfCheckEncodedValue = (bytes, what) => { | |
| 8189 | - if (bytes.byteLength > __WF_VALUE_CAP) { | |
| 8190 | - const failure = __wfError( | |
| 8191 | - `${what} is ${bytes.byteLength} bytes, above the 1 MiB limit; ` + | |
| 8192 | - "store large output externally and return a reference", | |
| 8193 | - ); | |
| 8194 | - failure.__wfPermanent = true; | |
| 8195 | - throw failure; | |
| 8196 | - } | |
| 8197 | -}; | |
| 8198 | -const __wfCheckValue = (value, what) => | |
| 8199 | - __wfCheckEncodedValue(__wfEncodeValue(value, what), what); | |
| 8200 | -const __wfErrorRecord = (error) => ({ | |
| 8201 | - name: String(error && error.name || "Error"), | |
| 8202 | - message: String(error && error.message || error), | |
| 8203 | -}); | |
| 8204 | -// A permanently failed step rejects on every replay, so user try/catch | |
| 8205 | -// around step.do keeps working after a resume, not only on the attempt that | |
| 8206 | -// failed live. | |
| 8207 | -const __wfReviveError = (record) => { | |
| 8208 | - const error = new Error(record.message); | |
| 8209 | - error.name = record.name; | |
| 8210 | - return error; | |
| 8211 | -}; | |
| 8212 | -const __wfLedgerPrefix = (generation) => `__wf.${generation}.`; | |
| 8213 | -const __wfEventPrefix = (generation) => | |
| 8214 | - __wfLedgerPrefix(generation) + "event."; | |
| 8215 | -const __wfEventKey = (generation, sequence) => | |
| 8216 | - __wfEventPrefix(generation) + String(sequence).padStart(9, "0"); | |
| 8217 | -// A ledger record replays only through the kind of call that wrote it. A | |
| 8218 | -// `do` renamed into a `sleep`, or two calls reordered under one name, would | |
| 8219 | -// otherwise read fields the other kind never wrote and continue on | |
| 8220 | -// undefined -- a deadline of NaN, a value of nothing -- instead of failing. | |
| 8221 | -const __wfKindCheck = (record, kind, name) => { | |
| 8222 | - if (record === undefined || record.kind === kind) return record; | |
| 8223 | - const failure = __wfError( | |
| 8224 | - `step ${JSON.stringify(name)} replays as ${kind} but its ledger record ` + | |
| 8225 | - `was written by ${record.kind}; a step keeps one kind across replays`, | |
| 8226 | - ); | |
| 8227 | - failure.__wfPermanent = true; | |
| 8228 | - throw failure; | |
| 8229 | -}; | |
| 8230 | -// Each step callback runs under an async-context frame naming its step (the | |
| 8231 | -// same CPED-backed frame __ctxRun uses, so it survives the callback's | |
| 8232 | -// awaits). A step started inside another step's callback would wedge | |
| 8233 | -// quiescence: the outer callback cannot settle while it awaits the blocked | |
| 8234 | -// inner step, so `running` never reaches zero and the instance can neither | |
| 8235 | -// suspend nor finish. The frame is what lets the inner call refuse loudly | |
| 8236 | -// at the nesting site instead. | |
| 8237 | -const __wfStepKey = Symbol("celld.wfStep"); | |
| 8238 | -const __wfEnclosingStep = () => { | |
| 8239 | - const frame = __als_get(); | |
| 8240 | - return frame === undefined ? undefined : frame.get(__wfStepKey); | |
| 8241 | -}; | |
| 8242 | -const __wfEnterStep = (name, fn) => { | |
| 8243 | - const prior = __als_get(); | |
| 8244 | - const frame = new Map(prior); | |
| 8245 | - frame.set(__wfStepKey, name); | |
| 8246 | - __als_set(frame); | |
| 8247 | - try { | |
| 8248 | - return fn(); | |
| 8249 | - } finally { | |
| 8250 | - __als_set(prior); | |
| 8251 | - } | |
| 8252 | -}; | |
| 8253 | - | |
| 8254 | -// Race an attempt against its deadline. The abandoned callback keeps | |
| 8255 | -// running -- there is no cancellation to send it -- but its result is | |
| 8256 | -// discarded and the timeout counts as a failed attempt, as upstream. | |
| 8257 | -const __wfTimeout = (promise, ms, name, attempt) => | |
| 8258 | - new Promise((resolve, reject) => { | |
| 8259 | - const timer = setTimeout( | |
| 8260 | - () => | |
| 8261 | - reject(new Error( | |
| 8262 | - `step ${JSON.stringify(name)} timed out after ${ms} ms (attempt ${attempt})`, | |
| 8263 | - )), | |
| 8264 | - ms, | |
| 8265 | - ); | |
| 8266 | - promise.then( | |
| 8267 | - (value) => { clearTimeout(timer); resolve(value); }, | |
| 8268 | - (error) => { clearTimeout(timer); reject(error); }, | |
| 8269 | - ); | |
| 8270 | - }); | |
| 8271 | - | |
| 8272 | -// Storage failures belong to the engine even when workflow code catches the | |
| 8273 | -// rejected step promise. Record them outside the Error object, so user code | |
| 8274 | -// cannot suppress a retry or forge one by returning a marked exception. | |
| 8275 | -const __wfTrackStorageFailures = (storage, driver) => { | |
| 8276 | - const tracked = Object.create(storage); | |
| 8277 | - for (const name of ["get", "put", "transactionSync"]) { | |
| 8278 | - Object.defineProperty(tracked, name, { | |
| 8279 | - value(...args) { | |
| 8280 | - try { | |
| 8281 | - const result = storage[name](...args); | |
| 8282 | - if (result !== null && typeof result === "object" && | |
| 8283 | - typeof result.then === "function") { | |
| 8284 | - return result.catch((error) => { | |
| 8285 | - driver.storageFailure ??= error; | |
| 8286 | - throw error; | |
| 8287 | - }); | |
| 8288 | - } | |
| 8289 | - return result; | |
| 8290 | - } catch (error) { | |
| 8291 | - driver.storageFailure ??= error; | |
| 8292 | - throw error; | |
| 8293 | - } | |
| 8294 | - }, | |
| 8295 | - }); | |
| 8296 | - } | |
| 8297 | - return tracked; | |
| 8298 | -}; | |
| 8299 | - | |
| 8300 | -// The WorkflowStep the driver hands to run(). Each method resolves its step | |
| 8301 | -// record by (name, occurrence count) -- the count is assigned synchronously | |
| 8302 | -// at call time, so `Promise.all` of two same-named steps gets deterministic | |
| 8303 | -// distinct keys in call order, and a repeated name in a loop cannot collide. | |
| 8304 | -const __wfMakeStep = (driver) => { | |
| 8305 | - const storage = driver.storage; | |
| 8306 | - // The shared step frame. `body` resolves to {value} or {block: at, kind}; | |
| 8307 | - // a blocked step leaves its promise unsettled forever in this invocation. | |
| 8308 | - // The running counter covers the whole body, ledger reads included, so | |
| 8309 | - // quiescence cannot fire between a step's read and its decision. | |
| 8310 | - const frame = (name, body) => { | |
| 8311 | - // A stale replay -- one whose invocation already suspended -- can wake | |
| 8312 | - // later if user code raced a step against an un-stepped await. It goes | |
| 8313 | - // quiet instead of executing an attempt beside the fresh replay. | |
| 8314 | - if (driver.finished) return __wfNever; | |
| 8315 | - const enclosing = __wfEnclosingStep(); | |
| 8316 | - if (enclosing !== undefined) { | |
| 8317 | - const failure = __wfError( | |
| 8318 | - `step ${JSON.stringify(name)} cannot start inside the callback of ` + | |
| 8319 | - `step ${JSON.stringify(enclosing)}; a step callback must not use ` + | |
| 8320 | - "the step API", | |
| 8321 | - ); | |
| 8322 | - failure.__wfPermanent = true; | |
| 8323 | - return Promise.reject(failure); | |
| 8324 | - } | |
| 8325 | - const count = (driver.counts.get(name) ?? 0) + 1; | |
| 8326 | - driver.counts.set(name, count); | |
| 8327 | - const ordinal = ++driver.ordinal; | |
| 8328 | - const key = driver.ledgerPrefix + `step.${count}.${name}`; | |
| 8329 | - // Step activity restarts the stall clock: a pending grace timer was | |
| 8330 | - // armed against a run() that looked stuck, and this call is progress. | |
| 8331 | - driver.clearStall(); | |
| 8332 | - driver.running += 1; | |
| 8333 | - return new Promise((resolve, reject) => { | |
| 8334 | - (async () => { | |
| 8335 | - const meta = await storage.get("__wf.meta"); | |
| 8336 | - if ( | |
| 8337 | - meta === undefined || meta.generation !== driver.generation || | |
| 8338 | - __wfTerminal(meta.status) || meta.status === "paused" || | |
| 8339 | - meta.status === "waitingForPause" | |
| 8340 | - ) { | |
| 8341 | - return { pause: true }; | |
| 8342 | - } | |
| 8343 | - return await body(key, count, ordinal); | |
| 8344 | - })().then( | |
| 8345 | - (result) => { | |
| 8346 | - driver.running -= 1; | |
| 8347 | - driver.clearStall(); | |
| 8348 | - if (result.pause === true) { | |
| 8349 | - driver.pauseRequested = true; | |
| 8350 | - driver.check(); | |
| 8351 | - return; | |
| 8352 | - } | |
| 8353 | - if (result.block !== undefined) { | |
| 8354 | - if (!driver.finished) { | |
| 8355 | - driver.blocked.push({ at: result.block, kind: result.kind }); | |
| 8356 | - } | |
| 8357 | - driver.check(); | |
| 8358 | - return; | |
| 8359 | - } | |
| 8360 | - driver.check(); | |
| 8361 | - resolve(result.value); | |
| 8362 | - }, | |
| 8363 | - (error) => { | |
| 8364 | - driver.running -= 1; | |
| 8365 | - driver.clearStall(); | |
| 8366 | - driver.check(); | |
| 8367 | - reject(error); | |
| 8368 | - }, | |
| 8369 | - ); | |
| 8370 | - }); | |
| 8371 | - }; | |
| 8372 | - const doStep = (name, configOrCallback, callbackOrRollback, maybeRollback) => { | |
| 8373 | - const hasConfig = typeof configOrCallback !== "function"; | |
| 8374 | - let config = hasConfig ? (configOrCallback ?? {}) : {}; | |
| 8375 | - const callback = hasConfig ? callbackOrRollback : configOrCallback; | |
| 8376 | - const rollback = hasConfig ? maybeRollback : callbackOrRollback; | |
| 8377 | - try { | |
| 8378 | - __wfStepName(name); | |
| 8379 | - config = __wfStepConfig(config, name); | |
| 8380 | - } catch (error) { | |
| 8381 | - return Promise.reject(error); | |
| 8382 | - } | |
| 8383 | - if (rollback !== undefined) { | |
| 8384 | - return Promise.reject(__wfError( | |
| 8385 | - "step rollbackOptions are not implemented in celld; remove the rollback handler", | |
| 8386 | - )); | |
| 8387 | - } | |
| 8388 | - if (config.sensitive !== undefined) { | |
| 8389 | - return Promise.reject(__wfError( | |
| 8390 | - "sensitive step output is not implemented in celld; remove `sensitive`", | |
| 8391 | - )); | |
| 8392 | - } | |
| 8393 | - if (typeof callback !== "function") { | |
| 8394 | - return Promise.reject(__wfError("step.do needs a callback function")); | |
| 8395 | - } | |
| 8396 | - return frame(name, async (key, count, ordinal) => { | |
| 8397 | - const record = __wfKindCheck(await storage.get(key), "do", name); | |
| 8398 | - if (record !== undefined && record.status === "completed") { | |
| 8399 | - return { value: record.value }; | |
| 8400 | - } | |
| 8401 | - if (record !== undefined && record.status === "failed") { | |
| 8402 | - throw __wfReviveError(record.error); | |
| 8403 | - } | |
| 8404 | - // A pending retry whose backoff has not elapsed blocks without | |
| 8405 | - // executing; the deadline was persisted when the attempt failed, so a | |
| 8406 | - // replay cannot reset the backoff. | |
| 8407 | - if (record !== undefined && record.nextAt > Date.now()) { | |
| 8408 | - return { block: record.nextAt, kind: "retry" }; | |
| 8409 | - } | |
| 8410 | - const attempt = (record === undefined ? 0 : record.attempt) + 1; | |
| 8411 | - const historyOrdinal = record?.ordinal ?? ordinal; | |
| 8412 | - const retries = config.retries ?? | |
| 8413 | - { limit: 5, delay: 10000, backoff: "exponential" }; | |
| 8414 | - const timeout = config.timeout ?? "10 minutes"; | |
| 8415 | - const timeoutMs = __wfDuration( | |
| 8416 | - timeout, | |
| 8417 | - `the timeout of step ${JSON.stringify(name)}`, | |
| 8418 | - ); | |
| 8419 | - // Upstream omits a dynamic delay from the step context. Copying the | |
| 8420 | - // config verbatim would expose the callback to itself as retry policy, | |
| 8421 | - // while callers expect only the serializable limit and backoff fields. | |
| 8422 | - const contextRetries = typeof retries.delay === "function" | |
| 8423 | - ? { limit: retries.limit, ...(retries.backoff === undefined | |
| 8424 | - ? {} | |
| 8425 | - : { backoff: retries.backoff }) } | |
| 8426 | - : retries; | |
| 8427 | - const context = { | |
| 8428 | - step: { name, count }, | |
| 8429 | - attempt, | |
| 8430 | - config: { retries: contextRetries, timeout }, | |
| 8431 | - }; | |
| 8432 | - try { | |
| 8433 | - // Persist the history entry before the callback starts. A concurrent | |
| 8434 | - // selected restart can therefore name an in-flight occurrence, and | |
| 8435 | - // its new generation fences the callback's eventual old-ledger write. | |
| 8436 | - await storage.put(key, { | |
| 8437 | - kind: "do", | |
| 8438 | - status: "running", | |
| 8439 | - attempt: attempt - 1, | |
| 8440 | - ordinal: historyOrdinal, | |
| 8441 | - }); | |
| 8442 | - const value = await __wfTimeout( | |
| 8443 | - __wfEnterStep(name, async () => callback(context)), | |
| 8444 | - timeoutMs, | |
| 8445 | - name, | |
| 8446 | - attempt, | |
| 8447 | - ); | |
| 8448 | - if (value !== undefined) { | |
| 8449 | - __wfCheckValue(value, `the return value of step ${JSON.stringify(name)}`); | |
| 8450 | - } | |
| 8451 | - await storage.put(key, { | |
| 8452 | - kind: "do", | |
| 8453 | - status: "completed", | |
| 8454 | - value, | |
| 8455 | - ordinal: historyOrdinal, | |
| 8456 | - }); | |
| 8457 | - return { value }; | |
| 8458 | - } catch (error) { | |
| 8459 | - // NonRetryableError skips retries by contract; a value-cap or | |
| 8460 | - // serialization failure is marked permanent above because another | |
| 8461 | - // attempt returns the same value. | |
| 8462 | - const permanent = error instanceof NonRetryableError || | |
| 8463 | - (error !== null && typeof error === "object" && | |
| 8464 | - (error.name === "NonRetryableError" || error.__wfPermanent === true)) || | |
| 8465 | - attempt > retries.limit; | |
| 8466 | - if (permanent) { | |
| 8467 | - await storage.put(key, { | |
| 8468 | - kind: "do", | |
| 8469 | - status: "failed", | |
| 8470 | - error: __wfErrorRecord(error), | |
| 8471 | - ordinal: historyOrdinal, | |
| 8472 | - }); | |
| 8473 | - throw error; | |
| 8474 | - } | |
| 8475 | - // Upstream documents the backoff names, not the arithmetic; the | |
| 8476 | - // simplest reading is used and recorded in the design page. When | |
| 8477 | - // `retries` is given without `backoff`, celld uses constant -- the | |
| 8478 | - // documented exponential default is the whole-config-omitted case. | |
| 8479 | - const dynamic = typeof retries.delay === "function"; | |
| 8480 | - const delay = dynamic | |
| 8481 | - ? await __wfEnterStep(name, () => retries.delay({ ctx: context, error })) | |
| 8482 | - : retries.delay; | |
| 8483 | - const base = __wfDuration( | |
| 8484 | - delay, | |
| 8485 | - `the retry delay of step ${JSON.stringify(name)}`, | |
| 8486 | - ); | |
| 8487 | - // A delay callback replaces the fixed base duration, not the backoff | |
| 8488 | - // policy. Skipping this factor makes a dynamic exponential or linear | |
| 8489 | - // policy retry earlier than the same policy with a fixed base. | |
| 8490 | - const factor = retries.backoff === "exponential" | |
| 8491 | - ? 2 ** (attempt - 1) | |
| 8492 | - : retries.backoff === "linear" | |
| 8493 | - ? attempt | |
| 8494 | - : 1; | |
| 8495 | - const nextAt = Date.now() + base * factor; | |
| 8496 | - await storage.put(key, { | |
| 8497 | - kind: "do", | |
| 8498 | - status: "retrying", | |
| 8499 | - attempt, | |
| 8500 | - nextAt, | |
| 8501 | - ordinal: historyOrdinal, | |
| 8502 | - }); | |
| 8503 | - return { block: nextAt, kind: "retry" }; | |
| 8504 | - } | |
| 8505 | - }); | |
| 8506 | - }; | |
| 8507 | - const sleepUntilDeadline = (name, key, ordinal, deadline) => (async () => { | |
| 8508 | - const record = __wfKindCheck(await storage.get(key), "sleep", name); | |
| 8509 | - if (record !== undefined && record.status === "completed") { | |
| 8510 | - return { value: undefined }; | |
| 8511 | - } | |
| 8512 | - const historyOrdinal = record?.ordinal ?? ordinal; | |
| 8513 | - let at = record === undefined ? undefined : record.deadline; | |
| 8514 | - if (at === undefined) { | |
| 8515 | - // The absolute deadline is computed once and persisted. Recomputing | |
| 8516 | - // from "now" on replay would extend the sleep by however long the | |
| 8517 | - // instance was down, so a crash could postpone a deadline forever. | |
| 8518 | - at = deadline(); | |
| 8519 | - if (at - Date.now() > __WF_MAX_WAIT_MS) { | |
| 8520 | - throw __wfError( | |
| 8521 | - `sleep ${JSON.stringify(name)} ends ${at - Date.now()} ms from now, ` + | |
| 8522 | - "above the upstream limit of 365 days", | |
| 8523 | - ); | |
| 8524 | - } | |
| 8525 | - await storage.put(key, { | |
| 8526 | - kind: "sleep", | |
| 8527 | - status: "sleeping", | |
| 8528 | - deadline: at, | |
| 8529 | - ordinal: historyOrdinal, | |
| 8530 | - }); | |
| 8531 | - } | |
| 8532 | - if (at <= Date.now()) { | |
| 8533 | - await storage.put(key, { | |
| 8534 | - kind: "sleep", | |
| 8535 | - status: "completed", | |
| 8536 | - ordinal: historyOrdinal, | |
| 8537 | - }); | |
| 8538 | - return { value: undefined }; | |
| 8539 | - } | |
| 8540 | - return { block: at, kind: "sleep" }; | |
| 8541 | - })(); | |
| 8542 | - return { | |
| 8543 | - do: doStep, | |
| 8544 | - sleep: (name, duration) => { | |
| 8545 | - let durationMs; | |
| 8546 | - try { | |
| 8547 | - __wfStepName(name); | |
| 8548 | - durationMs = __wfSleepDuration(duration, name); | |
| 8549 | - } catch (error) { | |
| 8550 | - return Promise.reject(error); | |
| 8551 | - } | |
| 8552 | - return frame(name, (key, _count, ordinal) => | |
| 8553 | - sleepUntilDeadline( | |
| 8554 | - name, | |
| 8555 | - key, | |
| 8556 | - ordinal, | |
| 8557 | - () => Date.now() + durationMs, | |
| 8558 | - )); | |
| 8559 | - }, | |
| 8560 | - sleepUntil: (name, timestamp) => { | |
| 8561 | - let at; | |
| 8562 | - try { | |
| 8563 | - __wfStepName(name); | |
| 8564 | - at = __wfSleepUntil(timestamp, name); | |
| 8565 | - } catch (error) { | |
| 8566 | - return Promise.reject(error); | |
| 8567 | - } | |
| 8568 | - return frame(name, (key, _count, ordinal) => | |
| 8569 | - sleepUntilDeadline(name, key, ordinal, () => { | |
| 8570 | - // A replay uses the persisted deadline after it has passed. Check | |
| 8571 | - // the moving future bound only while the deadline is first installed, | |
| 8572 | - // or every successful sleep would fail on the resume that completes it. | |
| 8573 | - if (at - Date.now() < 0) { | |
| 8574 | - throw __wfError( | |
| 8575 | - `sleepUntil ${JSON.stringify(name)} needs a future timestamp`, | |
| 8576 | - ); | |
| 8577 | - } | |
| 8578 | - return at; | |
| 8579 | - })); | |
| 8580 | - }, | |
| 8581 | - waitForEvent: (name, options) => { | |
| 8582 | - let checked; | |
| 8583 | - try { | |
| 8584 | - __wfStepName(name); | |
| 8585 | - checked = __wfWaitOptions(options, name); | |
| 8586 | - } catch (error) { | |
| 8587 | - return Promise.reject(error); | |
| 8588 | - } | |
| 8589 | - return frame(name, async (key, _count, ordinal) => { | |
| 8590 | - let record = __wfKindCheck(await storage.get(key), "event", name); | |
| 8591 | - if (record !== undefined && record.status === "completed") { | |
| 8592 | - return { value: record.value }; | |
| 8593 | - } | |
| 8594 | - if (record !== undefined && record.status === "failed") { | |
| 8595 | - throw __wfReviveError(record.error); | |
| 8596 | - } | |
| 8597 | - if (record === undefined) { | |
| 8598 | - record = { | |
| 8599 | - kind: "event", | |
| 8600 | - status: "waiting", | |
| 8601 | - type: checked.type, | |
| 8602 | - deadline: Date.now() + checked.timeoutMs, | |
| 8603 | - ordinal, | |
| 8604 | - }; | |
| 8605 | - await storage.put(key, record); | |
| 8606 | - } | |
| 8607 | - // The deadline is checked before the buffer: an event that arrived | |
| 8608 | - // after the persisted deadline must time the step out, not succeed | |
| 8609 | - // because the replay that noticed it ran late. | |
| 8610 | - if (record.deadline <= Date.now()) { | |
| 8611 | - const error = new Error( | |
| 8612 | - `waitForEvent ${JSON.stringify(name)} timed out waiting for an event ` + | |
| 8613 | - `of type ${JSON.stringify(record.type)}`, | |
| 8614 | - ); | |
| 8615 | - await storage.put(key, { | |
| 8616 | - kind: "event", | |
| 8617 | - status: "failed", | |
| 8618 | - error: __wfErrorRecord(error), | |
| 8619 | - ordinal: record.ordinal, | |
| 8620 | - }); | |
| 8621 | - throw error; | |
| 8622 | - } | |
| 8623 | - // Delivered events persist until a matching step consumes one, in | |
| 8624 | - // arrival order -- the zero-padded sequence key makes list order | |
| 8625 | - // arrival order -- so an event sent before the step is reached is | |
| 8626 | - // buffered, not lost. | |
| 8627 | - const consumed = storage.transactionSync((transaction) => { | |
| 8628 | - const current = __wfKindCheck(transaction.kv.get(key), "event", name); | |
| 8629 | - if (current !== undefined && current.status === "completed") { | |
| 8630 | - return { value: current.value }; | |
| 8631 | - } | |
| 8632 | - if (current !== undefined && current.status === "failed") { | |
| 8633 | - throw __wfReviveError(current.error); | |
| 8634 | - } | |
| 8635 | - for (const [eventKey, event] of transaction.kv.list({ | |
| 8636 | - prefix: __wfEventPrefix(driver.generation), | |
| 8637 | - })) { | |
| 8638 | - if (event.type !== current.type) continue; | |
| 8639 | - const value = { | |
| 8640 | - payload: event.payload, | |
| 8641 | - timestamp: new Date(event.timestampMs), | |
| 8642 | - type: event.type, | |
| 8643 | - }; | |
| 8644 | - // The delete and completed ledger record are one SQLite commit. | |
| 8645 | - // A crash can therefore expose both or neither, so an | |
| 8646 | - // acknowledged event cannot disappear between them. | |
| 8647 | - transaction.kv.delete(eventKey); | |
| 8648 | - /*__CELLD_TEST_WORKFLOW_EVENT_CONSUMED__*/ | |
| 8649 | - transaction.kv.put(key, { | |
| 8650 | - kind: "event", | |
| 8651 | - status: "completed", | |
| 8652 | - value, | |
| 8653 | - ordinal: current.ordinal, | |
| 8654 | - }); | |
| 8655 | - return { value }; | |
| 8656 | - } | |
| 8657 | - }); | |
| 8658 | - if (consumed !== undefined) return consumed; | |
| 8659 | - return { block: record.deadline, kind: "event" }; | |
| 8660 | - }); | |
| 8661 | - }, | |
| 8662 | - }; | |
| 8663 | -}; | |
| 8664 | - | |
| 8665 | -const __WorkflowCell = (() => { | |
| 8666 | - class StorageTransaction { | |
| 8667 | - constructor(storage, transaction) { | |
| 8668 | - this.kv = transaction.kv; | |
| 8669 | - this._scope = storage._scope; | |
| 8670 | - } | |
| 8671 | - setAlarm(t) { | |
| 8672 | - __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); | |
| 8673 | - } | |
| 8674 | - deleteAlarm() { | |
| 8675 | - __alarm_delete(this._scope); | |
| 8676 | - } | |
| 8677 | - } | |
| 8678 | - const transactionSync = (storage, callback) => | |
| 8679 | - storage.transactionSync((transaction) => | |
| 8680 | - callback(new StorageTransaction(storage, transaction)) | |
| 8681 | - ); | |
| 8682 | - | |
| 8683 | - // The adapter stays in this closure because Workflow needs synchronous | |
| 8684 | - // alarm writes inside transactionSync(). The public async alarm API runs | |
| 8685 | - // after that commit, while a global helper would let application code | |
| 8686 | - // split metadata from its wake or invoke the raw operation after commit. | |
| 8687 | - return class __WorkflowCell { | |
| 8688 | - constructor(state) { | |
| 8689 | - this._state = state; | |
| 8690 | - } | |
| 8691 | - async __wfCreate({ workflowName, instanceId, params, skipExisting = false }) { | |
| 8692 | - const storage = this._state.storage; | |
| 8693 | - if (params !== undefined) __wfCheckValue(params, "the workflow params"); | |
| 8694 | - const result = transactionSync(storage, (transaction) => { | |
| 8695 | - const meta = transaction.kv.get("__wf.meta"); | |
| 8696 | - if (meta !== undefined && skipExisting) return { id: instanceId, created: false }; | |
| 8697 | - if (meta !== undefined && !__wfTerminal(meta.status)) { | |
| 8698 | - throw __wfError( | |
| 8699 | - `instance ${JSON.stringify(instanceId)} already exists with status ` + | |
| 8700 | - JSON.stringify(meta.status), | |
| 8701 | - ); | |
| 8702 | - } | |
| 8703 | - if (meta !== undefined) { | |
| 8704 | - for (const [key] of transaction.kv.list({ | |
| 8705 | - prefix: __wfLedgerPrefix(meta.generation), | |
| 8706 | - })) { | |
| 8707 | - transaction.kv.delete(key); | |
| 8708 | - } | |
| 8709 | - } | |
| 8710 | - const generation = crypto.randomUUID(); | |
| 8711 | - transaction.kv.put("__wf.meta", { | |
| 8712 | - workflowName, | |
| 8713 | - instanceId, | |
| 8714 | - params, | |
| 8715 | - generation, | |
| 8716 | - createdMs: Date.now(), | |
| 8717 | - status: "queued", | |
| 8718 | - }); | |
| 8719 | - // The metadata and alarm are one SQLite commit. A committed creation | |
| 8720 | - // therefore always has the wake that can start or recover its drive. | |
| 8721 | - transaction.setAlarm(Date.now()); | |
| 8722 | - /*__CELLD_TEST_WORKFLOW_META_CREATED__*/ | |
| 8723 | - return { id: instanceId, created: true }; | |
| 8724 | - }); | |
| 8725 | - return result; | |
| 8726 | - } | |
| 8727 | - async __wfStatus() { | |
| 8728 | - const meta = await this._state.storage.get("__wf.meta"); | |
| 8729 | - // A cell exists on first address like any cell, so an absent ledger is | |
| 8730 | - // the only honest "no such instance" signal. Inventing an instance here | |
| 8731 | - // would turn every typo into an empty workflow. | |
| 8732 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8733 | - const status = { status: meta.status, rollback: null }; | |
| 8734 | - if (meta.error !== undefined) status.error = meta.error; | |
| 8735 | - if (meta.output !== undefined) status.output = meta.output; | |
| 8736 | - return status; | |
| 8737 | - } | |
| 8738 | - async __wfPause() { | |
| 8739 | - const storage = this._state.storage; | |
| 8740 | - transactionSync(storage, (transaction) => { | |
| 8741 | - const meta = transaction.kv.get("__wf.meta"); | |
| 8742 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8743 | - if (__wfTerminal(meta.status) || meta.status === "paused" || | |
| 8744 | - meta.status === "waitingForPause") return; | |
| 8745 | - if (meta.status === "running") { | |
| 8746 | - meta.status = "waitingForPause"; | |
| 8747 | - // A drive lost after this commit must re-enter and finish the pause. | |
| 8748 | - transaction.setAlarm(Date.now()); | |
| 8749 | - } else { | |
| 8750 | - meta.status = "paused"; | |
| 8751 | - meta.pausedMs = Date.now(); | |
| 8752 | - transaction.deleteAlarm(); | |
| 8753 | - } | |
| 8754 | - transaction.kv.put("__wf.meta", meta); | |
| 8755 | - }); | |
| 8756 | - } | |
| 8757 | - async __wfResume() { | |
| 8758 | - const storage = this._state.storage; | |
| 8759 | - transactionSync(storage, (transaction) => { | |
| 8760 | - const meta = transaction.kv.get("__wf.meta"); | |
| 8761 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8762 | - if (meta.status === "waitingForPause") { | |
| 8763 | - meta.status = "running"; | |
| 8764 | - transaction.kv.put("__wf.meta", meta); | |
| 8765 | - transaction.setAlarm(Date.now()); | |
| 8766 | - return; | |
| 8767 | - } | |
| 8768 | - if (meta.status !== "paused") { | |
| 8769 | - throw __wfError( | |
| 8770 | - `cannot resume an instance with status ${JSON.stringify(meta.status)}`, | |
| 8771 | - ); | |
| 8772 | - } | |
| 8773 | - const offset = Math.max(0, Date.now() - (meta.pausedMs ?? Date.now())); | |
| 8774 | - for (const [key, record] of transaction.kv.list({ | |
| 8775 | - prefix: __wfLedgerPrefix(meta.generation) + "step.", | |
| 8776 | - })) { | |
| 8777 | - if (record.status === "retrying") record.nextAt += offset; | |
| 8778 | - if (record.status === "sleeping" || record.status === "waiting") { | |
| 8779 | - record.deadline += offset; | |
| 8780 | - } | |
| 8781 | - transaction.kv.put(key, record); | |
| 8782 | - } | |
| 8783 | - delete meta.pausedMs; | |
| 8784 | - meta.status = "queued"; | |
| 8785 | - transaction.kv.put("__wf.meta", meta); | |
| 8786 | - transaction.setAlarm(Date.now()); | |
| 8787 | - }); | |
| 8788 | - } | |
| 8789 | - async __wfRestart(options) { | |
| 8790 | - const checked = __wfRestartOptions(options); | |
| 8791 | - const storage = this._state.storage; | |
| 8792 | - transactionSync(storage, (transaction) => { | |
| 8793 | - const meta = transaction.kv.get("__wf.meta"); | |
| 8794 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8795 | - const oldPrefix = __wfLedgerPrefix(meta.generation); | |
| 8796 | - let targetOrdinal; | |
| 8797 | - if (checked.from !== undefined) { | |
| 8798 | - const expectedKind = checked.from.type === "waitForEvent" | |
| 8799 | - ? "event" | |
| 8800 | - : checked.from.type; | |
| 8801 | - let occurrence = 0; | |
| 8802 | - const history = [...transaction.kv.list({ prefix: oldPrefix + "step." })] | |
| 8803 | - .filter(([, record]) => Number.isInteger(record.ordinal)) | |
| 8804 | - .sort((left, right) => left[1].ordinal - right[1].ordinal); | |
| 8805 | - // The ledger key is `<prefix>step.<per-name-count>.<name>`. Derive | |
| 8806 | - // the name from it because a record stores replay state, not identity. | |
| 8807 | - for (const [key, record] of history) { | |
| 8808 | - const marker = oldPrefix + "step."; | |
| 8809 | - const suffix = key.slice(marker.length); | |
| 8810 | - const dot = suffix.indexOf("."); | |
| 8811 | - const name = dot < 0 ? "" : suffix.slice(dot + 1); | |
| 8812 | - if (record.kind !== expectedKind || name !== checked.from.name) continue; | |
| 8813 | - occurrence += 1; | |
| 8814 | - if (occurrence === checked.from.count) { | |
| 8815 | - targetOrdinal = record.ordinal; | |
| 8816 | - break; | |
| 8817 | - } | |
| 8818 | - } | |
| 8819 | - if (targetOrdinal === undefined) { | |
| 8820 | - throw __wfError( | |
| 8821 | - `restart() could not find ${checked.from.type} step ` + | |
| 8822 | - `${JSON.stringify(checked.from.name)} occurrence ${checked.from.count}`, | |
| 8823 | - ); | |
| 8824 | - } | |
| 8825 | - } | |
| 8826 | - const generation = crypto.randomUUID(); | |
| 8827 | - const newPrefix = __wfLedgerPrefix(generation); | |
| 8828 | - if (targetOrdinal !== undefined) { | |
| 8829 | - for (const [key, record] of transaction.kv.list({ prefix: oldPrefix + "step." })) { | |
| 8830 | - if (Number.isInteger(record.ordinal) && record.ordinal < targetOrdinal) { | |
| 8831 | - transaction.kv.put(newPrefix + key.slice(oldPrefix.length), record); | |
| 8832 | - } | |
| 8833 | - } | |
| 8834 | - } | |
| 8835 | - for (const [key] of transaction.kv.list({ prefix: oldPrefix })) { | |
| 8836 | - transaction.kv.delete(key); | |
| 8837 | - } | |
| 8838 | - meta.generation = generation; | |
| 8839 | - meta.status = "queued"; | |
| 8840 | - delete meta.pausedMs; | |
| 8841 | - delete meta.output; | |
| 8842 | - delete meta.error; | |
| 8843 | - transaction.kv.put("__wf.meta", meta); | |
| 8844 | - transaction.setAlarm(Date.now()); | |
| 8845 | - }); | |
| 8846 | - } | |
| 8847 | - async __wfTerminate() { | |
| 8848 | - const storage = this._state.storage; | |
| 8849 | - transactionSync(storage, (transaction) => { | |
| 8850 | - const meta = transaction.kv.get("__wf.meta"); | |
| 8851 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8852 | - if (__wfTerminal(meta.status)) { | |
| 8853 | - throw __wfError( | |
| 8854 | - `cannot terminate an instance with status ${JSON.stringify(meta.status)}`, | |
| 8855 | - ); | |
| 8856 | - } | |
| 8857 | - meta.status = "terminated"; | |
| 8858 | - transaction.kv.put("__wf.meta", meta); | |
| 8859 | - transaction.deleteAlarm(); | |
| 8860 | - /*__CELLD_TEST_WORKFLOW_ALARM_DELETED__*/ | |
| 8861 | - }); | |
| 8862 | - } | |
| 8863 | - async __wfSendEvent(options) { | |
| 8864 | - const storage = this._state.storage; | |
| 8865 | - // The binding validates first to avoid an unnecessary cell call. Repeat | |
| 8866 | - // the check here because this RPC owns the durable event invariant: no | |
| 8867 | - // current or future internal caller can bypass validation before storage. | |
| 8868 | - const { type, payload } = __wfEventOptions(options); | |
| 8869 | - transactionSync(storage, (transaction) => { | |
| 8870 | - const meta = transaction.kv.get("__wf.meta"); | |
| 8871 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8872 | - if (__wfTerminal(meta.status)) { | |
| 8873 | - throw __wfError( | |
| 8874 | - `cannot send an event to an instance with status ${JSON.stringify(meta.status)}`, | |
| 8875 | - ); | |
| 8876 | - } | |
| 8877 | - const sequenceKey = __wfLedgerPrefix(meta.generation) + "eventSeq"; | |
| 8878 | - const sequence = transaction.kv.get(sequenceKey) ?? 0; | |
| 8879 | - transaction.kv.put(sequenceKey, sequence + 1); | |
| 8880 | - transaction.kv.put(__wfEventKey(meta.generation, sequence), { | |
| 8881 | - type, | |
| 8882 | - payload, | |
| 8883 | - timestampMs: Date.now(), | |
| 8884 | - }); | |
| 8885 | - // Allocation, the event body, and the nudge are one commit. Parallel | |
| 8886 | - // writers cannot reuse a sequence and a crash cannot expose a partial | |
| 8887 | - // acknowledged send. | |
| 8888 | - if (meta.status !== "paused" && meta.status !== "waitingForPause") { | |
| 8889 | - transaction.setAlarm(Date.now()); | |
| 8890 | - } | |
| 8891 | - }); | |
| 8892 | - } | |
| 8893 | - async alarm() { | |
| 8894 | - const storage = this._state.storage; | |
| 8895 | - // One drive at a time. A sendEvent nudge (setAlarm(now)) landing | |
| 8896 | - // mid-fire replaces the firing alarm in the core, and the replacement | |
| 8897 | - // can dispatch a second alarm() into this isolate while the first drive | |
| 8898 | - // still awaits user code. Two concurrent replays would both see the | |
| 8899 | - // same incomplete steps and double-execute their callbacks. The guard | |
| 8900 | - // is isolate-local and that is sufficient: every drive for a cell runs | |
| 8901 | - // in its owner's isolate, and a takeover starts a fresh isolate with no | |
| 8902 | - // drive in flight. The nudge is not lost -- the in-flight drive folds | |
| 8903 | - // `_wfNudge` into the minimum it re-arms, and if it suspended before | |
| 8904 | - // seeing the flag, the re-arm below starts a fresh drive immediately. | |
| 8905 | - // A failed drive is not re-raised here: the engine already retries the | |
| 8906 | - // alarm that fired it. | |
| 8907 | - if (this._wfDriving !== undefined) { | |
| 8908 | - this._wfNudge = Date.now(); | |
| 8909 | - await this._wfDriving.catch(() => {}); | |
| 8910 | - if (this._wfNudge !== undefined) { | |
| 8911 | - this._wfNudge = undefined; | |
| 8912 | - const meta = await storage.get("__wf.meta"); | |
| 8913 | - if ( | |
| 8914 | - meta !== undefined && !__wfTerminal(meta.status) && | |
| 8915 | - meta.status !== "paused" && meta.status !== "waitingForPause" | |
| 8916 | - ) { | |
| 8917 | - await storage.setAlarm(Date.now()); | |
| 8918 | - } | |
| 8919 | - } | |
| 8920 | - return; | |
| 8921 | - } | |
| 8922 | - const meta = await storage.get("__wf.meta"); | |
| 8923 | - // A terminal instance's pending alarm can still fire; seeing the status | |
| 8924 | - // and doing nothing is the whole terminate-race policy. | |
| 8925 | - if (meta === undefined || __wfTerminal(meta.status)) { | |
| 8926 | - await storage.deleteAlarm(); | |
| 8927 | - return; | |
| 8928 | - } | |
| 8929 | - if (meta.status === "paused") { | |
| 8930 | - await storage.deleteAlarm(); | |
| 8931 | - return; | |
| 8932 | - } | |
| 8933 | - if (meta.status === "waitingForPause") { | |
| 8934 | - transactionSync(storage, (transaction) => { | |
| 8935 | - const current = transaction.kv.get("__wf.meta"); | |
| 8936 | - if (current === undefined || current.generation !== meta.generation || | |
| 8937 | - current.status !== "waitingForPause") return; | |
| 8938 | - current.status = "paused"; | |
| 8939 | - current.pausedMs = Date.now(); | |
| 8940 | - transaction.kv.put("__wf.meta", current); | |
| 8941 | - transaction.deleteAlarm(); | |
| 8942 | - }); | |
| 8943 | - return; | |
| 8944 | - } | |
| 8945 | - // The fired alarm stays armed while the drive runs. The engine consumes | |
| 8946 | - // it only when this handler returns cleanly, and retries it when the | |
| 8947 | - // handler fails -- that retry is the crash safety net. Deleting it here | |
| 8948 | - // would commit the deletion durably mid-drive (durability is per SQLite | |
| 8949 | - // commit, and replication ships frames per commit), so a SIGKILL before | |
| 8950 | - // the suspend-time re-arm would strand a "running" instance with no | |
| 8951 | - // alarm and no wake entry. The suspend path re-arms explicitly, and a | |
| 8952 | - // terminal drive deletes. | |
| 8953 | - const driving = this._drive(meta); | |
| 8954 | - this._wfDriving = driving; | |
| 8955 | - try { | |
| 8956 | - await driving; | |
| 8957 | - } finally { | |
| 8958 | - this._wfDriving = undefined; | |
| 8959 | - } | |
| 8960 | - } | |
| 8961 | - async _drive(meta) { | |
| 8962 | - const storage = this._state.storage; | |
| 8963 | - // The drive owns `status`, `output`, and `error`; every other piece of | |
| 8964 | - // instance state belongs to the RPCs (sendEvent's sequence lives in its | |
| 8965 | - // own key for the same reason). The gate is open at every await, so a | |
| 8966 | - // terminate can land mid-drive: re-reading before each write, and | |
| 8967 | - // writing nothing once the status is terminal, is what makes "terminate | |
| 8968 | - // wins the race" true rather than asserted. Writing back the meta this | |
| 8969 | - // drive entered with would resurrect a terminated instance as "waiting" | |
| 8970 | - // and re-arm the alarm its terminate deleted. | |
| 8971 | - const settle = (mutate) => transactionSync(storage, (transaction) => { | |
| 8972 | - const current = transaction.kv.get("__wf.meta"); | |
| 8973 | - if (current === undefined || __wfTerminal(current.status) || | |
| 8974 | - current.generation !== meta.generation) return false; | |
| 8975 | - mutate(current, transaction); | |
| 8976 | - transaction.kv.put("__wf.meta", current); | |
| 8977 | - return true; | |
| 8978 | - }); | |
| 8979 | - const className = __cell.workflows[meta.workflowName]; | |
| 8980 | - const cls = className === undefined ? undefined : __cf.exports[className]; | |
| 8981 | - if (typeof cls !== "function" || | |
| 8982 | - typeof (cls.prototype && cls.prototype.run) !== "function") { | |
| 8983 | - // Deploy cannot see inside the bundle, so a missing export fails | |
| 8984 | - // here, loudly, with the class and the config key named. | |
| 8985 | - settle((current, transaction) => { | |
| 8986 | - current.status = "errored"; | |
| 8987 | - current.error = { | |
| 8988 | - name: "Error", | |
| 8989 | - message: className === undefined | |
| 8990 | - ? `workflow ${JSON.stringify(meta.workflowName)} is not declared ` + | |
| 8991 | - "in this deployment's `workflows`" | |
| 8992 | - : `workflow class ${JSON.stringify(className)} is not a module ` + | |
| 8993 | - "export with a run() method; export it and extend " + | |
| 8994 | - "WorkflowEntrypoint", | |
| 8995 | - }; | |
| 8996 | - transaction.deleteAlarm(); | |
| 8997 | - /*__CELLD_TEST_WORKFLOW_ALARM_DELETED__*/ | |
| 8998 | - }); | |
| 8999 | - return; | |
| 9000 | - } | |
| 9001 | - const driver = { | |
| 9002 | - storage: undefined, | |
| 9003 | - storageFailure: undefined, | |
| 9004 | - generation: meta.generation, | |
| 9005 | - ledgerPrefix: __wfLedgerPrefix(meta.generation), | |
| 9006 | - counts: new Map(), | |
| 9007 | - ordinal: 0, | |
| 9008 | - running: 0, | |
| 9009 | - blocked: [], | |
| 9010 | - pauseRequested: false, | |
| 9011 | - finished: false, | |
| 9012 | - checkQueued: false, | |
| 9013 | - stallTimer: undefined, | |
| 9014 | - clearStall() { | |
| 9015 | - if (this.stallTimer !== undefined) { | |
| 9016 | - clearTimeout(this.stallTimer); | |
| 9017 | - this.stallTimer = undefined; | |
| 9018 | - } | |
| 9019 | - }, | |
| 9020 | - }; | |
| 9021 | - driver.storage = __wfTrackStorageFailures(storage, driver); | |
| 9022 | - const outcome = new Promise((resolve) => { | |
| 9023 | - driver.finish = (result) => { | |
| 9024 | - if (driver.finished) return; | |
| 9025 | - driver.finished = true; | |
| 9026 | - driver.clearStall(); | |
| 9027 | - resolve(result); | |
| 9028 | - }; | |
| 9029 | - }); | |
| 9030 | - // Quiescence: when a step is blocked, no step callback is executing, | |
| 9031 | - // and a macrotask has passed, nothing can progress, so the invocation | |
| 9032 | - // suspends. The macrotask lets every microtask chain a completed step | |
| 9033 | - // unblocked drain first; checking on the spot would suspend an instance | |
| 9034 | - // whose next step is one `await` away from starting. | |
| 9035 | - driver.check = () => { | |
| 9036 | - if (driver.checkQueued || driver.finished) return; | |
| 9037 | - driver.checkQueued = true; | |
| 9038 | - setTimeout(() => { | |
| 9039 | - driver.checkQueued = false; | |
| 9040 | - if (driver.finished || driver.running !== 0) return; | |
| 9041 | - if (driver.pauseRequested) { | |
| 9042 | - driver.finish({ kind: "pause" }); | |
| 9043 | - return; | |
| 9044 | - } | |
| 9045 | - if (driver.blocked.length > 0) { | |
| 9046 | - driver.finish({ kind: "suspend" }); | |
| 9047 | - return; | |
| 9048 | - } | |
| 9049 | - // No step runs, none is blocked, and run() has not settled: it | |
| 9050 | - // awaits something that is not a step. Upstream permits that -- an | |
| 9051 | - // un-stepped `await fetch()` between steps is legal, merely | |
| 9052 | - // non-durable -- so this is not yet an error; but a promise that | |
| 9053 | - // never settles would wedge the alarm handler in silence, with the | |
| 9054 | - // instance "running" forever. A grace timer splits the two: if the | |
| 9055 | - // same nothing-can-progress state still holds when it fires, the | |
| 9056 | - // instance fails loudly. The timer is a plain in-isolate timeout, | |
| 9057 | - // not a durable alarm, on purpose: an eviction or a restart replays | |
| 9058 | - // run() from the top anyway, so losing the timer loses nothing -- | |
| 9059 | - // the replay re-enters the same stall and re-arms its own grace. | |
| 9060 | - if (driver.stallTimer !== undefined) return; | |
| 9061 | - driver.stallTimer = setTimeout(() => { | |
| 9062 | - driver.stallTimer = undefined; | |
| 9063 | - if (driver.finished || driver.running !== 0 || driver.blocked.length > 0) { | |
| 9064 | - return; | |
| 9065 | - } | |
| 9066 | - driver.finish({ | |
| 9067 | - kind: "error", | |
| 9068 | - error: __wfError( | |
| 9069 | - "run() has been awaiting something that is not a step for " + | |
| 9070 | - (__WF_STALL_GRACE_MS / 1000) + " seconds while no step is " + | |
| 9071 | - "running or blocked; a replay cannot resume this wait, so " + | |
| 9072 | - "wrap long async work in step.do", | |
| 9073 | - ), | |
| 9074 | - }); | |
| 9075 | - }, __WF_STALL_GRACE_MS); | |
| 9076 | - }, 0); | |
| 9077 | - }; | |
| 9078 | - if ( | |
| 9079 | - meta.status !== "running" && | |
| 9080 | - !(await settle((current) => { | |
| 9081 | - current.status = "running"; | |
| 9082 | - })) | |
| 9083 | - ) { | |
| 9084 | - return; | |
| 9085 | - } | |
| 9086 | - const step = __wfMakeStep(driver); | |
| 9087 | - const event = { | |
| 9088 | - payload: meta.params, | |
| 9089 | - timestamp: new Date(meta.createdMs), | |
| 9090 | - instanceId: meta.instanceId, | |
| 9091 | - workflowName: meta.workflowName, | |
| 9092 | - }; | |
| 9093 | - // ExecutionContext-shaped, as the WorkflowEntrypoint constructor | |
| 9094 | - // documents upstream. | |
| 9095 | - const ctx = { | |
| 9096 | - waitUntil: globalThis.__registerWaitUntil, | |
| 9097 | - passThroughOnException() {}, | |
| 9098 | - }; | |
| 9099 | - (async () => new cls(ctx, __cell.env).run(event, step))().then( | |
| 9100 | - (value) => driver.finish({ kind: "complete", value }), | |
| 9101 | - (error) => driver.finish({ kind: "error", error }), | |
| 9102 | - ); | |
| 9103 | - /*__CELLD_TEST_WORKFLOW_AFTER_RUN_STARTED__*/ | |
| 9104 | - let result = await outcome; | |
| 9105 | - // The workflow can catch a rejected step promise, but it cannot turn an | |
| 9106 | - // engine storage failure into a successful run. Preserve the alarm so | |
| 9107 | - // the runtime retries over the last committed ledger prefix. | |
| 9108 | - if (driver.storageFailure !== undefined) { | |
| 9109 | - throw driver.storageFailure; | |
| 9110 | - } | |
| 9111 | - const currentMeta = await storage.get("__wf.meta"); | |
| 9112 | - if ( | |
| 9113 | - result.kind === "pause" || | |
| 9114 | - (currentMeta !== undefined && | |
| 9115 | - currentMeta.generation === meta.generation && | |
| 9116 | - currentMeta.status === "waitingForPause") | |
| 9117 | - ) { | |
| 9118 | - /*__CELLD_TEST_WORKFLOW_BEFORE_PAUSE_SETTLE__*/ | |
| 9119 | - settle((current, transaction) => { | |
| 9120 | - // A resume can cancel waitingForPause after this drive selected its | |
| 9121 | - // pause result. Preserve that newer running state and its alarm, or | |
| 9122 | - // this stale settlement strands an acknowledged resume as paused. | |
| 9123 | - if (current.status !== "waitingForPause") return; | |
| 9124 | - current.status = "paused"; | |
| 9125 | - current.pausedMs = Date.now(); | |
| 9126 | - transaction.deleteAlarm(); | |
| 9127 | - }); | |
| 9128 | - return; | |
| 9129 | - } | |
| 9130 | - if (result.kind === "suspend") { | |
| 9131 | - let at = Math.min(...driver.blocked.map((entry) => entry.at)); | |
| 9132 | - // A nudge that landed mid-drive must not wait out the pending | |
| 9133 | - // deadline. It is visible in one of two places: getAlarm(), when the | |
| 9134 | - // nudge re-armed and no second alarm dispatched yet, or `_wfNudge`, | |
| 9135 | - // when a second alarm() already entered and parked on the drive | |
| 9136 | - // guard -- its dispatch consumed the armed alarm, so getAlarm() | |
| 9137 | - // alone would miss it. | |
| 9138 | - const nudge = await storage.getAlarm(); | |
| 9139 | - if (nudge !== null) at = Math.min(at, nudge); | |
| 9140 | - if (this._wfNudge !== undefined) { | |
| 9141 | - at = Math.min(at, this._wfNudge); | |
| 9142 | - this._wfNudge = undefined; | |
| 9143 | - } | |
| 9144 | - settle((current, transaction) => { | |
| 9145 | - current.status = "waiting"; | |
| 9146 | - transaction.setAlarm(at); | |
| 9147 | - }); | |
| 9148 | - // The explicit re-arm replaces the alarm that fired this drive. | |
| 9149 | - // Durability is per SQLite commit, not per turn: a crash can persist | |
| 9150 | - // any prefix of this invocation's ledger writes, and the unconsumed | |
| 9151 | - // fired alarm is what re-drives the replay over whatever prefix | |
| 9152 | - // survived. A terminated instance re-arms nothing; its leftover | |
| 9153 | - // alarm fires once, sees the terminal status, and retires itself. | |
| 9154 | - return; | |
| 9155 | - } | |
| 9156 | - if (result.kind === "complete") { | |
| 9157 | - try { | |
| 9158 | - if (result.value !== undefined) { | |
| 9159 | - __wfCheckValue(result.value, "the run() return value"); | |
| 9160 | - } | |
| 9161 | - } catch (error) { | |
| 9162 | - result = { kind: "error", error }; | |
| 9163 | - } | |
| 9164 | - if (result.kind === "complete") { | |
| 9165 | - // Keep settlement outside the value-validation catch. A storage | |
| 9166 | - // failure must escape the alarm handler so the engine retries the | |
| 9167 | - // still-armed drive; converting it to a user error would consume the | |
| 9168 | - // alarm and make a transient commit failure terminal. | |
| 9169 | - settle((current, transaction) => { | |
| 9170 | - current.status = "complete"; | |
| 9171 | - if (result.value !== undefined) current.output = result.value; | |
| 9172 | - // A concurrent nudge may have re-armed mid-run. Settlement retires | |
| 9173 | - // it in the same commit that makes the instance terminal. | |
| 9174 | - transaction.deleteAlarm(); | |
| 9175 | - /*__CELLD_TEST_WORKFLOW_ALARM_DELETED__*/ | |
| 9176 | - }); | |
| 9177 | - return; | |
| 9178 | - } | |
| 9179 | - } | |
| 9180 | - settle((current, transaction) => { | |
| 9181 | - current.status = "errored"; | |
| 9182 | - current.error = __wfErrorRecord(result.error); | |
| 9183 | - transaction.deleteAlarm(); | |
| 9184 | - /*__CELLD_TEST_WORKFLOW_ALARM_DELETED__*/ | |
| 9185 | - }); | |
| 9186 | - } | |
| 9187 | - }; | |
| 9188 | -})(); | |
| 9189 | -__cell.classes.__Workflow = __WorkflowCell; | |
| 9190 | -// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class | |
| 9191 | -// is the runtime's own, so grant it here, as __D1Database does. | |
| 9192 | -__cell.doExports.__Workflow = true; | |
| 9193 | - | |
| 9194 | -class NonRetryableError extends Error { | |
| 9195 | - constructor(message, name = "NonRetryableError") { | |
| 9196 | - super(message); | |
| 9197 | - this.name = name; | |
| 9198 | - } | |
| 9199 | -} | |
| 9200 | -// Backing object for the `cloudflare:workflows` builtin module. | |
| 9201 | -globalThis.__cfWorkflows = { NonRetryableError }; | |
| 9202 | - | |
| 9203 | -const __wfValidInstanceId = (id) => | |
| 9204 | - typeof id === "string" && id.length >= 1 && id.length <= 100 && | |
| 9205 | - __WF_NAME_RE.test(id); | |
| 9206 | -const __wfCreateOptions = (options, what, validateParams = true) => { | |
| 9207 | - if (!__wfOwnObject(options)) { | |
| 9208 | - throw __wfError(`${what} needs an object`); | |
| 9209 | - } | |
| 9210 | - // These are published options, not unknown extension fields. Reject them | |
| 9211 | - // until their semantics exist so celld cannot silently promise retention or | |
| 9212 | - // placement. The generated binding surfaces ignore other object fields. | |
| 9213 | - if (options.retention !== undefined) { | |
| 9214 | - throw __wfError(`${what} does not support option "retention"`); | |
| 9215 | - } | |
| 9216 | - if (options.locationHint !== undefined) { | |
| 9217 | - throw __wfError(`${what} does not support option "locationHint"`); | |
| 9218 | - } | |
| 9219 | - const id = options.id === undefined ? crypto.randomUUID() : options.id; | |
| 9220 | - if (!__wfValidInstanceId(id)) { | |
| 9221 | - throw __wfError( | |
| 9222 | - `invalid instance id ${JSON.stringify(id)}: use letters, digits, ` + | |
| 9223 | - "\"-\" and \"_\" (not starting with \"-\"), at most 100 characters", | |
| 9224 | - ); | |
| 9225 | - } | |
| 9226 | - if (validateParams && options.params !== undefined) { | |
| 9227 | - // The cell repeats this serialization check because it owns the durable | |
| 9228 | - // create invariant. A single create rejects before it addresses the cell. | |
| 9229 | - __wfCheckValue(options.params, "the workflow params"); | |
| 9230 | - } | |
| 9231 | - return { id, params: options.params }; | |
| 9232 | -}; | |
| 9233 | - | |
| 9234 | -// Named so SDKs that sniff a binding by `constructor.name` recognise it. | |
| 9235 | -class WorkflowInstance { | |
| 9236 | - constructor(workflowName, id) { | |
| 9237 | - Object.defineProperty(this, "_workflowName", { value: workflowName }); | |
| 9238 | - this.id = id; | |
| 9239 | - } | |
| 9240 | - // Resolved per call rather than cached: a cell can move between calls. | |
| 9241 | - get _stub() { | |
| 9242 | - // The reserved class is script-scoped (`deploy::workflow_class`), because | |
| 9243 | - // a workflow instance is: two co-hosted scripts must not share one entry | |
| 9244 | - // in the deployment's flat class registry. `__cell.script` is injected | |
| 9245 | - // before any binding runs, so this resolves at call time. | |
| 9246 | - return __cell.makeNamespace("__Workflow." + __cell.script) | |
| 9247 | - .getByName(this._workflowName + "/" + this.id); | |
| 9248 | - } | |
| 9249 | - async status() { | |
| 9250 | - return await this._stub.__wfStatus(); | |
| 9251 | - } | |
| 9252 | - async terminate(options) { | |
| 9253 | - if (options && options.rollback) { | |
| 9254 | - throw __wfError( | |
| 9255 | - "terminate({rollback: true}) is not implemented in celld; step " + | |
| 9256 | - "rollbackOptions are not implemented, so no handler could run", | |
| 9257 | - ); | |
| 9258 | - } | |
| 9259 | - await this._stub.__wfTerminate(); | |
| 9260 | - } | |
| 9261 | - async sendEvent(options) { | |
| 9262 | - await this._stub.__wfSendEvent(__wfEventOptions(options)); | |
| 9263 | - } | |
| 9264 | - async pause() { | |
| 9265 | - await this._stub.__wfPause(); | |
| 9266 | - } | |
| 9267 | - async resume() { | |
| 9268 | - await this._stub.__wfResume(); | |
| 9269 | - } | |
| 9270 | - async restart(options) { | |
| 9271 | - await this._stub.__wfRestart(__wfRestartOptions(options)); | |
| 9272 | - } | |
| 9273 | - async delete() { | |
| 9274 | - throw __wfError( | |
| 9275 | - "delete() is not implemented in celld yet; the instance state stays in " + | |
| 9276 | - "the cell until a delete surface exists", | |
| 9277 | - ); | |
| 9278 | - } | |
| 9279 | -} | |
| 9280 | - | |
| 9281 | -class Workflow { | |
| 9282 | - constructor(workflowName) { | |
| 9283 | - Object.defineProperty(this, "_workflowName", { value: workflowName }); | |
| 9284 | - } | |
| 9285 | - async _create(options, skipExisting) { | |
| 9286 | - const { id, params } = options; | |
| 9287 | - const instance = new WorkflowInstance(this._workflowName, id); | |
| 9288 | - const result = await instance._stub.__wfCreate({ | |
| 9289 | - workflowName: this._workflowName, | |
| 9290 | - instanceId: id, | |
| 9291 | - params, | |
| 9292 | - skipExisting, | |
| 9293 | - }); | |
| 9294 | - return result.created ? instance : undefined; | |
| 9295 | - } | |
| 9296 | - async create(options = {}) { | |
| 9297 | - return await this._create(__wfCreateOptions(options, "create()"), false); | |
| 9298 | - } | |
| 9299 | - async createBatch(batch) { | |
| 9300 | - if (!Array.isArray(batch)) { | |
| 9301 | - throw __wfError("createBatch() needs an array of create options"); | |
| 9302 | - } | |
| 9303 | - if (batch.length > 100) { | |
| 9304 | - throw __wfError( | |
| 9305 | - `createBatch() accepts at most 100 instances, got ${batch.length}`, | |
| 9306 | - ); | |
| 9307 | - } | |
| 9308 | - if (batch.length === 0) { | |
| 9309 | - throw __wfError("createBatch() needs at least one instance"); | |
| 9310 | - } | |
| 9311 | - // Cloudflare rejects a structural error in any item before it creates the | |
| 9312 | - // first instance, but it filters a params clone failure per item. Keep | |
| 9313 | - // these two gates separate so a bad ID stays atomic while a clone failure | |
| 9314 | - // does not suppress the valid items around it. | |
| 9315 | - const optionsList = batch.map((options, index) => | |
| 9316 | - __wfCreateOptions(options, `createBatch() item ${index}`, false)); | |
| 9317 | - const creatable = []; | |
| 9318 | - for (const options of optionsList) { | |
| 9319 | - let encoded; | |
| 9320 | - try { | |
| 9321 | - if (options.params !== undefined) { | |
| 9322 | - encoded = __wfEncodeValue(options.params, "the workflow params"); | |
| 9323 | - } | |
| 9324 | - } catch { | |
| 9325 | - continue; | |
| 9326 | - } | |
| 9327 | - if (encoded !== undefined) { | |
| 9328 | - __wfCheckEncodedValue(encoded, "the workflow params"); | |
| 9329 | - } | |
| 9330 | - creatable.push(options); | |
| 9331 | - } | |
| 9332 | - const created = []; | |
| 9333 | - for (const options of creatable) { | |
| 9334 | - const instance = await this._create(options, true); | |
| 9335 | - if (instance !== undefined) created.push(instance); | |
| 9336 | - } | |
| 9337 | - return created; | |
| 9338 | - } | |
| 9339 | - async get(id) { | |
| 9340 | - if (!__wfValidInstanceId(id)) { | |
| 9341 | - throw __wfError(`invalid instance id ${JSON.stringify(id)}`); | |
| 9342 | - } | |
| 9343 | - const instance = new WorkflowInstance(this._workflowName, id); | |
| 9344 | - // The cell exists on first address like any cell, but get() must not | |
| 9345 | - // mint an instance for a typo: an id with no ledger rejects here. | |
| 9346 | - await instance._stub.__wfStatus(); | |
| 9347 | - return instance; | |
| 9348 | - } | |
| 9349 | - async deleteBatch() { | |
| 9350 | - throw __wfError("deleteBatch() is not implemented in celld yet"); | |
| 9351 | - } | |
| 9352 | -} | |
| 9353 | - | |
| 9354 | -globalThis.__makeWorkflow = (workflowName) => new Workflow(workflowName); | |
| 9355 | -// `cloudflare:workers` module surface. The DO base class sets ctx/env the | |
| 9356 | -// way `class X extends DurableObject` expects; env aliases the cell env. | |
| 9357 | -globalThis.__cf = { | |
| 9358 | - DurableObject: class DurableObject { | |
| 9359 | - constructor(ctx, env) { this.ctx = ctx; this.env = env; } | |
| 9360 | - }, | |
| 9361 | - // The enumerable function-valued brand makes V8's structured clone | |
| 9362 | - // fail on every RpcTarget instance, forcing it off the silent | |
| 9363 | - // plain-clone path and into the stub lift (Workerd rejects these | |
| 9364 | - // from plain serialization outright). | |
| 9365 | - RpcTarget: class RpcTarget { | |
| 9366 | - constructor() { | |
| 9367 | - Object.defineProperty(this, "__celldRpcTarget", { | |
| 9368 | - value: __rpcNoClone, enumerable: true, | |
| 9369 | - }); | |
| 9370 | - } | |
| 9371 | - }, | |
| 9372 | - // Named entrypoint for `[[services]]` with `entrypoint = "Name"`. | |
| 9373 | - WorkerEntrypoint: class WorkerEntrypoint { | |
| 9374 | - constructor(ctx, env) { this.ctx = ctx; this.env = env; } | |
| 9375 | - }, | |
| 9376 | - // Base class for `workflows` classes. The reserved workflow cell | |
| 9377 | - // instantiates a subclass on every replay with an ExecutionContext-shaped | |
| 9378 | - // ctx -- never the cell's own DurableObjectState, which would hand user | |
| 9379 | - // code the ledger that replays it. | |
| 9380 | - WorkflowEntrypoint: class WorkflowEntrypoint { | |
| 9381 | - constructor(ctx, env) { this.ctx = ctx; this.env = env; } | |
| 9382 | - }, | |
| 9383 | - // `new RpcStub(target)` wraps any local object or function in a | |
| 9384 | - // loopback stub; the constructor returns the proxy, so instanceof | |
| 9385 | - // works through __makeStub's getPrototypeOf trap. | |
| 9386 | - RpcStub: class RpcStub { | |
| 9387 | - constructor(target) { | |
| 9388 | - if (target === null || | |
| 9389 | - (typeof target !== "object" && typeof target !== "function")) | |
| 9390 | - throw new TypeError( | |
| 9391 | - "RpcStub requires an object or function."); | |
| 9392 | - return __makeStub( | |
| 9393 | - __newEntry(target), typeof target === "function"); | |
| 9394 | - } | |
| 9395 | - }, | |
| 9396 | - RpcPromise: class RpcPromise extends Promise {}, | |
| 9397 | - RpcProperty: class RpcProperty {}, | |
| 9398 | - ServiceStub: class ServiceStub {}, | |
| 9399 | - // `import { waitUntil } from "cloudflare:workers"`: register into | |
| 9400 | - // the current event; outside any event this is Workerd's | |
| 9401 | - // global-scope error. | |
| 9402 | - waitUntil(promise) { | |
| 9403 | - if (__event_depth() === 0) | |
| 9404 | - throw new Error( | |
| 9405 | - "Disallowed operation called within global scope."); | |
| 9406 | - globalThis.__registerWaitUntil(promise); | |
| 9407 | - }, | |
| 9408 | - exports: {}, | |
| 9409 | - get env() { return globalThis.__cell.env; }, | |
| 9410 | -}; | |
| 9411 | -// Proxy standing in for unsupported node:*/cloudflare:* builtins. Property | |
| 9412 | -// walks stay inert — real bundles reference these at module scope, and | |
| 9413 | -// evaluation must not crash on a builtin the fetch path never exercises — | |
| 9414 | -// but a call or construct throws: the compat contract is "reject at first | |
| 9415 | -// use", and the old silent pass-through turned a missing builtin into a | |
| 9416 | -// wrong result far from the cause. Memoized by dotted path so repeated | |
| 9417 | -// reads keep identity (`mod.foo === mod.foo`). | |
| 9418 | -const __stubCache = new Map(); | |
| 9419 | -globalThis.__nodeStubFor = (path) => { | |
| 9420 | - let stub = __stubCache.get(path); | |
| 9421 | - if (stub) return stub; | |
| 9422 | - stub = new Proxy(function () {}, { | |
| 9423 | - get: (_t, p) => { | |
| 9424 | - // Never masquerade as a thenable. `await` probes `.then`; returning | |
| 9425 | - // a callable here creates a promise that can never settle. | |
| 9426 | - if (p === "then") return undefined; | |
| 9427 | - // coerce cleanly in string/number contexts so evaluation never throws | |
| 9428 | - if (p === Symbol.toPrimitive || p === "toString" || p === "valueOf") | |
| 9429 | - return () => ""; | |
| 9430 | - if (p === Symbol.toStringTag) return "NodeStub"; | |
| 9431 | - if (p === Symbol.iterator) return function* () {}; | |
| 9432 | - if (typeof p !== "string") return undefined; | |
| 9433 | - return globalThis.__nodeStubFor(path + "." + p); | |
| 9434 | - }, | |
| 9435 | - apply() { throw new Error(path + " is not implemented in celld"); }, | |
| 9436 | - construct() { throw new Error(path + " is not implemented in celld"); }, | |
| 9437 | - }); | |
| 9438 | - __stubCache.set(path, stub); | |
| 9439 | - return stub; | |
| 9440 | -}; | |
| 9441 | -globalThis.__nodeStub = globalThis.__nodeStubFor("node builtin"); | |
| 9442 | -if (!globalThis.Event) { | |
| 9443 | - globalThis.Event = class Event { | |
| 9444 | - // Private fields: stored in the object itself, so an Event costs no | |
| 9445 | - // side allocation and no defineProperty call at construction. The | |
| 9446 | - // public members are accessors because the DOM standard makes them | |
| 9447 | - // read-only; EventTarget drives them through _begin/_end. | |
| 9448 | - #type; #bubbles; #cancelable; #composed; | |
| 9449 | - #defaultPrevented = false; | |
| 9450 | - #eventPhase = 0; | |
| 9451 | - #target; #currentTarget; #path; | |
| 9452 | - #stop = false; #stopImmediate = false; #dispatching = false; | |
| 9453 | - // Workerd: events the runtime delivers are trusted; events a | |
| 9454 | - // script constructs and dispatches itself are not. | |
| 9455 | - #trusted = false; | |
| 9456 | - constructor(type, init = {}) { | |
| 9457 | - if (arguments.length === 0) | |
| 9458 | - throw new TypeError( | |
| 9459 | - "Failed to construct 'Event': 1 argument required, but only " + | |
| 9460 | - "0 present."); | |
| 9461 | - if (init !== undefined && init !== null && | |
| 9462 | - typeof init !== "object") | |
| 9463 | - throw new TypeError( | |
| 9464 | - "Failed to construct 'Event': The provided value is not of " + | |
| 9465 | - "type 'EventInit'."); | |
| 9466 | - const options = init || {}; | |
| 9467 | - // Template interpolation, not String(): it must throw for a | |
| 9468 | - // Symbol, which String() would happily format. | |
| 9469 | - this.#type = `${type}`; | |
| 9470 | - this.#bubbles = !!options.bubbles; | |
| 9471 | - this.#cancelable = !!options.cancelable; | |
| 9472 | - this.#composed = !!options.composed; | |
| 9473 | - } | |
| 9474 | - get type() { return this.#type; } | |
| 9475 | - get bubbles() { return this.#bubbles; } | |
| 9476 | - get cancelable() { return this.#cancelable; } | |
| 9477 | - get composed() { return this.#composed; } | |
| 9478 | - get defaultPrevented() { return this.#defaultPrevented; } | |
| 9479 | - get eventPhase() { return this.#eventPhase; } | |
| 9480 | - get target() { return this.#target; } | |
| 9481 | - get currentTarget() { return this.#currentTarget; } | |
| 9482 | - get isTrusted() { return this.#trusted; } | |
| 9483 | - get timeStamp() { return 0; } | |
| 9484 | - get returnValue() { return !this.#defaultPrevented; } | |
| 9485 | - // The one writable member, per the DOM standard. | |
| 9486 | - get cancelBubble() { return this.#stop; } | |
| 9487 | - set cancelBubble(value) { if (value) this.#stop = true; } | |
| 9488 | - composedPath() { return this.#path ? this.#path.slice() : []; } | |
| 9489 | - preventDefault() { | |
| 9490 | - if (this.#cancelable) this.#defaultPrevented = true; | |
| 9491 | - } | |
| 9492 | - stopPropagation() { this.#stop = true; } | |
| 9493 | - stopImmediatePropagation() { | |
| 9494 | - this.#stop = true; | |
| 9495 | - this.#stopImmediate = true; | |
| 9496 | - } | |
| 9497 | - // Internal dispatch hooks used by EventTarget. | |
| 9498 | - get _dispatching() { return this.#dispatching; } | |
| 9499 | - get _stopImmediate() { return this.#stopImmediate; } | |
| 9500 | - _trust() { this.#trusted = true; } | |
| 9501 | - _begin(target) { | |
| 9502 | - this.#dispatching = true; | |
| 9503 | - this.#target = target; | |
| 9504 | - this.#currentTarget = target; | |
| 9505 | - this.#eventPhase = 2; // AT_TARGET | |
| 9506 | - this.#path = [target]; | |
| 9507 | - this.#stop = false; | |
| 9508 | - this.#stopImmediate = false; | |
| 9509 | - } | |
| 9510 | - // Workerd leaves currentTarget set after dispatch (the DOM standard | |
| 9511 | - // nulls it); only the phase is reset. | |
| 9512 | - _end() { | |
| 9513 | - this.#eventPhase = 0; | |
| 9514 | - this.#dispatching = false; | |
| 9515 | - } | |
| 9516 | - }; | |
| 9517 | - { | |
| 9518 | - const phases = { | |
| 9519 | - NONE: 0, CAPTURING_PHASE: 1, AT_TARGET: 2, BUBBLING_PHASE: 3, | |
| 9520 | - }; | |
| 9521 | - for (const [name, value] of Object.entries(phases)) { | |
| 9522 | - const d = { value, writable: false, enumerable: true, | |
| 9523 | - configurable: false }; | |
| 9524 | - Object.defineProperty(globalThis.Event, name, d); | |
| 9525 | - Object.defineProperty(globalThis.Event.prototype, name, d); | |
| 9526 | - } | |
| 9527 | - } | |
| 9528 | -} | |
| 9529 | -if (!globalThis.CustomEvent) { | |
| 9530 | - globalThis.CustomEvent = class CustomEvent extends Event { | |
| 9531 | - constructor(type, init = {}) { | |
| 9532 | - super(type, init); | |
| 9533 | - this.detail = init.detail === undefined ? null : init.detail; | |
| 9534 | - } | |
| 9535 | - }; | |
| 9536 | -} | |
| 9537 | -if (!globalThis.ExtendableEvent) { | |
| 9538 | - // Exists as a type but is not constructable from user code. | |
| 9539 | - globalThis.ExtendableEvent = class ExtendableEvent extends Event { | |
| 9540 | - constructor() { | |
| 9541 | - throw new TypeError("Illegal constructor"); | |
| 9542 | - } | |
| 9543 | - }; | |
| 9544 | -} | |
| 9545 | -// An event-handler IDL attribute occupies one listener-list position. Replacing | |
| 9546 | -// its callback must retain that position, or listeners added after `onabort` | |
| 9547 | -// run before it and observe an order that differs from the web platform. | |
| 9548 | -const __eventHandlerEntry = Symbol("eventHandlerEntry"); | |
| 9549 | -const __getEventHandler = (target, type) => | |
| 9550 | - (target._listeners.get(type) || []) | |
| 9551 | - .find((entry) => entry[__eventHandlerEntry])?.callback ?? null; | |
| 9552 | -const __setEventHandler = (target, type, callback) => { | |
| 9553 | - const list = target._listeners.get(type) || []; | |
| 9554 | - const entry = list.find((item) => item[__eventHandlerEntry]); | |
| 9555 | - if (typeof callback !== "function") { | |
| 9556 | - if (entry) list.splice(list.indexOf(entry), 1); | |
| 9557 | - return; | |
| 9558 | - } | |
| 9559 | - if (entry) { | |
| 9560 | - entry.callback = callback; | |
| 9561 | - } else { | |
| 9562 | - list.push({ callback, once: false, [__eventHandlerEntry]: true }); | |
| 9563 | - target._listeners.set(type, list); | |
| 9564 | - } | |
| 9565 | -}; | |
| 9566 | -if (!globalThis.EventTarget) { | |
| 9567 | - globalThis.EventTarget = class EventTarget { | |
| 9568 | - constructor() { this._listeners = new Map(); } | |
| 9569 | - addEventListener(type, callback, options = {}) { | |
| 9570 | - if (callback === null || callback === undefined) return; | |
| 9571 | - if (typeof callback !== "function" && | |
| 9572 | - typeof callback.handleEvent !== "function") | |
| 9573 | - throw new TypeError( | |
| 9574 | - "Failed to execute 'addEventListener' on 'EventTarget': " + | |
| 9575 | - "parameter 2 is not of type 'EventListener'."); | |
| 9576 | - const object = typeof options === "object" && options !== null; | |
| 9577 | - // Capture and passive are accepted for portability but must be | |
| 9578 | - // false: Cells dispatches only at the target, so honouring them | |
| 9579 | - // would silently change ordering. | |
| 9580 | - if (object ? options.capture || options.passive : !!options) | |
| 9581 | - throw new TypeError( | |
| 9582 | - "Cells does not support the 'capture' or 'passive' options " + | |
| 9583 | - "on addEventListener()."); | |
| 9584 | - const signal = object ? options.signal : undefined; | |
| 9585 | - if (signal && signal.aborted) return; | |
| 9586 | - const key = String(type); | |
| 9587 | - const list = this._listeners.get(key) || []; | |
| 9588 | - if (list.some((e) => e.callback === callback)) return; | |
| 9589 | - list.push({ callback, once: object && !!options.once }); | |
| 9590 | - this._listeners.set(key, list); | |
| 9591 | - if (signal) | |
| 9592 | - signal.addEventListener("abort", () => | |
| 9593 | - this.removeEventListener(key, callback), { once: true }); | |
| 9594 | - } | |
| 9595 | - removeEventListener(type, callback, options = {}) { | |
| 9596 | - const object = typeof options === "object" && options !== null; | |
| 9597 | - if (object ? options.capture : !!options) | |
| 9598 | - throw new TypeError( | |
| 9599 | - "Cells does not support the 'capture' option on " + | |
| 9600 | - "removeEventListener()."); | |
| 9601 | - const list = this._listeners.get(String(type)); | |
| 9602 | - if (!list) return; | |
| 9603 | - const index = list.findIndex((e) => e.callback === callback); | |
| 9604 | - if (index >= 0) list.splice(index, 1); | |
| 9605 | - } | |
| 9606 | - dispatchEvent(event) { | |
| 9607 | - if (!(event instanceof Event)) | |
| 9608 | - throw new TypeError("argument is not an Event"); | |
| 9609 | - if (event._dispatching) | |
| 9610 | - throw new DOMException( | |
| 9611 | - "The event is already being dispatched.", | |
| 9612 | - "InvalidStateError"); | |
| 9613 | - event._begin(this); | |
| 9614 | - // Copy: a listener may add or remove listeners mid-dispatch. | |
| 9615 | - for (const item of (this._listeners.get(event.type) || []).slice()) { | |
| 9616 | - if (event._stopImmediate) break; | |
| 9617 | - if (item.once) | |
| 9618 | - this.removeEventListener(event.type, item.callback); | |
| 9619 | - if (typeof item.callback === "function") | |
| 9620 | - item.callback.call(this, event); | |
| 9621 | - else item.callback.handleEvent(event); | |
| 9622 | - } | |
| 9623 | - const handler = this["on" + event.type]; | |
| 9624 | - const hasEventHandler = (this._listeners.get(event.type) || []) | |
| 9625 | - .some((item) => item[__eventHandlerEntry]); | |
| 9626 | - if (!hasEventHandler && !event._stopImmediate && | |
| 9627 | - typeof handler === "function") | |
| 9628 | - handler.call(this, event); | |
| 9629 | - event._end(); | |
| 9630 | - return !event.defaultPrevented; | |
| 9631 | - } | |
| 9632 | - }; | |
| 9633 | -} | |
| 9634 | -// The global scope is itself an EventTarget. | |
| 9635 | -if (typeof globalThis.addEventListener !== "function") { | |
| 9636 | - const globalTarget = new EventTarget(); | |
| 9637 | - for (const name of | |
| 9638 | - ["addEventListener", "removeEventListener", "dispatchEvent"]) | |
| 9639 | - globalThis[name] = globalTarget[name].bind(globalTarget); | |
| 9640 | -} | |
| 9641 | -if (!globalThis.MessageEvent) { | |
| 9642 | - globalThis.MessageEvent = class MessageEvent extends Event { | |
| 9643 | - constructor(type, init = {}) { | |
| 9644 | - super(type, init); | |
| 9645 | - this.data = init.data; | |
| 9646 | - this.origin = String(init.origin || ""); | |
| 9647 | - this.lastEventId = String(init.lastEventId || ""); | |
| 9648 | - } | |
| 9649 | - }; | |
| 9650 | -} | |
| 9651 | -if (!globalThis.CloseEvent) { | |
| 9652 | - globalThis.CloseEvent = class CloseEvent extends Event { | |
| 9653 | - constructor(type, init = {}) { | |
| 9654 | - super(type, init); | |
| 9655 | - this.code = Number(init.code || 0); | |
| 9656 | - // `reason` is a USVString: a lone surrogate becomes U+FFFD rather than | |
| 9657 | - // travelling as an unpaired code unit. | |
| 9658 | - this.reason = String(init.reason || "").toWellFormed | |
| 9659 | - ? String(init.reason || "").toWellFormed() | |
| 9660 | - : String(init.reason || "").replace( | |
| 9661 | - /[\uD800-\uDFFF]/g, | |
| 9662 | - (unit, index, whole) => { | |
| 9663 | - const code = unit.charCodeAt(0); | |
| 9664 | - const next = whole.charCodeAt(index + 1); | |
| 9665 | - const prev = whole.charCodeAt(index - 1); | |
| 9666 | - const paired = code <= 0xDBFF | |
| 9667 | - ? next >= 0xDC00 && next <= 0xDFFF | |
| 9668 | - : prev >= 0xD800 && prev <= 0xDBFF; | |
| 9669 | - return paired ? unit : "\uFFFD"; | |
| 9670 | - }, | |
| 9671 | - ); | |
| 9672 | - this.wasClean = !!init.wasClean; | |
| 9673 | - } | |
| 9674 | - }; | |
| 9675 | -} | |
| 9676 | -if (!globalThis.DOMException) { | |
| 9677 | - globalThis.DOMException = class DOMException extends Error { | |
| 9678 | - constructor(message = "", name = "Error") { super(message); this.name = name; } | |
| 9679 | - }; | |
| 9680 | - // WebIDL legacy code constants, enumerable on both the interface | |
| 9681 | - // object and its prototype, in spec order. | |
| 9682 | - { | |
| 9683 | - const codes = [ | |
| 9684 | - ["INDEX_SIZE_ERR", 1], ["DOMSTRING_SIZE_ERR", 2], | |
| 9685 | - ["HIERARCHY_REQUEST_ERR", 3], ["WRONG_DOCUMENT_ERR", 4], | |
| 9686 | - ["INVALID_CHARACTER_ERR", 5], ["NO_DATA_ALLOWED_ERR", 6], | |
| 9687 | - ["NO_MODIFICATION_ALLOWED_ERR", 7], ["NOT_FOUND_ERR", 8], | |
| 9688 | - ["NOT_SUPPORTED_ERR", 9], ["INUSE_ATTRIBUTE_ERR", 10], | |
| 9689 | - ["INVALID_STATE_ERR", 11], ["SYNTAX_ERR", 12], | |
| 9690 | - ["INVALID_MODIFICATION_ERR", 13], ["NAMESPACE_ERR", 14], | |
| 9691 | - ["INVALID_ACCESS_ERR", 15], ["VALIDATION_ERR", 16], | |
| 9692 | - ["TYPE_MISMATCH_ERR", 17], ["SECURITY_ERR", 18], | |
| 9693 | - ["NETWORK_ERR", 19], ["ABORT_ERR", 20], | |
| 9694 | - ["URL_MISMATCH_ERR", 21], ["QUOTA_EXCEEDED_ERR", 22], | |
| 9695 | - ["TIMEOUT_ERR", 23], ["INVALID_NODE_TYPE_ERR", 24], | |
| 9696 | - ["DATA_CLONE_ERR", 25], | |
| 9697 | - ]; | |
| 9698 | - for (const [name, value] of codes) { | |
| 9699 | - const d = { value, writable: false, enumerable: true, | |
| 9700 | - configurable: false }; | |
| 9701 | - Object.defineProperty(globalThis.DOMException, name, d); | |
| 9702 | - Object.defineProperty(globalThis.DOMException.prototype, name, d); | |
| 9703 | - } | |
| 9704 | - // The legacy `code` member maps the error name to its constant, per | |
| 9705 | - // WebIDL; names outside the table (and every modern name) are 0. | |
| 9706 | - const legacy = { | |
| 9707 | - IndexSizeError: 1, HierarchyRequestError: 3, WrongDocumentError: 4, | |
| 9708 | - InvalidCharacterError: 5, NoModificationAllowedError: 7, | |
| 9709 | - NotFoundError: 8, NotSupportedError: 9, InUseAttributeError: 10, | |
| 9710 | - InvalidStateError: 11, SyntaxError: 12, InvalidModificationError: 13, | |
| 9711 | - NamespaceError: 14, InvalidAccessError: 15, TypeMismatchError: 17, | |
| 9712 | - SecurityError: 18, NetworkError: 19, AbortError: 20, | |
| 9713 | - URLMismatchError: 21, QuotaExceededError: 22, TimeoutError: 23, | |
| 9714 | - InvalidNodeTypeError: 24, DataCloneError: 25, | |
| 9715 | - }; | |
| 9716 | - Object.defineProperty(globalThis.DOMException.prototype, "code", { | |
| 9717 | - get() { return legacy[this.name] ?? 0; }, | |
| 9718 | - enumerable: true, configurable: true, | |
| 9719 | - }); | |
| 9720 | - } | |
| 9721 | -} | |
| 9722 | -if (!globalThis.AbortSignal) { | |
| 9723 | - const __abortBrand = Symbol("abortSignal"); | |
| 9724 | - globalThis.AbortSignal = class AbortSignal extends EventTarget { | |
| 9725 | - // The Headers/Blob clone-poisoning brand: V8's structured | |
| 9726 | - // clone throws on functions, so a live signal reaches the | |
| 9727 | - // RPC lift instead of silently flattening to plain data. | |
| 9728 | - constructor() { | |
| 9729 | - // Per spec AbortSignal has no constructor: it is only reachable | |
| 9730 | - // through AbortController, AbortSignal.abort/timeout/any. The internal | |
| 9731 | - // paths pass the brand to get past this. | |
| 9732 | - if (arguments[0] !== __abortBrand) { | |
| 9733 | - throw new TypeError("Illegal constructor"); | |
| 9734 | - } | |
| 9735 | - super(); | |
| 9736 | - this.aborted = false; | |
| 9737 | - this.reason = undefined; | |
| 9738 | - this.__celldHost = __rpcNoClone; | |
| 9739 | - } | |
| 9740 | - throwIfAborted() { if (this.aborted) throw this.reason; } | |
| 9741 | - static abort(reason = new DOMException("This operation was aborted", "AbortError")) { | |
| 9742 | - const c = new AbortController(); c.abort(reason); return c.signal; | |
| 9743 | - } | |
| 9744 | - static timeout(ms) { | |
| 9745 | - const c = new AbortController(); | |
| 9746 | - setTimeout(() => c.abort(new DOMException( | |
| 9747 | - "The operation was aborted due to timeout", "TimeoutError", | |
| 9748 | - )), ms); | |
| 9749 | - return c.signal; | |
| 9750 | - } | |
| 9751 | - static any(signals) { | |
| 9752 | - const c = new AbortController(); | |
| 9753 | - for (const signal of signals) { | |
| 9754 | - if (signal.aborted) { c.abort(signal.reason); break; } | |
| 9755 | - signal.addEventListener("abort", () => c.abort(signal.reason), { once: true }); | |
| 9756 | - } | |
| 9757 | - return c.signal; | |
| 9758 | - } | |
| 9759 | - }; | |
| 9760 | - Object.defineProperty(globalThis.AbortSignal.prototype, "onabort", { | |
| 9761 | - configurable: true, | |
| 9762 | - enumerable: true, | |
| 9763 | - get() { | |
| 9764 | - if (!(this instanceof globalThis.AbortSignal)) | |
| 9765 | - throw new TypeError("Illegal invocation"); | |
| 9766 | - return __getEventHandler(this, "abort"); | |
| 9767 | - }, | |
| 9768 | - set(value) { | |
| 9769 | - if (!(this instanceof globalThis.AbortSignal)) | |
| 9770 | - throw new TypeError("Illegal invocation"); | |
| 9771 | - __setEventHandler(this, "abort", value); | |
| 9772 | - }, | |
| 9773 | - }); | |
| 9774 | - globalThis.AbortController = class AbortController { | |
| 9775 | - constructor() { this.signal = new AbortSignal(__abortBrand); } | |
| 9776 | - abort(reason = new DOMException("This operation was aborted", "AbortError")) { | |
| 9777 | - __abortSignal(this.signal, reason); | |
| 9778 | - } | |
| 9779 | - }; | |
| 9780 | -} | |
| 9781 | -if (!globalThis.Blob) { | |
| 9782 | - // Same clone-poisoning brand as Headers: an enumerable | |
| 9783 | - // function-valued property makes V8's structured clone throw, so | |
| 9784 | - // a Blob reaches the RPC lift instead of silently flattening. | |
| 9785 | - const __blobNoClone = () => {}; | |
| 9786 | - globalThis.Blob = class Blob { | |
| 9787 | - constructor(parts = [], options = {}) { | |
| 9788 | - // size is assigned before type so both land in the order the | |
| 9789 | - // inspect output below reports them. | |
| 9790 | - if (options && options.endings !== undefined) | |
| 9791 | - throw new Error( | |
| 9792 | - "The 'endings' field on 'Options' is not implemented."); | |
| 9793 | - this.size = 0; | |
| 9794 | - // A type outside U+0020..U+007E is not a valid MIME type and is | |
| 9795 | - // dropped rather than stored. | |
| 9796 | - const rawType = String(options.type || ""); | |
| 9797 | - this.type = /^[\u0020-\u007e]*$/.test(rawType) | |
| 9798 | - ? rawType.toLowerCase() : ""; | |
| 9799 | - this.__celldHost = __blobNoClone; | |
| 9800 | - // Two passes. First convert every part in order — string | |
| 9801 | - // conversion runs user code (Symbol.toPrimitive), which may | |
| 9802 | - // resize a backing buffer. Buffers and views are carried through | |
| 9803 | - // as-is so a length-tracking view is measured *after* those side | |
| 9804 | - // effects, matching Workerd. Then allocate once and copy. | |
| 9805 | - // | |
| 9806 | - // The previous shape pushed every byte into a plain array with a | |
| 9807 | - // spread, costing roughly 8x the memory and exceeding the | |
| 9808 | - // argument limit on multi-megabyte parts. | |
| 9809 | - const sources = []; | |
| 9810 | - for (const part of parts) { | |
| 9811 | - if (part instanceof Blob) sources.push(part._bytes); | |
| 9812 | - else if (part instanceof ArrayBuffer || | |
| 9813 | - ArrayBuffer.isView(part)) sources.push(part); | |
| 9814 | - else sources.push(new TextEncoder().encode(String(part))); | |
| 9815 | - } | |
| 9816 | - const chunks = sources.map((source) => | |
| 9817 | - source instanceof Uint8Array ? source | |
| 9818 | - : source instanceof ArrayBuffer ? new Uint8Array(source) | |
| 9819 | - : new Uint8Array( | |
| 9820 | - source.buffer, source.byteOffset, source.byteLength)); | |
| 9821 | - let total = 0; | |
| 9822 | - for (const chunk of chunks) total += chunk.byteLength; | |
| 9823 | - const LIMIT = 134217728; | |
| 9824 | - if (total > LIMIT) | |
| 9825 | - throw new RangeError( | |
| 9826 | - `Blob size ${total} exceeds limit ${LIMIT}`); | |
| 9827 | - const bytes = new Uint8Array(total); | |
| 9828 | - let offset = 0; | |
| 9829 | - for (const chunk of chunks) { | |
| 9830 | - bytes.set(chunk, offset); | |
| 9831 | - offset += chunk.byteLength; | |
| 9832 | - } | |
| 9833 | - // Non-enumerable: the backing store is not part of the object's | |
| 9834 | - // observable shape (inspect, JSON, spread). | |
| 9835 | - Object.defineProperty(this, "_bytes", { | |
| 9836 | - value: bytes, writable: true, configurable: true, | |
| 9837 | - }); | |
| 9838 | - this.size = total; | |
| 9839 | - } | |
| 9840 | - async arrayBuffer() { return this._bytes.slice().buffer; } | |
| 9841 | - async bytes() { return this._bytes.slice(); } | |
| 9842 | - async text() { return new TextDecoder().decode(this._bytes); } | |
| 9843 | - stream() { | |
| 9844 | - const bytes = this._bytes; | |
| 9845 | - return new ReadableStream({ | |
| 9846 | - start(controller) { | |
| 9847 | - if (bytes.byteLength) controller.enqueue(bytes.slice()); | |
| 9848 | - controller.close(); | |
| 9849 | - }, | |
| 9850 | - }); | |
| 9851 | - } | |
| 9852 | - [Symbol.for("nodejs.util.inspect.custom")]() { | |
| 9853 | - return `Blob { size: ${this.size}, type: '${this.type}' }`; | |
| 9854 | - } | |
| 9855 | - slice(start = 0, end = this.size, type = "") { | |
| 9856 | - const norm = (n, fallback) => { | |
| 9857 | - n = n === undefined ? fallback : Number(n); | |
| 9858 | - return n < 0 ? Math.max(this.size + n, 0) : Math.min(n, this.size); | |
| 9859 | - }; | |
| 9860 | - const a = norm(start, 0), b = norm(end, this.size); | |
| 9861 | - return new Blob( | |
| 9862 | - [this._bytes.subarray(a, Math.max(a, b))], { type }); | |
| 9863 | - } | |
| 9864 | - get [Symbol.toStringTag]() { return "Blob"; } | |
| 9865 | - }; | |
| 9866 | -} | |
| 9867 | -if (!globalThis.File) { | |
| 9868 | - // WebIDL-ish per Workerd: name is required, name/lastModified are | |
| 9869 | - // brand-checked prototype getters (enumerable, matching the | |
| 9870 | - // workers_api_getters_setters_on_prototype flag), and lastModified | |
| 9871 | - // coerces via ToNumber (throws for BigInt), NaN becoming 0. | |
| 9872 | - globalThis.File = class File extends Blob { | |
| 9873 | - #name; | |
| 9874 | - #lastModified; | |
| 9875 | - constructor(parts, name, options = {}) { | |
| 9876 | - if (arguments.length < 2) | |
| 9877 | - throw new TypeError( | |
| 9878 | - "Failed to construct 'File': 2 arguments required, but " + | |
| 9879 | - `only ${arguments.length} present.`); | |
| 9880 | - super(parts, options); | |
| 9881 | - this.#name = String(name); | |
| 9882 | - const lm = options == null ? undefined : options.lastModified; | |
| 9883 | - if (lm === undefined) this.#lastModified = Date.now(); | |
| 9884 | - else { | |
| 9885 | - const n = +lm; // ToNumber: throws for BigInt, like WebIDL | |
| 9886 | - this.#lastModified = Number.isFinite(n) ? Math.trunc(n) : 0; | |
| 9887 | - } | |
| 9888 | - } | |
| 9889 | - get name() { return this.#name; } | |
| 9890 | - get lastModified() { return this.#lastModified; } | |
| 9891 | - get [Symbol.toStringTag]() { return "File"; } | |
| 9892 | - [Symbol.for("nodejs.util.inspect.custom")]() { | |
| 9893 | - return `File { name: '${this.name}', ` + | |
| 9894 | - `lastModified: ${this.lastModified}, size: ${this.size}, ` + | |
| 9895 | - `type: '${this.type}' }`; | |
| 9896 | - } | |
| 9897 | - }; | |
| 9898 | - for (const key of ["name", "lastModified"]) { | |
| 9899 | - const desc = | |
| 9900 | - Object.getOwnPropertyDescriptor(File.prototype, key); | |
| 9901 | - desc.enumerable = true; | |
| 9902 | - Object.defineProperty(File.prototype, key, desc); | |
| 9903 | - } | |
| 9904 | -} | |
| 9905 | -if (!globalThis.FormData) { | |
| 9906 | -// Byte offsets the multipart scanner compares against. A part body is | |
| 9907 | -// arbitrary bytes, so every framing decision below is made on bytes. | |
| 9908 | -const __CR = 13, __LF = 10, __DASH = 45; | |
| 9909 | -const __bytesIndexOf = (haystack, needle, from) => { | |
| 9910 | - const last = haystack.length - needle.length; | |
| 9911 | - outer: for (let i = from; i <= last; i++) { | |
| 9912 | - for (let j = 0; j < needle.length; j++) | |
| 9913 | - if (haystack[i + j] !== needle[j]) continue outer; | |
| 9914 | - return i; | |
| 9915 | - } | |
| 9916 | - return -1; | |
| 9917 | -}; | |
| 9918 | -// A boundary delimiter is a delimiter only at the start of a line (RFC 2046 | |
| 9919 | -// section 5.1.1). Searching for the bytes anywhere would let a binary part | |
| 9920 | -// that happens to contain `--<boundary>` split itself, which is a corrupt | |
| 9921 | -// upload rather than a parse error, so the caller never learns of it. | |
| 9922 | -const __delimiterIndex = (bytes, delimiter, from) => { | |
| 9923 | - for (let at = from;;) { | |
| 9924 | - const found = __bytesIndexOf(bytes, delimiter, at); | |
| 9925 | - if (found < 0) return -1; | |
| 9926 | - if (found === 0 || bytes[found - 1] === __LF) return found; | |
| 9927 | - at = found + 1; | |
| 9928 | - } | |
| 9929 | -}; | |
| 9930 | -// A `Content-Disposition` parameter, anchored to the start of a parameter: | |
| 9931 | -// the parameter name must follow the header name or a `;`. An unanchored | |
| 9932 | -// pattern found the `name=` inside `filename=`, so a part whose header wrote | |
| 9933 | -// the filename first landed under the filename. The grammar does not | |
| 9934 | -// constrain the parameter order, and both orders occur in the wild. Hoisted | |
| 9935 | -// because the previous shape compiled a regex per parameter per part. | |
| 9936 | -const __CD_NAME = | |
| 9937 | - /(?:^|;)\s*name\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i; | |
| 9938 | -const __CD_FILENAME = | |
| 9939 | - /(?:^|;)\s*filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i; | |
| 9940 | -// Body -> FormData for multipart/form-data and | |
| 9941 | -// application/x-www-form-urlencoded. Kept out of the class so V8 only | |
| 9942 | -// pre-parses it; the body is compiled on first actual formData() call. | |
| 9943 | -// | |
| 9944 | -// `bytes` is the undecoded body. A file part must reach `File` as the bytes | |
| 9945 | -// that arrived: decoding the body first and slicing part bodies out of the | |
| 9946 | -// string replaced every non-UTF-8 sequence with U+FFFD, and the re-encode in | |
| 9947 | -// the `Blob` constructor then wrote those replacement bytes into the file. | |
| 9948 | -globalThis.__parseFormData = (bytes, contentType) => { | |
| 9949 | - const ct = String(contentType || ""); | |
| 9950 | - if (/^\s*application\/x-www-form-urlencoded/i.test(ct)) { | |
| 9951 | - // This form is decoded as UTF-8, so a declared charset that is not UTF-8 | |
| 9952 | - // cannot be honoured. Refuse rather than mis-decode. | |
| 9953 | - const charset = /;\s*charset\s*=\s*"?([^";]+)/i.exec(ct); | |
| 9954 | - if (charset && !/^utf-?8$/i.test(charset[1].trim())) | |
| 9955 | - throw new TypeError( | |
| 9956 | - `Unsupported charset "${charset[1].trim()}". FormData can only ` + | |
| 9957 | - "parse UTF-8 encoded bodies."); | |
| 9958 | - const form = new FormData(); | |
| 9959 | - for (const [key, value] of new URLSearchParams( | |
| 9960 | - new TextDecoder().decode(bytes))) | |
| 9961 | - form.append(key, value); | |
| 9962 | - return form; | |
| 9963 | - } | |
| 9964 | - if (!/^\s*multipart\/form-data/i.test(ct)) | |
| 9965 | - throw new TypeError( | |
| 9966 | - "Unrecognized Content-Type header value. FormData can only " + | |
| 9967 | - "parse the following MIME types: multipart/form-data, " + | |
| 9968 | - "application/x-www-form-urlencoded"); | |
| 9969 | - const found = /boundary\s*=\s*(?:"([^"]*)"|([^;]+))/i.exec(ct); | |
| 9970 | - if (!found) | |
| 9971 | - throw new TypeError( | |
| 9972 | - "No boundary was found in the multipart/form-data " + | |
| 9973 | - "Content-Type header."); | |
| 9974 | - const boundary = (found[1] !== undefined ? found[1] : found[2]).trim(); | |
| 9975 | - const form = new FormData(); | |
| 9976 | - const delimiter = new TextEncoder().encode("--" + boundary); | |
| 9977 | - // Walk the delimiters rather than splitting on them, so that a body whose | |
| 9978 | - // framing is truncated or corrupt is refused instead of silently yielding | |
| 9979 | - // the parts that happened to parse. Only the framing is checked; a part's | |
| 9980 | - // own bytes are carried through unexamined. The preamble before the first | |
| 9981 | - // delimiter and the epilogue after the closing one are ignored. | |
| 9982 | - let cursor = __delimiterIndex(bytes, delimiter, 0); | |
| 9983 | - if (cursor < 0) | |
| 9984 | - throw new TypeError( | |
| 9985 | - "No boundary delimiter was found in the multipart/form-data body."); | |
| 9986 | - cursor += delimiter.length; | |
| 9987 | - for (;;) { | |
| 9988 | - // What follows a delimiter decides everything: "--" closes the body, a | |
| 9989 | - // line break opens another part, and anything else is malformed. | |
| 9990 | - if (bytes[cursor] === __DASH && bytes[cursor + 1] === __DASH) break; | |
| 9991 | - const lineBreak = bytes[cursor] === __CR && bytes[cursor + 1] === __LF | |
| 9992 | - ? 2 | |
| 9993 | - : bytes[cursor] === __LF ? 1 : 0; | |
| 9994 | - if (lineBreak === 0) | |
| 9995 | - throw new TypeError( | |
| 9996 | - "A boundary delimiter must be followed by CRLF, LF, or \"--\"."); | |
| 9997 | - cursor += lineBreak; | |
| 9998 | - const partStart = cursor; | |
| 9999 | - const next = __delimiterIndex(bytes, delimiter, partStart); | |
| 10000 | - if (next < 0) | |
| 10001 | - throw new TypeError( | |
| 10002 | - "The multipart/form-data body ended without a closing boundary " + | |
| 10003 | - "delimiter."); | |
| 10004 | - // The line break before a delimiter belongs to the delimiter, not to the | |
| 10005 | - // part it terminates. | |
| 10006 | - let chunkEnd = next; | |
| 10007 | - if (chunkEnd > partStart && bytes[chunkEnd - 1] === __LF) { | |
| 10008 | - chunkEnd -= 1; | |
| 10009 | - if (chunkEnd > partStart && bytes[chunkEnd - 1] === __CR) chunkEnd -= 1; | |
| 10010 | - } | |
| 10011 | - cursor = next + delimiter.length; | |
| 10012 | - // The headers end at the first blank line. Either line break can be CRLF | |
| 10013 | - // or a bare LF, which accepted inputs can contain. | |
| 10014 | - let headerEnd = -1, bodyStart = -1; | |
| 10015 | - for (let i = partStart; i < chunkEnd; i++) { | |
| 10016 | - const first = bytes[i] === __CR && bytes[i + 1] === __LF | |
| 10017 | - ? 2 | |
| 10018 | - : bytes[i] === __LF ? 1 : 0; | |
| 10019 | - if (first === 0) continue; | |
| 10020 | - const after = i + first; | |
| 10021 | - const second = bytes[after] === __CR && bytes[after + 1] === __LF | |
| 10022 | - ? 2 | |
| 10023 | - : bytes[after] === __LF ? 1 : 0; | |
| 10024 | - if (second === 0) continue; | |
| 10025 | - headerEnd = i; | |
| 10026 | - bodyStart = after + second; | |
| 10027 | - break; | |
| 10028 | - } | |
| 10029 | - if (headerEnd < 0) | |
| 10030 | - throw new TypeError( | |
| 10031 | - "A FormData part's headers must be terminated by a blank line."); | |
| 10032 | - // Part headers are text. Decoding this slice as UTF-8 keeps a non-ASCII | |
| 10033 | - // name or filename intact and cannot reach the part body. | |
| 10034 | - const rawHeaders = new TextDecoder().decode( | |
| 10035 | - bytes.subarray(partStart, headerEnd)); | |
| 10036 | - const body = bytes.subarray(bodyStart, chunkEnd); | |
| 10037 | - let disposition = null; | |
| 10038 | - let type = ""; | |
| 10039 | - for (const line of rawHeaders.split(/\r?\n/)) { | |
| 10040 | - const colon = line.indexOf(":"); | |
| 10041 | - if (colon < 0) continue; | |
| 10042 | - const name = line.slice(0, colon).trim().toLowerCase(); | |
| 10043 | - const value = line.slice(colon + 1).trim(); | |
| 10044 | - if (name === "content-disposition") disposition = value; | |
| 10045 | - else if (name === "content-type") type = value; | |
| 10046 | - } | |
| 10047 | - if (disposition === null) | |
| 10048 | - throw new TypeError( | |
| 10049 | - "Content-Disposition header is required for each FormData " + | |
| 10050 | - "part."); | |
| 10051 | - const kind = disposition.split(";")[0].trim(); | |
| 10052 | - if (kind.toLowerCase() !== "form-data") | |
| 10053 | - throw new TypeError( | |
| 10054 | - "Content-Disposition header for FormData part must have the " + | |
| 10055 | - "value \"form-data\", possibly followed by parameters. Got: " + | |
| 10056 | - "\"" + kind + "\""); | |
| 10057 | - const param = (pattern) => { | |
| 10058 | - const m = pattern.exec(disposition); | |
| 10059 | - if (!m) return undefined; | |
| 10060 | - const raw = m[1] !== undefined ? m[1] : (m[2] || "").trim(); | |
| 10061 | - if (/\\$/.test(raw.replace(/\\\\/g, ""))) | |
| 10062 | - throw new TypeError( | |
| 10063 | - "Name or filename can't end with backslash"); | |
| 10064 | - return raw.replace(/\\(.)/g, "$1"); | |
| 10065 | - }; | |
| 10066 | - const name = param(__CD_NAME); | |
| 10067 | - if (name === undefined) | |
| 10068 | - throw new TypeError( | |
| 10069 | - "Content-Disposition header for FormData part must have a " + | |
| 10070 | - "name parameter."); | |
| 10071 | - const filename = param(__CD_FILENAME); | |
| 10072 | - // A part without a filename is an entry value, which the spec defines as a | |
| 10073 | - // string, so this one part is decoded as UTF-8. A file part keeps its | |
| 10074 | - // bytes. | |
| 10075 | - if (filename === undefined) | |
| 10076 | - form.append(name, new TextDecoder().decode(body)); | |
| 10077 | - else | |
| 10078 | - form.append( | |
| 10079 | - name, new File([body], filename, { type: type || "" })); | |
| 10080 | - } | |
| 10081 | - return form; | |
| 10082 | -}; | |
| 10083 | - // Spec entry conversion: strings stay strings; a Blob becomes a | |
| 10084 | - // File named "blob" (or `filename`); a File is renamed only when a | |
| 10085 | - // filename is supplied. | |
| 10086 | - const __formDataValue = (value, filename) => { | |
| 10087 | - if (!(value instanceof Blob)) return String(value); | |
| 10088 | - if (value instanceof File && filename === undefined) return value; | |
| 10089 | - return new File( | |
| 10090 | - [value], | |
| 10091 | - filename === undefined ? "blob" : String(filename), | |
| 10092 | - { | |
| 10093 | - type: value.type, | |
| 10094 | - lastModified: | |
| 10095 | - value instanceof File ? value.lastModified : undefined, | |
| 10096 | - }, | |
| 10097 | - ); | |
| 10098 | - }; | |
| 10099 | - globalThis.FormData = class FormData { | |
| 10100 | - constructor() { this._entries = []; } | |
| 10101 | - append(name, value, filename) { | |
| 10102 | - this._entries.push( | |
| 10103 | - [String(name), __formDataValue(value, filename)]); | |
| 10104 | - } | |
| 10105 | - set(name, value, filename) { | |
| 10106 | - value = __formDataValue(value, filename); | |
| 10107 | - const key = String(name); | |
| 10108 | - // Spec: replace the first match in place, keeping its position, | |
| 10109 | - // and drop any later matches. | |
| 10110 | - const first = this._entries.findIndex(([k]) => k === key); | |
| 10111 | - if (first < 0) { this._entries.push([key, value]); return; } | |
| 10112 | - this._entries[first] = [key, value]; | |
| 10113 | - for (let i = this._entries.length - 1; i > first; i--) | |
| 10114 | - if (this._entries[i][0] === key) this._entries.splice(i, 1); | |
| 10115 | - } | |
| 10116 | - get(name) { | |
| 10117 | - const row = this._entries.find(([key]) => key === String(name)); | |
| 10118 | - return row ? row[1] : null; | |
| 10119 | - } | |
| 10120 | - getAll(name) { | |
| 10121 | - return this._entries.filter(([key]) => key === String(name)).map(([, value]) => value); | |
| 10122 | - } | |
| 10123 | - has(name) { return this._entries.some(([key]) => key === String(name)); } | |
| 10124 | - delete(name) { | |
| 10125 | - const key = String(name); | |
| 10126 | - // Splice in place: the iterators below read the live list, so the | |
| 10127 | - // array identity must survive a delete during iteration. | |
| 10128 | - for (let i = this._entries.length - 1; i >= 0; i--) | |
| 10129 | - if (this._entries[i][0] === key) this._entries.splice(i, 1); | |
| 10130 | - } | |
| 10131 | - // Iteration is live: the iterator holds an index and re-reads the | |
| 10132 | - // entry list, so entries appended during iteration are visited and | |
| 10133 | - // an exhausted iterator resumes if entries are added later. A | |
| 10134 | - // generator cannot do this — once it returns it is done forever. | |
| 10135 | - _iterate(pick) { | |
| 10136 | - const self = this; | |
| 10137 | - let index = 0; | |
| 10138 | - const iterator = { | |
| 10139 | - next() { | |
| 10140 | - if (index >= self._entries.length) | |
| 10141 | - return { value: undefined, done: true }; | |
| 10142 | - return { value: pick(self._entries[index++]), done: false }; | |
| 10143 | - }, | |
| 10144 | - [Symbol.iterator]() { return iterator; }, | |
| 10145 | - }; | |
| 10146 | - return iterator; | |
| 10147 | - } | |
| 10148 | - entries() { return this._iterate((e) => [e[0], e[1]]); } | |
| 10149 | - keys() { return this._iterate((e) => e[0]); } | |
| 10150 | - values() { return this._iterate((e) => e[1]); } | |
| 10151 | - [Symbol.iterator]() { return this.entries(); } | |
| 10152 | - forEach(callback, thisArg) { | |
| 10153 | - if (typeof callback !== "function") | |
| 10154 | - throw new TypeError( | |
| 10155 | - "Failed to execute 'forEach' on 'FormData': parameter 1 is " + | |
| 10156 | - "not of type 'Function'."); | |
| 10157 | - for (const [key, value] of this.entries()) | |
| 10158 | - callback.call(thisArg, value, key, this); | |
| 10159 | - } | |
| 10160 | - }; | |
| 10161 | -} | |
| 10162 | -// Node's Buffer lives in src/js/node_buffer.js, compiled | |
| 10163 | -// lazily (LAZY_GLOBALS / LAZY_MODULES) on first use. | |
| 10164 | -if (!globalThis.ErrorEvent) { | |
| 10165 | - globalThis.ErrorEvent = class ErrorEvent extends Event { | |
| 10166 | - constructor(type, init = {}) { | |
| 10167 | - super(type, init); | |
| 10168 | - this.message = String(init.message ?? ""); | |
| 10169 | - this.filename = String(init.filename ?? ""); | |
| 10170 | - this.lineno = Number(init.lineno ?? 0); | |
| 10171 | - this.colno = Number(init.colno ?? 0); | |
| 10172 | - this.error = init.error; | |
| 10173 | - } | |
| 10174 | - }; | |
| 10175 | -} | |
| 10176 | -// Web API globals a real bundle references at module scope but that the | |
| 10177 | -// prelude doesn't provide. Stub as empty classes (guarded so we never | |
| 10178 | -// clobber a real prelude implementation). Enough to LOAD; every name in | |
| 10179 | -// this first list has a real implementation elsewhere, so the empty class | |
| 10180 | -// only exists for the load-order window. | |
| 10181 | -for (const n of ["WebSocket", "EventTarget", "Event", "MessageEvent", | |
| 10182 | - "CloseEvent", "ErrorEvent", "SubtleCrypto", "TransformStream", | |
| 10183 | - "ReadableStream", "WritableStream", "ReadableStreamDefaultReader", | |
| 10184 | - "WritableStreamDefaultWriter", | |
| 10185 | - "ByteLengthQueuingStrategy", "CountQueuingStrategy", | |
| 10186 | - "TextEncoderStream", "TextDecoderStream"]) { | |
| 10187 | - if (!globalThis[n]) globalThis[n] = class {}; | |
| 10188 | -} | |
| 10189 | -// These have no implementation anywhere in celld. An empty class would | |
| 10190 | -// let `new BroadcastChannel(...)` hand back an inert object that fails | |
| 10191 | -// far from the cause; the compat contract is "reject at first use", so | |
| 10192 | -// the name loads but construction throws. (EventSource, MessageChannel, | |
| 10193 | -// and MessagePort are real; their scripts run after the harness.) | |
| 10194 | -for (const n of ["BroadcastChannel", "FileReader"]) { | |
| 10195 | - if (!globalThis[n]) globalThis[n] = class { | |
| 10196 | - constructor() { | |
| 10197 | - throw new Error(n + " is not implemented in celld"); | |
| 10198 | - } | |
| 10199 | - }; | |
| 10200 | -} | |
| 10201 | -globalThis.__sockets = new Map(); | |
| 10202 | -globalThis.WebSocket = class WebSocket extends EventTarget { | |
| 10203 | - // The spec names, which workerd exposes and real bundles use. celld only | |
| 10204 | - // had the READY_STATE_* aliases, which no other runtime defines. | |
| 10205 | - static CONNECTING = 0; | |
| 10206 | - static OPEN = 1; | |
| 10207 | - static CLOSING = 2; | |
| 10208 | - static CLOSED = 3; | |
| 10209 | - static READY_STATE_CONNECTING = 0; | |
| 10210 | - static READY_STATE_OPEN = 1; | |
| 10211 | - static READY_STATE_CLOSING = 2; | |
| 10212 | - static READY_STATE_CLOSED = 3; | |
| 10213 | - constructor(id, protocols = [], boundTarget = null) { | |
| 10214 | - super(); | |
| 10215 | - const dialed = typeof id === "string"; | |
| 10216 | - // A socket bound to a Durable Object's socket behaves like a dialed one | |
| 10217 | - // in every way that matters here: the host carries its frames, so every | |
| 10218 | - // operation goes out through `__ws_*` on this id rather than to a peer | |
| 10219 | - // in this heap. | |
| 10220 | - const outbound = dialed || boundTarget !== null; | |
| 10221 | - this._outbound = outbound; | |
| 10222 | - this._boundTarget = boundTarget; | |
| 10223 | - this._bound = false; | |
| 10224 | - this._pendingClose = null; | |
| 10225 | - this._id = outbound ? __ws_alloc() : Number(id); | |
| 10226 | - this._attachment = undefined; | |
| 10227 | - this._target = null; | |
| 10228 | - this._accepted = false; | |
| 10229 | - this._hibernatable = false; | |
| 10230 | - this._pending = []; | |
| 10231 | - // The other end of an in-isolate upgrade (a WebSocketPair served | |
| 10232 | - // over a same-script service binding); frames route to it | |
| 10233 | - // directly instead of through the host connection. | |
| 10234 | - this._loopback = null; | |
| 10235 | - this.readyState = outbound ? 0 : 1; | |
| 10236 | - this._binaryType = __cell.compat?.websocketStandardBinaryType | |
| 10237 | - ? "blob" | |
| 10238 | - : "arraybuffer"; | |
| 10239 | - // A server-side socket has no URL, and reports null rather than an empty | |
| 10240 | - // string -- workerd's inspect output pins this. A socket that came back | |
| 10241 | - // from an upgrade has none either: nothing in this isolate dialed it. | |
| 10242 | - this.url = dialed ? id : null; | |
| 10243 | - this.protocol = ""; | |
| 10244 | - this.extensions = ""; | |
| 10245 | - if (boundTarget !== null) { | |
| 10246 | - // The caller drives this socket itself, exactly as a Worker drives one | |
| 10247 | - // it opened. The host pipe is not built until `accept()`, so a | |
| 10248 | - // response passed straight back out is left alone. | |
| 10249 | - this._polled = true; | |
| 10250 | - this._target = boundTarget; | |
| 10251 | - } | |
| 10252 | - if (dialed) { | |
| 10253 | - // workerd validates the URL in the constructor and throws | |
| 10254 | - // synchronously; letting the connector reject later would surface a | |
| 10255 | - // scheme mistake as a network failure instead of a TypeError. | |
| 10256 | - let parsed; | |
| 10257 | - try { | |
| 10258 | - parsed = new URL(id); | |
| 10259 | - } catch { | |
| 10260 | - throw new DOMException( | |
| 10261 | - "WebSocket Constructor: The url is invalid.", | |
| 10262 | - "SyntaxError"); | |
| 10263 | - } | |
| 10264 | - if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") { | |
| 10265 | - throw new DOMException( | |
| 10266 | - "WebSocket Constructor: The url scheme must be ws or wss.", | |
| 10267 | - "SyntaxError"); | |
| 10268 | - } | |
| 10269 | - // A Durable Object socket is pushed events by the host so it can revive | |
| 10270 | - // a hibernated cell. A Worker socket has no cell: the isolate polls it, | |
| 10271 | - // and it lives and dies with the request, which is the lifetime | |
| 10272 | - // Cloudflare gives one too. | |
| 10273 | - const scope = __currentActorScope(); | |
| 10274 | - this._polled = !scope; | |
| 10275 | - const requested = typeof protocols === "string" | |
| 10276 | - ? [protocols] | |
| 10277 | - : Array.from(protocols, String); | |
| 10278 | - for (const value of requested) { | |
| 10279 | - // RFC 6455 subprotocols are HTTP tokens; a space or separator would | |
| 10280 | - // otherwise be smuggled into the Sec-WebSocket-Protocol header. | |
| 10281 | - if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) { | |
| 10282 | - throw new DOMException( | |
| 10283 | - `WebSocket Constructor: The subprotocol '${value}' is invalid.`, | |
| 10284 | - "SyntaxError"); | |
| 10285 | - } | |
| 10286 | - } | |
| 10287 | - if (new Set(requested).size !== requested.length) { | |
| 10288 | - throw new DOMException( | |
| 10289 | - "WebSocket Constructor: The subprotocols must be unique.", | |
| 10290 | - "SyntaxError"); | |
| 10291 | - } | |
| 10292 | - __sockets.set(this._id, this); | |
| 10293 | - const connection = __ws_connect(this._id, scope, id, JSON.stringify(requested)); | |
| 10294 | - __registerWaitUntil(connection); | |
| 10295 | - if (this._polled) this._startPump(); | |
| 10296 | - connection.then((protocol) => { | |
| 10297 | - if (this.readyState === WebSocket.READY_STATE_CLOSING) { | |
| 10298 | - if (this._pendingClose) { | |
| 10299 | - const [code, reason] = this._pendingClose; | |
| 10300 | - __ws_close(this._id, code, reason); | |
| 10301 | - } | |
| 10302 | - return; | |
| 10303 | - } | |
| 10304 | - if (this.readyState !== WebSocket.READY_STATE_CONNECTING) return; | |
| 10305 | - this.protocol = protocol; | |
| 10306 | - this.readyState = WebSocket.READY_STATE_OPEN; | |
| 10307 | - this.dispatchEvent(new Event("open")); | |
| 10308 | - }, (error) => { | |
| 10309 | - this.readyState = WebSocket.READY_STATE_CLOSED; | |
| 10310 | - __sockets.delete(this._id); | |
| 10311 | - this.dispatchEvent(new ErrorEvent("error", { message: String(error?.message || error), error })); | |
| 10312 | - this._dispatchClose(1006, "", false); | |
| 10313 | - }); | |
| 10314 | - } | |
| 10315 | - } | |
| 10316 | - // The pump ends only when the socket closes, so it must NOT be registered | |
| 10317 | - // as waitUntil work: that would hold the request open for as long as the | |
| 10318 | - // socket lives, and the host reclaims an abandoned socket only once the | |
| 10319 | - // request has retired. Its `__ws_next` ops are driven while the request | |
| 10320 | - // runs and normally resolve with the host's 1001 "request ended" close. | |
| 10321 | - // They resolve as 1006 only if the sender disappears without a close frame. | |
| 10322 | - _startPump() { | |
| 10323 | - if (this._pumping) return; | |
| 10324 | - this._pumping = true; | |
| 10325 | - this._pump().catch(() => {}); | |
| 10326 | - } | |
| 10327 | - // Drain the host queue for an isolate-polled socket. Each `__ws_next` is an | |
| 10328 | - // ordinary async op the request owns; a request that retires with the | |
| 10329 | - // socket still open closes it, which ends this loop with a close frame. | |
| 10330 | - async _pump() { | |
| 10331 | - for (;;) { | |
| 10332 | - const frame = await __ws_next(this._id); | |
| 10333 | - const tag = frame[0]; | |
| 10334 | - const body = frame.subarray(1); | |
| 10335 | - if (tag === 0) { | |
| 10336 | - this._dispatchMessage(new TextDecoder().decode(body)); | |
| 10337 | - } else if (tag === 1) { | |
| 10338 | - this._dispatchMessage( | |
| 10339 | - body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength), | |
| 10340 | - ); | |
| 10341 | - } else if (tag === 2) { | |
| 10342 | - if (this.readyState === WebSocket.READY_STATE_CONNECTING) { | |
| 10343 | - this.protocol = new TextDecoder().decode(body); | |
| 10344 | - this.readyState = WebSocket.READY_STATE_OPEN; | |
| 10345 | - this.dispatchEvent(new Event("open")); | |
| 10346 | - } | |
| 10347 | - } else { | |
| 10348 | - const info = JSON.parse(new TextDecoder().decode(body)); | |
| 10349 | - this._dispatchClose(info.code, info.reason, info.wasClean); | |
| 10350 | - return; | |
| 10351 | - } | |
| 10352 | - } | |
| 10353 | - } | |
| 10354 | - // Deliver whatever this end queued before it had somewhere to send. | |
| 10355 | - _flushToPeer() { | |
| 10356 | - const peer = this._loopback; | |
| 10357 | - if (!peer) return; | |
| 10358 | - for (const frame of this._pending.splice(0)) { | |
| 10359 | - if (frame[0] === "send") { | |
| 10360 | - queueMicrotask(() => peer._dispatchMessage(frame[1])); | |
| 10361 | - } else if (frame[0] === "send-binary") { | |
| 10362 | - const data = frame[1]; | |
| 10363 | - const bytes = data instanceof ArrayBuffer | |
| 10364 | - ? data | |
| 10365 | - : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); | |
| 10366 | - queueMicrotask(() => peer._dispatchMessage(bytes)); | |
| 10367 | - } else { | |
| 10368 | - queueMicrotask(() => peer._dispatchClose(frame[1], frame[2], true)); | |
| 10369 | - } | |
| 10370 | - } | |
| 10371 | - } | |
| 10372 | - get binaryType() { return this._binaryType; } | |
| 10373 | - // The spec ignores an unrecognised value rather than throwing. | |
| 10374 | - set binaryType(value) { | |
| 10375 | - if (value === "blob" || value === "arraybuffer") this._binaryType = value; | |
| 10376 | - } | |
| 10377 | - accept() { | |
| 10378 | - this._accepted = true; | |
| 10379 | - // A pair used directly, without being returned through a 101 response, | |
| 10380 | - // still has to carry frames once both ends are accepted. celld only | |
| 10381 | - // linked a pair on the upgrade path, so such a pair queued forever. | |
| 10382 | - if (this._peer && this._peer._accepted && !this._loopback) { | |
| 10383 | - this._loopback = this._peer; | |
| 10384 | - this._peer._loopback = this; | |
| 10385 | - this._flushToPeer(); | |
| 10386 | - this._peer._flushToPeer(); | |
| 10387 | - } | |
| 10388 | - // A socket obtained from a `fetch()` upgrade is already connected and | |
| 10389 | - // delivers nothing until it is accepted; this is where it starts. | |
| 10390 | - if (this._outbound && this.readyState === WebSocket.READY_STATE_CONNECTING) { | |
| 10391 | - // Bind before the pump: the op registers this socket's queue on this | |
| 10392 | - // thread, so the first `__ws_next` cannot run ahead of it. | |
| 10393 | - if (this._boundTarget !== null && !this._bound) { | |
| 10394 | - this._bound = true; | |
| 10395 | - __ws_bind_target( | |
| 10396 | - this._id, | |
| 10397 | - JSON.stringify(this._boundTarget), | |
| 10398 | - __currentActorScope(), | |
| 10399 | - ); | |
| 10400 | - } | |
| 10401 | - this.readyState = WebSocket.READY_STATE_OPEN; | |
| 10402 | - if (this._polled) this._startPump(); | |
| 10403 | - } | |
| 10404 | - } | |
| 10405 | - send(data) { | |
| 10406 | - if (this.readyState !== WebSocket.READY_STATE_OPEN) | |
| 10407 | - throw new DOMException("WebSocket is not open", "InvalidStateError"); | |
| 10408 | - const binary = data instanceof ArrayBuffer || ArrayBuffer.isView(data); | |
| 10409 | - const text = binary ? null : String(data); | |
| 10410 | - if (this._loopback) { | |
| 10411 | - const peer = this._loopback; | |
| 10412 | - const message = binary | |
| 10413 | - ? (data instanceof ArrayBuffer ? data.slice(0) : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)) | |
| 10414 | - : text; | |
| 10415 | - queueMicrotask(() => peer._dispatchMessage(message)); | |
| 10416 | - return; | |
| 10417 | - } | |
| 10418 | - // The pending queue belongs to an inbound pair socket that has been | |
| 10419 | - // accepted but not yet bound to a host transport. An outbound socket is | |
| 10420 | - // already bound -- queueing here would silently swallow its frames. | |
| 10421 | - if (!this._outbound && this._accepted && !this._target) { | |
| 10422 | - this._pending.push([binary ? "send-binary" : "send", binary ? data : text]); | |
| 10423 | - return; | |
| 10424 | - } | |
| 10425 | - if (binary) { | |
| 10426 | - const bytes = data instanceof ArrayBuffer | |
| 10427 | - ? new Uint8Array(data) | |
| 10428 | - : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); | |
| 10429 | - __ws_send_binary(this._id, bytes); | |
| 10430 | - } else { | |
| 10431 | - __ws_send(this._id, text); | |
| 10432 | - } | |
| 10433 | - } | |
| 10434 | - close(code = 1000, reason = "") { | |
| 10435 | - // WHATWG: an application may send 1000 or 3000-4999. Everything else is | |
| 10436 | - // reserved for the protocol itself. | |
| 10437 | - const wanted = Number(code); | |
| 10438 | - if (wanted !== 1000 && !(wanted >= 3000 && wanted <= 4999)) { | |
| 10439 | - throw new DOMException( | |
| 10440 | - `WebSocket close code ${code} is not permitted`, | |
| 10441 | - "InvalidAccessError"); | |
| 10442 | - } | |
| 10443 | - // RFC 6455 5.5: the close frame body is at most 125 bytes, two of which | |
| 10444 | - // are the code. Measured in UTF-8, so a multibyte reason can exceed the | |
| 10445 | - // cap at well under 123 characters. | |
| 10446 | - if (new TextEncoder().encode(String(reason)).length > 123) { | |
| 10447 | - throw new DOMException( | |
| 10448 | - "WebSocket close reason must not exceed 123 bytes", | |
| 10449 | - "SyntaxError"); | |
| 10450 | - } | |
| 10451 | - // Outbound sockets follow the WebSocket spec: closing a closed socket is a | |
| 10452 | - // no-op. Inbound sockets must NOT take that shortcut -- a Durable Object | |
| 10453 | - // answers a peer-initiated close from inside `webSocketClose`, by which | |
| 10454 | - // point `_dispatchClose` has already marked this side closed, and its | |
| 10455 | - // reply carries the reason the client is entitled to see. | |
| 10456 | - if (this._outbound && this.readyState === WebSocket.READY_STATE_CLOSED) { | |
| 10457 | - return; | |
| 10458 | - } | |
| 10459 | - const connecting = this.readyState === WebSocket.READY_STATE_CONNECTING; | |
| 10460 | - this.readyState = WebSocket.READY_STATE_CLOSING; | |
| 10461 | - if (this._outbound && connecting) { | |
| 10462 | - this._pendingClose = [code, reason]; | |
| 10463 | - return; | |
| 10464 | - } | |
| 10465 | - if (this._outbound) { | |
| 10466 | - __ws_close(this._id, code, reason); | |
| 10467 | - return; | |
| 10468 | - } | |
| 10469 | - this.readyState = 3; | |
| 10470 | - if (this._loopback) { | |
| 10471 | - const peer = this._loopback; | |
| 10472 | - queueMicrotask(() => peer._dispatchClose(code, reason, true)); | |
| 10473 | - return; | |
| 10474 | - } | |
| 10475 | - if (this._accepted && !this._target) { | |
| 10476 | - this._pending.push(["close", code, reason]); | |
| 10477 | - return; | |
| 10478 | - } | |
| 10479 | - __ws_close(this._id, code, reason); | |
| 10480 | - } | |
| 10481 | - _flushPending() { | |
| 10482 | - const pending = this._pending.splice(0); | |
| 10483 | - for (const frame of pending) { | |
| 10484 | - if (frame[0] === "send") __ws_send(this._id, frame[1]); | |
| 10485 | - else if (frame[0] === "send-binary") { | |
| 10486 | - const data = frame[1]; | |
| 10487 | - const bytes = data instanceof ArrayBuffer | |
| 10488 | - ? new Uint8Array(data) | |
| 10489 | - : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); | |
| 10490 | - __ws_send_binary(this._id, bytes); | |
| 10491 | - } | |
| 10492 | - else __ws_close(this._id, frame[1], frame[2]); | |
| 10493 | - } | |
| 10494 | - } | |
| 10495 | - serializeAttachment(value) { | |
| 10496 | - // Structured clone, not JSON: Cloudflare accepts anything cloneable | |
| 10497 | - // here, so a Date must come back a Date and a Map a Map. | |
| 10498 | - this._attachment = value; | |
| 10499 | - __ws_attachment_set(this._id, __sc_encode(value)); | |
| 10500 | - } | |
| 10501 | - deserializeAttachment() { return this._attachment; } | |
| 10502 | - _dispatchMessage(data) { | |
| 10503 | - if (this._binaryType === "blob" && data instanceof ArrayBuffer) { | |
| 10504 | - data = new Blob([data]); | |
| 10505 | - } | |
| 10506 | - const event = new MessageEvent("message", { data }); | |
| 10507 | - event._trust(); | |
| 10508 | - this.dispatchEvent(event); | |
| 10509 | - } | |
| 10510 | - _dispatchClose(code, reason, wasClean) { | |
| 10511 | - if (this.readyState === WebSocket.READY_STATE_CLOSED) return; | |
| 10512 | - this.readyState = WebSocket.READY_STATE_CLOSED; | |
| 10513 | - __sockets.delete(this._id); | |
| 10514 | - // An abnormal closure fires `error` before `close`. Code written against | |
| 10515 | - // the standard onerror never ran otherwise, which matters most for an | |
| 10516 | - // outbound socket: its peer is a remote server that can simply vanish. | |
| 10517 | - // An abnormal closure fires `error` before `close`. Code written against | |
| 10518 | - // the standard onerror never ran otherwise, which matters most for an | |
| 10519 | - // outbound socket: its peer is a remote server that can simply vanish. | |
| 10520 | - // An abnormal closure fires `error` before `close`. Code written against | |
| 10521 | - // the standard onerror never ran otherwise, which matters most for an | |
| 10522 | - // outbound socket: its peer is a remote server that can simply vanish. | |
| 10523 | - if (!wasClean) { | |
| 10524 | - this.dispatchEvent(new ErrorEvent("error", { | |
| 10525 | - message: reason | |
| 10526 | - ? `WebSocket closed abnormally: ${reason}` | |
| 10527 | - : "WebSocket closed abnormally", | |
| 10528 | - })); | |
| 10529 | - } | |
| 10530 | - const event = new CloseEvent("close", { code, reason, wasClean }); | |
| 10531 | - event._trust(); | |
| 10532 | - this.dispatchEvent(event); | |
| 10533 | - } | |
| 10534 | -}; | |
| 10535 | -globalThis.__makeSocket = (id) => new WebSocket(id); | |
| 10536 | -globalThis.__socketFromRow = (row) => { | |
| 10537 | - let ws = __sockets.get(Number(row.id)); | |
| 10538 | - if (!ws) { | |
| 10539 | - ws = __makeSocket(row.id); | |
| 10540 | - __sockets.set(Number(row.id), ws); | |
| 10541 | - } | |
| 10542 | - ws._tags = row.tags || []; | |
| 10543 | - ws._hibernatable = true; | |
| 10544 | - if (row.attachment != null) { | |
| 10545 | - try { | |
| 10546 | - ws._attachment = __sc_decode(new Uint8Array(row.attachment)); | |
| 10547 | - } catch { | |
| 10548 | - ws._attachment = undefined; | |
| 10549 | - } | |
| 10550 | - } | |
| 10551 | - return ws; | |
| 10552 | -}; | |
| 10553 | -// Workerd's api::WebSocketRequestResponsePair (websocket.h): an immutable | |
| 10554 | -// request/response pair for state.setWebSocketAutoResponse. | |
| 10555 | -globalThis.WebSocketRequestResponsePair = | |
| 10556 | - class WebSocketRequestResponsePair { | |
| 10557 | - #request; | |
| 10558 | - #response; | |
| 10559 | - constructor(request, response) { | |
| 10560 | - this.#request = String(request); | |
| 10561 | - this.#response = String(response); | |
| 10562 | - } | |
| 10563 | - get request() { return this.#request; } | |
| 10564 | - get response() { return this.#response; } | |
| 10565 | - }; | |
| 10566 | -globalThis.WebSocketPair = function WebSocketPair() { | |
| 10567 | - const id = __ws_alloc(); | |
| 10568 | - const client = __makeSocket(id); | |
| 10569 | - const server = __makeSocket(id); | |
| 10570 | - client._peer = server; | |
| 10571 | - server._peer = client; | |
| 10572 | - // Indexed AND iterable: `const [client, server] = new WebSocketPair()` is | |
| 10573 | - // the form most Cloudflare code uses. | |
| 10574 | - return { | |
| 10575 | - 0: client, | |
| 10576 | - 1: server, | |
| 10577 | - length: 2, | |
| 10578 | - [Symbol.iterator]() { | |
| 10579 | - return [client, server][Symbol.iterator](); | |
| 10580 | - }, | |
| 10581 | - }; | |
| 10582 | -}; | |
| 10583 | -// Cloudflare exposes the time of the last I/O, not a clock that advances | |
| 10584 | -// while JavaScript runs. Keep Date and performance on one turn timestamp so | |
| 10585 | -// neither becomes a timing side channel and the two APIs cannot disagree. | |
| 10586 | -const __NativeDate = Date; | |
| 10587 | -let __ioTimestamp = 0; | |
| 10588 | -const __CloudflareDate = function Date(...args) { | |
| 10589 | - if (new.target) { | |
| 10590 | - return Reflect.construct( | |
| 10591 | - __NativeDate, | |
| 10592 | - args.length === 0 ? [__ioTimestamp] : args, | |
| 10593 | - new.target, | |
| 10594 | - ); | |
| 10595 | - } | |
| 10596 | - return new __NativeDate(__ioTimestamp).toString(); | |
| 10597 | -}; | |
| 10598 | -Object.defineProperties(__CloudflareDate, { | |
| 10599 | - length: { value: 7 }, | |
| 10600 | - prototype: { value: __NativeDate.prototype }, | |
| 10601 | - now: { | |
| 10602 | - value: () => __ioTimestamp, | |
| 10603 | - writable: true, | |
| 10604 | - configurable: true, | |
| 10605 | - }, | |
| 10606 | - parse: { | |
| 10607 | - value: __NativeDate.parse, | |
| 10608 | - writable: true, | |
| 10609 | - configurable: true, | |
| 10610 | - }, | |
| 10611 | - UTC: { | |
| 10612 | - value: __NativeDate.UTC, | |
| 10613 | - writable: true, | |
| 10614 | - configurable: true, | |
| 10615 | - }, | |
| 10616 | -}); | |
| 10617 | -Object.defineProperty(__NativeDate.prototype, "constructor", { | |
| 10618 | - value: __CloudflareDate, | |
| 10619 | - writable: true, | |
| 10620 | - configurable: true, | |
| 10621 | -}); | |
| 10622 | -globalThis.Date = __CloudflareDate; | |
| 10623 | -globalThis.performance = { | |
| 10624 | - now: () => __ioTimestamp, | |
| 10625 | - timeOrigin: 0, | |
| 10626 | - mark() {}, | |
| 10627 | - measure() {}, | |
| 10628 | -}; | |
| 10629 | -Object.defineProperty(globalThis, "__advanceIoTime", { | |
| 10630 | - value(timestamp) { | |
| 10631 | - __ioTimestamp = timestamp; | |
| 10632 | - }, | |
| 10633 | -}); | |
| 10634 | -if (!globalThis.navigator) globalThis.navigator = { | |
| 10635 | - userAgent: "Cloudflare-Workers", hardwareConcurrency: 1, | |
| 10636 | - language: "en", languages: ["en"], | |
| 10637 | -}; | |
| 10638 | -if (!globalThis.queueMicrotask) | |
| 10639 | - globalThis.queueMicrotask = (f) => Promise.resolve().then(f); | |
| 10640 | -if (!globalThis.scheduler) | |
| 10641 | - globalThis.scheduler = { | |
| 10642 | - wait: (ms) => new Promise((resolve) => setTimeout(resolve, Number(ms) || 0)), | |
| 10643 | - }; | |
| 10644 | -if (!globalThis.structuredClone) { | |
| 10645 | - const structuredCloneRandom = $$randomValues; | |
| 10646 | - globalThis.structuredClone = (value, options) => { | |
| 10647 | - const transfer = options?.transfer === undefined | |
| 10648 | - ? [] : Array.from(options.transfer); | |
| 10649 | - const seen = new Set(); | |
| 10650 | - for (let index = 0; index < transfer.length; index++) { | |
| 10651 | - const item = transfer[index]; | |
| 10652 | - if (!(item instanceof ArrayBuffer)) | |
| 10653 | - throw new DOMException( | |
| 10654 | - `Value at index ${index} is not transferable`, "DataCloneError"); | |
| 10655 | - if (item.detached) | |
| 10656 | - throw new DOMException( | |
| 10657 | - `ArrayBuffer at index ${index} is already detached`, | |
| 10658 | - "DataCloneError"); | |
| 10659 | - if (seen.has(item)) | |
| 10660 | - throw new DOMException( | |
| 10661 | - `ArrayBuffer at index ${index} is a duplicate`, "DataCloneError"); | |
| 10662 | - seen.add(item); | |
| 10663 | - } | |
| 10664 | - | |
| 10665 | - // Blob, File, CryptoKey, and DOMException are JavaScript-backed in Cells, | |
| 10666 | - // so V8 does not see the native host objects that Deno registers with its | |
| 10667 | - // serializer. Replace only those objects before the V8 pass, then restore | |
| 10668 | - // them after it. A per-call random token prevents an application object | |
| 10669 | - // from being mistaken for a temporary record after deserialization. | |
| 10670 | - const hostMarker = "__celldStructuredCloneHost"; | |
| 10671 | - const hostTokenBytes = new Uint32Array(4); | |
| 10672 | - structuredCloneRandom(hostTokenBytes); | |
| 10673 | - const hostToken = Array.from(hostTokenBytes).join(":"); | |
| 10674 | - const projected = new Map(); | |
| 10675 | - const passesThroughV8 = (input) => | |
| 10676 | - input instanceof Date || input instanceof RegExp || | |
| 10677 | - input instanceof Error || input instanceof ArrayBuffer || | |
| 10678 | - input instanceof WebAssembly.Module || | |
| 10679 | - (typeof SharedArrayBuffer === "function" && | |
| 10680 | - input instanceof SharedArrayBuffer) || | |
| 10681 | - ArrayBuffer.isView(input); | |
| 10682 | - const project = (input) => { | |
| 10683 | - if (input === null || typeof input !== "object") return input; | |
| 10684 | - if (projected.has(input)) return projected.get(input); | |
| 10685 | - | |
| 10686 | - let record; | |
| 10687 | - if (typeof File === "function" && input instanceof File) { | |
| 10688 | - record = { [hostMarker]: hostToken, kind: "File" }; | |
| 10689 | - projected.set(input, record); | |
| 10690 | - record.bytes = input._bytes; | |
| 10691 | - record.type = input.type; | |
| 10692 | - record.name = input.name; | |
| 10693 | - record.lastModified = input.lastModified; | |
| 10694 | - return record; | |
| 10695 | - } | |
| 10696 | - if (typeof Blob === "function" && input instanceof Blob) { | |
| 10697 | - record = { [hostMarker]: hostToken, kind: "Blob" }; | |
| 10698 | - projected.set(input, record); | |
| 10699 | - record.bytes = input._bytes; | |
| 10700 | - record.type = input.type; | |
| 10701 | - return record; | |
| 10702 | - } | |
| 10703 | - if (typeof CryptoKey === "function" && input instanceof CryptoKey) { | |
| 10704 | - record = { [hostMarker]: hostToken, kind: "CryptoKey" }; | |
| 10705 | - projected.set(input, record); | |
| 10706 | - record.type = input.type; | |
| 10707 | - record.algorithm = input.algorithm; | |
| 10708 | - record.extractable = input.extractable; | |
| 10709 | - record.usages = input.usages; | |
| 10710 | - record.material = input.__celldMaterial; | |
| 10711 | - return record; | |
| 10712 | - } | |
| 10713 | - if (input instanceof DOMException) { | |
| 10714 | - record = { [hostMarker]: hostToken, kind: "DOMException" }; | |
| 10715 | - projected.set(input, record); | |
| 10716 | - record.message = input.message; | |
| 10717 | - record.name = input.name; | |
| 10718 | - return record; | |
| 10719 | - } | |
| 10720 | - // These types do not have the Web IDL Serializable marker. Reject them | |
| 10721 | - // instead of exposing their JavaScript implementation as a plain object. | |
| 10722 | - if ((typeof URL === "function" && input instanceof URL) || | |
| 10723 | - (typeof URLSearchParams === "function" && | |
| 10724 | - input instanceof URLSearchParams) || | |
| 10725 | - (typeof Headers === "function" && input instanceof Headers) || | |
| 10726 | - (typeof FormData === "function" && input instanceof FormData) || | |
| 10727 | - (typeof Request === "function" && input instanceof Request) || | |
| 10728 | - (typeof Response === "function" && input instanceof Response) || | |
| 10729 | - (typeof MessagePort === "function" && input instanceof MessagePort)) | |
| 10730 | - throw new DOMException( | |
| 10731 | - "Cannot clone object of unsupported type.", "DataCloneError"); | |
| 10732 | - if (Array.isArray(input)) { | |
| 10733 | - record = new Array(input.length); | |
| 10734 | - projected.set(input, record); | |
| 10735 | - for (const key of Object.keys(input)) record[key] = project(input[key]); | |
| 10736 | - return record; | |
| 10737 | - } | |
| 10738 | - if (input instanceof Map) { | |
| 10739 | - record = new Map(); | |
| 10740 | - projected.set(input, record); | |
| 10741 | - for (const [key, entry] of input) | |
| 10742 | - record.set(project(key), project(entry)); | |
| 10743 | - return record; | |
| 10744 | - } | |
| 10745 | - if (input instanceof Set) { | |
| 10746 | - record = new Set(); | |
| 10747 | - projected.set(input, record); | |
| 10748 | - for (const entry of input) record.add(project(entry)); | |
| 10749 | - return record; | |
| 10750 | - } | |
| 10751 | - if (passesThroughV8(input)) return input; | |
| 10752 | - | |
| 10753 | - record = {}; | |
| 10754 | - projected.set(input, record); | |
| 10755 | - for (const key of Object.keys(input)) record[key] = project(input[key]); | |
| 10756 | - return record; | |
| 10757 | - }; | |
| 10758 | - | |
| 10759 | - // Deno delegates the general graph to V8 and normalizes its clone error. | |
| 10760 | - // Cells already exposes the V8 value serializer for storage and RPC, so | |
| 10761 | - // one encode/decode preserves native internal slots, cycles, and shared | |
| 10762 | - // backing stores without a second JavaScript object walker. | |
| 10763 | - let result; | |
| 10764 | - try { | |
| 10765 | - result = __structured_clone(project(value)); | |
| 10766 | - } catch (error) { | |
| 10767 | - if (error instanceof TypeError) | |
| 10768 | - throw new DOMException(error.message, "DataCloneError"); | |
| 10769 | - throw error; | |
| 10770 | - } | |
| 10771 | - | |
| 10772 | - const revived = new Map(); | |
| 10773 | - const revive = (input) => { | |
| 10774 | - if (input === null || typeof input !== "object") return input; | |
| 10775 | - if (revived.has(input)) return revived.get(input); | |
| 10776 | - | |
| 10777 | - let output; | |
| 10778 | - switch (input[hostMarker] === hostToken ? input.kind : undefined) { | |
| 10779 | - case "Blob": | |
| 10780 | - output = new Blob([input.bytes], { type: input.type }); | |
| 10781 | - revived.set(input, output); | |
| 10782 | - return output; | |
| 10783 | - case "File": | |
| 10784 | - output = new File([input.bytes], input.name, { | |
| 10785 | - type: input.type, lastModified: input.lastModified, | |
| 10786 | - }); | |
| 10787 | - revived.set(input, output); | |
| 10788 | - return output; | |
| 10789 | - case "CryptoKey": | |
| 10790 | - output = new CryptoKey( | |
| 10791 | - input.type, input.algorithm, input.extractable, | |
| 10792 | - input.usages, input.material); | |
| 10793 | - revived.set(input, output); | |
| 10794 | - return output; | |
| 10795 | - case "DOMException": | |
| 10796 | - output = new DOMException(input.message, input.name); | |
| 10797 | - revived.set(input, output); | |
| 10798 | - return output; | |
| 10799 | - } | |
| 10800 | - revived.set(input, input); | |
| 10801 | - if (Array.isArray(input)) { | |
| 10802 | - for (const key of Object.keys(input)) input[key] = revive(input[key]); | |
| 10803 | - } else if (input instanceof Map) { | |
| 10804 | - const entries = Array.from(input); | |
| 10805 | - input.clear(); | |
| 10806 | - for (const [key, entry] of entries) | |
| 10807 | - input.set(revive(key), revive(entry)); | |
| 10808 | - } else if (input instanceof Set) { | |
| 10809 | - const entries = Array.from(input); | |
| 10810 | - input.clear(); | |
| 10811 | - for (const entry of entries) input.add(revive(entry)); | |
| 10812 | - } else if (!passesThroughV8(input)) { | |
| 10813 | - for (const key of Object.keys(input)) input[key] = revive(input[key]); | |
| 10814 | - } | |
| 10815 | - return input; | |
| 10816 | - }; | |
| 10817 | - result = revive(result); | |
| 10818 | - // Validate the complete list and clone the value before detaching any | |
| 10819 | - // source. A later invalid entry therefore cannot leave an earlier buffer | |
| 10820 | - // detached after the operation fails. | |
| 10821 | - for (const item of transfer) item.transfer(); | |
| 10822 | - return result; | |
| 10823 | - }; | |
| 10824 | -} | |
| 10825 | -// Web Crypto is installed after the rest of the harness so it can use | |
| 10826 | -// DOMException, structuredClone, and Buffer. | |
| 10827 | -// `Buffer` is read at call time, which materializes the lazy global. | |
| 10828 | -const __zlibSync = (mode, data) => | |
| 10829 | - Buffer.from(__zlib(mode, Buffer.from(data))); | |
| 10830 | -globalThis.__zlibModule = { | |
| 10831 | - constants: { | |
| 10832 | - Z_NO_FLUSH: 0, | |
| 10833 | - Z_PARTIAL_FLUSH: 1, | |
| 10834 | - Z_SYNC_FLUSH: 2, | |
| 10835 | - Z_FULL_FLUSH: 3, | |
| 10836 | - Z_FINISH: 4, | |
| 10837 | - Z_BLOCK: 5, | |
| 10838 | - }, | |
| 10839 | - gzipSync: (data, _options) => __zlibSync("gzip", data), | |
| 10840 | - gunzipSync: (data, _options) => __zlibSync("gunzip", data), | |
| 10841 | - deflateSync: (data, _options) => __zlibSync("deflate", data), | |
| 10842 | - inflateSync: (data, _options) => __zlibSync("inflate", data), | |
| 10843 | - deflateRawSync: (data, _options) => __zlibSync("deflateRaw", data), | |
| 10844 | - inflateRawSync: (data, _options) => __zlibSync("inflateRaw", data), | |
| 10845 | -}; | |
| 10846 | -if (!globalThis.process) globalThis.process = { | |
| 10847 | - env: {}, platform: "linux", arch: "x64", version: "v20.0.0", | |
| 10848 | - versions: { node: "20.0.0" }, argv: [], cwd: () => "/", | |
| 10849 | - stdin: { fd: 0, isTTY: false }, | |
| 10850 | - stdout: { fd: 1, isTTY: false, write: (s) => { __log(String(s)); return true; } }, | |
| 10851 | - stderr: { fd: 2, isTTY: false, write: (s) => { __log(String(s)); return true; } }, | |
| 10852 | - nextTick: (f, ...a) => queueMicrotask(() => f(...a)), | |
| 10853 | - on() {}, once() {}, off() {}, emit() {}, hrtime: () => [0, 0], | |
| 10854 | -}; | |
| 10855 | -globalThis.process.exit = (code = 0) => { | |
| 10856 | - const actorScope = __currentActorScope(); | |
| 10857 | - if (actorScope) { | |
| 10858 | - const instance = __cell.instances[actorScope]; | |
| 10859 | - if (instance?.__celldState) | |
| 10860 | - instance.__celldState._resetAfterConcurrencyFailure(); | |
| 10861 | - } | |
| 10862 | - __process_exit(Number(code) || 0, actorScope); | |
| 10863 | -}; | |
| 10864 | -globalThis.process.getBuiltinModule = | |
| 10865 | - (id) => __builtin_module(String(id)); | |
| 10866 | -if (!globalThis.global) globalThis.global = globalThis; | |
| 10867 | -// Events belong to the request, and the host owns the request. `__event_*` | |
| 10868 | -// and `__wait_until` operate on whichever context the host has made current | |
| 10869 | -// for this turn, so nothing here has to know which request is running — and | |
| 10870 | -// two requests sharing an isolate cannot pop each other's events. | |
| 10871 | -globalThis.__registerWaitUntil = (promise) => { | |
| 10872 | - const tracked = Promise.resolve(promise).catch((error) => { | |
| 10873 | - console.error("waitUntil rejected", error); | |
| 10874 | - }); | |
| 10875 | - __wait_until(tracked); | |
| 10876 | -}; | |
| 10877 | -// `props` are the per-stub props a loopback service stub carries | |
| 10878 | -// (ctx.props); `exports` is built once, on first access. | |
| 10879 | -const __defaultProps = {}; | |
| 10880 | -const __entrypointContext = (props = __defaultProps) => ({ | |
| 10881 | - waitUntil: globalThis.__registerWaitUntil, | |
| 10882 | - passThroughOnException() {}, | |
| 10883 | - abort: __ctxAbortCurrent, | |
| 10884 | - props, | |
| 10885 | - get exports() { return __ctxExports(); }, | |
| 10886 | -}); | |
| 10887 | -globalThis.__beginEvent = (props = __defaultProps) => { | |
| 10888 | - __event_begin(); | |
| 10889 | - return __entrypointContext(props); | |
| 10890 | -}; | |
| 10891 | -globalThis.__endEvent = () => __event_end(); | |
| 10892 | -// Workerd's writable filesystem is memory-backed and request-scoped. The | |
| 10893 | -// native IoContext owns the directory tree; this facade supplies Node's path, | |
| 10894 | -// error, Promise, and Stats shapes without exposing a host filesystem. | |
| 10895 | -const __fsPath = (value) => { | |
| 10896 | - if (value instanceof URL) { | |
| 10897 | - if (value.protocol !== "file:") { | |
| 10898 | - const error = new TypeError('The URL must be of scheme file'); | |
| 10899 | - error.code = "ERR_INVALID_URL_SCHEME"; | |
| 10900 | - throw error; | |
| 10901 | - } | |
| 10902 | - value = decodeURIComponent(value.pathname); | |
| 10903 | - } else if (globalThis.Buffer?.isBuffer(value)) { | |
| 10904 | - value = value.toString(); | |
| 10905 | - } else if (typeof value !== "string") { | |
| 10906 | - const error = new TypeError( | |
| 10907 | - 'The "path" argument must be of type string or an instance of Buffer or URL', | |
| 10908 | - ); | |
| 10909 | - error.code = "ERR_INVALID_ARG_TYPE"; | |
| 10910 | - throw error; | |
| 10911 | - } | |
| 10912 | - if (value.includes("\0")) { | |
| 10913 | - const error = new TypeError('The argument "path" must not contain null bytes'); | |
| 10914 | - error.code = "ERR_INVALID_ARG_VALUE"; | |
| 10915 | - throw error; | |
| 10916 | - } | |
| 10917 | - const absolute = value.startsWith("/") ? value : process.cwd() + "/" + value; | |
| 10918 | - const parts = []; | |
| 10919 | - for (const part of absolute.split("/")) { | |
| 10920 | - if (!part || part === ".") continue; | |
| 10921 | - if (part === "..") parts.pop(); | |
| 10922 | - else parts.push(part); | |
| 10923 | - } | |
| 10924 | - return "/" + parts.join("/"); | |
| 10925 | -}; | |
| 10926 | -const __fsError = (code, syscall, path) => { | |
| 10927 | - const e = new Error(`${code}: ${syscall} '${path}'`); | |
| 10928 | - e.errno = { EPERM: -1, ENOENT: -2, EEXIST: -17, ENOTDIR: -20 }[code]; | |
| 10929 | - e.code = code; | |
| 10930 | - e.syscall = syscall; | |
| 10931 | - e.path = path; | |
| 10932 | - return e; | |
| 10933 | -}; | |
| 10934 | -const __enoent = (path = "") => { throw __fsError("ENOENT", "open", path); }; | |
| 10935 | -const __fsStatsBadge = Symbol("fs.Stats"); | |
| 10936 | -class __FsStats { | |
| 10937 | - constructor(badge, kind, size, bigint) { | |
| 10938 | - if (badge !== __fsStatsBadge) throw new TypeError("Illegal constructor"); | |
| 10939 | - const file = kind === 3; | |
| 10940 | - this.dev = 0; | |
| 10941 | - this.ino = 0; | |
| 10942 | - // A bundle file is 0o100444 and a writable temporary directory is 0o40666, | |
| 10943 | - // matching the mode values workerd's fs-stat-test.js asserts. | |
| 10944 | - this.mode = (file ? 0o100000 : 0o40000) | 0o444 | (kind === 2 ? 0o222 : 0); | |
| 10945 | - this.nlink = 1; | |
| 10946 | - this.uid = 0; | |
| 10947 | - this.gid = 0; | |
| 10948 | - this.rdev = 0; | |
| 10949 | - this.size = size; | |
| 10950 | - this.blksize = 0; | |
| 10951 | - this.blocks = 0; | |
| 10952 | - this.atimeMs = this.mtimeMs = this.ctimeMs = this.birthtimeMs = 0; | |
| 10953 | - this.atime = new Date(0); | |
| 10954 | - this.mtime = new Date(0); | |
| 10955 | - this.ctime = new Date(0); | |
| 10956 | - this.birthtime = new Date(0); | |
| 10957 | - Object.defineProperty(this, "__kind", { value: file ? "file" : "directory" }); | |
| 10958 | - if (bigint) { | |
| 10959 | - for (const name of [ | |
| 10960 | - "dev", "ino", "mode", "nlink", "uid", "gid", "rdev", "size", | |
| 10961 | - "blksize", "blocks", "atimeMs", "mtimeMs", "ctimeMs", "birthtimeMs", | |
| 10962 | - ]) this[name] = BigInt(this[name]); | |
| 10963 | - this.atimeNs = 0n; | |
| 10964 | - this.mtimeNs = 0n; | |
| 10965 | - this.ctimeNs = 0n; | |
| 10966 | - this.birthtimeNs = 0n; | |
| 10967 | - } | |
| 10968 | - } | |
| 10969 | - isFile() { return this.__kind === "file"; } | |
| 10970 | - isDirectory() { return this.__kind === "directory"; } | |
| 10971 | - isBlockDevice() { return false; } | |
| 10972 | - isCharacterDevice() { return false; } | |
| 10973 | - isSymbolicLink() { return false; } | |
| 10974 | - isFIFO() { return false; } | |
| 10975 | - isSocket() { return false; } | |
| 10976 | -} | |
| 10977 | -const __fsOptions = (options, names) => { | |
| 10978 | - if (options === undefined) return {}; | |
| 10979 | - if (options === null || typeof options !== "object") { | |
| 10980 | - const error = new TypeError('The "options" argument must be of type object'); | |
| 10981 | - error.code = "ERR_INVALID_ARG_TYPE"; | |
| 10982 | - throw error; | |
| 10983 | - } | |
| 10984 | - for (const name of names) { | |
| 10985 | - if (options[name] !== undefined && typeof options[name] !== "boolean") { | |
| 10986 | - const error = new TypeError(`The "options.${name}" property must be of type boolean`); | |
| 10987 | - error.code = "ERR_INVALID_ARG_TYPE"; | |
| 10988 | - throw error; | |
| 10989 | - } | |
| 10990 | - } | |
| 10991 | - return options; | |
| 10992 | -}; | |
| 10993 | -const __fsMkdirSync = (value, options = {}) => { | |
| 10994 | - const path = __fsPath(value); | |
| 10995 | - if (typeof options === "number") options = { mode: options }; | |
| 10996 | - options = __fsOptions(options, ["recursive"]); | |
| 10997 | - const result = __vfs_mkdir(path, options.recursive === true); | |
| 10998 | - if (result && !result.startsWith("/")) throw __fsError(result, "mkdir", path); | |
| 10999 | - return result || undefined; | |
| 11000 | -}; | |
| 11001 | -const __fsStatSync = (value, options, syscall = "stat") => { | |
| 11002 | - const path = __fsPath(value); | |
| 11003 | - options = __fsOptions(options, ["bigint", "throwIfNoEntry"]); | |
| 11004 | - const [kind, size] = __vfs_stat(path); | |
| 11005 | - if (!kind) { | |
| 11006 | - if (options.throwIfNoEntry === false) return undefined; | |
| 11007 | - throw __fsError("ENOENT", syscall, path); | |
| 11008 | - } | |
| 11009 | - return new __FsStats(__fsStatsBadge, kind, size, options.bigint === true); | |
| 11010 | -}; | |
| 11011 | -const __fsLstatSync = (value, options) => __fsStatSync(value, options, "lstat"); | |
| 11012 | -const __fsRealpathSync = (value) => { | |
| 11013 | - const path = __fsPath(value); | |
| 11014 | - if (!__vfs_stat(path)[0]) throw __fsError("ENOENT", "realpath", path); | |
| 11015 | - return path; | |
| 11016 | -}; | |
| 11017 | -const __fsExistsSync = (value) => { | |
| 11018 | - try { return __vfs_stat(__fsPath(value))[0] !== 0; } | |
| 11019 | - catch { return false; } | |
| 11020 | -}; | |
| 11021 | -// Node returns a Buffer unless an encoding is given, as a string or as | |
| 11022 | -// `options.encoding`. Only `utf8` is decoded here; any other encoding falls | |
| 11023 | -// through to Buffer's own decoder. | |
| 11024 | -const __fsReadFileSync = (value, options) => { | |
| 11025 | - const path = __fsPath(value); | |
| 11026 | - const encoding = typeof options === "string" ? options : options?.encoding; | |
| 11027 | - const bytes = __vfs_read_file(path); | |
| 11028 | - if (bytes === undefined) { | |
| 11029 | - // A directory read fails differently from a missing path, so the stat | |
| 11030 | - // decides which error the caller sees. | |
| 11031 | - if (__vfs_stat(path)[0]) throw __fsError("EISDIR", "read", path); | |
| 11032 | - throw __fsError("ENOENT", "open", path); | |
| 11033 | - } | |
| 11034 | - const buffer = Buffer.from(bytes); | |
| 11035 | - return encoding ? buffer.toString(encoding) : buffer; | |
| 11036 | -}; | |
| 11037 | -// `fs.constants`, with the four access modes from workerd's | |
| 11038 | -// `src/node/internal/internal_fs_constants.ts`. The table carries only the | |
| 11039 | -// modes `access` reads. Every other constant belongs to an operation the | |
| 11040 | -// virtual filesystem does not implement, and that operation already fails | |
| 11041 | -// loudly at the unimplemented-builtin stub, so publishing its constants would | |
| 11042 | -// only make a caller build a mode for a call it cannot make. | |
| 11043 | -const __fsConstants = Object.freeze({ F_OK: 0, X_OK: 1, W_OK: 2, R_OK: 4 }); | |
| 11044 | -// Node validates a mode before it reaches the filesystem, so a bad mode is an | |
| 11045 | -// argument error and never a filesystem error. The range is the union of the | |
| 11046 | -// four access modes, which is what workerd's `validateMode` allows. | |
| 11047 | -const __fsMode = (mode) => { | |
| 11048 | - if (mode === undefined) return __fsConstants.F_OK; | |
| 11049 | - if (typeof mode !== "number") { | |
| 11050 | - const error = new TypeError('The "mode" argument must be of type number'); | |
| 11051 | - error.code = "ERR_INVALID_ARG_TYPE"; | |
| 11052 | - throw error; | |
| 11053 | - } | |
| 11054 | - if (!Number.isInteger(mode) || mode < 0 || mode > 7) { | |
| 11055 | - const error = new RangeError( | |
| 11056 | - `The value of "mode" is out of range. It must be >= 0 && <= 7. Received ${mode}`, | |
| 11057 | - ); | |
| 11058 | - error.code = "ERR_OUT_OF_RANGE"; | |
| 11059 | - throw error; | |
| 11060 | - } | |
| 11061 | - return mode; | |
| 11062 | -}; | |
| 11063 | -// `access` reports what the virtual filesystem can do and not a POSIX | |
| 11064 | -// permission, so it follows workerd's `accessSyncImpl`: no file is executable, | |
| 11065 | -// therefore `X_OK` always fails, and an unwritable path fails exactly like a | |
| 11066 | -// missing one, so a caller cannot tell the two apart. Kind 2 is the writable | |
| 11067 | -// tree; see `op_vfs_stat`. | |
| 11068 | -const __fsAccessSync = (value, mode) => { | |
| 11069 | - const path = __fsPath(value); | |
| 11070 | - mode = __fsMode(mode); | |
| 11071 | - const [kind] = __vfs_stat(path); | |
| 11072 | - const denied = mode & __fsConstants.X_OK | |
| 11073 | - || !kind | |
| 11074 | - || (mode & __fsConstants.W_OK && kind !== 2); | |
| 11075 | - if (denied) throw __fsError("ENOENT", "access", path); | |
| 11076 | -}; | |
| 11077 | -// The callback forms run the same synchronous core as `fs.promises`. | |
| 11078 | -// Validation and the operation are separate arguments, not one function, | |
| 11079 | -// because they fail differently: an argument error throws, and only a | |
| 11080 | -// filesystem error reaches the callback. One combined body would route both to | |
| 11081 | -// the callback and hide a caller's bug behind an error it did not expect. | |
| 11082 | -// | |
| 11083 | -// `validate()` runs before the callback check, which is workerd's order: each | |
| 11084 | -// entry point in `internal_fs_callback.ts` validates its path and its options, | |
| 11085 | -// and only then calls `callWithSingleArgCallback`. Node checks the callback | |
| 11086 | -// first, so a call that has a bad path and no callback reports the path here | |
| 11087 | -// and reports the callback in Node. Both are `ERR_INVALID_ARG_TYPE`, and the | |
| 11088 | -// runtime follows workerd. | |
| 11089 | -const __fsDeliver = (validate, run, callback, deliver) => { | |
| 11090 | - validate(); | |
| 11091 | - if (typeof callback !== "function") { | |
| 11092 | - const error = new TypeError('The "cb" argument must be of type function'); | |
| 11093 | - error.code = "ERR_INVALID_ARG_TYPE"; | |
| 11094 | - throw error; | |
| 11095 | - } | |
| 11096 | - let result; | |
| 11097 | - try { | |
| 11098 | - result = run(); | |
| 11099 | - } catch (error) { | |
| 11100 | - // A callback delivered in this turn would let a caller observe the result | |
| 11101 | - // before its own call returned, which Node never does. | |
| 11102 | - queueMicrotask(() => callback(error)); | |
| 11103 | - return; | |
| 11104 | - } | |
| 11105 | - queueMicrotask(() => deliver(result)); | |
| 11106 | -}; | |
| 11107 | -// An operation with a result calls back with `(error, result)`, and one | |
| 11108 | -// without calls back with `(error)` alone. Workerd splits the two the same way | |
| 11109 | -// (`callWithSingleArgCallback` and `callWithErrorOnlyCallback`), because a | |
| 11110 | -// caller can read `arguments.length` and see the difference. | |
| 11111 | -const __fsCallback = (validate, run, callback) => | |
| 11112 | - __fsDeliver(validate, run, callback, (result) => callback(null, result)); | |
| 11113 | -const __fsErrorOnlyCallback = (validate, run, callback) => | |
| 11114 | - __fsDeliver(validate, run, callback, () => callback(null)); | |
| 11115 | -// Node accepts `(path, callback)` or `(path, options, callback)` everywhere. | |
| 11116 | -const __fsCallbackArgs = (options, callback) => | |
| 11117 | - typeof options === "function" ? [undefined, options] : [options, callback]; | |
| 11118 | -const __fsAccess = (value, mode, callback) => { | |
| 11119 | - [mode, callback] = __fsCallbackArgs(mode, callback); | |
| 11120 | - __fsErrorOnlyCallback( | |
| 11121 | - () => { __fsPath(value); __fsMode(mode); }, | |
| 11122 | - () => __fsAccessSync(value, mode), | |
| 11123 | - callback, | |
| 11124 | - ); | |
| 11125 | -}; | |
| 11126 | -const __fsStat = (value, options, callback) => { | |
| 11127 | - [options, callback] = __fsCallbackArgs(options, callback); | |
| 11128 | - __fsCallback( | |
| 11129 | - () => { __fsPath(value); __fsOptions(options, ["bigint", "throwIfNoEntry"]); }, | |
| 11130 | - () => __fsStatSync(value, options), | |
| 11131 | - callback, | |
| 11132 | - ); | |
| 11133 | -}; | |
| 11134 | -const __fsLstat = (value, options, callback) => { | |
| 11135 | - [options, callback] = __fsCallbackArgs(options, callback); | |
| 11136 | - __fsCallback( | |
| 11137 | - () => { __fsPath(value); __fsOptions(options, ["bigint", "throwIfNoEntry"]); }, | |
| 11138 | - () => __fsLstatSync(value, options), | |
| 11139 | - callback, | |
| 11140 | - ); | |
| 11141 | -}; | |
| 11142 | -const __fsRealpath = (value, options, callback) => { | |
| 11143 | - [options, callback] = __fsCallbackArgs(options, callback); | |
| 11144 | - __fsCallback( | |
| 11145 | - () => __fsPath(value), | |
| 11146 | - () => __fsRealpathSync(value), | |
| 11147 | - callback, | |
| 11148 | - ); | |
| 11149 | -}; | |
| 11150 | -const __fsReadFile = (value, options, callback) => { | |
| 11151 | - [options, callback] = __fsCallbackArgs(options, callback); | |
| 11152 | - __fsCallback( | |
| 11153 | - () => __fsPath(value), | |
| 11154 | - () => __fsReadFileSync(value, options), | |
| 11155 | - callback, | |
| 11156 | - ); | |
| 11157 | -}; | |
| 11158 | -const __fsMkdir = (value, options, callback) => { | |
| 11159 | - [options, callback] = __fsCallbackArgs(options, callback); | |
| 11160 | - __fsCallback( | |
| 11161 | - () => { | |
| 11162 | - __fsPath(value); | |
| 11163 | - // A number is the mode, which `mkdirSync` validates but does not apply. | |
| 11164 | - if (typeof options !== "number") __fsOptions(options, ["recursive"]); | |
| 11165 | - }, | |
| 11166 | - () => __fsMkdirSync(value, options), | |
| 11167 | - callback, | |
| 11168 | - ); | |
| 11169 | -}; | |
| 11170 | -globalThis.__fsPromises = { | |
| 11171 | - // The promise form validates inside the promise, so an argument error | |
| 11172 | - // rejects instead of throwing. Workerd makes the same split, because a | |
| 11173 | - // caller of a promise API has no synchronous frame to catch. | |
| 11174 | - async access(...args) { return __fsAccessSync(...args); }, | |
| 11175 | - async mkdir(...args) { return __fsMkdirSync(...args); }, | |
| 11176 | - async stat(...args) { return __fsStatSync(...args); }, | |
| 11177 | - async lstat(...args) { return __fsLstatSync(...args); }, | |
| 11178 | - async realpath(...args) { return __fsRealpathSync(...args); }, | |
| 11179 | - async readFile(...args) { return __fsReadFileSync(...args); }, | |
| 11180 | -}; | |
| 11181 | -const __fsSurface = { | |
| 11182 | - Stats: __FsStats, | |
| 11183 | - constants: __fsConstants, | |
| 11184 | - promises: globalThis.__fsPromises, | |
| 11185 | - accessSync: __fsAccessSync, | |
| 11186 | - access: __fsAccess, | |
| 11187 | - existsSync: __fsExistsSync, | |
| 11188 | - mkdirSync: __fsMkdirSync, | |
| 11189 | - statSync: __fsStatSync, | |
| 11190 | - lstatSync: __fsLstatSync, | |
| 11191 | - realpathSync: __fsRealpathSync, | |
| 11192 | - readFileSync: __fsReadFileSync, | |
| 11193 | - stat: __fsStat, | |
| 11194 | - lstat: __fsLstat, | |
| 11195 | - realpath: __fsRealpath, | |
| 11196 | - readFile: __fsReadFile, | |
| 11197 | - mkdir: __fsMkdir, | |
| 11198 | -}; | |
| 11199 | -globalThis.__fs = new Proxy(__fsSurface, { get: (target, p) => { | |
| 11200 | - if (Reflect.has(target, p)) return Reflect.get(target, p); | |
| 11201 | - if (["readdirSync", "readlinkSync"].includes(p)) return __enoent; | |
| 11202 | - // Writable file contents and every mutation remain explicit unsupported | |
| 11203 | - // surfaces until a failing application seam requires them. | |
| 11204 | - if (typeof p !== "string") return undefined; | |
| 11205 | - return globalThis.__nodeStubFor("node:fs." + p); | |
| 11206 | -}}); | |
| 11207 | -const __bridgeResponseStream = (body, requestControllers) => { | |
| 11208 | - const streamId = __response_stream_create(); | |
| 11209 | - const pump = (async () => { | |
| 11210 | - const reader = body.getReader(); | |
| 11211 | - const consumerClosed = __response_stream_closed(streamId) | |
| 11212 | - .then((status) => status === "cancelled" | |
| 11213 | - ? { consumerClosed: true } | |
| 11214 | - : new Promise(() => {})); | |
| 11215 | - const cancelProducer = async () => { | |
| 11216 | - const reason = new Error("The client has disconnected"); | |
| 11217 | - for (const controller of requestControllers || []) { | |
| 11218 | - if (!controller.signal.aborted) controller.abort(reason); | |
| 11219 | - } | |
| 11220 | - try { | |
| 11221 | - await reader.cancel(reason); | |
| 11222 | - } catch {} | |
| 11223 | - await __response_stream_close(streamId, ""); | |
| 11224 | - }; | |
| 11225 | - try { | |
| 11226 | - for (;;) { | |
| 11227 | - const result = await Promise.race([ | |
| 11228 | - reader.read().then((read) => ({ read })), | |
| 11229 | - consumerClosed, | |
| 11230 | - ]); | |
| 11231 | - if (result.consumerClosed) { | |
| 11232 | - await cancelProducer(); | |
| 11233 | - return; | |
| 11234 | - } | |
| 11235 | - if (result.read.done) { | |
| 11236 | - await __response_stream_close(streamId, ""); | |
| 11237 | - return; | |
| 11238 | - } | |
| 11239 | - const bytes = __bodyBytes(result.read.value); | |
| 11240 | - for (let offset = 0; offset < bytes.byteLength; offset += 64 * 1024) { | |
| 11241 | - await __response_stream_write( | |
| 11242 | - streamId, | |
| 11243 | - bytes.subarray(offset, offset + 64 * 1024), | |
| 11244 | - ); | |
| 11245 | - } | |
| 11246 | - } | |
| 11247 | - } catch (error) { | |
| 11248 | - if (String(error).includes("response stream consumer canceled")) { | |
| 11249 | - await cancelProducer(); | |
| 11250 | - return; | |
| 11251 | - } | |
| 11252 | - await __response_stream_close(streamId, String(error)); | |
| 11253 | - } | |
| 11254 | - })(); | |
| 11255 | - globalThis.__registerWaitUntil(pump); | |
| 11256 | - return streamId; | |
| 11257 | -}; | |
| 11258 | -globalThis.__readResponse = (r) => { | |
| 93 | +// for object bodies that are not streams or Blobs -- an object with | |
| 94 | +// a custom toString/@@toPrimitive stringifies instead, unless it is | |
| 95 | +// an array or async-iterable (Workerd's precedence). Returns null | |
| 96 | +// for the string-coercion path. | |
| 97 | +function __iterableBody(body) { | |
| 98 | + if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) | |
| 99 | + return null; | |
| 100 | + const asyncIter = body[Symbol.asyncIterator]; | |
| 101 | + if (typeof asyncIter === "function") { | |
| 102 | + const iterator = asyncIter.call(body); | |
| 103 | + return new ReadableStream({ | |
| 104 | + async pull(controller) { | |
| 105 | + const result = await iterator.next(); | |
| 106 | + if (result.done) { controller.close(); return; } | |
| 107 | + controller.enqueue(__chunkBytes(result.value)); | |
| 108 | + }, | |
| 109 | + cancel(reason) { | |
| 110 | + if (typeof iterator.return === "function") | |
| 111 | + iterator.return(reason); | |
| 112 | + }, | |
| 113 | + }, { highWaterMark: 0 }); | |
| 114 | + } | |
| 115 | + if (!Array.isArray(body) && | |
| 116 | + (body.toString !== Object.prototype.toString || | |
| 117 | + body[Symbol.toPrimitive] !== undefined)) | |
| 118 | + return null; | |
| 119 | + if (typeof body[Symbol.iterator] !== "function") return null; | |
| 120 | + const chunks = []; | |
| 121 | + let length = 0; | |
| 122 | + for (const chunk of body) { | |
| 123 | + if (!(chunk instanceof ArrayBuffer) && !ArrayBuffer.isView(chunk)) | |
| 124 | + return null; | |
| 125 | + const view = __chunkBytes(chunk); | |
| 126 | + chunks.push(view); | |
| 127 | + length += view.byteLength; | |
| 128 | + } | |
| 129 | + const bytes = new Uint8Array(length); | |
| 130 | + let offset = 0; | |
| 131 | + for (const view of chunks) { | |
| 132 | + bytes.set(view, offset); | |
| 133 | + offset += view.byteLength; | |
| 134 | + } | |
| 135 | + return bytes; | |
| 136 | +} | |
| 137 | +// Drain a Request/Response body stream, caching the result on the | |
| 138 | +// instance so later consumers see the materialized bytes. | |
| 139 | +async function __drainBody(target) { | |
| 140 | + const chunks = []; | |
| 141 | + let length = 0; | |
| 142 | + const reader = target.body.getReader(); | |
| 143 | + for (;;) { | |
| 144 | + const result = await reader.read(); | |
| 145 | + if (result.done) break; | |
| 146 | + chunks.push(result.value); | |
| 147 | + length += result.value.byteLength; | |
| 148 | + } | |
| 149 | + const bytes = new Uint8Array(length); | |
| 150 | + let offset = 0; | |
| 151 | + for (const chunk of chunks) { | |
| 152 | + bytes.set(chunk, offset); | |
| 153 | + offset += chunk.byteLength; | |
| 154 | + } | |
| 155 | + target._bodyBytes = bytes; | |
| 156 | + // text() memoizes into _body on demand. Decoding here charges every | |
| 157 | + // binary passthrough the cost of a string it never reads. | |
| 158 | + target._body = undefined; | |
| 159 | + return bytes; | |
| 160 | +} | |
| 161 | +class CelldBodyStream extends ReadableStream { | |
| 162 | + constructor(owner) { | |
| 163 | + // Couple the stream to its buffered owner, so _bodyBytes and the stream | |
| 164 | + // cannot be installed from different arrays. Copying the owner's bytes | |
| 165 | + // again here doubles the external memory held for every constructed body. | |
| 166 | + if (!(owner instanceof globalThis.Request) && | |
| 167 | + !(owner instanceof globalThis.Response)) | |
| 168 | + throw new TypeError("CelldBodyStream requires a buffered body owner"); | |
| 169 | + const bytes = owner._bodyBytes; | |
| 170 | + if (!(bytes instanceof Uint8Array)) | |
| 171 | + throw new TypeError("CelldBodyStream owner requires buffered body bytes"); | |
| 172 | + const st = { bytes, off: 0 }; | |
| 173 | + super({ | |
| 174 | + pull(controller) { | |
| 175 | + if (st.off >= st.bytes.byteLength) { | |
| 176 | + controller.close(); | |
| 177 | + return; | |
| 178 | + } | |
| 179 | + const end = Math.min(st.off + 64 * 1024, st.bytes.byteLength); | |
| 180 | + controller.enqueue(st.bytes.subarray(st.off, end)); | |
| 181 | + st.off = end; | |
| 182 | + }, | |
| 183 | + }, { highWaterMark: 0 }); | |
| 184 | + this._st = st; | |
| 185 | + this.__celldBodyBytes = bytes; | |
| 186 | + // Known length, so re-using this stream as a subrequest body | |
| 187 | + // still advertises Content-Length. | |
| 188 | + this._expectedLength = bytes.byteLength; | |
| 189 | + } | |
| 190 | + get __celldBodyText() { return new TextDecoder().decode(this.__celldBodyBytes); } | |
| 191 | + // Workerd body streams are internal streams, so BYOB readers | |
| 192 | + // work on them. Naming ReadableStreamBYOBReader compiles the | |
| 193 | + // lazy byte-stream prelude; a worker that never asks for byob | |
| 194 | + // mode never pays for it. | |
| 195 | + getReader(options) { | |
| 196 | + if (options !== undefined && options !== null && | |
| 197 | + options.mode !== undefined) { | |
| 198 | + if (String(options.mode) !== "byob") | |
| 199 | + throw new TypeError(`Invalid reader mode '${options.mode}'`); | |
| 200 | + if (this._ictl === undefined) | |
| 201 | + this._ictl = ReadableStreamBYOBReader._buffered(this._st); | |
| 202 | + return new ReadableStreamBYOBReader(this); | |
| 203 | + } | |
| 204 | + return super.getReader(options); | |
| 205 | + } | |
| 206 | + // Cancelling a body stream poisons later consumption: text() | |
| 207 | + // and friends reject, as they would over a real socket. | |
| 208 | + _cancel(reason) { | |
| 209 | + this._cancelled = true; | |
| 210 | + return super._cancel(reason); | |
| 211 | + } | |
| 212 | +} | |
| 213 | +class CelldHttpBodyStream extends ReadableStream { | |
| 214 | + constructor(streamId) { | |
| 215 | + const id = Number(streamId); | |
| 216 | + super({ | |
| 217 | + async pull(controller) { | |
| 218 | + // A chunk arrives as a Uint8Array. The host moves it in without | |
| 219 | + // a copy. The end of the stream arrives as a string. | |
| 220 | + const chunk = await __http_stream_read(id); | |
| 221 | + if (typeof chunk === "string") controller.close(); | |
| 222 | + else controller.enqueue(chunk); | |
| 223 | + }, | |
| 224 | + cancel() { __http_stream_cancel(id); }, | |
| 225 | + }, { highWaterMark: 0 }); | |
| 226 | + this.__celldStreamId = id; | |
| 227 | + } | |
| 228 | + tee() { | |
| 229 | + if (this.locked) throw new TypeError("ReadableStream is locked"); | |
| 230 | + this._locked = true; | |
| 231 | + this._disturbed = true; | |
| 232 | + const [left, right] = JSON.parse( | |
| 233 | + __http_stream_tee(this.__celldStreamId), | |
| 234 | + ); | |
| 235 | + return [ | |
| 236 | + new CelldHttpBodyStream(left), | |
| 237 | + new CelldHttpBodyStream(right), | |
| 238 | + ]; | |
| 239 | + } | |
| 240 | +} | |
| 241 | +globalThis.Response = class Response { | |
| 242 | + constructor(body, init = {}) { | |
| 243 | + // Streaming/iterable detection runs only for object bodies, so | |
| 244 | + // the common string path skips every instanceof below. | |
| 245 | + let stream = null; | |
| 246 | + let typed = null; | |
| 247 | + if (body !== null && typeof body === "object") { | |
| 248 | + if (body instanceof ReadableStream) stream = body; | |
| 249 | + else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ } | |
| 250 | + else { | |
| 251 | + const iterable = __iterableBody(body); | |
| 252 | + if (iterable instanceof ReadableStream) stream = iterable; | |
| 253 | + else if (iterable !== null) body = iterable; | |
| 254 | + } | |
| 255 | + } | |
| 256 | + this._bodyBytes = stream !== null | |
| 257 | + ? null | |
| 258 | + : typed ? typed.bytes : __bodyBytes(body); | |
| 259 | + // Never decoded eagerly: a whole-body UTF-8 decode costs seconds for a | |
| 260 | + // large binary body (an archive, a git pack) and can exceed V8's string | |
| 261 | + // length. On Response the field is deliberately write-only -- text() | |
| 262 | + // decodes fresh from _bodyBytes and only Request.text() memoizes into | |
| 263 | + // _body -- but the assignment stays: __drainBody and __adoptBody assign | |
| 264 | + // _body on both classes, so defining it here keeps the hidden-class | |
| 265 | + // shape stable. Do not add a Response reader; do not "simplify" this | |
| 266 | + // away. | |
| 267 | + this._body = undefined; | |
| 268 | + // Hono rebuilds a response after middleware with | |
| 269 | + // `new Response(response.body, response)`; the held stream (or a | |
| 270 | + // fresh CelldBodyStream) preserves the payload across that | |
| 271 | + // standard clone shape. | |
| 272 | + this.body = body == null | |
| 273 | + ? null | |
| 274 | + : stream !== null | |
| 275 | + ? stream | |
| 276 | + : new CelldBodyStream(this); | |
| 277 | + this.status = init.status === undefined ? 200 : Number(init.status); | |
| 278 | + this.statusText = init.statusText === undefined ? "" : String(init.statusText); | |
| 279 | + this.headers = new Headers(init.headers); | |
| 280 | + if (typed && typed.type && !this.headers.has("content-type")) | |
| 281 | + this.headers.set("content-type", typed.type); | |
| 282 | + this.webSocket = init.webSocket ?? null; | |
| 283 | + this._wsTarget = init.__wsTarget || init._wsTarget || null; | |
| 284 | + this.ok = this.status >= 200 && this.status <= 299; | |
| 285 | + this.redirected = false; | |
| 286 | + this.type = "default"; | |
| 287 | + this.url = ""; | |
| 288 | + this.bodyUsed = false; | |
| 289 | + if (init.cf !== undefined) this.cf = init.cf; | |
| 290 | + } | |
| 291 | + static json(data, init = {}) { | |
| 292 | + const headers = new Headers(init.headers || {}); | |
| 293 | + if (!headers.has("content-type")) | |
| 294 | + headers.set("content-type", "application/json"); | |
| 295 | + return new Response(JSON.stringify(data), { ...init, headers }); | |
| 296 | + } | |
| 297 | + static redirect(url, status = 302) { | |
| 298 | + const input = String(url); | |
| 299 | + const statusCode = Number(status) | 0; | |
| 300 | + if (![301, 302, 303, 307, 308].includes(statusCode)) { | |
| 301 | + throw new RangeError( | |
| 302 | + `${statusCode} is not a redirect status code. ` + | |
| 303 | + "It must be one of: 301, 302, 303, 307, or 308."); | |
| 304 | + } | |
| 305 | + const response = new Response(null, { | |
| 306 | + status: statusCode, | |
| 307 | + headers: { Location: new URL(input).href }, | |
| 308 | + }); | |
| 309 | + // A redirect response owns a guarded header list. Without the guard, an | |
| 310 | + // application can rewrite Location after construction, which differs | |
| 311 | + // from both Fetch and Workerd even though the initial response is valid. | |
| 312 | + Object.defineProperty(response.headers, "_immutable", { value: true }); | |
| 313 | + return response; | |
| 314 | + } | |
| 315 | + static error() { | |
| 316 | + const response = new Response(null); | |
| 317 | + response.status = 0; | |
| 318 | + response.ok = false; | |
| 319 | + response.type = "error"; | |
| 320 | + return response; | |
| 321 | + } | |
| 322 | + async _consume() { | |
| 323 | + if (this._bodyBytes !== null) { | |
| 324 | + if (this.body !== null && this.body._cancelled) | |
| 325 | + throw new TypeError( | |
| 326 | + "Body has already been used. It can only be used once. " + | |
| 327 | + "Use tee() first if you need to read it multiple times."); | |
| 328 | + return this._bodyBytes; | |
| 329 | + } | |
| 330 | + return __drainBody(this); | |
| 331 | + } | |
| 332 | + async text() { | |
| 333 | + this.bodyUsed = true; | |
| 334 | + return new TextDecoder().decode(await this._consume()); | |
| 335 | + } | |
| 336 | + async json() { return JSON.parse(await this.text()); } | |
| 337 | + async formData() { | |
| 338 | + // The undecoded bytes, not `text()`: a UTF-8 decode replaces each invalid | |
| 339 | + // sequence in a binary file part with one U+FFFD, so both the bytes and | |
| 340 | + // the length change. | |
| 341 | + this.bodyUsed = true; | |
| 342 | + return __celld.__parseFormData( | |
| 343 | + await this._consume(), this.headers.get('content-type')); | |
| 344 | + } | |
| 345 | + async arrayBuffer() { | |
| 346 | + this.bodyUsed = true; | |
| 347 | + return (await this._consume()).slice().buffer; | |
| 348 | + } | |
| 349 | + async blob() { | |
| 350 | + return new Blob([await this.arrayBuffer()], | |
| 351 | + { type: this.headers.get("content-type") || "" }); | |
| 352 | + } | |
| 353 | + clone() { | |
| 354 | + if (this.bodyUsed) throw new TypeError("Body has already been consumed"); | |
| 355 | + if (this._bodyBytes === null) | |
| 356 | + throw new TypeError("Cannot clone a streaming response before consumption"); | |
| 357 | + const response = new Response( | |
| 358 | + this.body === null ? null : this._bodyBytes, | |
| 359 | + { | |
| 360 | + status: this.status, statusText: this.statusText, headers: this.headers, | |
| 361 | + webSocket: this.webSocket, __wsTarget: this._wsTarget, cf: this.cf, | |
| 362 | + }, | |
| 363 | + ); | |
| 364 | + response.type = this.type; | |
| 365 | + return response; | |
| 366 | + } | |
| 367 | +}; | |
| 368 | +// Hoisted: this would otherwise allocate an array and scan it on | |
| 369 | +// every Request construction, which is the HTTP hot path. | |
| 370 | +const __HTTP_METHODS = new Set( | |
| 371 | + ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]); | |
| 372 | +const __FETCH_REDIRECT_MODES = new Set(["follow", "manual", "error"]); | |
| 373 | +globalThis.Request = class Request { | |
| 374 | + constructor(input, init = {}) { | |
| 375 | + const prior = input instanceof Request ? input : null; | |
| 376 | + const suppliedSignal = init.signal !== undefined; | |
| 377 | + // The cache option needs the cache_option_enabled compat flag, | |
| 378 | + // which Cells does not implement (Workerd's cache-disabled path). | |
| 379 | + if (init.cache !== undefined) | |
| 380 | + throw new Error("The 'cache' field on 'RequestInitializerDict' " + | |
| 381 | + "is not implemented."); | |
| 382 | + this.url = prior ? prior.url : String(input); | |
| 383 | + { | |
| 384 | + // Workers upper-cases every method (the | |
| 385 | + // upper_case_all_http_methods flag) but rejects anything outside | |
| 386 | + // the known set, reporting the original casing. | |
| 387 | + const raw = String(init.method === undefined | |
| 388 | + ? (prior ? prior.method : "GET") : init.method); | |
| 389 | + const upper = raw.toUpperCase(); | |
| 390 | + if (!__HTTP_METHODS.has(upper)) | |
| 391 | + throw new TypeError(`Invalid HTTP method string: ${raw}`); | |
| 392 | + this.method = upper; | |
| 393 | + } | |
| 394 | + const hasBody = | |
| 395 | + Object.prototype.hasOwnProperty.call(init, "body"); | |
| 396 | + let body = hasBody ? init.body : null; | |
| 397 | + let stream = null; | |
| 398 | + let typed = null; | |
| 399 | + if (hasBody && body !== null && typeof body === "object") { | |
| 400 | + if (body instanceof ReadableStream) stream = body; | |
| 401 | + else if ((typed = __typedBody(body)) !== null) { /* bytes and type */ } | |
| 402 | + else { | |
| 403 | + const iterable = __iterableBody(body); | |
| 404 | + if (iterable instanceof ReadableStream) stream = iterable; | |
| 405 | + else if (iterable !== null) body = iterable; | |
| 406 | + } | |
| 407 | + } | |
| 408 | + if (!hasBody && prior && prior._bodyBytes === null) { | |
| 409 | + // Adopt the prior request's stream; per spec the prior body | |
| 410 | + // is disturbed by the new request. | |
| 411 | + stream = prior.body; | |
| 412 | + prior.bodyUsed = true; | |
| 413 | + } | |
| 414 | + this._bodyBytes = stream !== null | |
| 415 | + ? null | |
| 416 | + : hasBody | |
| 417 | + ? (typed ? typed.bytes : __bodyBytes(body)) | |
| 418 | + : (prior ? prior._bodyBytes.slice() : new Uint8Array()); | |
| 419 | + // Body text is decoded on the first text()/json(), not here: a request | |
| 420 | + // whose body is never read never pays the decode. | |
| 421 | + this._body = undefined; | |
| 422 | + // Headers are stored raw and built on the first `.headers` access. The | |
| 423 | + // hot paths -- a hello world, a Worker that only forwards to a cell -- | |
| 424 | + // read none, so `new Headers` and the JSON.parse behind it never run. | |
| 425 | + if (init.__headersJson !== undefined) { | |
| 426 | + this._headersJson = init.__headersJson; | |
| 427 | + this._headersInit = undefined; | |
| 428 | + } else if (init.headers === undefined && prior) { | |
| 429 | + this._headersJson = prior._headersJson; | |
| 430 | + // Per spec `new Request(request)` copies the header list. The prior | |
| 431 | + // request's `Headers` object cannot stand in for it: `new Headers(h)` | |
| 432 | + // reads `h` through its iterator, which sorts, lower-cases and | |
| 433 | + // combines, so forwarding a request whose headers were read would | |
| 434 | + // undo the wire shape the outbound paths preserve. | |
| 435 | + this._headersInit = prior._headers | |
| 436 | + ? prior._headers.__celldHeaderList | |
| 437 | + : prior._headersInit; | |
| 438 | + } else { | |
| 439 | + this._headersJson = undefined; | |
| 440 | + this._headersInit = init.headers; | |
| 441 | + } | |
| 442 | + this._headers = null; | |
| 443 | + // A typed body's default content-type must land now; only user-built | |
| 444 | + // typed bodies reach this, never the incoming request path. | |
| 445 | + if (typed && typed.type && !this.headers.has("content-type")) { | |
| 446 | + this.headers.set("content-type", typed.type); | |
| 447 | + } | |
| 448 | + this.bodyUsed = false; | |
| 449 | + // The body stream and the signal stay eager, own properties: the RPC and | |
| 450 | + // storage serializers fall back to the lift-into-marker path only when a | |
| 451 | + // value is not directly structured-cloneable, and a Request's un-cloneable | |
| 452 | + // body stream (or AbortSignal) is what triggers that. Making them lazy | |
| 453 | + // getters let `__sc_encode` clone the Request into a broken plain object | |
| 454 | + // and skip the lift -- the serializeHttpTypes conformance failure. | |
| 455 | + this.body = stream !== null | |
| 456 | + ? stream | |
| 457 | + : ["GET", "HEAD"].includes(this.method) | |
| 458 | + ? null : new CelldBodyStream(this); | |
| 459 | + this.redirect = String(init.redirect === undefined | |
| 460 | + ? (prior ? prior.redirect : "follow") | |
| 461 | + : init.redirect); | |
| 462 | + if (!__FETCH_REDIRECT_MODES.has(this.redirect)) { | |
| 463 | + throw new TypeError(`Invalid redirect mode: ${this.redirect}`); | |
| 464 | + } | |
| 465 | + const cf = init.cf === undefined | |
| 466 | + ? (prior ? prior.cf : undefined) : init.cf; | |
| 467 | + if (cf !== undefined) this.cf = cf; | |
| 468 | + this.signal = suppliedSignal | |
| 469 | + ? init.signal | |
| 470 | + : (prior ? prior.signal : new AbortController().signal); | |
| 471 | + this._signalForSubrequests = init.__celldIncomingSignal | |
| 472 | + ? null | |
| 473 | + : suppliedSignal | |
| 474 | + ? this.signal | |
| 475 | + : (prior ? prior._signalForSubrequests : null); | |
| 476 | + } | |
| 477 | + get headers() { | |
| 478 | + if (this._headers === null) { | |
| 479 | + const src = this._headersJson !== undefined | |
| 480 | + ? JSON.parse(this._headersJson) | |
| 481 | + : this._headersInit; | |
| 482 | + this._headers = new Headers(src); | |
| 483 | + this._headersJson = undefined; | |
| 484 | + this._headersInit = undefined; | |
| 485 | + } | |
| 486 | + return this._headers; | |
| 487 | + } | |
| 488 | + set headers(value) { | |
| 489 | + this._headers = value instanceof Headers ? value : new Headers(value); | |
| 490 | + this._headersJson = undefined; | |
| 491 | + this._headersInit = undefined; | |
| 492 | + } | |
| 493 | + async _consume() { | |
| 494 | + if (this._bodyBytes !== null) return this._bodyBytes; | |
| 495 | + return __drainBody(this); | |
| 496 | + } | |
| 497 | + async text() { | |
| 498 | + this.bodyUsed = true; | |
| 499 | + const bytes = await this._consume(); | |
| 500 | + return this._body ??= new TextDecoder().decode(bytes); | |
| 501 | + } | |
| 502 | + async json() { return JSON.parse(await this.text()); } | |
| 503 | + async formData() { | |
| 504 | + // The undecoded bytes, not `text()`: a UTF-8 decode replaces each invalid | |
| 505 | + // sequence in a binary file part with one U+FFFD, so both the bytes and | |
| 506 | + // the length change. | |
| 507 | + this.bodyUsed = true; | |
| 508 | + return __celld.__parseFormData( | |
| 509 | + await this._consume(), this.headers.get('content-type')); | |
| 510 | + } | |
| 511 | + async arrayBuffer() { | |
| 512 | + this.bodyUsed = true; | |
| 513 | + return (await this._consume()).slice().buffer; | |
| 514 | + } | |
| 515 | + async blob() { | |
| 516 | + return new Blob([await this.arrayBuffer()], | |
| 517 | + { type: this.headers.get("content-type") || "" }); | |
| 518 | + } | |
| 519 | + clone() { | |
| 520 | + if (this.bodyUsed) throw new TypeError("Body has already been consumed"); | |
| 521 | + if (this._bodyBytes === null) { | |
| 522 | + // Streaming body: tee, keep one branch, clone the other. | |
| 523 | + const [left, right] = this.body.tee(); | |
| 524 | + this.body = left; | |
| 525 | + return new Request(this, { body: right }); | |
| 526 | + } | |
| 527 | + return new Request(this); | |
| 528 | + } | |
| 529 | +}; | |
| 530 | +const __makeRequest = __celld.__makeRequest = ( | |
| 531 | + url, method, body, headersJson = "[]", signal = undefined, | |
| 532 | + incomingSignal = false, | |
| 533 | +) => new Request(url, { | |
| 534 | + // The raw header JSON, not a parsed object: an incoming request whose | |
| 535 | + // handler never reads `.headers` (a hello world, or a Worker that only | |
| 536 | + // routes to a cell) then never parses it. See `get headers()`. | |
| 537 | + // celld cannot prove Cloudflare edge metadata, so the object stays empty. | |
| 538 | + // In particular, no client-controlled header becomes a country or a colo; | |
| 539 | + // the forwarded-authority trust flag does not establish geolocation trust. | |
| 540 | + method, body, __headersJson: headersJson, signal, cf: {}, | |
| 541 | + __celldIncomingSignal: incomingSignal, | |
| 542 | +}); | |
| 543 | +const __fmt = (a) => a.map((x) => { | |
| 544 | + if (typeof x === "string") return x; | |
| 545 | + if (x instanceof Error) return x.stack || (x.name + ": " + x.message); | |
| 546 | + try { return JSON.stringify(x); } catch { return String(x); } | |
| 547 | +}).join(" "); | |
| 548 | +const __consoleNoop = () => {}; | |
| 549 | +globalThis.console = { | |
| 550 | + debug: (...a) => __log(__fmt(a)), | |
| 551 | + error: (...a) => __log("ERROR " + __fmt(a)), | |
| 552 | + info: (...a) => __log(__fmt(a)), | |
| 553 | + log: (...a) => __log(__fmt(a)), | |
| 554 | + warn: (...a) => __log("WARN " + __fmt(a)), | |
| 555 | + clear: __consoleNoop, | |
| 556 | + count: __consoleNoop, | |
| 557 | + group: __consoleNoop, | |
| 558 | + table: __consoleNoop, | |
| 559 | + trace: __consoleNoop, | |
| 560 | + assert: __consoleNoop, | |
| 561 | + countReset: __consoleNoop, | |
| 562 | + dir: __consoleNoop, | |
| 563 | + dirxml: __consoleNoop, | |
| 564 | + groupCollapsed: __consoleNoop, | |
| 565 | + groupEnd: __consoleNoop, | |
| 566 | + profile: __consoleNoop, | |
| 567 | + profileEnd: __consoleNoop, | |
| 568 | + time: __consoleNoop, | |
| 569 | + timeEnd: __consoleNoop, | |
| 570 | + timeLog: __consoleNoop, | |
| 571 | + timeStamp: __consoleNoop, | |
| 572 | + createTask: () => { | |
| 573 | + throw new Error("console.createTask() is not implemented"); | |
| 574 | + }, | |
| 575 | +}; | |
| 576 | + | |
| 577 | +// async-op shims: outbound fetch + timers, driven by the host event loop. | |
| 578 | +// Move one request body through a host subrequest seam. A body that already | |
| 579 | +// names a host stream keeps that stream incremental. An ordinary JavaScript | |
| 580 | +// stream has no host owner, so it uses the existing byte fallback. | |
| 581 | +const __subrequestBody = async (req, absent = false) => { | |
| 582 | + if (absent) return { body: undefined, streamId: undefined }; | |
| 583 | + if (req._bodyBytes !== null) | |
| 584 | + return { body: req._bodyBytes, streamId: undefined }; | |
| 585 | + const streamId = req.body?.__celldStreamId; | |
| 586 | + if (streamId === undefined) { | |
| 587 | + req.bodyUsed = true; | |
| 588 | + return { body: await req._consume(), streamId: undefined }; | |
| 589 | + } | |
| 590 | + // The receiver now owns the one host source. Lock the wrapper so a later | |
| 591 | + // read fails instead of racing the receiver, and expose the transfer through | |
| 592 | + // the standard Body flag. | |
| 593 | + req.bodyUsed = true; | |
| 594 | + req.body.getReader(); | |
| 595 | + return { body: new Uint8Array(), streamId }; | |
| 596 | +}; | |
| 597 | +// A data: URL carries its response inline; RFC 2397 percent-decoding | |
| 598 | +// happens byte-wise, so a payload that is deliberately invalid UTF-8 | |
| 599 | +// survives to the consumer (HTMLRewriter's own suite depends on it). | |
| 600 | +const __dataUrlResponse = (url) => { | |
| 601 | + // The URL parser strips leading and trailing C0 controls and spaces | |
| 602 | + // before doing anything else; a literal trailing space in a data: URL | |
| 603 | + // is therefore not part of the payload, while an encoded %20 is. | |
| 604 | + url = url.replace(/^[\x00-\x20]+/, "").replace(/[\x00-\x20]+$/, ""); | |
| 605 | + const match = /^data:([^,]*),([\s\S]*)$/.exec(url); | |
| 606 | + if (!match) throw new TypeError("Invalid data: URL"); | |
| 607 | + let [, meta, payload] = match; | |
| 608 | + const base64 = /;base64$/i.test(meta); | |
| 609 | + if (base64) meta = meta.replace(/;base64$/i, ""); | |
| 610 | + let bytes; | |
| 611 | + if (base64) { | |
| 612 | + // The data: URL processor percent-decodes the body before it decodes the | |
| 613 | + // base64, so `data:text/plain;base64,YQ%3D%3D` carries the padding of | |
| 614 | + // "YQ==". Decode byte-wise, as the non-base64 branch below does: a `%` | |
| 615 | + // that does not start a valid escape stays literal and the base64 decode | |
| 616 | + // rejects it. | |
| 617 | + payload = payload.replace( | |
| 618 | + /%([0-9a-f]{2})/gi, | |
| 619 | + (_, hex) => String.fromCharCode(parseInt(hex, 16)), | |
| 620 | + ); | |
| 621 | + const bin = atob(payload); | |
| 622 | + bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0)); | |
| 623 | + } else { | |
| 624 | + const out = []; | |
| 625 | + for (let i = 0; i < payload.length; i++) { | |
| 626 | + const c = payload[i]; | |
| 627 | + if (c === "%" && /^[0-9A-Fa-f]{2}$/.test(payload.slice(i + 1, i + 3))) { | |
| 628 | + out.push(parseInt(payload.slice(i + 1, i + 3), 16)); | |
| 629 | + i += 2; | |
| 630 | + } else { | |
| 631 | + out.push(payload.charCodeAt(i) & 0xff); | |
| 632 | + } | |
| 633 | + } | |
| 634 | + bytes = Uint8Array.from(out); | |
| 635 | + } | |
| 636 | + return new Response(bytes, { | |
| 637 | + headers: { "content-type": meta || "text/plain;charset=US-ASCII" }, | |
| 638 | + }); | |
| 639 | +}; | |
| 640 | +globalThis.fetch = async (input, init) => { | |
| 641 | + const rawUrl = typeof input === "string" ? input : input?.url; | |
| 642 | + if (typeof rawUrl === "string" && rawUrl.startsWith("data:")) { | |
| 643 | + return __dataUrlResponse(rawUrl); | |
| 644 | + } | |
| 645 | + const req = new Request(input, init); | |
| 646 | + // `fetch(url, { headers: { Upgrade: "websocket" } })` is the other way | |
| 647 | + // Cloudflare opens an outbound socket, and the one most examples use. | |
| 648 | + if ((req.headers.get("upgrade") ?? "").toLowerCase() === "websocket") { | |
| 649 | + return await __fetchWebSocketUpgrade(req); | |
| 650 | + } | |
| 651 | + // The caller's signal, never the incoming request's own. | |
| 652 | + const signal = req._signalForSubrequests; | |
| 653 | + if (signal?.aborted) throw signal.reason; | |
| 654 | + // The bytes go to the host as a typed array, the same way every other | |
| 655 | + // subrequest op takes a body. Encoding them as a JSON number array cost | |
| 656 | + // roughly ten times the body in transient allocation, and it corrupted | |
| 657 | + // nothing only because the host decoded the same shape back. | |
| 658 | + const { body, streamId } = await __subrequestBody( | |
| 659 | + req, ["GET", "HEAD"].includes(req.method)); | |
| 660 | + // The header list, not the iterator: the iterator sorts, lower-cases and | |
| 661 | + // combines, so `Array.from(req.headers)` would send one `X-Trace: a, b` | |
| 662 | + // for two appends and put celld's casing on the wire in place of the | |
| 663 | + // author's. `op_fetch` builds the request with `RequestBuilder::header`, | |
| 664 | + // which appends, so repeats survive. | |
| 665 | + let raw; | |
| 666 | + try { | |
| 667 | + const dispatch = __op_fetch( | |
| 668 | + req.method, req.url, body, | |
| 669 | + JSON.stringify(req.headers.__celldHeaderList), req.redirect, | |
| 670 | + streamId, signal != null, | |
| 671 | + ); | |
| 672 | + if (signal) { | |
| 673 | + // An abort and the response can cross, leaving a body stream nobody | |
| 674 | + // reads holding its upstream connection until the sweeper expires it. | |
| 675 | + // Every arm is silenced because the caller already owns both outcomes. | |
| 676 | + dispatch.then((late) => { | |
| 677 | + if (!signal.aborted) return; | |
| 678 | + const abandoned = JSON.parse(late).streamId; | |
| 679 | + if (abandoned !== undefined) __http_stream_cancel(abandoned); | |
| 680 | + }, () => {}).catch(() => {}); | |
| 681 | + } | |
| 682 | + raw = await (signal ? __awaitCancellableDoCall(dispatch, signal) : dispatch); | |
| 683 | + } catch (error) { | |
| 684 | + // An abort is the caller's reason, not a network error, so it skips | |
| 685 | + // every translation below. | |
| 686 | + if (signal?.aborted && error === signal.reason) throw error; | |
| 687 | + // The Fetch API represents a redirect refusal as a network error, which | |
| 688 | + // rejects with TypeError. Keep the host message for diagnostics. | |
| 689 | + if (req.redirect === "error") { | |
| 690 | + throw new TypeError(error?.message ?? String(error)); | |
| 691 | + } | |
| 692 | + throw error; | |
| 693 | + } | |
| 694 | + const r = JSON.parse(raw); | |
| 695 | + // Direct network responses always carry a stream id. A transferred | |
| 696 | + // globalOutbound Fetcher can answer with an inline body, as service | |
| 697 | + // bindings do, so preserve both response representations. | |
| 698 | + const responseBody = r.streamId !== undefined | |
| 699 | + ? new CelldHttpBodyStream(r.streamId) | |
| 700 | + : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); | |
| 701 | + const response = new Response( | |
| 702 | + responseBody, | |
| 703 | + { status: r.status, headers: r.headers }, | |
| 704 | + ); | |
| 705 | + response.url = req.url; | |
| 706 | + return response; | |
| 707 | +}; | |
| 708 | +const __fetchWebSocketUpgrade = __celld.__fetchWebSocketUpgrade = | |
| 709 | + async (req) => { | |
| 710 | + const scope = __currentActorScope(); | |
| 711 | + const id = __ws_alloc(); | |
| 712 | + const socket = __makeSocket(id); | |
| 713 | + socket._outbound = true; | |
| 714 | + socket._polled = !scope; | |
| 715 | + socket.url = req.url; | |
| 716 | + socket.readyState = WebSocket.READY_STATE_CONNECTING; | |
| 717 | + __sockets.set(id, socket); | |
| 718 | + let raw; | |
| 719 | + try { | |
| 720 | + raw = JSON.parse(await __ws_upgrade( | |
| 721 | + id, | |
| 722 | + scope, | |
| 723 | + req.url, | |
| 724 | + // The iterator, not the header list, unlike every other outbound | |
| 725 | + // path. The handshake builder on the host side puts these into a | |
| 726 | + // `HeaderMap` with `insert`, which replaces, and it reads the | |
| 727 | + // offered subprotocols with a first-match `find`. Both would drop | |
| 728 | + // every repeat but one. Sending the combined form keeps | |
| 729 | + // `Sec-WebSocket-Protocol: a` plus `: b` meaning `a, b`, which is | |
| 730 | + // what the peer must see. Moving this to the header list needs the | |
| 731 | + // host to append instead, so it is a separate change. | |
| 732 | + JSON.stringify(Array.from(req.headers)), | |
| 733 | + )); | |
| 734 | + } catch (error) { | |
| 735 | + __sockets.delete(id); | |
| 736 | + throw error; | |
| 737 | + } | |
| 738 | + if (!raw.upgraded) { | |
| 739 | + // The server answered without upgrading. That is an ordinary response, | |
| 740 | + // not a connection error, and it is returned unchanged. | |
| 741 | + __sockets.delete(id); | |
| 742 | + const response = new Response(new Uint8Array(raw.body), { | |
| 743 | + status: raw.status, | |
| 744 | + headers: raw.headers, | |
| 745 | + }); | |
| 746 | + response.url = req.url; | |
| 747 | + return response; | |
| 748 | + } | |
| 749 | + socket.protocol = raw.protocol ?? ""; | |
| 750 | + const response = new Response(null, { status: 101 }); | |
| 751 | + response.webSocket = socket; | |
| 752 | + response.url = req.url; | |
| 753 | + return response; | |
| 754 | +}; | |
| 755 | +__celld.__makeAssetsBinding = (script) => ({ | |
| 756 | + async fetch(input, init) { | |
| 757 | + const req = input instanceof Request ? new Request(input, init) : new Request(input, init); | |
| 758 | + const r = JSON.parse(await __asset_fetch( | |
| 759 | + script, | |
| 760 | + req.method, | |
| 761 | + req.url, | |
| 762 | + JSON.stringify(Array.from(req.headers)), | |
| 763 | + )); | |
| 764 | + const responseBody = r.streamId !== undefined | |
| 765 | + ? new CelldHttpBodyStream(r.streamId) | |
| 766 | + : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); | |
| 767 | + const response = new Response( | |
| 768 | + responseBody, | |
| 769 | + { status: r.status, headers: r.headers }, | |
| 770 | + ); | |
| 771 | + response.url = req.url; | |
| 772 | + return response; | |
| 773 | + }, | |
| 774 | +}); | |
| 775 | +// An `r2_buckets` binding, served out of the fleet bucket under the | |
| 776 | +// reserved `r2/<bucketName>/` prefix. celld runs on blob storage rather | |
| 777 | +// than providing it, so a binding gets the store the node already holds | |
| 778 | +// credentials for; a node started without a bucket has nowhere to put a | |
| 779 | +// blob and every method says so. | |
| 780 | +// | |
| 781 | +// The whole `R2Bucket` surface is here: `head`, `get`, `put`, `delete`, | |
| 782 | +// `list`, `createMultipartUpload` and `resumeMultipartUpload`, with | |
| 783 | +// `httpMetadata`, `customMetadata`, `checksums`, `storageClass`, `onlyIf` | |
| 784 | +// and every range spelling. What celld cannot honor still fails loudly | |
| 785 | +// rather than pretending -- a silent gap is the failure mode the binding | |
| 786 | +// is written to avoid. Those are `ssecKey` (celld has no customer-key | |
| 787 | +// encryption), a conditional `put` of a body too big for one request, and | |
| 788 | +// a multipart upload resumed on a node other than the one that opened it. | |
| 789 | +const __r2Reject = (bucket, method, detail) => { | |
| 790 | + throw new Error( | |
| 791 | + `R2 ${method} is not implemented in celld (binding ${bucket})` + | |
| 792 | + (detail ? `: ${detail}` : ""), | |
| 793 | + ); | |
| 794 | +}; | |
| 795 | +// R2's key rules, checked here so a key the real thing refuses is refused | |
| 796 | +// here too rather than quietly written. | |
| 797 | +const __r2Key = (binding, method, key) => { | |
| 798 | + const text = String(key); | |
| 799 | + const length = new TextEncoder().encode(text).length; | |
| 800 | + if (length === 0 || length > 1024) { | |
| 801 | + throw new Error( | |
| 802 | + `R2 ${method} (binding ${binding}): a key is 1 to 1024 bytes, not ${length}`, | |
| 803 | + ); | |
| 804 | + } | |
| 805 | + return text; | |
| 806 | +}; | |
| 807 | +const __r2Hex = (value) => { | |
| 808 | + if (typeof value === "string") return value.trim().toLowerCase(); | |
| 809 | + const bytes = value instanceof ArrayBuffer | |
| 810 | + ? new Uint8Array(value) | |
| 811 | + : ArrayBuffer.isView(value) | |
| 812 | + ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) | |
| 813 | + : null; | |
| 814 | + if (!bytes) return null; | |
| 815 | + let out = ""; | |
| 816 | + for (const byte of bytes) out += byte.toString(16).padStart(2, "0"); | |
| 817 | + return out; | |
| 818 | +}; | |
| 819 | +const __r2Bytes = (hex) => { | |
| 820 | + const out = new Uint8Array(hex.length >> 1); | |
| 821 | + for (let at = 0; at < out.length; at++) { | |
| 822 | + out[at] = parseInt(hex.substr(at * 2, 2), 16); | |
| 823 | + } | |
| 824 | + return out.buffer; | |
| 825 | +}; | |
| 826 | +// Read a `ReadableStream` to one `Uint8Array`. Bodies drained this way | |
| 827 | +// are the ones the caller asked to have whole. | |
| 828 | +const __r2Drain = async (stream) => { | |
| 829 | + const reader = stream.getReader(); | |
| 830 | + const chunks = []; | |
| 831 | + let total = 0; | |
| 832 | + for (;;) { | |
| 833 | + const { done, value } = await reader.read(); | |
| 834 | + if (done) break; | |
| 835 | + chunks.push(value); | |
| 836 | + total += value.length; | |
| 837 | + } | |
| 838 | + const out = new Uint8Array(total); | |
| 839 | + let at = 0; | |
| 840 | + for (const chunk of chunks) { | |
| 841 | + out.set(chunk, at); | |
| 842 | + at += chunk.length; | |
| 843 | + } | |
| 844 | + return out; | |
| 845 | +}; | |
| 846 | +const __r2Ms = (value) => { | |
| 847 | + if (value === undefined || value === null) return undefined; | |
| 848 | + const ms = value instanceof Date ? value.getTime() : Number(value); | |
| 849 | + return Number.isFinite(ms) ? ms : undefined; | |
| 850 | +}; | |
| 851 | +// `httpMetadata` is either an `R2HTTPMetadata` or a `Headers`, and R2 | |
| 852 | +// takes both on the way in. | |
| 853 | +const __r2Http = (value) => { | |
| 854 | + if (value === undefined || value === null) return {}; | |
| 855 | + const from = (name, key) => | |
| 856 | + typeof value.get === "function" ? value.get(name) ?? undefined : value[key]; | |
| 857 | + const http = { | |
| 858 | + contentType: from("content-type", "contentType"), | |
| 859 | + contentLanguage: from("content-language", "contentLanguage"), | |
| 860 | + contentDisposition: from("content-disposition", "contentDisposition"), | |
| 861 | + contentEncoding: from("content-encoding", "contentEncoding"), | |
| 862 | + cacheControl: from("cache-control", "cacheControl"), | |
| 863 | + cacheExpiry: __r2Ms( | |
| 864 | + typeof value.get === "function" ? value.get("expires") : value.cacheExpiry, | |
| 865 | + ), | |
| 866 | + }; | |
| 867 | + for (const [name, entry] of Object.entries(http)) { | |
| 868 | + if (entry === undefined || entry === null) delete http[name]; | |
| 869 | + else if (name !== "cacheExpiry") http[name] = String(entry); | |
| 870 | + } | |
| 871 | + return http; | |
| 872 | +}; | |
| 873 | +// `onlyIf` is either an `R2Conditional` or a `Headers`; the header | |
| 874 | +// spelling of "only if it has not changed since" is If-Unmodified-Since, | |
| 875 | +// which is `uploadedBefore`. | |
| 876 | +const __r2OnlyIf = (value) => { | |
| 877 | + if (value === undefined || value === null) return undefined; | |
| 878 | + const only = typeof value.get === "function" | |
| 879 | + ? { | |
| 880 | + etagMatches: value.get("if-match") ?? undefined, | |
| 881 | + etagDoesNotMatch: value.get("if-none-match") ?? undefined, | |
| 882 | + uploadedAfter: __r2Ms(Date.parse(value.get("if-modified-since") ?? "")), | |
| 883 | + uploadedBefore: __r2Ms(Date.parse(value.get("if-unmodified-since") ?? "")), | |
| 884 | + } | |
| 885 | + : { | |
| 886 | + etagMatches: value.etagMatches, | |
| 887 | + etagDoesNotMatch: value.etagDoesNotMatch, | |
| 888 | + uploadedAfter: __r2Ms(value.uploadedAfter), | |
| 889 | + uploadedBefore: __r2Ms(value.uploadedBefore), | |
| 890 | + }; | |
| 891 | + for (const [name, entry] of Object.entries(only)) { | |
| 892 | + if (entry === undefined || entry === null || Number.isNaN(entry)) { | |
| 893 | + delete only[name]; | |
| 894 | + } else if (name.startsWith("etag")) only[name] = String(entry); | |
| 895 | + } | |
| 896 | + return Object.keys(only).length ? only : undefined; | |
| 897 | +}; | |
| 898 | +// A range is an `R2Range` or a `Headers` carrying a Range header. R2 | |
| 899 | +// takes `offset` alone, `length` alone, both, or `suffix`. | |
| 900 | +const __r2Range = (binding, value) => { | |
| 901 | + if (value === undefined || value === null) return undefined; | |
| 902 | + if (typeof value.get === "function") { | |
| 903 | + const header = value.get("range"); | |
| 904 | + if (!header) return undefined; | |
| 905 | + const parsed = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); | |
| 906 | + if (!parsed) { | |
| 907 | + __r2Reject(binding, "get(range)", `celld cannot parse ${header}`); | |
| 908 | + } | |
| 909 | + const [, first, last] = parsed; | |
| 910 | + if (first === "") return { suffix: Number(last) }; | |
| 911 | + if (last === "") return { offset: Number(first) }; | |
| 912 | + return { offset: Number(first), length: Number(last) - Number(first) + 1 }; | |
| 913 | + } | |
| 914 | + const range = {}; | |
| 915 | + if (value.suffix !== undefined && value.suffix !== null) { | |
| 916 | + range.suffix = Number(value.suffix); | |
| 917 | + } | |
| 918 | + if (value.offset !== undefined && value.offset !== null) { | |
| 919 | + range.offset = Number(value.offset); | |
| 920 | + } | |
| 921 | + if (value.length !== undefined && value.length !== null) { | |
| 922 | + range.length = Number(value.length); | |
| 923 | + } | |
| 924 | + for (const [name, entry] of Object.entries(range)) { | |
| 925 | + if (!Number.isFinite(entry) || entry < 0) { | |
| 926 | + __r2Reject(binding, "get(range)", `\`${name}\` must be a whole number`); | |
| 927 | + } | |
| 928 | + } | |
| 929 | + return Object.keys(range).length ? range : undefined; | |
| 930 | +}; | |
| 931 | +// R2 hashes an object's bytes and hands the digests back as | |
| 932 | +// `ArrayBuffer`s, with a `toJSON()` that spells them in hex. | |
| 933 | +const __r2Checksums = (hex) => { | |
| 934 | + const checksums = { | |
| 935 | + toJSON() { | |
| 936 | + const json = {}; | |
| 937 | + for (const [name, digest] of Object.entries(hex)) json[name] = digest; | |
| 938 | + return json; | |
| 939 | + }, | |
| 940 | + }; | |
| 941 | + for (const [name, digest] of Object.entries(hex)) { | |
| 942 | + checksums[name] = __r2Bytes(digest); | |
| 943 | + } | |
| 944 | + return checksums; | |
| 945 | +}; | |
| 946 | +// One object as R2 describes it. `object` is the host's record; `body`, | |
| 947 | +// when there is one, makes this an `R2ObjectBody`. | |
| 948 | +const __r2Object = (object, body) => { | |
| 949 | + const http = { ...object.http }; | |
| 950 | + if (http.cacheExpiry !== undefined) { | |
| 951 | + http.cacheExpiry = new Date(http.cacheExpiry); | |
| 952 | + } | |
| 953 | + const etag = object.etag ? String(object.etag).replace(/^"|"$/g, "") : ""; | |
| 954 | + const r2 = { | |
| 955 | + key: object.key, | |
| 956 | + version: object.version ?? etag, | |
| 957 | + size: object.size, | |
| 958 | + etag, | |
| 959 | + httpEtag: etag ? `"${etag}"` : "", | |
| 960 | + uploaded: new Date(object.uploaded), | |
| 961 | + httpMetadata: http, | |
| 962 | + customMetadata: object.custom ?? {}, | |
| 963 | + checksums: __r2Checksums(object.checksums ?? {}), | |
| 964 | + storageClass: object.storageClass ?? "Standard", | |
| 965 | + // R2 fills the response headers from the object's own metadata, which | |
| 966 | + // is what makes `return new Response(object.body, { headers })` serve | |
| 967 | + // a stored file correctly. | |
| 968 | + writeHttpMetadata(headers) { | |
| 969 | + const write = (name, value) => { | |
| 970 | + if (value !== undefined && value !== null) headers.set(name, value); | |
| 971 | + }; | |
| 972 | + write("content-type", http.contentType); | |
| 973 | + write("content-language", http.contentLanguage); | |
| 974 | + write("content-disposition", http.contentDisposition); | |
| 975 | + write("content-encoding", http.contentEncoding); | |
| 976 | + write("cache-control", http.cacheControl); | |
| 977 | + if (http.cacheExpiry !== undefined) { | |
| 978 | + headers.set("expires", http.cacheExpiry.toUTCString()); | |
| 979 | + } | |
| 980 | + }, | |
| 981 | + }; | |
| 982 | + if (object.range) r2.range = { ...object.range }; | |
| 983 | + if (!body) return r2; | |
| 984 | + const drain = () => __r2Drain(body); | |
| 985 | + r2.body = body; | |
| 986 | + Object.defineProperty(r2, "bodyUsed", { | |
| 987 | + get: () => body.locked || body._disturbed === true, | |
| 988 | + }); | |
| 989 | + r2.arrayBuffer = async () => (await drain()).buffer; | |
| 990 | + r2.bytes = drain; | |
| 991 | + r2.text = async () => new TextDecoder().decode(await drain()); | |
| 992 | + r2.json = async () => JSON.parse(new TextDecoder().decode(await drain())); | |
| 993 | + r2.blob = async () => new Blob([await drain()]); | |
| 994 | + return r2; | |
| 995 | +}; | |
| 996 | +// The write-side options every writing method shares, in the shape the | |
| 997 | +// host ops read. | |
| 998 | +const __r2WriteOptions = (binding, method, options) => { | |
| 999 | + const o = options ?? {}; | |
| 1000 | + if (o.ssecKey !== undefined) { | |
| 1001 | + __r2Reject( | |
| 1002 | + binding, | |
| 1003 | + `${method}(ssecKey)`, | |
| 1004 | + "celld has no customer-key encryption", | |
| 1005 | + ); | |
| 1006 | + } | |
| 1007 | + const custom = {}; | |
| 1008 | + for (const [name, value] of Object.entries(o.customMetadata ?? {})) { | |
| 1009 | + custom[name] = String(value); | |
| 1010 | + } | |
| 1011 | + const verify = {}; | |
| 1012 | + for (const name of ["md5", "sha1", "sha256", "sha384", "sha512"]) { | |
| 1013 | + if (o[name] === undefined || o[name] === null) continue; | |
| 1014 | + const hex = __r2Hex(o[name]); | |
| 1015 | + if (hex === null) { | |
| 1016 | + __r2Reject( | |
| 1017 | + binding, | |
| 1018 | + `${method}(${name})`, | |
| 1019 | + "a checksum is hex or an ArrayBuffer", | |
| 1020 | + ); | |
| 1021 | + } | |
| 1022 | + verify[name] = hex; | |
| 1023 | + } | |
| 1024 | + const storageClass = o.storageClass === undefined || o.storageClass === null | |
| 1025 | + ? undefined | |
| 1026 | + : String(o.storageClass); | |
| 1027 | + if (storageClass !== undefined && | |
| 1028 | + !["Standard", "InfrequentAccess"].includes(storageClass) | |
| 1029 | + ) { | |
| 1030 | + __r2Reject( | |
| 1031 | + binding, | |
| 1032 | + `${method}(storageClass)`, | |
| 1033 | + `${storageClass} is not an R2 storage class`, | |
| 1034 | + ); | |
| 1035 | + } | |
| 1036 | + return { | |
| 1037 | + http: __r2Http(o.httpMetadata), | |
| 1038 | + custom, | |
| 1039 | + storageClass, | |
| 1040 | + onlyIf: __r2OnlyIf(o.onlyIf), | |
| 1041 | + verify, | |
| 1042 | + }; | |
| 1043 | +}; | |
| 1044 | +// A `put` body, as either the bytes to send in one request or the stream | |
| 1045 | +// to feed the host chunk by chunk. R2 takes all of these. | |
| 1046 | +const __r2Value = async (binding, value) => { | |
| 1047 | + if (value === undefined || value === null) return new Uint8Array(0); | |
| 1048 | + if (typeof value === "string") return new TextEncoder().encode(value); | |
| 1049 | + if (value instanceof Uint8Array) return value; | |
| 1050 | + if (ArrayBuffer.isView(value)) { | |
| 1051 | + return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); | |
| 1052 | + } | |
| 1053 | + if (value instanceof ArrayBuffer) return new Uint8Array(value); | |
| 1054 | + if (typeof Blob !== "undefined" && value instanceof Blob) { | |
| 1055 | + return new Uint8Array(await value.arrayBuffer()); | |
| 1056 | + } | |
| 1057 | + if (value && typeof value.getReader === "function") return value; | |
| 1058 | + return __r2Reject( | |
| 1059 | + binding, | |
| 1060 | + "put", | |
| 1061 | + "a body is a string, an ArrayBuffer, a view, a Blob, a ReadableStream, or null", | |
| 1062 | + ); | |
| 1063 | +}; | |
| 1064 | +// Feed a `ReadableStream` body to the host one chunk at a time. The host | |
| 1065 | +// writes one request when the whole body fits in a part and a multipart | |
| 1066 | +// upload when it does not, so a Worker can stream a body far larger than | |
| 1067 | +// its heap. | |
| 1068 | +const __r2PutStream = async (bucketName, key, stream, options) => { | |
| 1069 | + const id = Number(await __r2_put_begin(bucketName, key, JSON.stringify(options))); | |
| 1070 | + const reader = stream.getReader(); | |
| 1071 | + try { | |
| 1072 | + for (;;) { | |
| 1073 | + const { done, value } = await reader.read(); | |
| 1074 | + if (done) break; | |
| 1075 | + if (!value || value.length === 0) continue; | |
| 1076 | + await __r2_put_chunk( | |
| 1077 | + id, | |
| 1078 | + value instanceof Uint8Array | |
| 1079 | + ? value | |
| 1080 | + : new Uint8Array(value.buffer, value.byteOffset, value.byteLength), | |
| 1081 | + ); | |
| 1082 | + } | |
| 1083 | + } catch (error) { | |
| 1084 | + await __r2_put_end(id, true); | |
| 1085 | + throw error; | |
| 1086 | + } | |
| 1087 | + return JSON.parse(await __r2_put_end(id, false)); | |
| 1088 | +}; | |
| 1089 | +// One open multipart upload. `id` resolves to the host's upload id, so | |
| 1090 | +// `resumeMultipartUpload` can hand back a handle without awaiting -- as R2 | |
| 1091 | +// does -- and surface a bad id on the first method that uses it. | |
| 1092 | +const __r2Multipart = (binding, bucketName, key, id) => ({ | |
| 1093 | + key, | |
| 1094 | + get uploadId() { | |
| 1095 | + return String(id.value ?? ""); | |
| 1096 | + }, | |
| 1097 | + async uploadPart(partNumber, value, options) { | |
| 1098 | + if (options?.ssecKey !== undefined) { | |
| 1099 | + __r2Reject(binding, "uploadPart(ssecKey)", "celld has no customer-key encryption"); | |
| 1100 | + } | |
| 1101 | + const body = await __r2Value(binding, value); | |
| 1102 | + const bytes = body instanceof Uint8Array ? body : await __r2Drain(body); | |
| 1103 | + const r = JSON.parse(await __r2_mp_part(await id.host, partNumber | 0, bytes)); | |
| 1104 | + // The object store owns the part list this completion acts on, so it | |
| 1105 | + // never hands back a part etag to name one with. | |
| 1106 | + return { partNumber: r.partNumber, etag: "" }; | |
| 1107 | + }, | |
| 1108 | + async complete(parts) { | |
| 1109 | + const numbers = (parts ?? []).map((part) => part.partNumber | 0); | |
| 1110 | + return __r2Object(JSON.parse( | |
| 1111 | + await __r2_mp_complete(await id.host, JSON.stringify(numbers)), | |
| 1112 | + )); | |
| 1113 | + }, | |
| 1114 | + async abort() { | |
| 1115 | + await __r2_mp_abort(await id.host); | |
| 1116 | + }, | |
| 1117 | +}); | |
| 1118 | +__celld.__makeR2Bucket = (binding, bucketName) => ({ | |
| 1119 | + async head(key) { | |
| 1120 | + const name = __r2Key(binding, "head", key); | |
| 1121 | + const r = JSON.parse(await __r2_head(bucketName, name)); | |
| 1122 | + return r.state === "miss" ? null : __r2Object(r.object); | |
| 1123 | + }, | |
| 1124 | + async get(key, options) { | |
| 1125 | + const name = __r2Key(binding, "get", key); | |
| 1126 | + const o = options ?? {}; | |
| 1127 | + if (o.ssecKey !== undefined) { | |
| 1128 | + __r2Reject(binding, "get(ssecKey)", "celld has no customer-key encryption"); | |
| 1129 | + } | |
| 1130 | + const request = { | |
| 1131 | + range: __r2Range(binding, o.range), | |
| 1132 | + onlyIf: __r2OnlyIf(o.onlyIf), | |
| 1133 | + }; | |
| 1134 | + const r = JSON.parse(await __r2_get(bucketName, name, JSON.stringify(request))); | |
| 1135 | + if (r.state === "miss") return null; | |
| 1136 | + // A refused `onlyIf` answers the object without its body, which is how | |
| 1137 | + // a caller tells "not modified" from "not there". | |
| 1138 | + if (r.state === "unmet") return __r2Object(r.object); | |
| 1139 | + return __r2Object(r.object, new CelldHttpBodyStream(r.streamId)); | |
| 1140 | + }, | |
| 1141 | + async put(key, value, options) { | |
| 1142 | + const name = __r2Key(binding, "put", key); | |
| 1143 | + const write = __r2WriteOptions(binding, "put", options); | |
| 1144 | + const body = await __r2Value(binding, value); | |
| 1145 | + const r = body instanceof Uint8Array | |
| 1146 | + ? JSON.parse(await __r2_put(bucketName, name, body, JSON.stringify(write))) | |
| 1147 | + : await __r2PutStream(bucketName, name, body, write); | |
| 1148 | + // R2 answers a refused `onlyIf` with `null` rather than throwing. | |
| 1149 | + return r.stored ? __r2Object(r.object) : null; | |
| 1150 | + }, | |
| 1151 | + async delete(keys) { | |
| 1152 | + const list = (Array.isArray(keys) ? keys : [keys]).map((key) => | |
| 1153 | + __r2Key(binding, "delete", key) | |
| 1154 | + ); | |
| 1155 | + if (list.length > 1000) { | |
| 1156 | + throw new Error( | |
| 1157 | + `R2 delete (binding ${binding}) takes at most 1000 keys, not ${list.length}`, | |
| 1158 | + ); | |
| 1159 | + } | |
| 1160 | + if (list.length) await __r2_delete(bucketName, JSON.stringify(list)); | |
| 1161 | + }, | |
| 1162 | + async list(options) { | |
| 1163 | + const o = options ?? {}; | |
| 1164 | + const include = Array.isArray(o.include) ? o.include : []; | |
| 1165 | + for (const entry of include) { | |
| 1166 | + if (!["httpMetadata", "customMetadata"].includes(entry)) { | |
| 1167 | + __r2Reject(binding, "list(include)", `${entry} is not an R2 listing extra`); | |
| 1168 | + } | |
| 1169 | + } | |
| 1170 | + const request = { | |
| 1171 | + prefix: o.prefix === undefined || o.prefix === null ? "" : String(o.prefix), | |
| 1172 | + cursor: o.cursor === undefined || o.cursor === null ? null : String(o.cursor), | |
| 1173 | + startAfter: o.startAfter === undefined || o.startAfter === null | |
| 1174 | + ? null | |
| 1175 | + : String(o.startAfter), | |
| 1176 | + limit: o.limit === undefined || o.limit === null ? 0 : o.limit | 0, | |
| 1177 | + delimiter: o.delimiter === undefined || o.delimiter === null | |
| 1178 | + ? null | |
| 1179 | + : String(o.delimiter), | |
| 1180 | + include: include.length > 0, | |
| 1181 | + }; | |
| 1182 | + const r = JSON.parse(await __r2_list(bucketName, JSON.stringify(request))); | |
| 1183 | + const objects = r.objects.map((object) => { | |
| 1184 | + // A listing carries the extras it was asked for and nothing else, | |
| 1185 | + // so a caller cannot mistake an empty map for an empty object. | |
| 1186 | + if (!include.includes("httpMetadata")) object.http = {}; | |
| 1187 | + if (!include.includes("customMetadata")) object.custom = {}; | |
| 1188 | + return __r2Object(object); | |
| 1189 | + }); | |
| 1190 | + // R2 omits `cursor` entirely when the listing is complete, and callers | |
| 1191 | + // test `truncated` before reading it. | |
| 1192 | + const page = { objects, truncated: r.truncated, delimitedPrefixes: r.prefixes }; | |
| 1193 | + if (r.truncated && r.cursor) page.cursor = r.cursor; | |
| 1194 | + return page; | |
| 1195 | + }, | |
| 1196 | + async createMultipartUpload(key, options) { | |
| 1197 | + const name = __r2Key(binding, "createMultipartUpload", key); | |
| 1198 | + const write = __r2WriteOptions(binding, "createMultipartUpload", options); | |
| 1199 | + if (write.onlyIf) { | |
| 1200 | + __r2Reject( | |
| 1201 | + binding, | |
| 1202 | + "createMultipartUpload(onlyIf)", | |
| 1203 | + "a multipart completion takes no precondition", | |
| 1204 | + ); | |
| 1205 | + } | |
| 1206 | + // R2 takes a checksum on `put`, which sees the whole body, and not on a | |
| 1207 | + // multipart upload, which never does. | |
| 1208 | + for (const name of Object.keys(write.verify)) { | |
| 1209 | + __r2Reject(binding, `createMultipartUpload(${name})`, "R2 takes a checksum on `put`"); | |
| 1210 | + } | |
| 1211 | + const uploadId = await __r2_mp_begin(bucketName, name, JSON.stringify(write)); | |
| 1212 | + return __r2Multipart(binding, bucketName, name, { | |
| 1213 | + value: uploadId, | |
| 1214 | + host: Promise.resolve(Number(uploadId)), | |
| 1215 | + }); | |
| 1216 | + }, | |
| 1217 | + // R2 hands back a handle without checking it; so does this, and the | |
| 1218 | + // first method that uses it says whether the upload is still open. | |
| 1219 | + resumeMultipartUpload(key, uploadId) { | |
| 1220 | + const name = __r2Key(binding, "resumeMultipartUpload", key); | |
| 1221 | + const id = String(uploadId); | |
| 1222 | + const host = __r2_mp_resume(bucketName, name, id).then(Number); | |
| 1223 | + // A handle nobody uses must not become an unhandled rejection; the | |
| 1224 | + // first method that awaits `host` still sees the failure. | |
| 1225 | + host.catch(() => {}); | |
| 1226 | + return __r2Multipart(binding, bucketName, name, { value: id, host }); | |
| 1227 | + }, | |
| 1228 | +}); | |
| 1229 | +// A host timer op resolves once, so an interval arms a new one after every | |
| 1230 | +// round. `__timers` maps the id the caller holds to the op that is armed | |
| 1231 | +// right now: for a timeout that is the same id, and for an interval it is a | |
| 1232 | +// fresh id each round. Clearing therefore cancels the armed op, not the id. | |
| 1233 | +const __timers = new Map(); | |
| 1234 | +const __clearTimer = (id) => { | |
| 1235 | + const armed = __timers.get(id); | |
| 1236 | + if (armed === undefined) return; | |
| 1237 | + __timers.delete(id); | |
| 1238 | + __timer_cancel(armed); | |
| 1239 | +}; | |
| 1240 | +globalThis.setTimeout = (cb, ms, ...a) => { | |
| 1241 | + const id = __timer_alloc(); | |
| 1242 | + __timers.set(id, id); | |
| 1243 | + __op_timer(id, ms | 0).then(() => { | |
| 1244 | + if (!__timers.delete(id)) return; | |
| 1245 | + cb(...a); | |
| 1246 | + }); | |
| 1247 | + return id; | |
| 1248 | +}; | |
| 1249 | +globalThis.setInterval = (cb, ms, ...a) => { | |
| 1250 | + const id = __timer_alloc(); | |
| 1251 | + const delay = ms | 0; | |
| 1252 | + const arm = (armed) => { | |
| 1253 | + __timers.set(id, armed); | |
| 1254 | + __op_timer(armed, delay).then(() => { | |
| 1255 | + // Cancelling drops the entry and cancelling then re-arming replaces | |
| 1256 | + // it, so a round whose op is no longer the armed one is dead and | |
| 1257 | + // stops here. A cancelled op still resolves, which is why this test | |
| 1258 | + // is on identity and not on the op alone. | |
| 1259 | + if (__timers.get(id) !== armed) return; | |
| 1260 | + // Arm the next round before the callback runs. A `clearInterval` | |
| 1261 | + // inside the callback must end the interval, and arming after the | |
| 1262 | + // callback would undo it. | |
| 1263 | + arm(__timer_alloc()); | |
| 1264 | + cb(...a); | |
| 1265 | + }); | |
| 1266 | + }; | |
| 1267 | + arm(id); | |
| 1268 | + return id; | |
| 1269 | +}; | |
| 1270 | +// One id space and one cancel, because a caller can cross the two. | |
| 1271 | +globalThis.clearTimeout = __clearTimer; | |
| 1272 | +globalThis.clearInterval = __clearTimer; | |
| 1273 | + | |
| 1274 | +const __sqlCursorFinalizer = typeof FinalizationRegistry === "function" | |
| 1275 | + ? new FinalizationRegistry((cursorId) => __sql_cursor_close(cursorId)) | |
| 1276 | + : null; | |
| 1277 | + | |
| 1278 | +// A `SqlStorageCursor` over one exec's result (Cloudflare DO SQL API). | |
| 1279 | +class SqlCursor { | |
| 1280 | + // `res` is what `__sql_cursor_start` returns: V8 values throughout, with the | |
| 1281 | + // first row already stepped. A failing query throws out of the op, so there | |
| 1282 | + // is no in-band error field to test here. | |
| 1283 | + constructor(res) { | |
| 1284 | + this.columns = res.columns; | |
| 1285 | + this.rowsWritten = Number(res.rowsWritten || 0); | |
| 1286 | + this.reusedCachedQueryForTest = Boolean(res.reusedCachedQuery); | |
| 1287 | + this._deferredError = null; | |
| 1288 | + this._cursorId = Number(res.cursorId || 0); | |
| 1289 | + this._prefetched = res.row; | |
| 1290 | + this.rowsRead = this._prefetched === null ? 0 : 1; | |
| 1291 | + this._finalizerToken = null; | |
| 1292 | + if (this._cursorId && __sqlCursorFinalizer) { | |
| 1293 | + this._finalizerToken = {}; | |
| 1294 | + __sqlCursorFinalizer.register( | |
| 1295 | + this, this._cursorId, this._finalizerToken, | |
| 1296 | + ); | |
| 1297 | + } | |
| 1298 | + } | |
| 1299 | + _obj(r) { const o = {}; for (let i = 0; i < this.columns.length; i++) o[this.columns[i]] = r[i]; return o; } | |
| 1300 | + _finishNative() { | |
| 1301 | + if (this._finalizerToken && __sqlCursorFinalizer) | |
| 1302 | + __sqlCursorFinalizer.unregister(this._finalizerToken); | |
| 1303 | + this._finalizerToken = null; | |
| 1304 | + this._cursorId = 0; | |
| 1305 | + } | |
| 1306 | + _advanceNative() { | |
| 1307 | + if (!this._cursorId) { | |
| 1308 | + this._prefetched = null; | |
| 1309 | + return; | |
| 1310 | + } | |
| 1311 | + // The op answers with V8 values, not JSON: an array is a row, a number is | |
| 1312 | + // the cursor's final rowsWritten, and a failure throws. The throw is | |
| 1313 | + // caught and deferred, because a consumer must still receive the last good | |
| 1314 | + // row -- the error belongs to the call after it, not to this one. | |
| 1315 | + let result; | |
| 1316 | + try { | |
| 1317 | + result = __sql_cursor_next(this._cursorId); | |
| 1318 | + } catch (error) { | |
| 1319 | + this._deferredError = error; | |
| 1320 | + this._prefetched = null; | |
| 1321 | + this._finishNative(); | |
| 1322 | + return; | |
| 1323 | + } | |
| 1324 | + if (Array.isArray(result)) { | |
| 1325 | + this._prefetched = result; | |
| 1326 | + this.rowsRead++; | |
| 1327 | + return; | |
| 1328 | + } | |
| 1329 | + this.rowsWritten = Number(result || this.rowsWritten); | |
| 1330 | + this._prefetched = null; | |
| 1331 | + this._finishNative(); | |
| 1332 | + } | |
| 1333 | + _nextRaw() { | |
| 1334 | + if (this._deferredError) { | |
| 1335 | + const error = this._deferredError; | |
| 1336 | + this._deferredError = null; | |
| 1337 | + throw error; | |
| 1338 | + } | |
| 1339 | + if (this._prefetched === null) return { done: true }; | |
| 1340 | + const value = this._prefetched; | |
| 1341 | + this._advanceNative(); | |
| 1342 | + return { done: false, value }; | |
| 1343 | + } | |
| 1344 | + toArray() { | |
| 1345 | + const rows = []; | |
| 1346 | + while (true) { | |
| 1347 | + const result = this.next(); | |
| 1348 | + if (result.done) return rows; | |
| 1349 | + rows.push(result.value); | |
| 1350 | + if (__heap_limit_excessively_exceeded()) | |
| 1351 | + throw new Error( | |
| 1352 | + "the isolate is over its V8 heap limit, so it stopped " + | |
| 1353 | + "materializing a result set (see CELLD_V8_HEAP_LIMIT_MB)"); | |
| 1354 | + } | |
| 1355 | + } | |
| 1356 | + one() { | |
| 1357 | + const first = this.next(); | |
| 1358 | + if (first.done) | |
| 1359 | + throw new Error("Expected exactly one result from SQL query, but got no results"); | |
| 1360 | + if (!this.next().done) | |
| 1361 | + throw new Error("Expected exactly one result from SQL query, but got multiple results"); | |
| 1362 | + return first.value; | |
| 1363 | + } | |
| 1364 | + *raw() { | |
| 1365 | + while (true) { | |
| 1366 | + const result = this._nextRaw(); | |
| 1367 | + if (result.done) return; | |
| 1368 | + yield result.value; | |
| 1369 | + } | |
| 1370 | + } | |
| 1371 | + get columnNames() { return this.columns; } | |
| 1372 | + next() { | |
| 1373 | + const result = this._nextRaw(); | |
| 1374 | + return result.done ? result : { done: false, value: this._obj(result.value) }; | |
| 1375 | + } | |
| 1376 | + [Symbol.iterator]() { return this; } | |
| 1377 | +} | |
| 1378 | +class SqlStorage { | |
| 1379 | + // The state is what the abort guard in `exec` reads; a storage built | |
| 1380 | + // without one would bypass the guard silently. | |
| 1381 | + constructor(scope, state, storage) { | |
| 1382 | + if (!state) throw new TypeError("SqlStorage requires its DurableObjectState"); | |
| 1383 | + this._scope = scope; | |
| 1384 | + this._state = state; | |
| 1385 | + this._storage = storage; | |
| 1386 | + } | |
| 1387 | + prepare(query) { | |
| 1388 | + this._storage._assertTransactionActive("sql.prepare"); | |
| 1389 | + const storage = this; | |
| 1390 | + const source = String(query); | |
| 1391 | + return (...binds) => storage.exec(source, ...binds); | |
| 1392 | + } | |
| 1393 | + exec(query, ...binds) { | |
| 1394 | + this._storage._assertTransactionActive("sql.exec"); | |
| 1395 | + // A callback that outlived its block runs on an object that was reset, | |
| 1396 | + // whose replacement uses the same connection: a statement from it | |
| 1397 | + // would land in the replacement's state. The KV surface drops such | |
| 1398 | + // writes silently; SQL refuses aloud, since a cursor can carry reads. | |
| 1399 | + if (this._state._aborted) { | |
| 1400 | + throw new Error("the Durable Object was reset; this event's storage is closed"); | |
| 1401 | + } | |
| 1402 | + const jsonBinds = []; | |
| 1403 | + const byteBinds = []; | |
| 1404 | + for (let index = 0; index < binds.length; index++) { | |
| 1405 | + const value = binds[index]; | |
| 1406 | + let bytes; | |
| 1407 | + if (value instanceof ArrayBuffer) { | |
| 1408 | + bytes = new Uint8Array(value); | |
| 1409 | + } else if (ArrayBuffer.isView(value)) { | |
| 1410 | + bytes = new Uint8Array( | |
| 1411 | + value.buffer, value.byteOffset, value.byteLength, | |
| 1412 | + ); | |
| 1413 | + } | |
| 1414 | + if (bytes === undefined) { | |
| 1415 | + jsonBinds.push(value); | |
| 1416 | + } else { | |
| 1417 | + // Copy every buffer before JSON.stringify can call a later value's | |
| 1418 | + // toJSON(). That callback can resize, detach, or mutate this backing | |
| 1419 | + // buffer, but exec() has already accepted the bytes at this point. | |
| 1420 | + byteBinds.push([index, new Uint8Array(bytes)]); | |
| 1421 | + jsonBinds.push(null); | |
| 1422 | + } | |
| 1423 | + } | |
| 1424 | + const json = JSON.stringify(jsonBinds); | |
| 1425 | + return new SqlCursor(byteBinds.length === 0 | |
| 1426 | + ? __sql_cursor_start(this._scope, query, json) | |
| 1427 | + : __sql_cursor_start(this._scope, query, json, byteBinds)); | |
| 1428 | + } | |
| 1429 | + ingest(input) { | |
| 1430 | + this._storage._assertTransactionActive("sql.ingest"); | |
| 1431 | + const result = JSON.parse(__sql_ingest(this._scope, String(input))); | |
| 1432 | + if (result.error) throw new Error("SQL error: " + result.error); | |
| 1433 | + return result; | |
| 1434 | + } | |
| 1435 | + get databaseSize() { | |
| 1436 | + this._storage._assertTransactionActive("sql.databaseSize"); | |
| 1437 | + return __sql_database_size(this._scope); | |
| 1438 | + } | |
| 1439 | + setMaxPageCountForTest(pages) { | |
| 1440 | + if (typeof __sql_set_max_page_count_for_test !== "function") | |
| 1441 | + throw new Error("setMaxPageCountForTest is only available in tests"); | |
| 1442 | + __sql_set_max_page_count_for_test(this._scope, Number(pages)); | |
| 1443 | + } | |
| 1444 | + setWriteFaultForTest(enabled) { | |
| 1445 | + if (typeof __sql_set_write_fault_for_test !== "function") | |
| 1446 | + throw new Error("setWriteFaultForTest is only available in tests"); | |
| 1447 | + __sql_set_write_fault_for_test(!!enabled); | |
| 1448 | + } | |
| 1449 | + setCacheSizeForTest(pages) { | |
| 1450 | + if (typeof __sql_set_cache_size_for_test !== "function") | |
| 1451 | + throw new Error("setCacheSizeForTest is only available in tests"); | |
| 1452 | + __sql_set_cache_size_for_test(this._scope, Number(pages)); | |
| 1453 | + } | |
| 1454 | + setInterruptFaultForTest(enabled) { | |
| 1455 | + if (typeof __sql_set_interrupt_fault_for_test !== "function") | |
| 1456 | + throw new Error( | |
| 1457 | + "setInterruptFaultForTest is only available in tests"); | |
| 1458 | + __sql_set_interrupt_fault_for_test(this._scope, !!enabled); | |
| 1459 | + } | |
| 1460 | + registerNomemFunctionForTest() { | |
| 1461 | + if (typeof __sql_register_nomem_function_for_test !== "function") | |
| 1462 | + throw new Error( | |
| 1463 | + "registerNomemFunctionForTest is only available in tests"); | |
| 1464 | + __sql_register_nomem_function_for_test(this._scope); | |
| 1465 | + } | |
| 1466 | +} | |
| 1467 | +function __readStoredValue(scope, key, read) { | |
| 1468 | + try { | |
| 1469 | + return read(); | |
| 1470 | + } catch (error) { | |
| 1471 | + const message = String(error && error.message || error); | |
| 1472 | + if (!message.toLowerCase().includes("deserialize cloned data")) | |
| 1473 | + throw error; | |
| 1474 | + const contextual = new Error( | |
| 1475 | + "actor storage deserialization failed; actorId = " + | |
| 1476 | + scope + "; key = " + key + "; " + message, | |
| 1477 | + ); | |
| 1478 | + contextual.cause = error; | |
| 1479 | + throw contextual; | |
| 1480 | + } | |
| 1481 | +} | |
| 1482 | +class SyncKvListIterator { | |
| 1483 | + constructor(root, generation, cursor) { | |
| 1484 | + this._root = root; | |
| 1485 | + this._generation = generation; | |
| 1486 | + this._cursor = cursor; | |
| 1487 | + } | |
| 1488 | + [Symbol.iterator]() { return this; } | |
| 1489 | + next() { | |
| 1490 | + if (this._generation !== this._root._syncKvListGeneration) { | |
| 1491 | + throw new Error( | |
| 1492 | + "kv.list() iterator was invalidated because a new call to kv.list() was started. " + | |
| 1493 | + "Only one kv.list() iterator can exist at a time.", | |
| 1494 | + ); | |
| 1495 | + } | |
| 1496 | + const value = | |
| 1497 | + __storage_sync_list_next(this._cursor, __storedSentinel); | |
| 1498 | + if (value === null) return { done: true, value: undefined }; | |
| 1499 | + value[1] = __unwrapStored(value[1]); | |
| 1500 | + return { done: false, value }; | |
| 1501 | + } | |
| 1502 | +} | |
| 1503 | +class SyncKvStorage { | |
| 1504 | + constructor(storage) { | |
| 1505 | + this._storage = storage; | |
| 1506 | + this._root = storage._transactionRoot; | |
| 1507 | + } | |
| 1508 | + get(key) { | |
| 1509 | + this._storage._assertTransactionActive("kv.get"); | |
| 1510 | + key = String(key); | |
| 1511 | + return __unwrapStored(__readStoredValue( | |
| 1512 | + this._storage._scope, key, | |
| 1513 | + () => __storage_get(this._storage._scope, key, | |
| 1514 | + __storedSentinel), | |
| 1515 | + )); | |
| 1516 | + } | |
| 1517 | + put(key, value) { | |
| 1518 | + this._storage._assertTransactionActive("kv.put"); | |
| 1519 | + key = String(key); | |
| 1520 | + try { | |
| 1521 | + __storage_put(this._storage._scope, key, value); | |
| 1522 | + } catch (error) { | |
| 1523 | + __storage_put_serialized(this._storage._scope, key, | |
| 1524 | + __storedBytes(value, error)); | |
| 1525 | + } | |
| 1526 | + } | |
| 1527 | + delete(key) { | |
| 1528 | + this._storage._assertTransactionActive("kv.delete"); | |
| 1529 | + return __storage_delete(this._storage._scope, String(key)); | |
| 1530 | + } | |
| 1531 | + list(options = {}) { | |
| 1532 | + this._storage._assertTransactionActive("kv.list"); | |
| 1533 | + const generation = ++this._root._syncKvListGeneration; | |
| 1534 | + const cursor = __storage_sync_list_start( | |
| 1535 | + this._storage._scope, JSON.stringify(options), | |
| 1536 | + ); | |
| 1537 | + return new SyncKvListIterator( | |
| 1538 | + this._root, generation, cursor, | |
| 1539 | + ); | |
| 1540 | + } | |
| 1541 | +} | |
| 1542 | +class DurableObjectStorage { | |
| 1543 | + constructor( | |
| 1544 | + scope, | |
| 1545 | + state = null, | |
| 1546 | + transactionRoot = null, | |
| 1547 | + transactionDepth = 0, | |
| 1548 | + transactionControl = null, | |
| 1549 | + ) { | |
| 1550 | + this._scope = scope; | |
| 1551 | + this._state = state; | |
| 1552 | + this.sql = new SqlStorage(scope, state, this); | |
| 1553 | + this._transactionRoot = transactionRoot || this; | |
| 1554 | + this._transactionDepth = transactionDepth; | |
| 1555 | + this._transactionControl = transactionControl; | |
| 1556 | + if (!transactionRoot) { | |
| 1557 | + this._transactionSerial = 0; | |
| 1558 | + this._transactionTail = Promise.resolve(); | |
| 1559 | + this._transactionOwner = ""; | |
| 1560 | + this._activeTransaction = null; | |
| 1561 | + this._syncKvListGeneration = 0; | |
| 1562 | + } | |
| 1563 | + this._kv = new SyncKvStorage(this); | |
| 1564 | + } | |
| 1565 | + get kv() { return this._kv; } | |
| 1566 | + _transactionStatus() { | |
| 1567 | + let status = null; | |
| 1568 | + for (let control = this._transactionControl; control; control = control.parent) { | |
| 1569 | + if (control.rolledBack) return "rolled back"; | |
| 1570 | + if (control.committed) status = "committed"; | |
| 1571 | + } | |
| 1572 | + return status; | |
| 1573 | + } | |
| 1574 | + _assertTransactionActive(operation) { | |
| 1575 | + const status = this._transactionStatus(); | |
| 1576 | + if (status) throw new Error("Cannot " + operation + "() on " + status + " transaction"); | |
| 1577 | + } | |
| 1578 | + _flushPendingPuts() { | |
| 1579 | + // An admitted put can resume after its boundary flushed and ended the | |
| 1580 | + // transaction. Its promise completes without flushing a later scope. | |
| 1581 | + if (this._transactionStatus()) return false; | |
| 1582 | + if (this._state && this._state._aborted) return false; | |
| 1583 | + __storage_flush_pending_puts(this._scope); | |
| 1584 | + return true; | |
| 1585 | + } | |
| 1586 | + async get(k) { | |
| 1587 | + this._assertTransactionActive("get"); | |
| 1588 | + // Transaction operations reach SQLite before their caller can roll back. | |
| 1589 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1590 | + if (!this._flushPendingPuts()) return; | |
| 1591 | + const key = Array.isArray(k) ? JSON.stringify(k) : String(k); | |
| 1592 | + return __readStoredValue(this._scope, key, () => { | |
| 1593 | + if (Array.isArray(k)) | |
| 1594 | + return __unwrapStoredMap( | |
| 1595 | + __storage_get_many(this._scope, k, __storedSentinel)); | |
| 1596 | + return __unwrapStored( | |
| 1597 | + __storage_get(this._scope, k, __storedSentinel)); | |
| 1598 | + }); | |
| 1599 | + } | |
| 1600 | + async put(k, val) { | |
| 1601 | + this._assertTransactionActive("put"); | |
| 1602 | + if (typeof k === "string") { | |
| 1603 | + try { | |
| 1604 | + __storage_queue_put(this._scope, k, val); | |
| 1605 | + } catch (error) { | |
| 1606 | + __storage_queue_put_serialized(this._scope, k, | |
| 1607 | + __storedBytes(val, error)); | |
| 1608 | + } | |
| 1609 | + await Promise.resolve(); | |
| 1610 | + this._flushPendingPuts(); | |
| 1611 | + return; | |
| 1612 | + } | |
| 1613 | + const source = k instanceof Map ? Array.from(k) : Object.entries(k); | |
| 1614 | + if (source.length === 0) return; | |
| 1615 | + const entries = | |
| 1616 | + source.map(([key, value]) => [String(key), value]); | |
| 1617 | + try { | |
| 1618 | + __storage_queue_put_many(this._scope, entries); | |
| 1619 | + } catch (error) { | |
| 1620 | + // A batch with a stub entry: encode every entry first (plain | |
| 1621 | + // entries keep their native clone bytes, stub entries take | |
| 1622 | + // the stored-stub envelope), then queue -- so a genuinely | |
| 1623 | + // uncloneable entry still queues nothing, like the batch op, | |
| 1624 | + // which serializes fully before queueing. | |
| 1625 | + const encoded = entries.map(([key, value]) => { | |
| 1626 | + try { | |
| 1627 | + return [key, __sc_encode(value)]; | |
| 1628 | + } catch (error_) { | |
| 1629 | + return [key, __storedBytes(value, error_)]; | |
| 1630 | + } | |
| 1631 | + }); | |
| 1632 | + for (const [key, bytes] of encoded) | |
| 1633 | + __storage_queue_put_serialized(this._scope, key, bytes); | |
| 1634 | + } | |
| 1635 | + await Promise.resolve(); | |
| 1636 | + this._flushPendingPuts(); | |
| 1637 | + } | |
| 1638 | + async delete(k) { | |
| 1639 | + this._assertTransactionActive("delete"); | |
| 1640 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1641 | + if (!this._flushPendingPuts()) return; | |
| 1642 | + if (Array.isArray(k)) { | |
| 1643 | + if (k.length === 0) return 0; | |
| 1644 | + return __storage_delete_many(this._scope, k); | |
| 1645 | + } | |
| 1646 | + return __storage_delete(this._scope, k); | |
| 1647 | + } | |
| 1648 | + async list(options = {}) { | |
| 1649 | + this._assertTransactionActive("list"); | |
| 1650 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1651 | + if (!this._flushPendingPuts()) return new Map(); | |
| 1652 | + return __unwrapStoredMap(__storage_list( | |
| 1653 | + this._scope, JSON.stringify(options), __storedSentinel)); | |
| 1654 | + } | |
| 1655 | + async deleteAll() { | |
| 1656 | + this._assertTransactionActive("deleteAll"); | |
| 1657 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1658 | + if (!this._flushPendingPuts()) return; | |
| 1659 | + __storage_delete_all(this._scope, __cell.deleteAllDeletesAlarm); | |
| 1660 | + } | |
| 1661 | + // Resolves once every write this cell committed before the call is | |
| 1662 | + // proven durable, by the proof the output gate requires before it releases | |
| 1663 | + // an egress. Workerd resolves when the pending writes have completed; on | |
| 1664 | + // celld the local file is a cache, so "completed" is "proven". The host op | |
| 1665 | + // rejects when that proof fails or times out, so an application never | |
| 1666 | + // treats a lost write as safe. | |
| 1667 | + async sync() { | |
| 1668 | + this._assertTransactionActive("sync"); | |
| 1669 | + await Promise.resolve(); | |
| 1670 | + const status = this._transactionStatus(); | |
| 1671 | + // An admitted sync can resume after transactionSync commits or rolls | |
| 1672 | + // back. Its boundary settled the queued puts, so prove the surviving | |
| 1673 | + // state without flushing a later transaction through this handle. A | |
| 1674 | + // new call after that boundary still fails the entry guard above. | |
| 1675 | + if (this._state?._aborted || (status === null && !this._flushPendingPuts())) | |
| 1676 | + throw new Error( | |
| 1677 | + "storage.sync: " + this._scope + " was aborted; the object is no " + | |
| 1678 | + "longer running"); | |
| 1679 | + await __storage_sync(this._scope); | |
| 1680 | + } | |
| 1681 | + async setAlarm(t) { | |
| 1682 | + this._assertTransactionActive("setAlarm"); | |
| 1683 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1684 | + if (!this._flushPendingPuts()) return; | |
| 1685 | + if (this._state?._facetDepth > 0) | |
| 1686 | + throw new Error("Facets currently cannot set alarms."); | |
| 1687 | + __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); | |
| 1688 | + } | |
| 1689 | + async getAlarm() { | |
| 1690 | + this._assertTransactionActive("getAlarm"); | |
| 1691 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1692 | + if (!this._flushPendingPuts()) return null; | |
| 1693 | + const v = __alarm_get(this._scope); | |
| 1694 | + return v === null ? null : v; | |
| 1695 | + } | |
| 1696 | + async deleteAlarm() { | |
| 1697 | + this._assertTransactionActive("deleteAlarm"); | |
| 1698 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1699 | + if (!this._flushPendingPuts()) return; | |
| 1700 | + __alarm_delete(this._scope); | |
| 1701 | + } | |
| 1702 | + _transactionStart() { | |
| 1703 | + const root = this._transactionRoot; | |
| 1704 | + const savepoint = "cells_tx_" + (++root._transactionSerial); | |
| 1705 | + __storage_transaction_control( | |
| 1706 | + this._scope, "start", this._transactionDepth > 0, savepoint, | |
| 1707 | + ); | |
| 1708 | + return savepoint; | |
| 1709 | + } | |
| 1710 | + _transactionCommit(savepoint) { | |
| 1711 | + __storage_transaction_control( | |
| 1712 | + this._scope, "commit", this._transactionDepth > 0, savepoint, | |
| 1713 | + ); | |
| 1714 | + } | |
| 1715 | + _transactionRollback(savepoint, explicit = false) { | |
| 1716 | + __storage_transaction_control( | |
| 1717 | + this._scope, | |
| 1718 | + explicit ? "rollback_explicit" : "rollback", | |
| 1719 | + this._transactionDepth > 0, | |
| 1720 | + savepoint, | |
| 1721 | + ); | |
| 1722 | + } | |
| 1723 | + _transactionView(transactionControl) { | |
| 1724 | + return new DurableObjectStorage( | |
| 1725 | + this._scope, | |
| 1726 | + this._state, | |
| 1727 | + this._transactionRoot, | |
| 1728 | + this._transactionDepth + 1, | |
| 1729 | + transactionControl, | |
| 1730 | + ); | |
| 1731 | + } | |
| 1732 | + rollback() { | |
| 1733 | + const control = this._transactionControl; | |
| 1734 | + if (!control) | |
| 1735 | + throw new TypeError("rollback() must be called on a transaction"); | |
| 1736 | + if (control.rolledBack) return; | |
| 1737 | + this._assertTransactionActive("rollback"); | |
| 1738 | + // An asynchronous child can still own a nested savepoint. Mark this view | |
| 1739 | + // terminal now, but let its runner release the child before it rolls this | |
| 1740 | + // layer back. | |
| 1741 | + if (control.pending.size === 0) control.rollback(); | |
| 1742 | + control.rolledBack = true; | |
| 1743 | + } | |
| 1744 | + transactionSync(f) { | |
| 1745 | + this._assertTransactionActive("transactionSync"); | |
| 1746 | + const root = this._transactionRoot; | |
| 1747 | + const owner = String(__io_context_id()); | |
| 1748 | + if (this._transactionDepth === 0 && owner !== "" && | |
| 1749 | + root._transactionOwner === owner && root._activeTransaction !== null) | |
| 1750 | + return root._activeTransaction.transactionSync(f); | |
| 1751 | + const savepoint = this._transactionStart(); | |
| 1752 | + const control = this._newTransactionControl(savepoint); | |
| 1753 | + try { | |
| 1754 | + const value = f(this._transactionView(control)); | |
| 1755 | + if (!control.rolledBack) { | |
| 1756 | + this._transactionCommit(savepoint); | |
| 1757 | + control.committed = true; | |
| 1758 | + } | |
| 1759 | + return value; | |
| 1760 | + } catch (error) { | |
| 1761 | + if (!control.rolledBack) { | |
| 1762 | + try { | |
| 1763 | + this._transactionRollback(savepoint); | |
| 1764 | + control.rolledBack = true; | |
| 1765 | + } catch (rollbackError) { | |
| 1766 | + this._abortAfterFailedRollback(rollbackError, error); | |
| 1767 | + } | |
| 1768 | + } | |
| 1769 | + throw error; | |
| 1770 | + } | |
| 1771 | + } | |
| 1772 | + _newTransactionControl(savepoint) { | |
| 1773 | + const control = { | |
| 1774 | + rolledBack: false, | |
| 1775 | + rollbackPerformed: false, | |
| 1776 | + committed: false, | |
| 1777 | + parent: this._transactionControl, | |
| 1778 | + pending: new Set(), | |
| 1779 | + rollback: () => { | |
| 1780 | + this._transactionRollback(savepoint, true); | |
| 1781 | + control.rollbackPerformed = true; | |
| 1782 | + }, | |
| 1783 | + }; | |
| 1784 | + return control; | |
| 1785 | + } | |
| 1786 | + async _drainNestedTransactions(control) { | |
| 1787 | + while (control.pending.size !== 0) | |
| 1788 | + await Promise.allSettled(Array.from(control.pending)); | |
| 1789 | + } | |
| 1790 | + async _runTransactionWith(f, savepoint, control) { | |
| 1791 | + const view = this._transactionView(control); | |
| 1792 | + const root = this._transactionRoot; | |
| 1793 | + const owner = String(__io_context_id()); | |
| 1794 | + const installsActive = owner !== "" && root._transactionOwner === owner; | |
| 1795 | + const previousActive = root._activeTransaction; | |
| 1796 | + if (installsActive) root._activeTransaction = view; | |
| 1797 | + try { | |
| 1798 | + const value = await f(view); | |
| 1799 | + // A helper can start a reentrant transaction through the root storage | |
| 1800 | + // handle and omit the returned promise. That child already owns a | |
| 1801 | + // savepoint, so ending this layer first would make SQLite release the | |
| 1802 | + // child's savepoint and let its continuation run against a false owner. | |
| 1803 | + await this._drainNestedTransactions(control); | |
| 1804 | + if (!control.rolledBack) { | |
| 1805 | + this._transactionCommit(savepoint); | |
| 1806 | + control.committed = true; | |
| 1807 | + } else if (!control.rollbackPerformed) { | |
| 1808 | + control.rollback(); | |
| 1809 | + } | |
| 1810 | + return value; | |
| 1811 | + } catch (error) { | |
| 1812 | + await this._drainNestedTransactions(control); | |
| 1813 | + if (!control.rollbackPerformed) { | |
| 1814 | + // The flag records a rollback that happened, not one that was | |
| 1815 | + // attempted: a rollback that fails leaves the savepoint open, and a | |
| 1816 | + // later transaction on the same connection would commit its writes. | |
| 1817 | + // Nothing can be said about the connection then, so the object is | |
| 1818 | + // aborted rather than left to serve from it. | |
| 1819 | + try { | |
| 1820 | + this._transactionRollback(savepoint); | |
| 1821 | + control.rolledBack = true; | |
| 1822 | + control.rollbackPerformed = true; | |
| 1823 | + } catch (rollbackError) { | |
| 1824 | + this._abortAfterFailedRollback(rollbackError, error); | |
| 1825 | + } | |
| 1826 | + } | |
| 1827 | + throw error; | |
| 1828 | + } finally { | |
| 1829 | + if (installsActive && root._activeTransaction === view) | |
| 1830 | + root._activeTransaction = previousActive; | |
| 1831 | + } | |
| 1832 | + } | |
| 1833 | + // `cause` is the failure that led to the rollback; the abort's error keeps | |
| 1834 | + // it, so a debugger can walk back to the callback's own throw. The | |
| 1835 | + // rollback failure is reported even when the object is already aborted, | |
| 1836 | + // as it is after a block's limit: the abort then changes nothing, and the | |
| 1837 | + // log line is the only trace the failure leaves. | |
| 1838 | + _abortAfterFailedRollback(rollbackError, cause) { | |
| 1839 | + // Inside a catch, so the log must not become the throw that leaves it: | |
| 1840 | + // the slot release after the caller's rethrow depends on that. | |
| 1841 | + try { console.error("transaction rollback failed", rollbackError); } catch {} | |
| 1842 | + const state = this._transactionRoot._state; | |
| 1843 | + if (state && !state._aborted) { | |
| 1844 | + state.abort( | |
| 1845 | + new Error( | |
| 1846 | + "a transaction rollback failed: " + __describeFailure(rollbackError), | |
| 1847 | + { cause }, | |
| 1848 | + ), | |
| 1849 | + ); | |
| 1850 | + } | |
| 1851 | + } | |
| 1852 | + async _runTransaction(f) { | |
| 1853 | + const savepoint = this._transactionStart(); | |
| 1854 | + return this._runTransactionWith(f, savepoint, this._newTransactionControl(savepoint)); | |
| 1855 | + } | |
| 1856 | + async transaction(f) { | |
| 1857 | + this._assertTransactionActive("transaction"); | |
| 1858 | + if (this._transactionDepth > 0) { | |
| 1859 | + const nested = this._runTransaction(f); | |
| 1860 | + const pending = this._transactionControl.pending; | |
| 1861 | + pending.add(nested); | |
| 1862 | + nested.then( | |
| 1863 | + () => pending.delete(nested), | |
| 1864 | + () => pending.delete(nested), | |
| 1865 | + ); | |
| 1866 | + return nested; | |
| 1867 | + } | |
| 1868 | + const root = this._transactionRoot; | |
| 1869 | + const owner = String(__io_context_id()); | |
| 1870 | + if (owner !== "" && root._transactionOwner === owner && | |
| 1871 | + root._activeTransaction !== null) | |
| 1872 | + return root._activeTransaction.transaction(f); | |
| 1873 | + // Workerd runs the callback under blockConcurrencyWhile: the input gate | |
| 1874 | + // shuts, so no other event starts in the object while the transaction is | |
| 1875 | + // open. Without it another event's reads saw uncommitted rows, its | |
| 1876 | + // writes joined the open transaction on the same connection, and a | |
| 1877 | + // rollback discarded a write celld had already acknowledged (#714). The | |
| 1878 | + // callback's failure is caught inside the block: a failed transaction | |
| 1879 | + // rolls back and rejects, and must not reset the object the way a failed | |
| 1880 | + // critical section does. | |
| 1881 | + // | |
| 1882 | + // The tail orders transactions one event starts concurrently, which the | |
| 1883 | + // gate does not separate. Its slot is taken here, in call order: taken | |
| 1884 | + // inside the block it would be taken in the order the gate woke the | |
| 1885 | + // callers, which is not theirs to keep. It is released inside the block, | |
| 1886 | + // when the callback has settled, and not when the block has: a second | |
| 1887 | + // transaction the same event starts while the first runs rides the | |
| 1888 | + // outer hold as a nested block, and the outer block waits for nested | |
| 1889 | + // ones before it releases, so a slot held until the block's end would | |
| 1890 | + // wait on itself. | |
| 1891 | + const previous = root._transactionTail; | |
| 1892 | + let release; | |
| 1893 | + root._transactionTail = new Promise((resolve) => { release = resolve; }); | |
| 1894 | + let control = null; | |
| 1895 | + let started = false; | |
| 1896 | + let abandoned = null; | |
| 1897 | + const guarded = async () => { | |
| 1898 | + started = true; | |
| 1899 | + let ownsTransaction = false; | |
| 1900 | + try { | |
| 1901 | + await previous; | |
| 1902 | + // The block ended while this waited for its slot, or the object was | |
| 1903 | + // reset under it by an enclosing block that failed: the caller has | |
| 1904 | + // its rejection and the gate is open again, so starting the | |
| 1905 | + // transaction now would run it beside whatever the object serves. | |
| 1906 | + if (abandoned !== null) return { error: abandoned }; | |
| 1907 | + if (root._state._aborted) { | |
| 1908 | + return { error: new Error("the Durable Object was reset before the transaction started") }; | |
| 1909 | + } | |
| 1910 | + // A callback can compose a helper which reaches the root | |
| 1911 | + // `ctx.storage` handle instead of the transaction view. The input | |
| 1912 | + // gate excludes other events, but an event which entered before the | |
| 1913 | + // gate closed can still be waiting for this slot. Keep the owner with | |
| 1914 | + // the open transaction so only the callback's event takes the | |
| 1915 | + // savepoint path; another event still waits on the tail. | |
| 1916 | + root._transactionOwner = owner; | |
| 1917 | + ownsTransaction = true; | |
| 1918 | + // The start is a host op that can fail like any other statement, and | |
| 1919 | + // a failure there is the transaction's to report, not the block's: | |
| 1920 | + // a throw that escaped here would reset the object. | |
| 1921 | + try { | |
| 1922 | + const savepoint = this._transactionStart(); | |
| 1923 | + control = this._newTransactionControl(savepoint); | |
| 1924 | + return { value: await this._runTransactionWith(f, savepoint, control) }; | |
| 1925 | + } catch (error) { | |
| 1926 | + return { error }; | |
| 1927 | + } | |
| 1928 | + } finally { | |
| 1929 | + if (ownsTransaction && root._transactionOwner === owner) { | |
| 1930 | + root._activeTransaction = null; | |
| 1931 | + root._transactionOwner = ""; | |
| 1932 | + } | |
| 1933 | + release(); | |
| 1934 | + } | |
| 1935 | + }; | |
| 1936 | + let outcome; | |
| 1937 | + try { | |
| 1938 | + outcome = await root._state.blockConcurrencyWhile(guarded); | |
| 1939 | + } catch (error) { | |
| 1940 | + // The block itself failed: its limit ended the callback while it still | |
| 1941 | + // ran, or the block ahead of it failed and this one never started. A | |
| 1942 | + // transaction the callback still holds would otherwise stay open on | |
| 1943 | + // the connection the object's replacement uses, and the callback's | |
| 1944 | + // late commit would carry the replacement's writes with it. Roll it | |
| 1945 | + // back now, unless the callback's continuation committed in the same | |
| 1946 | + // tick the limit won; the callback's own commit is skipped from here | |
| 1947 | + // on. The slot stays with the callback until it settles: the callback | |
| 1948 | + // still runs on the connection, and a transaction started beside it | |
| 1949 | + // would interleave with its remaining statements. A routed child must | |
| 1950 | + // release its savepoint before this layer rolls back, so a live child | |
| 1951 | + // leaves the rollback for `_runTransactionWith`. A block that failed | |
| 1952 | + // before the callback started holds nothing, so its slot is released | |
| 1953 | + // here or nothing ever would. | |
| 1954 | + abandoned = error; | |
| 1955 | + if (control && !control.rolledBack && !control.committed) { | |
| 1956 | + try { | |
| 1957 | + if (control.pending.size === 0) control.rollback(); | |
| 1958 | + control.rolledBack = true; | |
| 1959 | + } catch (rollbackError) { | |
| 1960 | + this._abortAfterFailedRollback(rollbackError, error); | |
| 1961 | + } | |
| 1962 | + } | |
| 1963 | + if (!started) release(); | |
| 1964 | + throw error; | |
| 1965 | + } | |
| 1966 | + if ("error" in outcome) throw outcome.error; | |
| 1967 | + return outcome.value; | |
| 1968 | + } | |
| 1969 | +} | |
| 1970 | +class DurableObjectId { | |
| 1971 | + constructor(className, value, name = undefined) { | |
| 1972 | + Object.defineProperties(this, { | |
| 1973 | + _className: { value: className }, | |
| 1974 | + _value: { value }, | |
| 1975 | + }); | |
| 1976 | + this.name = name; | |
| 1977 | + this.jurisdiction = undefined; | |
| 1978 | + } | |
| 1979 | + toString() { return this._value; } | |
| 1980 | + equals(other) { | |
| 1981 | + return other instanceof DurableObjectId && other._value === this._value; | |
| 1982 | + } | |
| 1983 | + _scope() { return this._className + ":" + this._value; } | |
| 1984 | +} | |
| 1985 | +globalThis.DurableObjectRoutingError = class DurableObjectRoutingError | |
| 1986 | + extends Error { | |
| 1987 | + constructor(detail = {}) { | |
| 1988 | + super("The Durable Object owner is currently unreachable"); | |
| 1989 | + this.name = "DurableObjectRoutingError"; | |
| 1990 | + this.code = "owner_unreachable"; | |
| 1991 | + this.retryable = true; | |
| 1992 | + if (typeof detail.scope === "string") this.scope = detail.scope; | |
| 1993 | + if (typeof detail.owner === "string") this.owner = detail.owner; | |
| 1994 | + } | |
| 1995 | +}; | |
| 1996 | +const __durableObjectRoutingError = (error) => { | |
| 1997 | + const marker = "__CELLD_DO_ROUTING_ERROR__:"; | |
| 1998 | + const message = String(error && error.message || error); | |
| 1999 | + const offset = message.indexOf(marker); | |
| 2000 | + if (offset < 0) return null; | |
| 2001 | + try { | |
| 2002 | + return new DurableObjectRoutingError( | |
| 2003 | + JSON.parse(message.slice(offset + marker.length)), | |
| 2004 | + ); | |
| 2005 | + } catch { | |
| 2006 | + return new DurableObjectRoutingError(); | |
| 2007 | + } | |
| 2008 | +}; | |
| 2009 | +// A cell's input gate as the isolate sees it, for the one delivery | |
| 2010 | +// point that is inside the isolate rather than in front of it: an | |
| 2011 | +// RPC stub op. `events` records every block that has asked for the | |
| 2012 | +// gate, so no window exists in which a block has started and the | |
| 2013 | +// isolate still thinks the cell is open. `holder` names the block | |
| 2014 | +// actually running; another event can still be queued. | |
| 2015 | +// | |
| 2016 | +// A stub minted while a block runs carries that block's token and | |
| 2017 | +// re-enters it instead of queueing behind it. That is Workerd's | |
| 2018 | +// `IoContext::makeReentryCallback`, and without it a callback the | |
| 2019 | +// block itself sent out could never come back. | |
| 2020 | +const __cellBlocks = new Map(); | |
| 2021 | +const __blockEnter = (scope, event, owner) => { | |
| 2022 | + let settleReady; | |
| 2023 | + let rejectReady; | |
| 2024 | + const ready = new Promise((resolve, reject) => { | |
| 2025 | + settleReady = resolve; | |
| 2026 | + rejectReady = reject; | |
| 2027 | + }); | |
| 2028 | + const record = { | |
| 2029 | + owner, | |
| 2030 | + reaction: String(__io_context_id()), | |
| 2031 | + actorEvent: __currentActorEvent(), | |
| 2032 | + retired: false, | |
| 2033 | + ready, | |
| 2034 | + settleReady, | |
| 2035 | + rejectReady, | |
| 2036 | + }; | |
| 2037 | + const block = __cellBlocks.get(scope); | |
| 2038 | + if (block !== undefined) { | |
| 2039 | + block.events.set(event, record); | |
| 2040 | + return { block, record }; | |
| 2041 | + } | |
| 2042 | + const fresh = { | |
| 2043 | + holder: null, | |
| 2044 | + events: new Map([[event, record]]), | |
| 2045 | + }; | |
| 2046 | + __cellBlocks.set(scope, fresh); | |
| 2047 | + return { block: fresh, record }; | |
| 2048 | +}; | |
| 2049 | +const __blockLeave = (scope, block, event) => { | |
| 2050 | + if (!block.events.delete(event)) return; | |
| 2051 | + if (block.holder === event) block.holder = null; | |
| 2052 | + if (block.events.size === 0 && __cellBlocks.get(scope) === block) | |
| 2053 | + __cellBlocks.delete(scope); | |
| 2054 | +}; | |
| 2055 | +const __durableClassMeta = new WeakMap(); | |
| 2056 | +let __nextFacetOwner = 1; | |
| 2057 | +// Takes encoded props, not the caller's options bag: an options bag reaching | |
| 2058 | +// here is a bag nothing validated, and reading one key out of it is how every | |
| 2059 | +// other key came to be dropped in silence. The loader stub validates the bag | |
| 2060 | +// and encodes its value before it creates the class. | |
| 2061 | +const __makeDurableObjectClass = (idPromise, name, propsSc) => { | |
| 2062 | + const value = {}; | |
| 2063 | + __durableClassMeta.set(value, { | |
| 2064 | + idPromise, | |
| 2065 | + name: name === null || name === undefined ? "default" : String(name), | |
| 2066 | + propsSc, | |
| 2067 | + }); | |
| 2068 | + return value; | |
| 2069 | +}; | |
| 2070 | +class DurableObjectFacets { | |
| 2071 | + constructor(state) { | |
| 2072 | + this._state = state; | |
| 2073 | + this._owner = String(__nextFacetOwner++); | |
| 2074 | + this._next = 1; | |
| 2075 | + this._running = new Map(); | |
| 2076 | + this._barriers = new Map(); | |
| 2077 | + } | |
| 2078 | + _validName(name) { | |
| 2079 | + name = String(name); | |
| 2080 | + if (new TextEncoder().encode(name).length > 256) | |
| 2081 | + throw new TypeError("Facet name is too long (max 256 characters)."); | |
| 2082 | + return name; | |
| 2083 | + } | |
| 2084 | + get(name, getStartupOptions) { | |
| 2085 | + name = this._validName(name); | |
| 2086 | + if (this._state._facetDepth >= 3) | |
| 2087 | + throw new Error( | |
| 2088 | + "Facet nesting depth limit exceeded. The maximum depth including the root Durable Object is 4."); | |
| 2089 | + if (typeof getStartupOptions !== "function") | |
| 2090 | + throw new TypeError("The facet startup callback must be a function."); | |
| 2091 | + let record = this._running.get(name); | |
| 2092 | + if (record !== undefined) return record.stub; | |
| 2093 | + // Each run gets a distinct host scope. An aborted request can still have | |
| 2094 | + // a pending continuation, so reusing its scope would let that continuation | |
| 2095 | + // enter the replacement instance after the abort barrier opens. | |
| 2096 | + record = { | |
| 2097 | + aborted: false, | |
| 2098 | + error: undefined, | |
| 2099 | + owner: this._owner + ":" + this._next++, | |
| 2100 | + started: null, | |
| 2101 | + stub: null, | |
| 2102 | + }; | |
| 2103 | + const barrier = this._barriers.get(name); | |
| 2104 | + const start = () => record.started ??= Promise.resolve(barrier) | |
| 2105 | + .then(getStartupOptions) | |
| 2106 | + .then(async (options) => { | |
| 2107 | + const meta = __durableClassMeta.get(options?.class); | |
| 2108 | + if (meta === undefined) | |
| 2109 | + throw new TypeError( | |
| 2110 | + "FacetStartupOptions.class must be a DurableObjectClass."); | |
| 2111 | + const loader = await meta.idPromise; | |
| 2112 | + const id = options.id instanceof DurableObjectId | |
| 2113 | + ? options.id.toString() | |
| 2114 | + : options.id === undefined ? this._state.id.toString() : String(options.id); | |
| 2115 | + return [loader, meta.name, id, meta.propsSc]; | |
| 2116 | + }); | |
| 2117 | + const invoke = async (operation) => { | |
| 2118 | + if (record.aborted) throw record.error; | |
| 2119 | + return operation(await start()); | |
| 2120 | + }; | |
| 2121 | + const target = {}; | |
| 2122 | + // Methods share the loaded-worker RPC transport. A facet stub is not | |
| 2123 | + // awaitable, and a property is a single callable pipeline node. | |
| 2124 | + const session = { | |
| 2125 | + get: () => Promise.reject(new Error( | |
| 2126 | + "Awaitable properties on facets are not supported yet.")), | |
| 2127 | + call: (path, args) => invoke(async ([loader, className, id, propsSc]) => { | |
| 2128 | + if (path.length !== 1) | |
| 2129 | + throw new Error( | |
| 2130 | + "Pipelined property paths on facets are not supported yet."); | |
| 2131 | + return __rpcDes(await __facet_rpc( | |
| 2132 | + loader, className, this._state._scope, record.owner, name, id, | |
| 2133 | + propsSc, path[0], __rpcOut(args, false))); | |
| 2134 | + }), | |
| 2135 | + }; | |
| 2136 | + // Arrow closures retain the manager because `target.fetch`'s method | |
| 2137 | + // receiver is the target object, not the DurableObjectFacets instance. | |
| 2138 | + const manager = this; | |
| 2139 | + target.fetch = async function(input, init) { | |
| 2140 | + return invoke(async ([loader, className, id, propsSc]) => { | |
| 2141 | + const req = new Request(input, init); | |
| 2142 | + const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 2143 | + const { body, streamId } = await __subrequestBody(req); | |
| 2144 | + const response = JSON.parse(await __facet_fetch( | |
| 2145 | + loader, className, manager._state._scope, record.owner, name, id, | |
| 2146 | + propsSc, req.url, req.method, body, headers, streamId)); | |
| 2147 | + const responseBody = response.streamId !== undefined | |
| 2148 | + ? new CelldHttpBodyStream(response.streamId) | |
| 2149 | + : response.body !== undefined ? response.body | |
| 2150 | + : Uint8Array.from(response.bodyBytes || []); | |
| 2151 | + return __wrapServiceResponse(new Response(responseBody, { | |
| 2152 | + status: response.status, | |
| 2153 | + headers: response.headers, | |
| 2154 | + }), req.url); | |
| 2155 | + }); | |
| 2156 | + }; | |
| 2157 | + record.stub = new Proxy(target, { | |
| 2158 | + get(base, prop) { | |
| 2159 | + if (prop === "then") return undefined; | |
| 2160 | + if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 2161 | + if (typeof prop !== "string") return undefined; | |
| 2162 | + return __makeNode(session, [prop], null); | |
| 2163 | + }, | |
| 2164 | + }); | |
| 2165 | + this._running.set(name, record); | |
| 2166 | + return record.stub; | |
| 2167 | + } | |
| 2168 | + _abort(name, reason) { | |
| 2169 | + name = this._validName(name); | |
| 2170 | + const record = this._running.get(name); | |
| 2171 | + if (record === undefined) return Promise.resolve(); | |
| 2172 | + record.aborted = true; | |
| 2173 | + record.error = reason; | |
| 2174 | + this._running.delete(name); | |
| 2175 | + const barrier = record.started === null ? Promise.resolve() : record.started | |
| 2176 | + .then(([loader, className]) => | |
| 2177 | + __facet_abort( | |
| 2178 | + loader, className, this._state._scope, record.owner, name), () => {}); | |
| 2179 | + this._barriers.set(name, barrier); | |
| 2180 | + const clear = () => { | |
| 2181 | + if (this._barriers.get(name) === barrier) this._barriers.delete(name); | |
| 2182 | + }; | |
| 2183 | + barrier.then(clear, clear); | |
| 2184 | + return barrier; | |
| 2185 | + } | |
| 2186 | + abort(name, reason) { | |
| 2187 | + this._abort(name, reason); | |
| 2188 | + } | |
| 2189 | + delete(name) { | |
| 2190 | + name = this._validName(name); | |
| 2191 | + const barrier = this._abort(name, new Error("Facet was deleted.")).then(() => | |
| 2192 | + __facet_delete(this._state._scope, name)); | |
| 2193 | + this._barriers.set(name, barrier); | |
| 2194 | + const clear = () => { | |
| 2195 | + if (this._barriers.get(name) === barrier) this._barriers.delete(name); | |
| 2196 | + }; | |
| 2197 | + // Keep a failed delete as the name's barrier. Clearing it would let the | |
| 2198 | + // next get reload the image which the failed operation did not delete. | |
| 2199 | + barrier.then(clear, () => {}); | |
| 2200 | + } | |
| 2201 | + _release() { | |
| 2202 | + for (const name of Array.from(this._running.keys())) | |
| 2203 | + this._abort(name, new Error("The parent Durable Object was released.")); | |
| 2204 | + } | |
| 2205 | +} | |
| 2206 | +// The reason a failed critical section gives its waiters. It must not throw: | |
| 2207 | +// it runs where a throw would skip the gate's release, and a value with no | |
| 2208 | +// string form, such as `Object.create(null)`, is a legal thing to throw. | |
| 2209 | +function __describeFailure(error) { | |
| 2210 | + try { | |
| 2211 | + return String((error && error.message) || error); | |
| 2212 | + } catch { | |
| 2213 | + return "critical section failed"; | |
| 2214 | + } | |
| 2215 | +} | |
| 2216 | +// ---- Containers ----------------------------------------------------------- | |
| 2217 | +// `ctx.container` for a class named in the deployment's `containers`. The | |
| 2218 | +// surface and every message follow workerd's api/container.c++; the host | |
| 2219 | +// ops perform the effects against the node's container engine, and the | |
| 2220 | +// scope names the cell the way the storage ops do. | |
| 2221 | +const __containerEnvList = (env, what) => { | |
| 2222 | + const list = []; | |
| 2223 | + if (env === undefined || env === null) return list; | |
| 2224 | + for (const [name, value] of Object.entries(env)) { | |
| 2225 | + const text = String(value); | |
| 2226 | + if (name.includes("=")) | |
| 2227 | + throw new Error(`Environment variable names cannot contain '=': ${name}`); | |
| 2228 | + if (name.includes("\0")) | |
| 2229 | + throw new Error(`Environment variable names cannot contain '\\0': ${name}`); | |
| 2230 | + if (text.includes("\0")) | |
| 2231 | + throw new Error(`Environment variable values cannot contain '\\0': ${name}`); | |
| 2232 | + list.push([name, text]); | |
| 2233 | + } | |
| 2234 | + return list; | |
| 2235 | +}; | |
| 2236 | +const __execOutputMode = (mode, kind) => { | |
| 2237 | + const value = mode === undefined ? "pipe" : String(mode); | |
| 2238 | + if (value === "pipe" || value === "ignore" || | |
| 2239 | + (kind === "stderr" && value === "combined")) return value; | |
| 2240 | + throw new TypeError(`Invalid ${kind} option: ${value}`); | |
| 2241 | +}; | |
| 2242 | +const __validSignal = (signo) => Number.isInteger(signo) && signo > 0 && signo <= 64; | |
| 2243 | +const __execStream = (id, which) => new ReadableStream({ | |
| 2244 | + type: "bytes", | |
| 2245 | + async pull(controller) { | |
| 2246 | + const chunk = await __container_exec_read(id, which); | |
| 2247 | + if (chunk.byteLength === 0) controller.close(); | |
| 2248 | + else controller.enqueue(new Uint8Array(chunk)); | |
| 2249 | + }, | |
| 2250 | +}); | |
| 2251 | +class ContainerExecOutput { | |
| 2252 | + constructor(stdout, stderr, exitCode) { | |
| 2253 | + this.stdout = stdout; | |
| 2254 | + this.stderr = stderr; | |
| 2255 | + this.exitCode = exitCode; | |
| 2256 | + } | |
| 2257 | +} | |
| 2258 | +class ContainerExecProcess { | |
| 2259 | + constructor(id, pid, stdinMode, stdoutMode, stderrMode) { | |
| 2260 | + this._id = id; | |
| 2261 | + this.pid = pid; | |
| 2262 | + this._outputCalled = false; | |
| 2263 | + this._exitCode = null; | |
| 2264 | + this.stdout = stdoutMode === "pipe" ? __execStream(id, 1) : null; | |
| 2265 | + this.stderr = stderrMode === "pipe" ? __execStream(id, 2) : null; | |
| 2266 | + this.stdin = stdinMode === "pipe" | |
| 2267 | + ? new WritableStream({ | |
| 2268 | + write: (chunk) => __container_exec_write(id, __bytesOf(chunk)), | |
| 2269 | + close: () => __container_exec_close(id), | |
| 2270 | + abort: () => __container_exec_close(id), | |
| 2271 | + }) | |
| 2272 | + : null; | |
| 2273 | + } | |
| 2274 | + get exitCode() { | |
| 2275 | + if (this._exitCode === null) { | |
| 2276 | + this._exitCode = __container_exec_wait(this._id).then(Number); | |
| 2277 | + } | |
| 2278 | + return this._exitCode; | |
| 2279 | + } | |
| 2280 | + async output() { | |
| 2281 | + if (this._outputCalled) throw new TypeError("output() can only be called once."); | |
| 2282 | + this._outputCalled = true; | |
| 2283 | + for (const [stream, name] of [[this.stdout, "stdout"], [this.stderr, "stderr"]]) { | |
| 2284 | + if (stream && stream.locked) | |
| 2285 | + throw new TypeError(`Cannot call output() after ${name} has started being consumed.`); | |
| 2286 | + } | |
| 2287 | + const all = (stream) => stream | |
| 2288 | + ? new Response(stream).arrayBuffer() | |
| 2289 | + : Promise.resolve(new ArrayBuffer(0)); | |
| 2290 | + const [stdout, stderr] = await Promise.all([all(this.stdout), all(this.stderr)]); | |
| 2291 | + const exitCode = await this.exitCode; | |
| 2292 | + // Nothing else can read the process now, so the host can forget it. | |
| 2293 | + __container_exec_drop(this._id); | |
| 2294 | + return new ContainerExecOutput(stdout, stderr, exitCode); | |
| 2295 | + } | |
| 2296 | + kill(signal = 15) { | |
| 2297 | + if (!__validSignal(signal)) throw new RangeError("Invalid signal number."); | |
| 2298 | + __container_exec_kill(this._id, signal).catch(() => {}); | |
| 2299 | + } | |
| 2300 | +} | |
| 2301 | +const __bytesOf = (chunk) => { | |
| 2302 | + if (chunk instanceof Uint8Array) return chunk; | |
| 2303 | + if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk); | |
| 2304 | + if (ArrayBuffer.isView(chunk)) | |
| 2305 | + return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); | |
| 2306 | + throw new TypeError("stdin accepts bytes"); | |
| 2307 | +}; | |
| 2308 | +// The Fetcher `getTcpPort()` returns: `fetch()` speaks HTTP to the port over | |
| 2309 | +// the node's route to the container, and `connect()` is the raw socket. | |
| 2310 | +class ContainerPort { | |
| 2311 | + constructor(scope, port) { | |
| 2312 | + this._scope = scope; | |
| 2313 | + this._port = port; | |
| 2314 | + } | |
| 2315 | + async fetch(input, init) { | |
| 2316 | + const request = new Request(input, init); | |
| 2317 | + const url = new URL(request.url); | |
| 2318 | + if (url.protocol === "https:") | |
| 2319 | + throw new Error( | |
| 2320 | + "Connecting to a container using HTTPS is not currently supported; use HTTP " + | |
| 2321 | + "instead. TLS is unnecessary anyway, as the connection is already secure by default.", | |
| 2322 | + ); | |
| 2323 | + if (url.protocol !== "http:") throw new TypeError(`Fetch API cannot load: ${url}`); | |
| 2324 | + const authority = url.host; | |
| 2325 | + url.host = __container_address(this._scope, this._port); | |
| 2326 | + const forwarded = new Request(url.toString(), request); | |
| 2327 | + forwarded.headers.set("host", authority); | |
| 2328 | + try { | |
| 2329 | + return await fetch(forwarded); | |
| 2330 | + } catch (error) { | |
| 2331 | + // A refused or reset connection is the port not listening yet, which | |
| 2332 | + // the `@cloudflare/containers` start loop recognizes by this phrase | |
| 2333 | + // and retries; any other failure keeps its own message. | |
| 2334 | + const message = error?.message ?? String(error); | |
| 2335 | + if (/error sending request|connection|connect/i.test(message)) { | |
| 2336 | + throw new Error( | |
| 2337 | + `The container is not listening on port ${this._port}: ${message}`, | |
| 2338 | + ); | |
| 2339 | + } | |
| 2340 | + throw error; | |
| 2341 | + } | |
| 2342 | + } | |
| 2343 | + connect(address, options) { | |
| 2344 | + if (options?.secureTransport === "on") | |
| 2345 | + throw new Error( | |
| 2346 | + "Connencting to a container using TLS is not currently supported. It is " + | |
| 2347 | + "unnecessary anyway, as the connection is already secure by default.", | |
| 2348 | + ); | |
| 2349 | + return __celld.__cfSockets.connect( | |
| 2350 | + __container_address(this._scope, this._port), options); | |
| 2351 | + } | |
| 2352 | +} | |
| 2353 | +class Container { | |
| 2354 | + constructor(scope) { | |
| 2355 | + this._scope = scope; | |
| 2356 | + this._destroyReason = undefined; | |
| 2357 | + } | |
| 2358 | + // The host's answer, not a JavaScript flag: a monitor() promise can be | |
| 2359 | + // dropped with its event, so the flag it would maintain could go stale. | |
| 2360 | + get running() { return __container_running(this._scope); } | |
| 2361 | + start(options) { | |
| 2362 | + if (this.running) | |
| 2363 | + throw new Error("start() cannot be called on a container that is already running."); | |
| 2364 | + const o = options ?? {}; | |
| 2365 | + const params = { enableInternet: !!o.enableInternet, labels: [] }; | |
| 2366 | + if (o.entrypoint !== undefined) params.entrypoint = Array.from(o.entrypoint, String); | |
| 2367 | + params.env = __containerEnvList(o.env); | |
| 2368 | + if (o.labels !== undefined) { | |
| 2369 | + for (const [name, value] of Object.entries(o.labels)) { | |
| 2370 | + if (name.length === 0) throw new Error("Label names cannot be empty"); | |
| 2371 | + for (const text of [name, String(value)]) { | |
| 2372 | + for (let i = 0; i < text.length; i++) { | |
| 2373 | + if (text.charCodeAt(i) < 0x20) | |
| 2374 | + throw new Error(`Label names cannot contain control characters (index ${i})`); | |
| 2375 | + } | |
| 2376 | + } | |
| 2377 | + params.labels.push([name, String(value)]); | |
| 2378 | + } | |
| 2379 | + } | |
| 2380 | + if (o.hardTimeout !== undefined && !(o.hardTimeout > 0)) | |
| 2381 | + throw new RangeError("Hard timeout must be greater than 0"); | |
| 2382 | + // Fire and forget, as on Cloudflare: a start that fails reports | |
| 2383 | + // through monitor(). The host marks the run as running at once. | |
| 2384 | + this._destroyReason = undefined; | |
| 2385 | + __container_start(this._scope, JSON.stringify(params)).catch(() => {}); | |
| 2386 | + } | |
| 2387 | + async monitor() { | |
| 2388 | + if (!this.running) | |
| 2389 | + throw new Error("monitor() cannot be called on a container that is not running."); | |
| 2390 | + let raw; | |
| 2391 | + try { | |
| 2392 | + raw = await __container_monitor(this._scope); | |
| 2393 | + } catch (error) { | |
| 2394 | + this._destroyReason = undefined; | |
| 2395 | + throw error; | |
| 2396 | + } | |
| 2397 | + const exitCode = Number(raw); | |
| 2398 | + if (this._destroyReason !== undefined) { | |
| 2399 | + const reason = this._destroyReason; | |
| 2400 | + this._destroyReason = undefined; | |
| 2401 | + throw reason; | |
| 2402 | + } | |
| 2403 | + if (exitCode !== 0) { | |
| 2404 | + const error = new Error(`Container exited with unexpected exit code: ${exitCode}`); | |
| 2405 | + error.exitCode = exitCode; | |
| 2406 | + throw error; | |
| 2407 | + } | |
| 2408 | + } | |
| 2409 | + async destroy(error) { | |
| 2410 | + if (!this.running) return; | |
| 2411 | + if (this._destroyReason === undefined) this._destroyReason = error; | |
| 2412 | + await __container_destroy(this._scope); | |
| 2413 | + } | |
| 2414 | + signal(signo) { | |
| 2415 | + if (!__validSignal(signo)) throw new RangeError("Invalid signal number."); | |
| 2416 | + if (!this.running) | |
| 2417 | + throw new Error("signal() cannot be called on a container that is not running."); | |
| 2418 | + __container_signal(this._scope, signo).catch(() => {}); | |
| 2419 | + } | |
| 2420 | + getTcpPort(port) { | |
| 2421 | + if (!(Number.isInteger(port) && port > 0 && port < 65536)) | |
| 2422 | + throw new TypeError(`Invalid port number: ${port}`); | |
| 2423 | + return new ContainerPort(this._scope, port); | |
| 2424 | + } | |
| 2425 | + setInactivityTimeout(durationMs) { | |
| 2426 | + if (!(durationMs > 0)) | |
| 2427 | + throw new Error(`setInactivityTimeout() requires durationMs > 0, got ${durationMs}`); | |
| 2428 | + return __container_inactivity(this._scope, durationMs); | |
| 2429 | + } | |
| 2430 | + async exec(cmd, options) { | |
| 2431 | + if (!this.running) | |
| 2432 | + throw new Error("exec() cannot be called on a container that is not running."); | |
| 2433 | + if (!Array.isArray(cmd) || cmd.length === 0) | |
| 2434 | + throw new TypeError("exec() requires a non-empty command array."); | |
| 2435 | + const o = options ?? {}; | |
| 2436 | + const stdoutMode = __execOutputMode(o.stdout, "stdout"); | |
| 2437 | + const stderrMode = __execOutputMode(o.stderr, "stderr"); | |
| 2438 | + const combined = stderrMode === "combined"; | |
| 2439 | + if (combined && stdoutMode !== "pipe") | |
| 2440 | + throw new TypeError('stderr: "combined" requires stdout to be "pipe".'); | |
| 2441 | + if (o.cwd !== undefined && String(o.cwd).includes("\0")) | |
| 2442 | + throw new TypeError("cwd cannot contain '\\0' characters."); | |
| 2443 | + if (o.user !== undefined && String(o.user).includes("\0")) | |
| 2444 | + throw new TypeError("user cannot contain '\\0' characters."); | |
| 2445 | + let stdinMode = "none"; | |
| 2446 | + if (o.stdin !== undefined) { | |
| 2447 | + if (o.stdin === "pipe") stdinMode = "pipe"; | |
| 2448 | + else if (o.stdin instanceof ReadableStream) stdinMode = "stream"; | |
| 2449 | + else throw new TypeError('stdin must be a ReadableStream or the string "pipe".'); | |
| 2450 | + } | |
| 2451 | + const params = { | |
| 2452 | + cmd: Array.from(cmd, String), | |
| 2453 | + env: __containerEnvList(o.env), | |
| 2454 | + combined, | |
| 2455 | + }; | |
| 2456 | + if (o.cwd !== undefined) params.cwd = String(o.cwd); | |
| 2457 | + if (o.user !== undefined) params.user = String(o.user); | |
| 2458 | + const { id, pid } = JSON.parse( | |
| 2459 | + await __container_exec(this._scope, JSON.stringify(params)), | |
| 2460 | + ); | |
| 2461 | + if (stdinMode === "stream") { | |
| 2462 | + // Pump the caller's stream to the process; the pump is pending work | |
| 2463 | + // of the event, like a subrequest body. | |
| 2464 | + (async () => { | |
| 2465 | + const reader = o.stdin.getReader(); | |
| 2466 | + try { | |
| 2467 | + for (;;) { | |
| 2468 | + const { value, done } = await reader.read(); | |
| 2469 | + if (done) break; | |
| 2470 | + await __container_exec_write(id, __bytesOf(value)); | |
| 2471 | + } | |
| 2472 | + } finally { | |
| 2473 | + await __container_exec_close(id); | |
| 2474 | + } | |
| 2475 | + })().catch(() => {}); | |
| 2476 | + } else if (stdinMode === "none") { | |
| 2477 | + __container_exec_close(id).catch(() => {}); | |
| 2478 | + } | |
| 2479 | + return new ContainerExecProcess(id, pid, stdinMode, stdoutMode, stderrMode); | |
| 2480 | + } | |
| 2481 | + inspect() { | |
| 2482 | + return Promise.reject(new Error("inspect() is not implemented in celld")); | |
| 2483 | + } | |
| 2484 | + snapshotDirectory() { | |
| 2485 | + return Promise.reject(new Error("snapshotDirectory() is not implemented in celld")); | |
| 2486 | + } | |
| 2487 | + snapshotContainer() { | |
| 2488 | + return Promise.reject(new Error("snapshotContainer() is not implemented in celld")); | |
| 2489 | + } | |
| 2490 | + interceptOutboundHttp() { | |
| 2491 | + return Promise.reject(new Error("interceptOutboundHttp() is not implemented in celld")); | |
| 2492 | + } | |
| 2493 | + interceptOutboundHttps() { | |
| 2494 | + return Promise.reject(new Error("interceptOutboundHttps() is not implemented in celld")); | |
| 2495 | + } | |
| 2496 | + interceptAllOutboundHttp() { | |
| 2497 | + return Promise.reject(new Error("interceptAllOutboundHttp() is not implemented in celld")); | |
| 2498 | + } | |
| 2499 | + interceptOutboundTcp() { | |
| 2500 | + return Promise.reject(new Error("interceptOutboundTcp() is not implemented in celld")); | |
| 2501 | + } | |
| 2502 | +} | |
| 2503 | +class DurableObjectState { | |
| 2504 | + constructor(scope) { | |
| 2505 | + this._scope = scope; | |
| 2506 | + this._aborted = false; | |
| 2507 | + this.storage = new DurableObjectStorage(scope, this); | |
| 2508 | + this.facets = new DurableObjectFacets(this); | |
| 2509 | + this._gate = Promise.resolve(); | |
| 2510 | + this._blockDepth = 0; | |
| 2511 | + const facet = __cell.facetConfigs[scope]; | |
| 2512 | + this._facetDepth = facet?.depth ?? 0; | |
| 2513 | + const separator = scope.indexOf(":"); | |
| 2514 | + const className = separator < 0 ? scope : scope.slice(0, separator); | |
| 2515 | + const value = facet?.id ?? (separator < 0 ? scope : scope.slice(separator + 1)); | |
| 2516 | + this.id = new DurableObjectId( | |
| 2517 | + className, value, __cell.idNames[scope], | |
| 2518 | + ); | |
| 2519 | + this.props = facet?.props; | |
| 2520 | + // A class outside `containers` has no `ctx.container`, which is what | |
| 2521 | + // the `@cloudflare/containers` constructor checks. | |
| 2522 | + if (__cell.containers[className]) this.container = new Container(scope); | |
| 2523 | + } | |
| 2524 | + // Workerd's DurableObjectState.exports (actor-state.h): the same | |
| 2525 | + // loopback surface as ctx.exports on stateless entrypoints. | |
| 2526 | + get exports() { return __ctxExports(); } | |
| 2527 | + blockConcurrencyWhile(f) { | |
| 2528 | + // The native context binds the gate and its operations to one driver. | |
| 2529 | + // Its async continuations keep that driver even inside a foreign turn. | |
| 2530 | + return __with_input_gate_context(() => this._blockConcurrencyWhile(f)); | |
| 2531 | + } | |
| 2532 | + _blockConcurrencyWhile(f) { | |
| 2533 | + if (typeof f !== "function") | |
| 2534 | + throw new TypeError("blockConcurrencyWhile() requires a function"); | |
| 2535 | + if (this._blockDepth >= 64) | |
| 2536 | + throw new Error( | |
| 2537 | + "blockConcurrencyWhile() calls are nested too deeply.", | |
| 2538 | + ); | |
| 2539 | + if (this._blockDepth > 0) { | |
| 2540 | + // A stale reaction can run while an unrelated live block makes this | |
| 2541 | + // actor's depth nonzero. It cannot ride that hold when either half of | |
| 2542 | + // its retained [origin, driver] pair has already retired. | |
| 2543 | + if (__io_context_id() === "" || __io_context_id(true) === "") { | |
| 2544 | + return Promise.reject(new Error( | |
| 2545 | + "the cell event ended before it could acquire an input gate", | |
| 2546 | + )); | |
| 2547 | + } | |
| 2548 | + // A nested block rides the outer hold. One the outer body starts and | |
| 2549 | + // does not await would outlive that hold, and a `transaction()` | |
| 2550 | + // started that way is the shape that mattered: the outer block | |
| 2551 | + // returned, the gate opened, and another event wrote into the still | |
| 2552 | + // open transaction (#714). The outer block drains these before it | |
| 2553 | + // releases, so the hold lasts as long as any block under it. A nested | |
| 2554 | + // block that fails resets the object as any block does, and the outer | |
| 2555 | + // release must carry that failure, or the waiters would be admitted to | |
| 2556 | + // an object that no longer exists: the drain records it. | |
| 2557 | + const nested = this._runConcurrencyBlock(f); | |
| 2558 | + (this._nestedBlocks ||= []).push(nested.then(() => null, __describeFailure)); | |
| 2559 | + return nested; | |
| 2560 | + } | |
| 2561 | + // The host owns the gate (celld_logic::gate::InputGate). It replaces a | |
| 2562 | + // promise chain that could only order blocks against each other; the | |
| 2563 | + // gate sits at the delivery points, so nothing else is delivered to this | |
| 2564 | + // cell at all while the block runs. | |
| 2565 | + // | |
| 2566 | + // The acquire waits. It used to be synchronous, and had to be: a cell's | |
| 2567 | + // events came off one channel, so yielding even one microtask reopened a | |
| 2568 | + // window in which this cell delivered an event that then waited on a | |
| 2569 | + // gate nothing would release. Events are independent tasks now, so two | |
| 2570 | + // can reach a block together and the second has to queue -- and nothing | |
| 2571 | + // nests, so waiting cannot deadlock on an event suspended beneath it. | |
| 2572 | + // Asked for synchronously, awaited asynchronously, and the split is the | |
| 2573 | + // whole point. The op shuts the gate in this very call, so no event can | |
| 2574 | + // be delivered to this cell from here on -- that immediacy is what makes | |
| 2575 | + // `failCriticalSection()` reject a `ping()` issued right after it. | |
| 2576 | + // Waiting for the *ticket* is separate: events are independent tasks | |
| 2577 | + // now, so two of them can reach a block together and the second has to | |
| 2578 | + // queue behind the first. Calling this inside the async body instead | |
| 2579 | + // costs one microtask, and an event delivered in that window walks | |
| 2580 | + // straight into the critical section. | |
| 2581 | + const [eventText, owner, acquired] = __gate_acquire(this._scope); | |
| 2582 | + // An empty owner is an immediate refusal. Return its already-rejected | |
| 2583 | + // promise before recording the block, because no driver exists to settle | |
| 2584 | + // native work or to repair a readiness gate installed for stale work. | |
| 2585 | + if (owner === "") return acquired; | |
| 2586 | + const event = Number(eventText); | |
| 2587 | + const { block, record } = __blockEnter(this._scope, event, owner); | |
| 2588 | + const next = (async () => { | |
| 2589 | + try { | |
| 2590 | + await acquired; | |
| 2591 | + // A shutdown can retire the promise reaction while another event | |
| 2592 | + // owns this queued acquisition. The owner still has to consume its | |
| 2593 | + // ticket, but the retired callback must not run. | |
| 2594 | + if (record.retired) { | |
| 2595 | + __gate_release(this._scope, event, owner, null); | |
| 2596 | + return; | |
| 2597 | + } | |
| 2598 | + block.holder = event; | |
| 2599 | + // A critical section that fails resets the actor, so whatever queued | |
| 2600 | + // behind its gate must be refused rather than handed to the reset | |
| 2601 | + // one -- it was sent to a cell whose state no longer exists. The | |
| 2602 | + // failure rides with the release for that: waiters are woken with it | |
| 2603 | + // instead of merely woken. | |
| 2604 | + let failure = null; | |
| 2605 | + try { | |
| 2606 | + return await this._runConcurrencyBlock(f); | |
| 2607 | + } catch (error) { | |
| 2608 | + failure = __describeFailure(error); | |
| 2609 | + throw error; | |
| 2610 | + } finally { | |
| 2611 | + // Nested blocks are drained only after a body that returned: a | |
| 2612 | + // body that failed has reset the object, its waiters are refused | |
| 2613 | + // whatever the nested blocks do, and waiting for them would only | |
| 2614 | + // delay the refusal and a transaction's rollback behind it. Each | |
| 2615 | + // nested block has its own limit, so a drain is bounded by the | |
| 2616 | + // last one started, as workerd's nested critical sections are. | |
| 2617 | + while (failure === null && this._nestedBlocks && this._nestedBlocks.length > 0) { | |
| 2618 | + for (const nestedFailure of await Promise.all(this._nestedBlocks.splice(0))) { | |
| 2619 | + if (nestedFailure !== null && failure === null) failure = nestedFailure; | |
| 2620 | + } | |
| 2621 | + } | |
| 2622 | + this._nestedBlocks = undefined; | |
| 2623 | + __gate_release(this._scope, event, owner, failure); | |
| 2624 | + } | |
| 2625 | + } finally { | |
| 2626 | + // Also on a rejected `acquired`: the block ahead failed, this one | |
| 2627 | + // never ran, and the cell must not stay shut on its behalf. | |
| 2628 | + __blockLeave(this._scope, block, event); | |
| 2629 | + } | |
| 2630 | + })(); | |
| 2631 | + // `_ready()` awaits this. The host gate stops *other* events, but a | |
| 2632 | + // block taken in the constructor runs inside the very event that is | |
| 2633 | + // being delivered, so nothing external can hold that event back -- the | |
| 2634 | + // promise does. Concurrent blocks within one event go through | |
| 2635 | + // `_blockDepth` above and never reach here. | |
| 2636 | + this._gate = Promise.all([this._gate, record.ready]).then(() => undefined); | |
| 2637 | + // `_ready()` observes the original promise. This extra handler prevents | |
| 2638 | + // a constructor-time rejection from becoming unhandled before an event | |
| 2639 | + // reaches `_ready()`. | |
| 2640 | + this._gate.catch(() => {}); | |
| 2641 | + next.then(record.settleReady, record.rejectReady); | |
| 2642 | + return next; | |
| 2643 | + } | |
| 2644 | + _runConcurrencyBlock(f) { | |
| 2645 | + this._blockDepth++; | |
| 2646 | + let result; | |
| 2647 | + try { | |
| 2648 | + result = f(); | |
| 2649 | + } catch (error) { | |
| 2650 | + this._blockDepth--; | |
| 2651 | + this._resetAfterConcurrencyFailure(error); | |
| 2652 | + throw error; | |
| 2653 | + } | |
| 2654 | + const timerId = __timer_alloc(); | |
| 2655 | + let settled = false; | |
| 2656 | + const timeout = __op_timer( | |
| 2657 | + timerId, | |
| 2658 | + 30_000, | |
| 2659 | + ).then(() => { | |
| 2660 | + if (!settled) { | |
| 2661 | + throw new Error( | |
| 2662 | + "A call to blockConcurrencyWhile() in a Durable Object waited for " + | |
| 2663 | + "too long. The call was canceled and the Durable Object was reset.", | |
| 2664 | + ); | |
| 2665 | + } | |
| 2666 | + }); | |
| 2667 | + return Promise.race([Promise.resolve(result), timeout]).then( | |
| 2668 | + (value) => { | |
| 2669 | + settled = true; | |
| 2670 | + __timer_cancel(timerId); | |
| 2671 | + this._blockDepth--; | |
| 2672 | + return value; | |
| 2673 | + }, | |
| 2674 | + (error) => { | |
| 2675 | + settled = true; | |
| 2676 | + __timer_cancel(timerId); | |
| 2677 | + this._blockDepth--; | |
| 2678 | + this._resetAfterConcurrencyFailure(error); | |
| 2679 | + throw error; | |
| 2680 | + }, | |
| 2681 | + ); | |
| 2682 | + } | |
| 2683 | + _resetAfterConcurrencyFailure(error) { | |
| 2684 | + if (this._aborted) return; | |
| 2685 | + this._aborted = true; | |
| 2686 | + __storage_cancel_pending_puts(this._scope); | |
| 2687 | + const instance = __cell.instances[this._scope]; | |
| 2688 | + if (instance && instance.__celldState === this) | |
| 2689 | + delete __cell.instances[this._scope]; | |
| 2690 | + // Under a stub-mediated caller (this scope is not the current | |
| 2691 | + // event) the failure breaks the actor, as Workerd joins it | |
| 2692 | + // into the on-abort promise; a direct event keeps reset-only | |
| 2693 | + // semantics -- its caller sees the rejection itself. | |
| 2694 | + if (__currentActorScope() !== this._scope) | |
| 2695 | + __actorBreak(this._scope, error); | |
| 2696 | + } | |
| 2697 | + abort(reason) { | |
| 2698 | + if (this._aborted) return; | |
| 2699 | + this._aborted = true; | |
| 2700 | + __storage_cancel_pending_puts(this._scope); | |
| 2701 | + const instance = __cell.instances[this._scope]; | |
| 2702 | + if (instance && instance.__celldState === this) | |
| 2703 | + delete __cell.instances[this._scope]; | |
| 2704 | + const message = reason instanceof Error | |
| 2705 | + ? reason.message | |
| 2706 | + : String(reason); | |
| 2707 | + // Direct host-dispatched event on this actor: the uncatchable | |
| 2708 | + // terminate_execution path. Under a same-isolate stub caller, | |
| 2709 | + // termination would unwind the caller too, so break in JS. | |
| 2710 | + if (__currentActorScope() === this._scope) { | |
| 2711 | + __actor_abort(this._scope, message); | |
| 2712 | + return; | |
| 2713 | + } | |
| 2714 | + __actorBreak(this._scope, | |
| 2715 | + reason instanceof Error ? reason : new Error(message)); | |
| 2716 | + } | |
| 2717 | + _ready() { return this._gate; } | |
| 2718 | + getWebSockets(tag) { | |
| 2719 | + return JSON.parse(__ws_list(this._scope, tag)).map((row) => __socketFromRow(row)); | |
| 2720 | + } | |
| 2721 | + getTags(ws) { | |
| 2722 | + if (!(ws instanceof WebSocket) || !ws._hibernatable) { | |
| 2723 | + throw new Error( | |
| 2724 | + "you must call 'acceptWebSocket()' before attempting to access " + | |
| 2725 | + "the tags of a WebSocket."); | |
| 2726 | + } | |
| 2727 | + return Array.from(ws._tags); | |
| 2728 | + } | |
| 2729 | + acceptWebSocket(ws, tags = []) { | |
| 2730 | + if (__heap_over_admission_share()) | |
| 2731 | + throw new Error( | |
| 2732 | + "the isolate is near its V8 heap limit, so it refused a " + | |
| 2733 | + "WebSocket (see CELLD_V8_HEAP_LIMIT_MB)"); | |
| 2734 | + ws._target = { id: ws._id, scope: this._scope }; | |
| 2735 | + if (ws._peer) ws._peer._target = ws._target; | |
| 2736 | + ws._hibernatable = true; | |
| 2737 | + if (ws._peer) ws._peer._hibernatable = true; | |
| 2738 | + ws._tags = Array.from(tags, String); | |
| 2739 | + __ws_accept(ws._id, this._scope, JSON.stringify(ws._tags)); | |
| 2740 | + __sockets.set(ws._id, ws); | |
| 2741 | + } | |
| 2742 | + _socket(id) { | |
| 2743 | + return __sockets.get(Number(id)) || | |
| 2744 | + this.getWebSockets().find((ws) => ws._id === id) || | |
| 2745 | + __wsStub(id); | |
| 2746 | + } | |
| 2747 | + // Workerd actor-state.c++ setWebSocketAutoResponse: no pair unsets, and | |
| 2748 | + // each side is capped at 2048 UTF-8 bytes. The pair itself lives in the | |
| 2749 | + // shell -- a matched message is answered without waking this cell. | |
| 2750 | + setWebSocketAutoResponse(pair) { | |
| 2751 | + if (pair === undefined || pair === null) { | |
| 2752 | + __ws_auto_response_set(this._scope, null, null); | |
| 2753 | + return; | |
| 2754 | + } | |
| 2755 | + if (!(pair instanceof WebSocketRequestResponsePair)) | |
| 2756 | + throw new TypeError( | |
| 2757 | + "Failed to execute 'setWebSocketAutoResponse' on " + | |
| 2758 | + "'DurableObjectState': parameter 1 is not of type " + | |
| 2759 | + "'WebSocketRequestResponsePair'.", | |
| 2760 | + ); | |
| 2761 | + const max = 2048; | |
| 2762 | + const bytes = (s) => new TextEncoder().encode(s).length; | |
| 2763 | + const requestSize = bytes(pair.request); | |
| 2764 | + if (requestSize > max) | |
| 2765 | + throw new RangeError( | |
| 2766 | + `Request cannot be larger than ${max} bytes. ` + | |
| 2767 | + `A request of size ${requestSize} was provided.`, | |
| 2768 | + ); | |
| 2769 | + const responseSize = bytes(pair.response); | |
| 2770 | + if (responseSize > max) | |
| 2771 | + throw new RangeError( | |
| 2772 | + `Response cannot be larger than ${max} bytes. ` + | |
| 2773 | + `A response of size ${responseSize} was provided.`, | |
| 2774 | + ); | |
| 2775 | + __ws_auto_response_set(this._scope, pair.request, pair.response); | |
| 2776 | + } | |
| 2777 | + getWebSocketAutoResponse() { | |
| 2778 | + const pair = JSON.parse(__ws_auto_response_get(this._scope)); | |
| 2779 | + if (pair === null) return null; | |
| 2780 | + return new WebSocketRequestResponsePair(pair[0], pair[1]); | |
| 2781 | + } | |
| 2782 | + getWebSocketAutoResponseTimestamp(ws) { | |
| 2783 | + const ms = __ws_auto_response_ts(ws._id); | |
| 2784 | + return ms === null ? null : new Date(ms); | |
| 2785 | + } | |
| 2786 | + waitUntil(promise) { | |
| 2787 | + __registerWaitUntil(promise); | |
| 2788 | + } | |
| 2789 | +} | |
| 2790 | +function _instance(scope) { | |
| 2791 | + let inst = __cell.instances[scope]; | |
| 2792 | + if (!inst) { | |
| 2793 | + const className = scope.split(":")[0]; | |
| 2794 | + const cls = __cell.classes[className]; | |
| 2795 | + if (!cls) throw new Error("no DO class " + className); | |
| 2796 | + const state = new DurableObjectState(scope); | |
| 2797 | + inst = new cls(state, __cell.env); | |
| 2798 | + Object.defineProperty(inst, "__celldState", { value: state }); | |
| 2799 | + // Workerd worker-rpc.c++ getTargetInfo(): RPC needs `extends | |
| 2800 | + // DurableObject` unless the js_rpc compat flag is on. Decided | |
| 2801 | + // once here; dispatch reads a boolean. | |
| 2802 | + state._rpcOk = __cell.compat.jsRpc || | |
| 2803 | + __cell.doExports[className] === true; | |
| 2804 | + __cell.instances[scope] = inst; | |
| 2805 | + } | |
| 2806 | + return inst; | |
| 2807 | +} | |
| 2808 | +async function _readyInstance(scope) { | |
| 2809 | + const inst = _instance(scope); | |
| 2810 | + await inst.__celldState._ready(); | |
| 2811 | + return inst; | |
| 2812 | +} | |
| 2813 | +const __actorEventStack = []; | |
| 2814 | +const __currentActorEvent = () => { | |
| 2815 | + const context = String(__io_context_id()); | |
| 2816 | + if (context === "") return undefined; | |
| 2817 | + for (let index = __actorEventStack.length - 1; index >= 0; index--) { | |
| 2818 | + const event = __actorEventStack[index]; | |
| 2819 | + if (event.context === context) return event; | |
| 2820 | + } | |
| 2821 | + return undefined; | |
| 2822 | +}; | |
| 2823 | +const __currentActorScope = () => __currentActorEvent()?.scope ?? ""; | |
| 2824 | +const __beginActorEvent = (scope) => { | |
| 2825 | + __rpcSignalRefresh(); | |
| 2826 | + const event = { scope, context: String(__io_context_id()) }; | |
| 2827 | + __actorEventStack.push(event); | |
| 2828 | + return event; | |
| 2829 | +}; | |
| 2830 | +const __endActorEvent = (event) => { | |
| 2831 | + const index = __actorEventStack.lastIndexOf(event); | |
| 2832 | + if (index >= 0) __actorEventStack.splice(index, 1); | |
| 2833 | +}; | |
| 2834 | +const __endActorEventsForContext = (context) => { | |
| 2835 | + for (let index = __actorEventStack.length - 1; index >= 0; index--) { | |
| 2836 | + if (__actorEventStack[index].context === context) | |
| 2837 | + __actorEventStack.splice(index, 1); | |
| 2838 | + } | |
| 2839 | +}; | |
| 2840 | +const __incomingRequestSignals = new Map(); | |
| 2841 | +const __abortSignal = (signal, reason) => { | |
| 2842 | + if (signal.aborted) return; | |
| 2843 | + signal.aborted = true; | |
| 2844 | + signal.reason = reason; | |
| 2845 | + signal.dispatchEvent(new Event("abort")); | |
| 2846 | +}; | |
| 2847 | +const __abortIncomingRequest = __celld.__abortIncomingRequest = (requestId) => { | |
| 2848 | + const signal = __incomingRequestSignals.get(String(requestId)); | |
| 2849 | + if (signal && !signal.aborted) { | |
| 2850 | + __abortSignal(signal, new Error("The client has disconnected")); | |
| 2851 | + return true; | |
| 2852 | + } | |
| 2853 | + return false; | |
| 2854 | +}; | |
| 2855 | +__celld.__registerIncomingRequest = (requestId, request) => { | |
| 2856 | + __incomingRequestSignals.set(String(requestId), request.signal); | |
| 2857 | +}; | |
| 2858 | +__celld.__finishIncomingRequest = (requestId) => { | |
| 2859 | + __incomingRequestSignals.delete(String(requestId)); | |
| 2860 | +}; | |
| 2861 | +__celld.__retireInputGateContext = (context) => { | |
| 2862 | + for (const [scope, block] of __cellBlocks) { | |
| 2863 | + const retired = [...block.events].filter(([, record]) => | |
| 2864 | + record.owner === context || record.reaction === context | |
| 2865 | + ); | |
| 2866 | + if (retired.length === 0) continue; | |
| 2867 | + const holder = retired.find(([event]) => block.holder === event); | |
| 2868 | + if (holder === undefined) { | |
| 2869 | + // A queued callback has not changed the actor. Remove only that | |
| 2870 | + // callback, and let an unrelated holder continue with the same state. | |
| 2871 | + for (const [event, record] of retired) { | |
| 2872 | + record.retired = true; | |
| 2873 | + record.settleReady(); | |
| 2874 | + block.events.delete(event); | |
| 2875 | + if (record.actorEvent !== undefined) | |
| 2876 | + __endActorEvent(record.actorEvent); | |
| 2877 | + } | |
| 2878 | + if (block.events.size === 0 && __cellBlocks.get(scope) === block) | |
| 2879 | + __cellBlocks.delete(scope); | |
| 2880 | + continue; | |
| 2881 | + } | |
| 2882 | + // A running callback changed this actor and cannot reach its own | |
| 2883 | + // `finally`. Reset the actor, and release the host gate when the context | |
| 2884 | + // that started the callback differs from the turn that owns its work. | |
| 2885 | + const [holderEvent, holderRecord] = holder; | |
| 2886 | + __gate_release( | |
| 2887 | + scope, | |
| 2888 | + holderEvent, | |
| 2889 | + holderRecord.owner, | |
| 2890 | + "the cell's critical section ended without releasing", | |
| 2891 | + ); | |
| 2892 | + const instance = __cell.instances[scope]; | |
| 2893 | + if (instance !== undefined) instance.__celldState._aborted = true; | |
| 2894 | + __storage_cancel_pending_puts(scope); | |
| 2895 | + if (instance !== undefined && __cell.instances[scope] === instance) | |
| 2896 | + delete __cell.instances[scope]; | |
| 2897 | + for (const record of block.events.values()) { | |
| 2898 | + record.retired = true; | |
| 2899 | + record.settleReady(); | |
| 2900 | + if (record.actorEvent !== undefined) | |
| 2901 | + __endActorEvent(record.actorEvent); | |
| 2902 | + } | |
| 2903 | + // The old actor cannot run any block `finally`. A later event creates an | |
| 2904 | + // instance whose ready promise contains none of this actor's work. | |
| 2905 | + if (__cellBlocks.get(scope) === block) __cellBlocks.delete(scope); | |
| 2906 | + } | |
| 2907 | + __endActorEventsForContext(context); | |
| 2908 | +}; | |
| 2909 | +// Race a pending dispatch against the caller's abort signal: on abort, | |
| 2910 | +// run `abandon` (which reaches the target's side) and reject with the | |
| 2911 | +// caller's reason. The dispatch keeps its settle handlers, so a late | |
| 2912 | +// settlement after abandonment cannot trip the unhandled-rejection | |
| 2913 | +// signal. | |
| 2914 | +const __raceCallerAbort = (dispatch, signal, abandon) => | |
| 2915 | + new Promise((resolve, reject) => { | |
| 2916 | + let settled = false; | |
| 2917 | + const onAbort = () => { | |
| 2918 | + if (settled) return; | |
| 2919 | + settled = true; | |
| 2920 | + abandon(); | |
| 2921 | + reject(signal.reason); | |
| 2922 | + }; | |
| 2923 | + signal.addEventListener("abort", onAbort, { once: true }); | |
| 2924 | + dispatch.then( | |
| 2925 | + (value) => { | |
| 2926 | + if (settled) return; | |
| 2927 | + settled = true; | |
| 2928 | + signal.removeEventListener("abort", onAbort); | |
| 2929 | + resolve(value); | |
| 2930 | + }, | |
| 2931 | + (error) => { | |
| 2932 | + if (settled) return; | |
| 2933 | + settled = true; | |
| 2934 | + signal.removeEventListener("abort", onAbort); | |
| 2935 | + reject(error); | |
| 2936 | + }, | |
| 2937 | + ); | |
| 2938 | + }); | |
| 2939 | +const __awaitCancellableDoCall = (operation, signal) => { | |
| 2940 | + if (signal.aborted) { | |
| 2941 | + __do_call_cancel(operation.__celldCancelId); | |
| 2942 | + return Promise.reject(signal.reason); | |
| 2943 | + } | |
| 2944 | + return __raceCallerAbort(operation, signal, | |
| 2945 | + () => __do_call_cancel(operation.__celldCancelId)); | |
| 2946 | +}; | |
| 2947 | +// Workerd semantics: a Response crossing a service binding is a fresh | |
| 2948 | +// fetch-shaped Response -- immutable headers, default reason phrase, | |
| 2949 | +// the request URL, and a real body stream -- never the callee's own | |
| 2950 | +// mutable object. | |
| 2951 | +const __STATUS_TEXT = { | |
| 2952 | + 100: "Continue", 101: "Switching Protocols", 102: "Processing", | |
| 2953 | + 103: "Early Hints", 200: "OK", 201: "Created", 202: "Accepted", | |
| 2954 | + 203: "Non-Authoritative Information", 204: "No Content", | |
| 2955 | + 205: "Reset Content", 206: "Partial Content", 207: "Multi-Status", | |
| 2956 | + 208: "Already Reported", 226: "IM Used", 300: "Multiple Choices", | |
| 2957 | + 301: "Moved Permanently", 302: "Found", 303: "See Other", | |
| 2958 | + 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", | |
| 2959 | + 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", | |
| 2960 | + 402: "Payment Required", 403: "Forbidden", 404: "Not Found", | |
| 2961 | + 405: "Method Not Allowed", 406: "Not Acceptable", | |
| 2962 | + 407: "Proxy Authentication Required", 408: "Request Timeout", | |
| 2963 | + 409: "Conflict", 410: "Gone", 411: "Length Required", | |
| 2964 | + 412: "Precondition Failed", 413: "Payload Too Large", | |
| 2965 | + 414: "URI Too Long", 415: "Unsupported Media Type", | |
| 2966 | + 416: "Range Not Satisfiable", 417: "Expectation Failed", | |
| 2967 | + 418: "I'm a teapot", 421: "Misdirected Request", | |
| 2968 | + 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", | |
| 2969 | + 425: "Too Early", 426: "Upgrade Required", | |
| 2970 | + 428: "Precondition Required", 429: "Too Many Requests", | |
| 2971 | + 431: "Request Header Fields Too Large", | |
| 2972 | + 451: "Unavailable For Legal Reasons", 500: "Internal Server Error", | |
| 2973 | + 501: "Not Implemented", 502: "Bad Gateway", | |
| 2974 | + 503: "Service Unavailable", 504: "Gateway Timeout", | |
| 2975 | + 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", | |
| 2976 | + 507: "Insufficient Storage", 508: "Loop Detected", | |
| 2977 | + 510: "Not Extended", 511: "Network Authentication Required", | |
| 2978 | +}; | |
| 2979 | +const __ERROR_RESPONSE_MESSAGE = | |
| 2980 | + "Return value from serve handler must not be an error " + | |
| 2981 | + "response (like Response.error())"; | |
| 2982 | +const __wrapServiceResponse = (res, url) => { | |
| 2983 | + // Response.error() represents a Fetch network error, not an HTTP response. | |
| 2984 | + // Letting status 0 cross this seam turns it into an ordinary response and | |
| 2985 | + // makes callers continue after the target explicitly reported failure. | |
| 2986 | + if (res.type === "error" || res.status === 0) { | |
| 2987 | + throw new TypeError(__ERROR_RESPONSE_MESSAGE); | |
| 2988 | + } | |
| 2989 | + // A 101 that crossed isolates carries a target rather than a socket: the | |
| 2990 | + // pair's other end is in the isolate that answered, and the two cannot be | |
| 2991 | + // linked the way the loopback below links them. Give the caller a client | |
| 2992 | + // end the host can join to that target, on the same terms as a Durable | |
| 2993 | + // Object subrequest -- nothing binds until `accept()`, so a response | |
| 2994 | + // passed straight back out keeps the direct route to the real client. | |
| 2995 | + const bound = !res.webSocket && res._wsTarget && res.status === 101 | |
| 2996 | + ? new WebSocket(undefined, [], res._wsTarget) | |
| 2997 | + : undefined; | |
| 2998 | + const wrapped = new Response( | |
| 2999 | + // Buffered bodies re-stream (an empty buffer still yields a | |
| 3000 | + // stream, as over real HTTP); a streaming body passes through. | |
| 3001 | + res._bodyBytes !== null ? res._bodyBytes : res.body, | |
| 3002 | + { | |
| 3003 | + status: res.status, | |
| 3004 | + statusText: | |
| 3005 | + res.statusText || __STATUS_TEXT[res.status] || "", | |
| 3006 | + headers: res.headers, | |
| 3007 | + webSocket: res.webSocket || bound, | |
| 3008 | + __wsTarget: res._wsTarget, | |
| 3009 | + }, | |
| 3010 | + ); | |
| 3011 | + // The constructor copies headers, so mark the copy. | |
| 3012 | + Object.defineProperty(wrapped.headers, "_immutable", { value: true }); | |
| 3013 | + wrapped.url = url; | |
| 3014 | + // An upgraded pair whose both ends live in this isolate: link them | |
| 3015 | + // directly -- the host connection seam only reaches external | |
| 3016 | + // clients. Frames the handler queued before linking flush first. | |
| 3017 | + const client = wrapped.webSocket; | |
| 3018 | + if (wrapped.status === 101 && client && client._peer) { | |
| 3019 | + const server = client._peer; | |
| 3020 | + client._loopback = server; | |
| 3021 | + server._loopback = client; | |
| 3022 | + for (const frame of server._pending.splice(0)) { | |
| 3023 | + // "send-binary" joined this queue with outbound sockets; without a case | |
| 3024 | + // of its own it fell through to the close branch and tore the pair down | |
| 3025 | + // instead of delivering the frame. | |
| 3026 | + if (frame[0] === "send") | |
| 3027 | + queueMicrotask(() => client._dispatchMessage(frame[1])); | |
| 3028 | + else if (frame[0] === "send-binary") | |
| 3029 | + queueMicrotask(() => { | |
| 3030 | + const data = frame[1]; | |
| 3031 | + client._dispatchMessage( | |
| 3032 | + data instanceof ArrayBuffer ? data : data.buffer.slice( | |
| 3033 | + data.byteOffset, | |
| 3034 | + data.byteOffset + data.byteLength, | |
| 3035 | + ), | |
| 3036 | + ); | |
| 3037 | + }); | |
| 3038 | + else | |
| 3039 | + queueMicrotask( | |
| 3040 | + () => client._dispatchClose(frame[1], frame[2], true)); | |
| 3041 | + } | |
| 3042 | + } | |
| 3043 | + return wrapped; | |
| 3044 | +}; | |
| 3045 | +const __SERVICE_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); | |
| 3046 | +const __REQUEST_BODY_HEADERS = [ | |
| 3047 | + "content-encoding", "content-language", "content-length", | |
| 3048 | + "content-location", "content-type", "transfer-encoding", | |
| 3049 | +]; | |
| 3050 | +const __CROSS_ORIGIN_SENSITIVE_HEADERS = [ | |
| 3051 | + "authorization", "cookie", "proxy-authorization", | |
| 3052 | +]; | |
| 3053 | +// A service target only produces the first response. Fetch redirect handling | |
| 3054 | +// belongs to the caller, because the Location leaves through the caller's | |
| 3055 | +// ambient outbound policy rather than gaining the target service's authority. | |
| 3056 | +// Capture the replayable request state before dispatch: a same-isolate target | |
| 3057 | +// receives the Request itself and can consume or mutate it before it redirects. | |
| 3058 | +const __serviceRedirectState = (req) => ({ | |
| 3059 | + method: req.method, | |
| 3060 | + headers: req.headers.__celldHeaderList, | |
| 3061 | + body: req.body === null ? undefined | |
| 3062 | + : req._bodyBytes === null ? null : req._bodyBytes.slice(), | |
| 3063 | + signal: req._signalForSubrequests, | |
| 3064 | +}); | |
| 3065 | +const __finishServiceFetch = async (res, req, replay) => { | |
| 3066 | + const response = __wrapServiceResponse(res, req.url); | |
| 3067 | + if (!__SERVICE_REDIRECT_STATUSES.has(response.status)) return response; | |
| 3068 | + const location = response.headers.get("location"); | |
| 3069 | + if (location === null) return response; | |
| 3070 | + if (req.redirect === "manual") return response; | |
| 3071 | + | |
| 3072 | + // Nobody can consume the redirect response after this branch. Cancelling it | |
| 3073 | + // releases a cross-isolate body stream instead of waiting for its idle TTL. | |
| 3074 | + if (response.body !== null) { | |
| 3075 | + try { await response.body.cancel(); } catch { /* the redirect still wins */ } | |
| 3076 | + } | |
| 3077 | + if (req.redirect === "error") | |
| 3078 | + throw new TypeError("A redirect was returned for a request with redirect mode error."); | |
| 3079 | + | |
| 3080 | + const url = new URL(location, req.url).href; | |
| 3081 | + let method = replay.method; | |
| 3082 | + let body = replay.body; | |
| 3083 | + const headers = new Headers(replay.headers); | |
| 3084 | + if ((response.status === 301 || response.status === 302) && method === "POST" || | |
| 3085 | + response.status === 303 && method !== "GET" && method !== "HEAD") { | |
| 3086 | + method = "GET"; | |
| 3087 | + body = undefined; | |
| 3088 | + for (const name of __REQUEST_BODY_HEADERS) headers.delete(name); | |
| 3089 | + } else if (body === null) { | |
| 3090 | + // A transferred or live JavaScript stream has no replay copy. Fetch treats | |
| 3091 | + // the redirect as a network error instead of sending an empty replacement. | |
| 3092 | + throw new TypeError("Cannot follow a redirect with a non-replayable request body."); | |
| 3093 | + } | |
| 3094 | + // The ambient fetch starts a new native request, so its HTTP client cannot | |
| 3095 | + // know that these credentials came from another origin and remove them. Do | |
| 3096 | + // that at the service-to-network boundary before they can leak to Location. | |
| 3097 | + if (new URL(req.url).origin !== new URL(url).origin) { | |
| 3098 | + for (const name of __CROSS_ORIGIN_SENSITIVE_HEADERS) headers.delete(name); | |
| 3099 | + } | |
| 3100 | + const init = { method, headers, redirect: "follow" }; | |
| 3101 | + if (body !== undefined) init.body = body; | |
| 3102 | + if (replay.signal !== null) init.signal = replay.signal; | |
| 3103 | + const followed = await globalThis.fetch(url, init); | |
| 3104 | + followed.redirected = true; | |
| 3105 | + if (followed.url === "") followed.url = url; | |
| 3106 | + return followed; | |
| 3107 | +}; | |
| 3108 | +// `[[services]]` binding: a Fetcher pointed at another Worker in this | |
| 3109 | +// process. No identity to resolve, so it goes straight to __svc_call. | |
| 3110 | +// Worker Loader (Code Mode): spawn a fresh isolate from supplied code and | |
| 3111 | +// invoke its default or named entrypoint through the cross-isolate request and | |
| 3112 | +// RPC paths. | |
| 3113 | +// A Fetcher can cross into a loaded isolate only as this host-minted route. | |
| 3114 | +// Reading properties from a Proxy is not a trustworthy brand check, so the | |
| 3115 | +// metadata lives in a side table that application objects cannot forge. | |
| 3116 | +const __outboundMeta = new WeakMap(); | |
| 3117 | +const __loaderServiceMarker = "__celld$loaderSvc"; | |
| 3118 | +__celld.__makeLoader = () => { | |
| 3119 | + // `get(name, ...)` is memoized by name to one isolate; `load()` is anonymous. | |
| 3120 | + // A stub holds a Promise<id> so `getCode` may be async and load lazily. | |
| 3121 | + const byName = new Map(); | |
| 3122 | + // getEntrypoint() and getDurableObjectClass() take the same options bag, so | |
| 3123 | + // one function reads it and returns the only option celld implements. | |
| 3124 | + // Workerd ignores an option it does not know; celld refuses it, because a | |
| 3125 | + // silently dropped option is exactly the defect getEntrypoint() had. Keeping | |
| 3126 | + // the rule here rather than in each method is what stops the two from | |
| 3127 | + // drifting apart again. | |
| 3128 | + const loaderProps = (method, options) => { | |
| 3129 | + if (options === null || options === undefined) return undefined; | |
| 3130 | + if (typeof options !== "object") | |
| 3131 | + throw new TypeError(method + "() options must be an object."); | |
| 3132 | + const extra = Object.keys(options).filter((key) => key !== "props"); | |
| 3133 | + if (extra.length !== 0) | |
| 3134 | + throw new TypeError( | |
| 3135 | + method + '() does not support the option "' + extra.join('", "') + | |
| 3136 | + '". celld supports only "props".'); | |
| 3137 | + return options.props; | |
| 3138 | + }; | |
| 3139 | + // `props` cross to the loaded isolate by structured clone, on the same | |
| 3140 | + // transport that already carries the call's arguments (`__rpcOut` below). | |
| 3141 | + // JSON is the obvious alternative and it is wrong: JSON.stringify turns a | |
| 3142 | + // Map, a Set, a Date, a typed array, and a RegExp into a plain object or a | |
| 3143 | + // string and reports no error, so the callee reads a mangled value that the | |
| 3144 | + // same call's arguments would have carried intact. Encoding here, once per | |
| 3145 | + // loader API call, also rejects an unclonable value at that call rather than | |
| 3146 | + // at the first operation. | |
| 3147 | + const loaderPropsSc = (method, options) => { | |
| 3148 | + const props = loaderProps(method, options); | |
| 3149 | + if (props === undefined) return undefined; | |
| 3150 | + // `lift` false: the props cross an isolate boundary, so a stub inside them | |
| 3151 | + // is a DataCloneError, exactly as a stub inside an argument of the same | |
| 3152 | + // call is. | |
| 3153 | + return __rpcOut(props, false); | |
| 3154 | + }; | |
| 3155 | + const makeEntrypoint = (idPromise, entrypoint, propsSc) => { | |
| 3156 | + const target = { | |
| 3157 | + async fetch(input, init) { | |
| 3158 | + const id = await idPromise; | |
| 3159 | + const req = new Request(input, init); | |
| 3160 | + // The verbatim header list; see the note on the outbound `fetch`. | |
| 3161 | + // The loaded worker rebuilds a `Headers` from these pairs, so a | |
| 3162 | + // repeat and its casing survive the isolate boundary. | |
| 3163 | + const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 3164 | + const { body, streamId } = await __subrequestBody(req); | |
| 3165 | + const r = JSON.parse( | |
| 3166 | + await __loader_fetch( | |
| 3167 | + id, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3168 | + propsSc === undefined ? new Uint8Array() : propsSc)); | |
| 3169 | + const responseBody = r.streamId !== undefined | |
| 3170 | + ? new CelldHttpBodyStream(r.streamId) | |
| 3171 | + : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); | |
| 3172 | + return __wrapServiceResponse( | |
| 3173 | + new Response(responseBody, { status: r.status, headers: r.headers }), | |
| 3174 | + req.url); | |
| 3175 | + }, | |
| 3176 | + }; | |
| 3177 | + // Both the default and named entrypoints expose RPC: property access is a | |
| 3178 | + // callable pipeline node dispatched via __loader_rpc to that entrypoint in | |
| 3179 | + // the loaded worker (default -> the "default" export, which | |
| 3180 | + // register_entrypoints registers like any other). fetch stays on the | |
| 3181 | + // target. Only single-method calls are supported for now. | |
| 3182 | + const session = { | |
| 3183 | + get: () => Promise.reject(new Error( | |
| 3184 | + "Awaitable properties on loaded workers are not supported yet.")), | |
| 3185 | + call: (path, args) => (async () => { | |
| 3186 | + if (path.length !== 1) | |
| 3187 | + throw new Error( | |
| 3188 | + "Pipelined property paths on loaded workers are not supported " + | |
| 3189 | + "yet."); | |
| 3190 | + const id = await idPromise; | |
| 3191 | + return __rpcDes( | |
| 3192 | + await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false), | |
| 3193 | + propsSc)); | |
| 3194 | + })(), | |
| 3195 | + }; | |
| 3196 | + return new Proxy(target, { | |
| 3197 | + get: (base, prop) => { | |
| 3198 | + if (prop === "then") return undefined; | |
| 3199 | + if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 3200 | + if (typeof prop !== "string") return undefined; | |
| 3201 | + return __makeNode(session, [prop], null); | |
| 3202 | + }, | |
| 3203 | + }); | |
| 3204 | + }; | |
| 3205 | + // Anonymous load() workers are evicted when their only stub is GC'd: the | |
| 3206 | + // finalizer drops the worker's isolate so it does not leak. Named get() | |
| 3207 | + // workers are retained by `byName` (memoized) and so are not registered. | |
| 3208 | + const finalizer = typeof FinalizationRegistry === "function" | |
| 3209 | + ? new FinalizationRegistry((id) => __loader_drop(id)) | |
| 3210 | + : null; | |
| 3211 | + const makeStub = (idPromise, evictable) => { | |
| 3212 | + // Explicit disposal evicts the worker deterministically; the finalizer is | |
| 3213 | + // a GC backstop for anonymous stubs that are dropped without disposing. | |
| 3214 | + // __loader_drop is idempotent, so the two paths cannot double-free. | |
| 3215 | + const drop = () => { idPromise.then((id) => __loader_drop(id), () => {}); }; | |
| 3216 | + const stub = { | |
| 3217 | + getEntrypoint(name = null, options = {}) { | |
| 3218 | + return makeEntrypoint( | |
| 3219 | + idPromise, name === null ? "default" : String(name), | |
| 3220 | + loaderPropsSc("getEntrypoint", options)); | |
| 3221 | + }, | |
| 3222 | + getDurableObjectClass(name = null, options = {}) { | |
| 3223 | + return __makeDurableObjectClass( | |
| 3224 | + idPromise, name, loaderPropsSc("getDurableObjectClass", options)); | |
| 3225 | + }, | |
| 3226 | + dispose: drop, | |
| 3227 | + }; | |
| 3228 | + if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; | |
| 3229 | + if (evictable && finalizer) | |
| 3230 | + idPromise.then((id) => finalizer.register(stub, id), () => {}); | |
| 3231 | + return stub; | |
| 3232 | + }; | |
| 3233 | + // JSON.stringify silently drops binary values, so each non-string module -- | |
| 3234 | + // wasm bytes as a BufferSource, or an explicit module shape -- is normalized | |
| 3235 | + // first. JavaScript modules become plain strings, and wasm moves into a | |
| 3236 | + // side-band `[name, Uint8Array]` list so multi-MB blobs never take a | |
| 3237 | + // base64/JSON round-trip. | |
| 3238 | + const toBytes = (v) => v instanceof ArrayBuffer ? new Uint8Array(v) | |
| 3239 | + : ArrayBuffer.isView(v) | |
| 3240 | + ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : null; | |
| 3241 | + const moduleKinds = [ | |
| 3242 | + "js", "cjs", "py", "text", "data", "json", "wasm", | |
| 3243 | + ]; | |
| 3244 | + const encodeLoaderEnv = (value) => { | |
| 3245 | + if (value === undefined || value === null) | |
| 3246 | + return { env: undefined, envRoutes: [] }; | |
| 3247 | + const envRoutes = []; | |
| 3248 | + const seen = new Map(); | |
| 3249 | + const project = (v) => { | |
| 3250 | + if (v === null || | |
| 3251 | + (typeof v !== "object" && typeof v !== "function")) return v; | |
| 3252 | + const cached = seen.get(v); | |
| 3253 | + if (cached !== undefined) return cached; | |
| 3254 | + const route = __outboundMeta.get(v); | |
| 3255 | + if (route !== undefined) { | |
| 3256 | + const marker = { [__loaderServiceMarker]: envRoutes.length }; | |
| 3257 | + seen.set(v, marker); | |
| 3258 | + envRoutes.push([ | |
| 3259 | + route.script, | |
| 3260 | + route.entrypoint, | |
| 3261 | + route.propsSc ?? (route.props === undefined | |
| 3262 | + ? new Uint8Array() : __rpcOut(route.props, false)), | |
| 3263 | + ]); | |
| 3264 | + return marker; | |
| 3265 | + } | |
| 3266 | + if (Object.prototype.hasOwnProperty.call(v, __loaderServiceMarker)) | |
| 3267 | + throw new DOMException( | |
| 3268 | + `Worker Loader env contains the reserved key ` + | |
| 3269 | + `${JSON.stringify(__loaderServiceMarker)}.`, | |
| 3270 | + "DataCloneError"); | |
| 3271 | + if (typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 3272 | + __stubMeta.has(v) || __doStubMeta.has(v)) | |
| 3273 | + throw new DOMException( | |
| 3274 | + "Worker Loader env supports only Service Binding capabilities.", | |
| 3275 | + "DataCloneError"); | |
| 3276 | + if (v instanceof Map) { | |
| 3277 | + const out = new Map(); | |
| 3278 | + seen.set(v, out); | |
| 3279 | + for (const [key, item] of v) out.set(project(key), project(item)); | |
| 3280 | + return out; | |
| 3281 | + } | |
| 3282 | + if (v instanceof Set) { | |
| 3283 | + const out = new Set(); | |
| 3284 | + seen.set(v, out); | |
| 3285 | + for (const item of v) out.add(project(item)); | |
| 3286 | + return out; | |
| 3287 | + } | |
| 3288 | + const proto = Object.getPrototypeOf(v); | |
| 3289 | + if (!Array.isArray(v) && proto !== Object.prototype && proto !== null) | |
| 3290 | + return v; | |
| 3291 | + const out = Array.isArray(v) ? [] : {}; | |
| 3292 | + seen.set(v, out); | |
| 3293 | + for (const key of Object.keys(v)) out[key] = project(v[key]); | |
| 3294 | + return out; | |
| 3295 | + }; | |
| 3296 | + return { env: __sc_encode(project(value)), envRoutes }; | |
| 3297 | + }; | |
| 3298 | + const encodeModules = (c) => { | |
| 3299 | + if (c === null || typeof c !== "object" || c.modules === null | |
| 3300 | + || typeof c.modules !== "object") | |
| 3301 | + return { config: c, wasm: [], outbound: undefined }; | |
| 3302 | + const modules = {}; | |
| 3303 | + const wasm = []; | |
| 3304 | + for (const [name, value] of Object.entries(c.modules)) { | |
| 3305 | + const wrapped = value !== null && typeof value === "object" ? value : {}; | |
| 3306 | + const explicitKinds = moduleKinds.filter((kind) => | |
| 3307 | + Object.prototype.hasOwnProperty.call(wrapped, kind) | |
| 3308 | + ); | |
| 3309 | + if (explicitKinds.length > 1) | |
| 3310 | + throw new TypeError( | |
| 3311 | + `Worker Loader module ${JSON.stringify(name)} must contain exactly ` + | |
| 3312 | + "one module type."); | |
| 3313 | + const kind = explicitKinds[0]; | |
| 3314 | + if (kind === "js") { | |
| 3315 | + const source = wrapped[kind]; | |
| 3316 | + if (typeof source !== "string") | |
| 3317 | + throw new TypeError( | |
| 3318 | + `Worker Loader module ${JSON.stringify(name)} field ` + | |
| 3319 | + `${JSON.stringify(kind)} must be a string.`); | |
| 3320 | + modules[name] = source; | |
| 3321 | + continue; | |
| 3322 | + } | |
| 3323 | + const bytes = toBytes(value) ?? | |
| 3324 | + (kind === "wasm" ? toBytes(wrapped.wasm) : null); | |
| 3325 | + if (bytes !== null) wasm.push([name, bytes]); | |
| 3326 | + else modules[name] = value; | |
| 3327 | + } | |
| 3328 | + let outbound; | |
| 3329 | + let outboundProps; | |
| 3330 | + if (Object.prototype.hasOwnProperty.call(c, "globalOutbound")) { | |
| 3331 | + if (c.globalOutbound === undefined) { | |
| 3332 | + outbound = undefined; | |
| 3333 | + } else if (c.globalOutbound === null) { | |
| 3334 | + outbound = null; | |
| 3335 | + } else { | |
| 3336 | + const meta = __outboundMeta.get(c.globalOutbound); | |
| 3337 | + if (meta === undefined) | |
| 3338 | + throw new TypeError("globalOutbound must be a Fetcher or null."); | |
| 3339 | + // JSON carries only the host-minted route. Props use V8 structured | |
| 3340 | + // clone bytes, so their types and the cross-isolate clone boundary | |
| 3341 | + // match the other parameterized ctx.exports transports. | |
| 3342 | + outboundProps = meta.propsSc ?? (meta.props === undefined | |
| 3343 | + ? new Uint8Array() | |
| 3344 | + : __rpcOut(meta.props, false)); | |
| 3345 | + outbound = JSON.stringify({ | |
| 3346 | + script: meta.script, | |
| 3347 | + entrypoint: meta.entrypoint, | |
| 3348 | + }); | |
| 3349 | + } | |
| 3350 | + } | |
| 3351 | + const { env, envRoutes } = encodeLoaderEnv(c.env); | |
| 3352 | + const { | |
| 3353 | + globalOutbound: _globalOutbound, | |
| 3354 | + env: _env, | |
| 3355 | + ...rest | |
| 3356 | + } = c; | |
| 3357 | + return { | |
| 3358 | + config: { ...rest, modules }, wasm, outbound, outboundProps, | |
| 3359 | + env, envRoutes, | |
| 3360 | + }; | |
| 3361 | + }; | |
| 3362 | + // getCode is deferred into a microtask so a throw (or async getCode) | |
| 3363 | + // surfaces as a rejection when the worker is first used, not at get()/load(). | |
| 3364 | + const loadFrom = (getCode) => | |
| 3365 | + Promise.resolve().then(getCode) | |
| 3366 | + .then((c) => { | |
| 3367 | + const { | |
| 3368 | + config, wasm, outbound, outboundProps, env, envRoutes, | |
| 3369 | + } = encodeModules(c); | |
| 3370 | + return __loader_load( | |
| 3371 | + JSON.stringify(config), wasm, outbound, outboundProps, env, | |
| 3372 | + envRoutes); | |
| 3373 | + }); | |
| 3374 | + return { | |
| 3375 | + load(code) { return makeStub(loadFrom(() => code), true); }, | |
| 3376 | + get(name, getCode) { | |
| 3377 | + let idPromise = byName.get(name); | |
| 3378 | + if (idPromise === undefined) { | |
| 3379 | + idPromise = loadFrom(getCode); | |
| 3380 | + byName.set(name, idPromise); | |
| 3381 | + } | |
| 3382 | + return makeStub(idPromise, false); | |
| 3383 | + }, | |
| 3384 | + }; | |
| 3385 | +}; | |
| 3386 | + | |
| 3387 | +const __makeServiceBinding = __celld.__makeServiceBinding = | |
| 3388 | + (script, entrypoint = null, propsSc = undefined) => { | |
| 3389 | + const target = { | |
| 3390 | + async fetch(input, init) { | |
| 3391 | + const req = new Request(input, init); | |
| 3392 | + const signal = req._signalForSubrequests; | |
| 3393 | + if (signal?.aborted) throw signal.reason; | |
| 3394 | + // A stream body advertises its length the way the HTTP layer | |
| 3395 | + // would: known length -> Content-Length, unknown -> chunked. | |
| 3396 | + if (req._bodyBytes === null && | |
| 3397 | + !req.headers.has("content-length") && | |
| 3398 | + !req.headers.has("transfer-encoding")) { | |
| 3399 | + const length = req.body._expectedLength; | |
| 3400 | + if (length === undefined) | |
| 3401 | + req.headers.set("transfer-encoding", "chunked"); | |
| 3402 | + else req.headers.set("content-length", String(length)); | |
| 3403 | + } | |
| 3404 | + const redirectState = __serviceRedirectState(req); | |
| 3405 | + // Fast path: the target is this same script, so its handler lives in | |
| 3406 | + // this isolate. Skip the op + pool-thread hop and call it directly, | |
| 3407 | + // inside its own event so the target's waitUntil does not attach to | |
| 3408 | + // the caller's. Cross-script targets still need their own isolate. | |
| 3409 | + if (script === __cell.script && entrypoint !== null) { | |
| 3410 | + // Mirror __dispatchTo: the target sees a fresh incoming signal, | |
| 3411 | + // aborted with "The client has disconnected" when the caller | |
| 3412 | + // abandons the call or cancels the response body; the caller's | |
| 3413 | + // own signal races the dispatch so an abandoned call rejects | |
| 3414 | + // immediately instead of pinning on a hung target. | |
| 3415 | + const requestController = new AbortController(); | |
| 3416 | + const dispatch = __dispatchEntrypointFetch( | |
| 3417 | + entrypoint, | |
| 3418 | + new Request(req, { | |
| 3419 | + signal: requestController.signal, | |
| 3420 | + __celldIncomingSignal: true, | |
| 3421 | + })); | |
| 3422 | + const response = signal | |
| 3423 | + ? await __raceCallerAbort(dispatch, signal, () => | |
| 3424 | + requestController.abort( | |
| 3425 | + new Error("The client has disconnected"))) | |
| 3426 | + : await dispatch; | |
| 3427 | + __attachResponseRequestCancellation( | |
| 3428 | + response, requestController, true); | |
| 3429 | + return __finishServiceFetch(response, req, redirectState); | |
| 3430 | + } | |
| 3431 | + if (script === __cell.script && typeof __cell.selfFetch === "function") { | |
| 3432 | + if (__cell.svcDepth >= 8) | |
| 3433 | + throw new Error( | |
| 3434 | + "Service binding recursion limit exceeded (8)"); | |
| 3435 | + __cell.svcDepth = (__cell.svcDepth || 0) + 1; | |
| 3436 | + const ctx = __beginEvent(); | |
| 3437 | + try { | |
| 3438 | + return __finishServiceFetch( | |
| 3439 | + await __ctxRun(undefined, | |
| 3440 | + () => __cell.selfFetch(req, __cell.env, ctx)), | |
| 3441 | + req, redirectState); | |
| 3442 | + } finally { | |
| 3443 | + __cell.svcDepth--; | |
| 3444 | + __endEvent(); | |
| 3445 | + } | |
| 3446 | + } | |
| 3447 | + // The verbatim header list; see the note on the outbound `fetch`. The | |
| 3448 | + // target isolate rebuilds a `Headers` from these pairs, so a repeat and | |
| 3449 | + // its casing survive the crossing. | |
| 3450 | + const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 3451 | + // Cross-isolate calls carry exact bytes. A host-backed stream transfers | |
| 3452 | + // its one source to the target, and another stream uses the byte fallback. | |
| 3453 | + const { body, streamId } = await __subrequestBody(req); | |
| 3454 | + const r = JSON.parse(await (signal | |
| 3455 | + ? __awaitCancellableDoCall( | |
| 3456 | + __svc_call_cancellable( | |
| 3457 | + script, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3458 | + propsSc), | |
| 3459 | + signal) | |
| 3460 | + : __svc_call( | |
| 3461 | + script, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3462 | + propsSc))); | |
| 3463 | + const responseBody = r.streamId !== undefined | |
| 3464 | + ? new CelldHttpBodyStream(r.streamId) | |
| 3465 | + : r.body !== undefined | |
| 3466 | + ? r.body | |
| 3467 | + : Uint8Array.from(r.bodyBytes || []); | |
| 3468 | + return __finishServiceFetch( | |
| 3469 | + new Response(responseBody, { | |
| 3470 | + status: r.status, headers: r.headers, __wsTarget: r.wsTarget, | |
| 3471 | + }), | |
| 3472 | + req, redirectState); | |
| 3473 | + }, | |
| 3474 | + // Workerd's test-visible Fetcher.scheduled(): invoke the target's | |
| 3475 | + // scheduled handler and report the outcome. | |
| 3476 | + async scheduled(options = {}) { | |
| 3477 | + if (script !== __cell.script || entrypoint !== null || | |
| 3478 | + typeof __cell.selfScheduled !== "function") | |
| 3479 | + throw new Error( | |
| 3480 | + "scheduled() is only implemented for same-script service " + | |
| 3481 | + "bindings whose target has a scheduled handler"); | |
| 3482 | + let noRetry = false; | |
| 3483 | + const ctrl = { | |
| 3484 | + scheduledTime: options.scheduledTime === undefined | |
| 3485 | + ? Date.now() : Number(options.scheduledTime), | |
| 3486 | + cron: options.cron === undefined ? "" : String(options.cron), | |
| 3487 | + noRetry() { noRetry = true; }, | |
| 3488 | + }; | |
| 3489 | + const ctx = __beginEvent(); | |
| 3490 | + try { | |
| 3491 | + await __cell.selfScheduled(ctrl, __cell.env, ctx); | |
| 3492 | + return { outcome: "ok", noRetry }; | |
| 3493 | + } finally { | |
| 3494 | + const drain = __endEvent(); | |
| 3495 | + // scheduled() reports the event outcome, so it cannot return while the | |
| 3496 | + // work that defines that event is still pending. Fetch replies differ: | |
| 3497 | + // a streamed response can depend on waitUntil work and must return first. | |
| 3498 | + if (drain !== null) await drain; | |
| 3499 | + } | |
| 3500 | + }, | |
| 3501 | + }; | |
| 3502 | + // An omitted entrypoint selects the module's default export, which may be a | |
| 3503 | + // WorkerEntrypoint or an object handler. `entrypoint = "Name"` selects that | |
| 3504 | + // named class. Any property other than a reserved Fetcher method is an | |
| 3505 | + // awaitable/callable pipeline node: awaiting | |
| 3506 | + // resolves the property remotely (a property-GET wire op), calling | |
| 3507 | + // invokes it, and deeper access extends the path, resolved on the | |
| 3508 | + // receiver side in one op. Same-script dispatch stays in this | |
| 3509 | + // isolate, so stub-able values may cross. A property path rooted | |
| 3510 | + // directly at the binding is context-free (ctx null): awaiting it | |
| 3511 | + // starts a fresh session, as in Workerd. | |
| 3512 | + const rpcEntrypoint = entrypoint === null ? "default" : entrypoint; | |
| 3513 | + const session = __entrypointSession( | |
| 3514 | + rpcEntrypoint, script === __cell.script, script, undefined, propsSc); | |
| 3515 | + const binding = new Proxy(target, { | |
| 3516 | + getPrototypeOf: () => __cf.ServiceStub.prototype, | |
| 3517 | + get: (base, prop) => { | |
| 3518 | + if (prop === "then") return undefined; // a stub is not a thenable | |
| 3519 | + if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 3520 | + if (typeof prop !== "string") return undefined; | |
| 3521 | + // Workerd's test hook: the named method as a callable handle, | |
| 3522 | + // resolved -- and refused -- on the receiver side. | |
| 3523 | + if (prop === "getRpcMethodForTestOnly") | |
| 3524 | + return (name) => __makeNode(session, [String(name)], null); | |
| 3525 | + return __makeNode(session, [prop], null); | |
| 3526 | + }}); | |
| 3527 | + __outboundMeta.set(binding, { script, entrypoint, propsSc }); | |
| 3528 | + return binding; | |
| 3529 | +}; | |
| 3530 | + | |
| 3531 | +__celld.__installLoaderEnv = (bytes, routes) => { | |
| 3532 | + const env = __sc_decode(bytes); | |
| 3533 | + const seen = new Set(); | |
| 3534 | + const revive = (v) => { | |
| 3535 | + if (v === null || typeof v !== "object") return v; | |
| 3536 | + const routeIndex = Object.prototype.hasOwnProperty.call( | |
| 3537 | + v, __loaderServiceMarker) ? v[__loaderServiceMarker] : undefined; | |
| 3538 | + if (Number.isSafeInteger(routeIndex) && routeIndex >= 0) { | |
| 3539 | + // Rust supplies flat [script, entrypoint, props] triples, and the marker | |
| 3540 | + // stores the triple index rather than an offset into that array. | |
| 3541 | + const routeOffset = routeIndex * 3; | |
| 3542 | + if (!Number.isSafeInteger(routeOffset) || routeOffset + 2 >= routes.length) | |
| 3543 | + throw new DOMException( | |
| 3544 | + "Worker Loader env contains an invalid capability.", | |
| 3545 | + "DataCloneError"); | |
| 3546 | + return __makeServiceBinding( | |
| 3547 | + routes[routeOffset], routes[routeOffset + 1], routes[routeOffset + 2]); | |
| 3548 | + } | |
| 3549 | + if (seen.has(v)) return v; | |
| 3550 | + seen.add(v); | |
| 3551 | + if (v instanceof Map) { | |
| 3552 | + const entries = [...v]; | |
| 3553 | + v.clear(); | |
| 3554 | + for (const [key, item] of entries) v.set(revive(key), revive(item)); | |
| 3555 | + return v; | |
| 3556 | + } | |
| 3557 | + if (v instanceof Set) { | |
| 3558 | + const items = [...v]; | |
| 3559 | + v.clear(); | |
| 3560 | + for (const item of items) v.add(revive(item)); | |
| 3561 | + return v; | |
| 3562 | + } | |
| 3563 | + if (Array.isArray(v) || Object.getPrototypeOf(v) === Object.prototype || | |
| 3564 | + Object.getPrototypeOf(v) === null) | |
| 3565 | + for (const key of Object.keys(v)) v[key] = revive(v[key]); | |
| 3566 | + return v; | |
| 3567 | + }; | |
| 3568 | + Object.assign(__cell.env, revive(env)); | |
| 3569 | +}; | |
| 3570 | +// RPC marshalling: V8 structured clone (Workerd js-rpc semantics), so | |
| 3571 | +// undefined, Date, Map, Set, BigInt, typed arrays, and cycles survive. | |
| 3572 | +// A value V8 cannot clone throws DataCloneError, as in Workerd. | |
| 3573 | +// | |
| 3574 | +// The envelope's first byte tags the payload. 0xff (the clone version | |
| 3575 | +// header) = plain clone, decoded as-is. 0x01 = clone of a lifted tree in | |
| 3576 | +// which RpcTarget instances, functions, and Durable Object stubs were | |
| 3577 | +// replaced by stub markers; the lift runs only after a plain clone | |
| 3578 | +// already threw. A projection walk happens first because V8 silently erases | |
| 3579 | +// custom and null prototypes. 0x02 = a lifted tree carrying only by-value | |
| 3580 | +// host types (Blob/File, Headers, | |
| 3581 | +// Request/Response) and no capabilities -- decoded like 0x01, but a | |
| 3582 | +// reply so tagged does not root its callee context. 0x00 = clone of | |
| 3583 | +// [error, ownProps] -- a callee exception crossing as a real Error. | |
| 3584 | +const __dataCloneError = (error) => new DOMException( | |
| 3585 | + String(error && error.message || error), "DataCloneError"); | |
| 3586 | +const __rpcUnsupportedType = (value) => new DOMException( | |
| 3587 | + 'Could not serialize object of type "' + | |
| 3588 | + (__util_constructor_name(value) || "Object") + | |
| 3589 | + '". This type does not support serialization.', | |
| 3590 | + "DataCloneError"); | |
| 3591 | +// V8 clones a user-class instance and a null-prototype object as plain data, | |
| 3592 | +// but Workerd refuses both over RPC. Project the value graph before V8 can | |
| 3593 | +// erase that distinction. The projection also snapshots enumerable getters, | |
| 3594 | +// so validation and serialization cannot invoke one getter twice. Native | |
| 3595 | +// clone types and RPC host types keep their own serializers. | |
| 3596 | +const __rpcProject = (value) => { | |
| 3597 | + const seen = new Map(); | |
| 3598 | + const originals = new WeakMap(); | |
| 3599 | + const set = (target, key, value) => Object.defineProperty(target, key, { | |
| 3600 | + value, enumerable: true, configurable: true, writable: true, | |
| 3601 | + }); | |
| 3602 | + const project = (v) => { | |
| 3603 | + if (v === null || (typeof v !== "object" && typeof v !== "function")) | |
| 3604 | + return v; | |
| 3605 | + const cached = seen.get(v); | |
| 3606 | + if (cached !== undefined) return cached; | |
| 3607 | + if (typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 3608 | + __stubMeta.has(v) || __svcMeta.has(v) || __doStubMeta.has(v) || | |
| 3609 | + v instanceof Headers || v instanceof Blob || v instanceof Request || | |
| 3610 | + v instanceof Response || v instanceof ReadableStream || | |
| 3611 | + v instanceof WritableStream || v instanceof AbortSignal || | |
| 3612 | + v instanceof Date || v instanceof RegExp || v instanceof Error || | |
| 3613 | + v instanceof ArrayBuffer || ArrayBuffer.isView(v) || | |
| 3614 | + (typeof SharedArrayBuffer !== "undefined" && | |
| 3615 | + v instanceof SharedArrayBuffer) || | |
| 3616 | + (typeof CryptoKey !== "undefined" && v instanceof CryptoKey) || | |
| 3617 | + (typeof WebAssembly !== "undefined" && | |
| 3618 | + v instanceof WebAssembly.Module) || | |
| 3619 | + __util_proxy_details(v) !== undefined) return v; | |
| 3620 | + if (v instanceof Map) { | |
| 3621 | + const out = new Map(); | |
| 3622 | + seen.set(v, out); | |
| 3623 | + for (const [key, entry] of v) { | |
| 3624 | + out.set(project(key), project(entry)); | |
| 3625 | + } | |
| 3626 | + return out; | |
| 3627 | + } | |
| 3628 | + if (v instanceof Set) { | |
| 3629 | + const out = new Set(); | |
| 3630 | + seen.set(v, out); | |
| 3631 | + for (const entry of v) out.add(project(entry)); | |
| 3632 | + return out; | |
| 3633 | + } | |
| 3634 | + if (Array.isArray(v)) { | |
| 3635 | + const out = new Array(v.length); | |
| 3636 | + seen.set(v, out); | |
| 3637 | + originals.set(out, v); | |
| 3638 | + for (const key of Object.keys(v)) set(out, key, project(v[key])); | |
| 3639 | + return out; | |
| 3640 | + } | |
| 3641 | + if (Object.getPrototypeOf(v) !== Object.prototype) | |
| 3642 | + throw __rpcUnsupportedType(v); | |
| 3643 | + const out = {}; | |
| 3644 | + seen.set(v, out); | |
| 3645 | + originals.set(out, v); | |
| 3646 | + for (const key of Object.keys(v)) set(out, key, project(v[key])); | |
| 3647 | + return out; | |
| 3648 | + }; | |
| 3649 | + return { tree: project(value), originals }; | |
| 3650 | +}; | |
| 3651 | +const __tagged = (tag, sc) => { | |
| 3652 | + const out = new Uint8Array(sc.length + 1); | |
| 3653 | + out[0] = tag; | |
| 3654 | + out.set(sc, 1); | |
| 3655 | + return out; | |
| 3656 | +}; | |
| 3657 | +// ---- request-context confinement ------------------------------- | |
| 3658 | +// Workerd ties I/O objects to the IoContext of the event that made | |
| 3659 | +// them. Cells' equivalent: each dispatched event enters an | |
| 3660 | +// async-context frame (the same CPED the ALS rides, so it survives | |
| 3661 | +// awaits) carrying a context id. Stubs remember their owning | |
| 3662 | +// context and refuse to serialize elsewhere; pipeline nodes refuse | |
| 3663 | +// foreign awaits and calls -- each with Workerd's exact error. | |
| 3664 | +let __nextCtxId = 1; | |
| 3665 | +const __ctxKey = Symbol("celld.ctx"); | |
| 3666 | +const __ctxNow = () => { | |
| 3667 | + const frame = __als_get(); | |
| 3668 | + return frame === undefined ? undefined : frame.get(__ctxKey); | |
| 3669 | +}; | |
| 3670 | +// Run `fn` under context `id` (undefined = a fresh one). An async | |
| 3671 | +// fn started inside keeps the frame across its awaits. The prior | |
| 3672 | +// frame is cloned so user AsyncLocalStorage stores still flow into | |
| 3673 | +// same-isolate callees, as they did before contexts existed. | |
| 3674 | +const __ctxRun = (id, fn) => { | |
| 3675 | + const prior = __als_get(); | |
| 3676 | + const frame = new Map(prior); | |
| 3677 | + frame.set(__ctxKey, id ?? __nextCtxId++); | |
| 3678 | + __als_set(frame); | |
| 3679 | + try { | |
| 3680 | + return fn(); | |
| 3681 | + } finally { | |
| 3682 | + __als_set(prior); | |
| 3683 | + } | |
| 3684 | +}; | |
| 3685 | +const __ctxError = (kind) => new Error( | |
| 3686 | + "Cannot perform I/O on behalf of a different request. I/O " + | |
| 3687 | + "objects (such as streams, request/response bodies, and others) " + | |
| 3688 | + "created in the context of one request handler cannot be " + | |
| 3689 | + "accessed from a different request's handler. This is a " + | |
| 3690 | + "limitation of Cloudflare Workers which allows us to improve " + | |
| 3691 | + "overall performance. (I/O type: " + kind + ")"); | |
| 3692 | +// ---- abortable request contexts -------------------------------- | |
| 3693 | +// Workerd's ctx.abort(reason) on an entrypoint aborts the request's | |
| 3694 | +// IoContext: the in-flight call rejects with the reason, and stubs | |
| 3695 | +// the context holds are disposed (their disposal callbacks fire). | |
| 3696 | +// State is allocated only when a context first holds a stub handle | |
| 3697 | +// or aborts, so plain-data dispatch pays nothing; call paths gate | |
| 3698 | +// every abort lookup on `__abortedCtxs.size` (one field read). | |
| 3699 | +// Aborted ids stay recorded: a stub rooted in a dead context must | |
| 3700 | +// keep rejecting with the reason. | |
| 3701 | +const __abortedCtxs = new Map(); | |
| 3702 | +// An actor-flavored abort reason: in-flight ops reject with the | |
| 3703 | +// wrapped reason, later ops with Workerd's post-abort message | |
| 3704 | +// (upstream TODO(bug): should propagate the reason, but doesn't). | |
| 3705 | +class __ActorAbort { constructor(reason) { this.reason = reason; } } | |
| 3706 | +const __postAbortError = (aborted) => aborted instanceof __ActorAbort | |
| 3707 | + ? new Error("The execution context which hosts this callback " + | |
| 3708 | + "is no longer running.") | |
| 3709 | + : aborted; | |
| 3710 | +// ctx id -> Set of live stub handles (metas) the context holds. | |
| 3711 | +const __ctxStubs = new Map(); | |
| 3712 | +// ctx id -> Set of reject callbacks for stub ops in flight against | |
| 3713 | +// that context. A hung callee never settles, so a context abort | |
| 3714 | +// must reject its pending callers directly. | |
| 3715 | +const __ctxPendingOps = new Map(); | |
| 3716 | +const __opTrack = (ctx, reject) => { | |
| 3717 | + let set = __ctxPendingOps.get(ctx); | |
| 3718 | + if (set === undefined) __ctxPendingOps.set(ctx, set = new Set()); | |
| 3719 | + set.add(reject); | |
| 3720 | + return () => { | |
| 3721 | + set.delete(reject); | |
| 3722 | + if (set.size === 0) __ctxPendingOps.delete(ctx); | |
| 3723 | + }; | |
| 3724 | +}; | |
| 3725 | +const __ctxRegister = (meta) => { | |
| 3726 | + if (meta.ctx === undefined) return; | |
| 3727 | + let set = __ctxStubs.get(meta.ctx); | |
| 3728 | + if (set === undefined) __ctxStubs.set(meta.ctx, set = new Set()); | |
| 3729 | + set.add(meta); | |
| 3730 | +}; | |
| 3731 | +const __ctxUnregister = (meta) => { | |
| 3732 | + const set = __ctxStubs.get(meta.ctx); | |
| 3733 | + if (set === undefined) return; | |
| 3734 | + set.delete(meta); | |
| 3735 | + if (set.size === 0) __ctxStubs.delete(meta.ctx); | |
| 3736 | +}; | |
| 3737 | +// Tear down a context: dispose every handle it still holds, so a | |
| 3738 | +// dup() leaked into it reaches the sender's disposal callback. | |
| 3739 | +const __ctxEnd = (id) => { | |
| 3740 | + const set = __ctxStubs.get(id); | |
| 3741 | + if (set === undefined) return; | |
| 3742 | + __ctxStubs.delete(id); | |
| 3743 | + for (const meta of set) __disposeStub(meta); | |
| 3744 | +}; | |
| 3745 | +const __ctxAbort = (id, reason) => { | |
| 3746 | + if (id === undefined || __abortedCtxs.has(id)) return; | |
| 3747 | + const stored = reason === undefined | |
| 3748 | + ? new Error("The execution context has been aborted.") | |
| 3749 | + : reason; | |
| 3750 | + __abortedCtxs.set(id, stored); | |
| 3751 | + __ctxEnd(id); | |
| 3752 | + const pending = __ctxPendingOps.get(id); | |
| 3753 | + if (pending === undefined) return; | |
| 3754 | + __ctxPendingOps.delete(id); | |
| 3755 | + const live = | |
| 3756 | + stored instanceof __ActorAbort ? stored.reason : stored; | |
| 3757 | + for (const reject of pending) reject(live); | |
| 3758 | +}; | |
| 3759 | +// The entrypoint ctx.abort. Instances are cached across calls, so | |
| 3760 | +// the construction-time ctx cannot pin a request id (Workerd | |
| 3761 | +// constructs per request); the current frame's id at abort() time | |
| 3762 | +// is the request being served, which matches Workerd observably. | |
| 3763 | +const __ctxAbortCurrent = | |
| 3764 | + (reason) => __ctxAbort(__ctxNow(), reason); | |
| 3765 | +// ---- same-process RPC stubs ------------------------------------ | |
| 3766 | +// A stub entry owns a local target; `refs` counts live handles | |
| 3767 | +// across dup()s. When the last handle is disposed the target's own | |
| 3768 | +// Symbol.dispose runs (async, matching Workerd's disposal callback). | |
| 3769 | +// Stubs cross same-isolate transports only (same-script entrypoint | |
| 3770 | +// RPC and same-process routed dispatch); a marker revived elsewhere fails | |
| 3771 | +// loudly on use instead of aliasing an unrelated local entry. | |
| 3772 | +// `ctx` records the owning request context: the entry's for | |
| 3773 | +// running its target, the handle's for the serialize-elsewhere | |
| 3774 | +// check. | |
| 3775 | +const __stubEntries = new Map(); | |
| 3776 | +const __stubMeta = new WeakMap(); | |
| 3777 | +// Keep the Durable Object brand outside the user-visible object. Reading a | |
| 3778 | +// string property here would invoke an inherited getter before validation can | |
| 3779 | +// reject its unsupported prototype. | |
| 3780 | +const __doStubMeta = new WeakMap(); | |
| 3781 | +let __nextStubId = 1; | |
| 3782 | +const __stubIsolate = Math.random().toString(36).slice(2); | |
| 3783 | +const __newEntry = (target) => { | |
| 3784 | + // `scope` records the actor event that minted the entry (top of | |
| 3785 | + // the event stack at lift time), so an actor breakage can find | |
| 3786 | + // and abort the contexts hosting its exported stubs, and an op on | |
| 3787 | + // the stub can queue on that cell's input gate. `section` is the | |
| 3788 | + // critical section running at lift time, if any -- an op on this | |
| 3789 | + // stub re-enters it rather than queueing behind it. | |
| 3790 | + const scope = __currentActorScope() || undefined; | |
| 3791 | + const entry = { | |
| 3792 | + id: __nextStubId++, target, refs: 1, ctx: __ctxNow(), scope, | |
| 3793 | + section: __cellBlocks.get(scope)?.holder ?? null, | |
| 3794 | + }; | |
| 3795 | + __stubEntries.set(entry.id, entry); | |
| 3796 | + return entry; | |
| 3797 | +}; | |
| 3798 | +// Actors broken in JS: scope -> reason. Workerd's DO ctx.abort | |
| 3799 | +// rejects in-flight and future calls; when the abort fires under a | |
| 3800 | +// same-isolate stub caller, terminate_execution would unwind that | |
| 3801 | +// caller too (the routed dispatch re-enters the isolate), so the | |
| 3802 | +// breakage is recorded here instead: contexts hosting the actor's | |
| 3803 | +// exported stubs abort (in-flight ops reject with the reason, | |
| 3804 | +// later ops with the post-abort message) and RPC dispatch to the | |
| 3805 | +// scope rejects with the reason. Direct host-dispatched DO events | |
| 3806 | +// keep the uncatchable terminate_execution path. | |
| 3807 | +const __brokenActors = new Map(); | |
| 3808 | +const __actorBreak = (scope, reason) => { | |
| 3809 | + if (__brokenActors.has(scope)) return; | |
| 3810 | + __brokenActors.set(scope, reason); | |
| 3811 | + for (const entry of __stubEntries.values()) | |
| 3812 | + if (entry.scope === scope) | |
| 3813 | + __ctxAbort(entry.ctx, new __ActorAbort(reason)); | |
| 3814 | +}; | |
| 3815 | +// Everything this isolate holds for one cell scope that belongs to the | |
| 3816 | +// cell's residency rather than to the isolate, so a fresh instance | |
| 3817 | +// inherits none of it. `adopt_cell` calls this on both edges: the | |
| 3818 | +// give-back frees it, the take-in guarantees that no epoch spans. | |
| 3819 | +// Storage is not here -- `stop_cell` closes it host-side -- and sockets | |
| 3820 | +// live in the host registry, so a hibernated cell keeps them. | |
| 3821 | +const __cellRelease = (scope) => { | |
| 3822 | + __cell.instances[scope]?.ctx?.facets?._release(); | |
| 3823 | + delete __cell.instances[scope]; | |
| 3824 | + delete __cell.idNames[scope]; | |
| 3825 | + delete __cell.facetConfigs[scope]; | |
| 3826 | + __brokenActors.delete(scope); | |
| 3827 | + // An abandoned block can never run `__blockLeave`. A normal eviction | |
| 3828 | + // cannot abandon a block because its event keeps the cell in flight. A | |
| 3829 | + // stop that waits for nobody can, so the release drops every block record | |
| 3830 | + // together with the other state for this residency. | |
| 3831 | + __cellBlocks.delete(scope); | |
| 3832 | + // An entry holds `target`, which can be an object the released | |
| 3833 | + // instance owns. Dropping it ends that reachability; `released` is | |
| 3834 | + // what an already-revived handle reads, since it holds its entry | |
| 3835 | + // directly and never looks in this map again. | |
| 3836 | + for (const entry of __stubEntries.values()) { | |
| 3837 | + if (entry.scope !== scope) continue; | |
| 3838 | + entry.released = true; | |
| 3839 | + __stubEntries.delete(entry.id); | |
| 3840 | + // Break in-flight ops as an abort would, but not through | |
| 3841 | + // `__actorBreak`: that records the scope broken for the life of the | |
| 3842 | + // isolate, which is the state this function drops. | |
| 3843 | + __ctxAbort(entry.ctx, new __ActorAbort(__releasedStubError())); | |
| 3844 | + } | |
| 3845 | +}; | |
| 3846 | +const __releasedStubError = () => new Error( | |
| 3847 | + "The Durable Object that returned this RPC stub no longer runs on " + | |
| 3848 | + "this node."); | |
| 3849 | +const __disposeStub = (meta) => { | |
| 3850 | + if (meta.disposed) return; | |
| 3851 | + meta.disposed = true; | |
| 3852 | + __ctxUnregister(meta); | |
| 3853 | + const entry = meta.entry; | |
| 3854 | + if (--entry.refs > 0) return; | |
| 3855 | + __stubEntries.delete(entry.id); | |
| 3856 | + const disposer = entry.target?.[Symbol.dispose]; | |
| 3857 | + if (typeof disposer === "function") | |
| 3858 | + Promise.resolve().then(() => disposer.call(entry.target)); | |
| 3859 | +}; | |
| 3860 | +const __stubDisposedError = () => | |
| 3861 | + new Error("RPC stub used after being disposed."); | |
| 3862 | +// Shared brand value for RpcTarget instances; see the RpcTarget | |
| 3863 | +// constructor. | |
| 3864 | +const __rpcNoClone = () => {}; | |
| 3865 | +// Workerd method-visibility rules by target kind: an RpcTarget | |
| 3866 | +// exposes inherited methods/accessors (never own instance state, | |
| 3867 | +// never Object.prototype); a plain object or function exposes own | |
| 3868 | +// properties only. Property reads go through normal [[Get]] so | |
| 3869 | +// Proxy handlers participate, as in Workerd. | |
| 3870 | +const __rpcNoSuchMethod = (prop) => new TypeError( | |
| 3871 | + 'The RPC receiver does not implement the method "' + prop + '".'); | |
| 3872 | +// Bind through the intrinsic because a callable proxy can implement `.bind` | |
| 3873 | +// as a remote property. Reading that property can turn a valid named RPC | |
| 3874 | +// method into a non-function. Keep this rule shared by every RPC binding site. | |
| 3875 | +const __rpcBindMethod = (value, receiver) => | |
| 3876 | + Reflect.apply(Function.prototype.bind, value, [receiver]); | |
| 3877 | +const __stubResolve = (target, prop) => { | |
| 3878 | + if (target instanceof __cf.RpcTarget) { | |
| 3879 | + if (Object.hasOwn(target, prop) || !(prop in target) || | |
| 3880 | + prop in Object.prototype) throw __rpcNoSuchMethod(prop); | |
| 3881 | + } else if (!Object.hasOwn(target, prop)) { | |
| 3882 | + throw __rpcNoSuchMethod(prop); | |
| 3883 | + } | |
| 3884 | + const value = target[prop]; | |
| 3885 | + // Keep celld's own stubs and pipeline nodes unwrapped because the wrapper | |
| 3886 | + // would lose their metadata. | |
| 3887 | + return typeof value === "function" && !__stubMeta.has(value) && | |
| 3888 | + !(value instanceof __cf.RpcPromise) && | |
| 3889 | + !(value instanceof __cf.RpcProperty) | |
| 3890 | + ? __rpcBindMethod(value, target) : value; | |
| 3891 | +}; | |
| 3892 | +// ---- streams over RPC ------------------------------------------ | |
| 3893 | +// A live stream crosses as a handle in the caps table: the sender | |
| 3894 | +// locks the origin (reader/writer acquired at lift) behind a | |
| 3895 | +// bridge entry, and the receiver's endpoint is an ordinary | |
| 3896 | +// ReadableStream/WritableStream whose pulls and writes are stub | |
| 3897 | +// ops against the bridge -- one bounded reverse call per chunk, | |
| 3898 | +// the clone being the one wire copy. Backpressure is the op in | |
| 3899 | +// flight: hwm 0 pulls only on demand, and the writable carries | |
| 3900 | +// one chunk per op. EOF, close, and errors cross as op results; | |
| 3901 | +// teardown (param disposal, context end, context abort) runs the | |
| 3902 | +// bridge disposer, which cancels or aborts an unfinished origin | |
| 3903 | +// with Workerd's generic disconnect errors -- reasons do not | |
| 3904 | +// propagate, matching Workerd's own TODOs (and its verbatim | |
| 3905 | +// "endeded" typo). | |
| 3906 | +const __wsDisconnect = () => new Error( | |
| 3907 | + "WritableStream received over RPC was disconnected because " + | |
| 3908 | + "the remote execution context has endeded."); | |
| 3909 | +const __rsDisconnect = () => new Error( | |
| 3910 | + "ReadableStream received over RPC disconnected prematurely."); | |
| 3911 | +// Receiver wrapper stream -> its handle meta, for forwarding. | |
| 3912 | +const __rpcStreamMeta = new WeakMap(); | |
| 3913 | +const __readableBridge = (reader) => { | |
| 3914 | + const bridge = { | |
| 3915 | + done: false, | |
| 3916 | + async read() { | |
| 3917 | + let result; | |
| 3918 | + try { | |
| 3919 | + result = await reader.read(); | |
| 3920 | + } catch (error) { | |
| 3921 | + bridge.done = true; | |
| 3922 | + throw error; | |
| 3923 | + } | |
| 3924 | + if (result.done) bridge.done = true; | |
| 3925 | + return result; | |
| 3926 | + }, | |
| 3927 | + cancel() { | |
| 3928 | + if (bridge.done) return; | |
| 3929 | + bridge.done = true; | |
| 3930 | + reader.cancel(__rsDisconnect()).catch(() => {}); | |
| 3931 | + }, | |
| 3932 | + [Symbol.dispose]() { bridge.cancel(); }, | |
| 3933 | + }; | |
| 3934 | + return bridge; | |
| 3935 | +}; | |
| 3936 | +const __writableBridge = (writer) => { | |
| 3937 | + const bridge = { | |
| 3938 | + done: false, | |
| 3939 | + write: (chunk) => writer.write(chunk), | |
| 3940 | + close() { | |
| 3941 | + bridge.done = true; | |
| 3942 | + return writer.close(); | |
| 3943 | + }, | |
| 3944 | + abort() { | |
| 3945 | + bridge.done = true; | |
| 3946 | + return writer.abort(__wsDisconnect()); | |
| 3947 | + }, | |
| 3948 | + [Symbol.dispose]() { | |
| 3949 | + if (!bridge.done) bridge.abort().catch(() => {}); | |
| 3950 | + }, | |
| 3951 | + }; | |
| 3952 | + return bridge; | |
| 3953 | +}; | |
| 3954 | +const __liftStream = (v) => { | |
| 3955 | + const readable = v instanceof ReadableStream; | |
| 3956 | + const key = readable ? "__celld$rs" : "__celld$ws"; | |
| 3957 | + const meta = __rpcStreamMeta.get(v); | |
| 3958 | + if (meta !== undefined && !meta.disposed && !v.locked) { | |
| 3959 | + // Re-serializing a received, untouched stream forwards the | |
| 3960 | + // original handle: the reference moves (like a stub) and | |
| 3961 | + // the local wrapper is dead -- a round trip stays one hop. | |
| 3962 | + meta.disposed = true; | |
| 3963 | + __ctxUnregister(meta); | |
| 3964 | + return { [key]: meta.entry.id, t: __stubIsolate }; | |
| 3965 | + } | |
| 3966 | + if (v.locked) | |
| 3967 | + throw new TypeError(readable | |
| 3968 | + ? "The ReadableStream has been locked to a reader." | |
| 3969 | + : "The WritableStream has been locked to a writer."); | |
| 3970 | + const bridge = readable | |
| 3971 | + ? __readableBridge(v.getReader()) | |
| 3972 | + : __writableBridge(v.getWriter()); | |
| 3973 | + return { [key]: __newEntry(bridge).id, t: __stubIsolate }; | |
| 3974 | +}; | |
| 3975 | +// A signal is not a snapshot on the RPC wire. The marker carries a | |
| 3976 | +// process-wide identity, and the host forwards the source's single state | |
| 3977 | +// transition to every receiving isolate. A received signal keeps that | |
| 3978 | +// identity when an RPC forwards it again, so a chain does not add relays. | |
| 3979 | +const __rpcSignalMeta = new WeakMap(); | |
| 3980 | +const __rpcSignalReceivers = new Map(); | |
| 3981 | +const __rpcSignalSourceFinalizer = new FinalizationRegistry( | |
| 3982 | + (id) => __rpc_signal_release(id)); | |
| 3983 | +const __rpcSignalReceiverFinalizer = new FinalizationRegistry( | |
| 3984 | + ({ id, subscription }) => | |
| 3985 | + __rpc_signal_unsubscribe(id, subscription)); | |
| 3986 | +const __rpcSignalReasonOut = (reason) => { | |
| 3987 | + if (reason instanceof DOMException) | |
| 3988 | + return __sc_encode({ d: true, n: reason.name, m: reason.message }); | |
| 3989 | + try { | |
| 3990 | + return __sc_encode({ v: reason }); | |
| 3991 | + } catch { | |
| 3992 | + return __sc_encode({ v: new Error(String(reason)) }); | |
| 3993 | + } | |
| 3994 | +}; | |
| 3995 | +const __rpcSignalReasonIn = (bytes) => { | |
| 3996 | + const reason = __sc_decode(bytes); | |
| 3997 | + return reason.d | |
| 3998 | + ? new DOMException(reason.m, reason.n) | |
| 3999 | + : reason.v; | |
| 4000 | +}; | |
| 4001 | +const __rpcSignalSubscribe = (receiver) => { | |
| 4002 | + const signal = receiver.signal.deref(); | |
| 4003 | + if (signal === undefined) return false; | |
| 4004 | + const pending = __rpc_signal_wait(receiver.id); | |
| 4005 | + receiver.subscription = pending.__celldRpcSignalSubscription; | |
| 4006 | + pending.then((reason) => { | |
| 4007 | + const target = receiver.signal.deref(); | |
| 4008 | + if (target !== undefined && reason.byteLength !== 0) | |
| 4009 | + __abortSignal(target, __rpcSignalReasonIn(reason)); | |
| 4010 | + }); | |
| 4011 | + // A wait belongs to the request that installed it. A retained signal needs | |
| 4012 | + // a fresh wait in each later request, and its finalizer must unsubscribe the | |
| 4013 | + // newest one rather than the dead request's subscription. | |
| 4014 | + __rpcSignalReceiverFinalizer.unregister(receiver); | |
| 4015 | + __rpcSignalReceiverFinalizer.register(signal, receiver, receiver); | |
| 4016 | + return true; | |
| 4017 | +}; | |
| 4018 | +const __liftSignal = (signal) => { | |
| 4019 | + let meta = __rpcSignalMeta.get(signal); | |
| 4020 | + if (meta === undefined) { | |
| 4021 | + const id = __rpc_signal_new(); | |
| 4022 | + meta = { id }; | |
| 4023 | + __rpcSignalMeta.set(signal, meta); | |
| 4024 | + __rpcSignalSourceFinalizer.register(signal, id); | |
| 4025 | + if (signal.aborted) { | |
| 4026 | + __rpc_signal_abort(id, __rpcSignalReasonOut(signal.reason)); | |
| 4027 | + } else { | |
| 4028 | + signal.addEventListener("abort", (event) => { | |
| 4029 | + __rpc_signal_abort(id, | |
| 4030 | + __rpcSignalReasonOut(event.target.reason)); | |
| 4031 | + }, { once: true }); | |
| 4032 | + } | |
| 4033 | + } | |
| 4034 | + const marker = { "__celld$sig": meta.id, a: signal.aborted }; | |
| 4035 | + if (signal.aborted) marker.r = __rpcSignalReasonOut(signal.reason); | |
| 4036 | + return marker; | |
| 4037 | +}; | |
| 4038 | +const __rpcSignalRefresh = () => { | |
| 4039 | + for (const [id, receivers] of __rpcSignalReceivers) { | |
| 4040 | + const state = __rpc_signal_poll(id); | |
| 4041 | + const live = new Set(); | |
| 4042 | + for (const receiver of receivers) { | |
| 4043 | + const signal = receiver.signal.deref(); | |
| 4044 | + if (signal === undefined) continue; | |
| 4045 | + if (state instanceof Uint8Array) | |
| 4046 | + __abortSignal(signal, __rpcSignalReasonIn(state)); | |
| 4047 | + else if (state !== null && __rpcSignalSubscribe(receiver)) | |
| 4048 | + live.add(receiver); | |
| 4049 | + } | |
| 4050 | + if (live.size === 0 || state === null || state instanceof Uint8Array) | |
| 4051 | + __rpcSignalReceivers.delete(id); | |
| 4052 | + else | |
| 4053 | + __rpcSignalReceivers.set(id, live); | |
| 4054 | + } | |
| 4055 | +}; | |
| 4056 | +// Replace stub-able values with wire markers. Runs only after a | |
| 4057 | +// plain clone failed, so plain-data serialization never pays for | |
| 4058 | +// it. Passing an existing stub transfers its reference: the | |
| 4059 | +// sender's handle is disposed (dup() first to keep one) and the | |
| 4060 | +// receiver adopts it. Returns null when nothing was liftable. | |
| 4061 | +const __stubLift = (value, allowCapabilities = true, originals) => { | |
| 4062 | + let lifted = false; | |
| 4063 | + // Capabilities (stubs, disposers) root the callee context; | |
| 4064 | + // by-value host types do not -- they pick the 0x02 envelope. | |
| 4065 | + let caps = false; | |
| 4066 | + const seen = new Map(); | |
| 4067 | + const ctx = __ctxNow(); | |
| 4068 | + // A buffered body crosses as its bytes; a live-stream body | |
| 4069 | + // crosses as a stream handle (a capability, so the reply | |
| 4070 | + // roots its callee context and the pulls keep working). | |
| 4071 | + const liftBody = (v) => { | |
| 4072 | + if (v._bodyBytes !== null) return v._bodyBytes; | |
| 4073 | + caps = true; | |
| 4074 | + return __liftStream(v.body); | |
| 4075 | + }; | |
| 4076 | + const lift = (v) => { | |
| 4077 | + if (v === null || | |
| 4078 | + (typeof v !== "object" && typeof v !== "function")) return v; | |
| 4079 | + const cached = seen.get(v); | |
| 4080 | + if (cached !== undefined) return cached; | |
| 4081 | + const meta = __stubMeta.get(v); | |
| 4082 | + if (meta) { | |
| 4083 | + if (!allowCapabilities) return v; | |
| 4084 | + lifted = true; | |
| 4085 | + caps = true; | |
| 4086 | + if (meta.disposed) throw __stubDisposedError(); | |
| 4087 | + // A stub belongs to the request that received it; another | |
| 4088 | + // request cannot serialize it (Workerd's IoContext rule). | |
| 4089 | + if (meta.ctx !== ctx) throw __ctxError("Client"); | |
| 4090 | + meta.disposed = true; // the ref moves to the receiver | |
| 4091 | + __ctxUnregister(meta); | |
| 4092 | + const marker = { "__celld$stub": meta.entry.id, | |
| 4093 | + t: __stubIsolate, c: meta.callable }; | |
| 4094 | + seen.set(v, marker); | |
| 4095 | + return marker; | |
| 4096 | + } | |
| 4097 | + const svc = __svcMeta.get(v); | |
| 4098 | + if (svc !== undefined) { | |
| 4099 | + if (!allowCapabilities) return v; | |
| 4100 | + // A loopback service stub (ctx.exports): name + props cross | |
| 4101 | + // as plain data and revive as a fresh loopback stub. Props | |
| 4102 | + // are lifted too -- they may nest further stubs (Workerd's | |
| 4103 | + // nested channel tokens). | |
| 4104 | + lifted = true; | |
| 4105 | + caps = true; | |
| 4106 | + const marker = { "__celld$svc": svc.name, t: __stubIsolate }; | |
| 4107 | + seen.set(v, marker); | |
| 4108 | + if (svc.props !== undefined) marker.p = lift(svc.props); | |
| 4109 | + return marker; | |
| 4110 | + } | |
| 4111 | + // Workerd refuses to serialize its promise/property handles. | |
| 4112 | + if (v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty) | |
| 4113 | + throw new DOMException( | |
| 4114 | + 'Could not serialize object of type "' + | |
| 4115 | + (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + | |
| 4116 | + '". This type does not support serialization.', | |
| 4117 | + "DataCloneError"); | |
| 4118 | + if (typeof v === "function" || v instanceof __cf.RpcTarget) { | |
| 4119 | + if (!allowCapabilities) return v; | |
| 4120 | + lifted = true; | |
| 4121 | + caps = true; | |
| 4122 | + const marker = { "__celld$stub": __newEntry(v).id, | |
| 4123 | + t: __stubIsolate, | |
| 4124 | + c: typeof v === "function" }; | |
| 4125 | + seen.set(v, marker); | |
| 4126 | + return marker; | |
| 4127 | + } | |
| 4128 | + const doId = __doStubMeta.get(v); | |
| 4129 | + if (doId !== undefined) { | |
| 4130 | + if (!allowCapabilities) return v; | |
| 4131 | + lifted = true; | |
| 4132 | + caps = true; | |
| 4133 | + const marker = { "__celld$do": doId._className, | |
| 4134 | + v: doId._value, n: v.name ?? null }; | |
| 4135 | + seen.set(v, marker); | |
| 4136 | + return marker; | |
| 4137 | + } | |
| 4138 | + // HTTP host types cross by value, as in Workerd's RPC | |
| 4139 | + // serialization: entry lists for Headers, the buffered bytes | |
| 4140 | + // for bodies (the marker aliases the live buffer; the clone | |
| 4141 | + // is the one wire copy), and no signal -- the receiver mints | |
| 4142 | + // a fresh one. A live stream body cannot cross yet. | |
| 4143 | + let marker; | |
| 4144 | + if (v instanceof Headers) { | |
| 4145 | + if (!allowCapabilities) return v; | |
| 4146 | + marker = { "__celld$hdr": [...v] }; | |
| 4147 | + } else if (v instanceof Blob) { | |
| 4148 | + if (!allowCapabilities) return v; | |
| 4149 | + marker = { "__celld$blob": v._bytes, y: v.type }; | |
| 4150 | + if (v instanceof File) { | |
| 4151 | + marker.n = v.name; | |
| 4152 | + marker.m = v.lastModified; | |
| 4153 | + } | |
| 4154 | + } else if (v instanceof Request) { | |
| 4155 | + if (!allowCapabilities) return v; | |
| 4156 | + marker = { "__celld$req": v.url, m: v.method, | |
| 4157 | + h: [...v.headers], r: v.redirect, c: v.cf, | |
| 4158 | + b: liftBody(v) }; | |
| 4159 | + } else if (v instanceof Response) { | |
| 4160 | + if (!allowCapabilities) return v; | |
| 4161 | + marker = { "__celld$res": v.status, | |
| 4162 | + t: v.statusText || | |
| 4163 | + __STATUS_TEXT[v.status] || "", | |
| 4164 | + h: [...v.headers], c: v.cf, | |
| 4165 | + e: v.type === "error", | |
| 4166 | + b: v.body === null ? null : liftBody(v) }; | |
| 4167 | + } else if (v instanceof ReadableStream || | |
| 4168 | + v instanceof WritableStream) { | |
| 4169 | + if (!allowCapabilities) return v; | |
| 4170 | + caps = true; | |
| 4171 | + marker = __liftStream(v); | |
| 4172 | + } else if (v instanceof AbortSignal) { | |
| 4173 | + marker = __liftSignal(v); | |
| 4174 | + } | |
| 4175 | + if (marker !== undefined) { | |
| 4176 | + lifted = true; | |
| 4177 | + seen.set(v, marker); | |
| 4178 | + return marker; | |
| 4179 | + } | |
| 4180 | + const proto = Object.getPrototypeOf(v); | |
| 4181 | + if (!Array.isArray(v) && | |
| 4182 | + proto !== Object.prototype && proto !== null) { | |
| 4183 | + // A Proxy emulating neither a plain object nor an RpcTarget | |
| 4184 | + // is Workerd's canonical proxy serialization error. | |
| 4185 | + if (__util_proxy_details(v) !== undefined) | |
| 4186 | + throw new DOMException( | |
| 4187 | + "Proxy could not be serialized because it is not a " + | |
| 4188 | + "valid RPC receiver type. The Proxy must emulate either " + | |
| 4189 | + "a plain object or an RpcTarget, as indicated by the " + | |
| 4190 | + "Proxy's prototype chain.", "DataCloneError"); | |
| 4191 | + return v; // host/other: leave to the clone | |
| 4192 | + } | |
| 4193 | + const out = Array.isArray(v) ? [] : {}; | |
| 4194 | + seen.set(v, out); | |
| 4195 | + for (const key of Object.keys(v)) out[key] = lift(v[key]); | |
| 4196 | + const disposerSource = originals?.get(v) ?? v; | |
| 4197 | + const disposer = disposerSource[Symbol.dispose]; | |
| 4198 | + if (allowCapabilities && !Array.isArray(v) && | |
| 4199 | + typeof disposer === "function") { | |
| 4200 | + lifted = true; | |
| 4201 | + caps = true; | |
| 4202 | + out["__celld$disp"] = | |
| 4203 | + __newEntry(__rpcBindMethod(disposer, disposerSource)).id; | |
| 4204 | + } | |
| 4205 | + return out; | |
| 4206 | + }; | |
| 4207 | + const tree = lift(value); | |
| 4208 | + return lifted ? { tree, caps } : null; | |
| 4209 | +}; | |
| 4210 | +// Revive host-type markers into real instances, adopting the wire | |
| 4211 | +// bytes directly -- no copy beyond the clone's own. | |
| 4212 | +const __reviveBlob = (marker, bytes) => { | |
| 4213 | + const blob = marker.n !== undefined | |
| 4214 | + ? new File([], marker.n, | |
| 4215 | + { type: marker.y, lastModified: marker.m }) | |
| 4216 | + : new Blob([], { type: marker.y }); | |
| 4217 | + blob._bytes = bytes; | |
| 4218 | + blob.size = bytes.byteLength; | |
| 4219 | + return blob; | |
| 4220 | +}; | |
| 4221 | +const __adoptBody = (target, bytes) => { | |
| 4222 | + target._bodyBytes = bytes; | |
| 4223 | + target._body = undefined; // decoded lazily on the first text()/json() | |
| 4224 | + const body = target.body; | |
| 4225 | + if (body !== null) { | |
| 4226 | + body._st.bytes = bytes; | |
| 4227 | + body.__celldBodyBytes = bytes; | |
| 4228 | + body._expectedLength = bytes.byteLength; | |
| 4229 | + } | |
| 4230 | +}; | |
| 4231 | +// A non-bytes `b` is a live-stream body marker: revive it and | |
| 4232 | +// let the constructor adopt it as a streaming body. | |
| 4233 | +const __reviveRequest = (marker, url, revive) => { | |
| 4234 | + if (!(marker.b instanceof Uint8Array)) | |
| 4235 | + return new Request(url, { method: marker.m, | |
| 4236 | + headers: marker.h, redirect: marker.r, cf: marker.c, | |
| 4237 | + body: revive(marker.b) }); | |
| 4238 | + const req = new Request(url, { method: marker.m, | |
| 4239 | + headers: marker.h, redirect: marker.r, cf: marker.c }); | |
| 4240 | + __adoptBody(req, marker.b); | |
| 4241 | + return req; | |
| 4242 | +}; | |
| 4243 | +const __reviveResponse = (marker, revive) => { | |
| 4244 | + const bytes = marker.b instanceof Uint8Array; | |
| 4245 | + const res = new Response( | |
| 4246 | + marker.b === null ? null : bytes ? "" : revive(marker.b), { | |
| 4247 | + status: marker["__celld$res"], statusText: marker.t, | |
| 4248 | + headers: marker.h, cf: marker.c }); | |
| 4249 | + if (bytes) __adoptBody(res, marker.b); | |
| 4250 | + if (marker.e) res.type = "error"; | |
| 4251 | + return res; | |
| 4252 | +}; | |
| 4253 | +// Wire a received stream handle to a local endpoint built with | |
| 4254 | +// the ordinary constructors -- nothing new threads through the | |
| 4255 | +// stream hot paths. Read errors surface as Workerd's generic | |
| 4256 | +// premature-disconnect; write errors propagate (Workerd sends | |
| 4257 | +// real errors back through the write loop). | |
| 4258 | +const __foreignStreamOp = () => Promise.reject(new Error( | |
| 4259 | + "RPC streams cannot cross isolate boundaries yet.")); | |
| 4260 | +const __reviveStream = (marker, id, readable, handles) => { | |
| 4261 | + const entry = marker.t === __stubIsolate | |
| 4262 | + ? __stubEntries.get(id) : undefined; | |
| 4263 | + if (entry === undefined) | |
| 4264 | + return readable | |
| 4265 | + ? new ReadableStream({ pull: __foreignStreamOp }) | |
| 4266 | + : new WritableStream({ write: __foreignStreamOp, | |
| 4267 | + close: __foreignStreamOp, abort: __foreignStreamOp }); | |
| 4268 | + const meta = { entry, disposed: false, ctx: __ctxNow() }; | |
| 4269 | + __ctxRegister(meta); | |
| 4270 | + handles.push(meta); | |
| 4271 | + const stream = readable | |
| 4272 | + ? new ReadableStream({ | |
| 4273 | + async pull(controller) { | |
| 4274 | + let result; | |
| 4275 | + try { | |
| 4276 | + result = await __stubOp(meta, ["read"], []); | |
| 4277 | + } catch { | |
| 4278 | + throw __rsDisconnect(); | |
| 4279 | + } | |
| 4280 | + if (result.done) controller.close(); | |
| 4281 | + else controller.enqueue(result.value); | |
| 4282 | + }, | |
| 4283 | + cancel: () => | |
| 4284 | + __stubOp(meta, ["cancel"], []).catch(() => {}), | |
| 4285 | + }, { highWaterMark: 0 }) | |
| 4286 | + : new WritableStream({ | |
| 4287 | + write: (chunk) => __stubOp(meta, ["write"], [chunk]), | |
| 4288 | + close: () => __stubOp(meta, ["close"], []), | |
| 4289 | + abort: () => | |
| 4290 | + __stubOp(meta, ["abort"], []).catch(() => {}), | |
| 4291 | + }); | |
| 4292 | + __rpcStreamMeta.set(stream, meta); | |
| 4293 | + return stream; | |
| 4294 | +}; | |
| 4295 | +const __reviveSignal = (marker, id) => { | |
| 4296 | + const controller = new AbortController(); | |
| 4297 | + const signal = controller.signal; | |
| 4298 | + __rpcSignalMeta.set(signal, { id }); | |
| 4299 | + if (marker.a) { | |
| 4300 | + controller.abort(__rpcSignalReasonIn(marker.r)); | |
| 4301 | + return controller.signal; | |
| 4302 | + } | |
| 4303 | + let receivers = __rpcSignalReceivers.get(id); | |
| 4304 | + if (receivers === undefined) { | |
| 4305 | + receivers = new Set(); | |
| 4306 | + __rpcSignalReceivers.set(id, receivers); | |
| 4307 | + } | |
| 4308 | + const receiver = { id, signal: new WeakRef(signal), subscription: null }; | |
| 4309 | + receivers.add(receiver); | |
| 4310 | + __rpcSignalSubscribe(receiver); | |
| 4311 | + return signal; | |
| 4312 | +}; | |
| 4313 | +// The inverse: markers become live handles. `handles` collects the | |
| 4314 | +// revived stubs (for call-end param disposal or result-tree | |
| 4315 | +// disposal); `disposers` collects remote Symbol.dispose entries. | |
| 4316 | +const __stubRevive = (value) => { | |
| 4317 | + const handles = []; | |
| 4318 | + const disposers = []; | |
| 4319 | + const seen = new Set(); | |
| 4320 | + const revive = (v) => { | |
| 4321 | + if (v === null || typeof v !== "object") return v; | |
| 4322 | + const stubId = v["__celld$stub"]; | |
| 4323 | + if (stubId !== undefined) { | |
| 4324 | + const entry = v.t === __stubIsolate | |
| 4325 | + ? __stubEntries.get(stubId) : undefined; | |
| 4326 | + const stub = entry === undefined | |
| 4327 | + ? __foreignStub() | |
| 4328 | + : __makeStub(entry, v.c); | |
| 4329 | + const meta = __stubMeta.get(stub); | |
| 4330 | + if (meta) handles.push(meta); | |
| 4331 | + return stub; | |
| 4332 | + } | |
| 4333 | + const svcName = v["__celld$svc"]; | |
| 4334 | + if (svcName !== undefined) | |
| 4335 | + return v.t === __stubIsolate | |
| 4336 | + ? __entrypointStub(svcName, revive(v.p)) | |
| 4337 | + : __foreignStub(); | |
| 4338 | + const doClass = v["__celld$do"]; | |
| 4339 | + if (doClass !== undefined) { | |
| 4340 | + const namespace = __cell.makeNamespace(doClass); | |
| 4341 | + return namespace.get( | |
| 4342 | + new DurableObjectId(doClass, v.v, v.n ?? undefined)); | |
| 4343 | + } | |
| 4344 | + const hdr = v["__celld$hdr"]; | |
| 4345 | + if (hdr !== undefined) return new Headers(hdr); | |
| 4346 | + const blobBytes = v["__celld$blob"]; | |
| 4347 | + if (blobBytes !== undefined) return __reviveBlob(v, blobBytes); | |
| 4348 | + const reqUrl = v["__celld$req"]; | |
| 4349 | + if (reqUrl !== undefined) | |
| 4350 | + return __reviveRequest(v, reqUrl, revive); | |
| 4351 | + if (v["__celld$res"] !== undefined) | |
| 4352 | + return __reviveResponse(v, revive); | |
| 4353 | + const rsId = v["__celld$rs"]; | |
| 4354 | + if (rsId !== undefined) | |
| 4355 | + return __reviveStream(v, rsId, true, handles); | |
| 4356 | + const wsId = v["__celld$ws"]; | |
| 4357 | + if (wsId !== undefined) | |
| 4358 | + return __reviveStream(v, wsId, false, handles); | |
| 4359 | + const sigId = v["__celld$sig"]; | |
| 4360 | + if (sigId !== undefined) return __reviveSignal(v, sigId); | |
| 4361 | + if (seen.has(v)) return v; | |
| 4362 | + seen.add(v); | |
| 4363 | + if (Array.isArray(v)) { | |
| 4364 | + for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); | |
| 4365 | + return v; | |
| 4366 | + } | |
| 4367 | + const proto = Object.getPrototypeOf(v); | |
| 4368 | + if (proto !== Object.prototype && proto !== null) return v; | |
| 4369 | + for (const key of Object.keys(v)) { | |
| 4370 | + if (key === "__celld$disp") { | |
| 4371 | + const entry = __stubEntries.get(v[key]); | |
| 4372 | + if (entry) disposers.push(entry); | |
| 4373 | + delete v[key]; | |
| 4374 | + continue; | |
| 4375 | + } | |
| 4376 | + v[key] = revive(v[key]); | |
| 4377 | + } | |
| 4378 | + return v; | |
| 4379 | + }; | |
| 4380 | + return { value: revive(value), handles, disposers }; | |
| 4381 | +}; | |
| 4382 | +// A marker that crossed an isolate boundary: fail on use, loudly. | |
| 4383 | +const __foreignStub = () => new Proxy(function () {}, { | |
| 4384 | + get: (_b, prop) => { | |
| 4385 | + if (prop === "then" || typeof prop !== "string") return undefined; | |
| 4386 | + return () => Promise.reject(new Error( | |
| 4387 | + "RPC stubs cannot cross isolate boundaries yet.")); | |
| 4388 | + }, | |
| 4389 | + apply: () => Promise.reject(new Error( | |
| 4390 | + "RPC stubs cannot cross isolate boundaries yet.")), | |
| 4391 | +}); | |
| 4392 | +// Workerd's entrypoint method-visibility rules (worker-rpc.c++): | |
| 4393 | +// reserved lifecycle names are refused outright; only prototype | |
| 4394 | +// methods and accessors are visible -- never own instance state | |
| 4395 | +// (env/ctx live there) and never Object.prototype. | |
| 4396 | +const __entrypointReserved = new Set([ | |
| 4397 | + "constructor", "fetch", "connect", "alarm", "scheduled", | |
| 4398 | + "webSocketMessage", "webSocketClose", "webSocketError", "dup", | |
| 4399 | +]); | |
| 4400 | +const __entrypointResolve = (inst, prop) => { | |
| 4401 | + if (__entrypointReserved.has(prop)) | |
| 4402 | + throw new TypeError("'" + prop + | |
| 4403 | + "' is a reserved method and cannot be called over RPC."); | |
| 4404 | + if (Object.hasOwn(inst, prop) || !(prop in inst) || | |
| 4405 | + prop in Object.prototype) | |
| 4406 | + throw __rpcNoSuchMethod(prop); | |
| 4407 | + const value = inst[prop]; | |
| 4408 | + return typeof value === "function" && !__stubMeta.has(value) && | |
| 4409 | + !(value instanceof __cf.RpcPromise) && | |
| 4410 | + !(value instanceof __cf.RpcProperty) | |
| 4411 | + ? __rpcBindMethod(value, inst) : value; | |
| 4412 | +}; | |
| 4413 | +// A pipeline hop may continue only through plain data, functions, | |
| 4414 | +// RpcTargets, and stubs -- never through an RPC promise/property | |
| 4415 | +// handle or a class instance (Workerd's receiver rules). | |
| 4416 | +const __walkable = (v) => | |
| 4417 | + v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty | |
| 4418 | + ? false | |
| 4419 | + : typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 4420 | + (typeof v === "object" && v !== null && | |
| 4421 | + (Object.getPrototypeOf(v) === Object.prototype || | |
| 4422 | + Array.isArray(v))); | |
| 4423 | +// Receiver-side pipeline walk: resolve `path` from `root`, then | |
| 4424 | +// GET the final member (`args` null) or CALL it. Errors name the | |
| 4425 | +// path walked so far, as Workerd's do. A stub mid-walk continues | |
| 4426 | +// against its own target, in the stub's owning context. | |
| 4427 | +const __rpcWalk = async (root, path, args, entrypointRoot) => { | |
| 4428 | + let value = root; | |
| 4429 | + for (let i = 0; i < path.length; i++) { | |
| 4430 | + const meta = __stubMeta.get(value); | |
| 4431 | + if (meta) { | |
| 4432 | + if (meta.disposed) throw __stubDisposedError(); | |
| 4433 | + const rest = path.slice(i); | |
| 4434 | + return await __ctxRun(meta.entry.ctx, | |
| 4435 | + () => __rpcWalk(meta.entry.target, rest, args, false)); | |
| 4436 | + } | |
| 4437 | + if (i > 0 && !__walkable(value)) | |
| 4438 | + throw __rpcNoSuchMethod(path[i - 1]); | |
| 4439 | + const prop = path[i]; | |
| 4440 | + const next = entrypointRoot && i === 0 | |
| 4441 | + ? __entrypointResolve(value, prop) | |
| 4442 | + : __stubResolve(value, prop); | |
| 4443 | + if (i === path.length - 1) { | |
| 4444 | + if (args === null) return next; | |
| 4445 | + if (typeof next !== "function") | |
| 4446 | + throw new TypeError( | |
| 4447 | + '"' + path.join(".") + '" is not a function.'); | |
| 4448 | + return next(...args); | |
| 4449 | + } | |
| 4450 | + if (next instanceof __cf.RpcPromise || | |
| 4451 | + next instanceof __cf.RpcProperty) | |
| 4452 | + throw __rpcNoSuchMethod(prop); | |
| 4453 | + value = next; | |
| 4454 | + } | |
| 4455 | + // An empty path applies the root itself (a callable stub). | |
| 4456 | + if (args === null) return value; | |
| 4457 | + if (typeof value !== "function") | |
| 4458 | + throw new TypeError("The RPC stub is not callable."); | |
| 4459 | + return value(...args); | |
| 4460 | +}; | |
| 4461 | +// One stub-mediated op: clone through the RPC envelope both ways, | |
| 4462 | +// so nested stubs, errors, and uncloneables behave exactly as a | |
| 4463 | +// dispatched call. Args serialize in the caller's context (its | |
| 4464 | +// stubs must be its own to transfer); the decode, the walk, and | |
| 4465 | +// the reply serialization run in the stub's owning context, so | |
| 4466 | +// stubs minted by the target belong to the target's context. | |
| 4467 | +// Params received by the target are disposed when the op ends | |
| 4468 | +// (Workerd's param-disposal rule). | |
| 4469 | +const __stubOp = (meta, path, args) => { | |
| 4470 | + if (meta.disposed) return Promise.reject(__stubDisposedError()); | |
| 4471 | + const entry = meta.entry; | |
| 4472 | + // The cell that minted this stub left residency, so `entry.target` | |
| 4473 | + // belongs to an instance this node released. The stub fails here | |
| 4474 | + // rather than calling into it. | |
| 4475 | + if (entry.released) return Promise.reject(__releasedStubError()); | |
| 4476 | + // A stub rooted in an aborted context is broken: reject with the | |
| 4477 | + // abort reason, before and after the dispatch (the target may | |
| 4478 | + // abort its own context mid-call). Gated on one field read. | |
| 4479 | + if (__abortedCtxs.size !== 0) { | |
| 4480 | + const aborted = __abortedCtxs.get(entry.ctx); | |
| 4481 | + if (aborted !== undefined) | |
| 4482 | + return Promise.reject(__postAbortError(aborted)); | |
| 4483 | + } | |
| 4484 | + const argsSc = args === null ? null : __rpcOut(args, true); | |
| 4485 | + const dispatch = (async () => { | |
| 4486 | + // Workerd delivers RPC asynchronously: the callee must not run | |
| 4487 | + // before the caller's synchronous code. A call made just after | |
| 4488 | + // a not-yet-delivered ctx.abort counts as in flight (rejects | |
| 4489 | + // with the reason, not the post-abort message). Bodies queue | |
| 4490 | + // in call order, so e-order holds. | |
| 4491 | + await null; | |
| 4492 | + // The cell that minted this stub gates it like any other event. | |
| 4493 | + // The op is dispatched inside the isolate and never becomes a | |
| 4494 | + // drive, so it is the one delivery point that has to ask here | |
| 4495 | + // rather than in Rust. A stub carrying the running critical | |
| 4496 | + // section re-enters it; everything else queues, and a section | |
| 4497 | + // that failed refuses what queued. | |
| 4498 | + const cell = entry.scope; | |
| 4499 | + if (cell !== undefined) { | |
| 4500 | + const block = __cellBlocks.get(cell); | |
| 4501 | + if (block !== undefined && (entry.section === null || | |
| 4502 | + entry.section !== block.holder)) | |
| 4503 | + await __gate_wait(cell); | |
| 4504 | + } | |
| 4505 | + const reply = await __ctxRun(entry.ctx, | |
| 4506 | + () => __rpcRun(async () => { | |
| 4507 | + const decoded = | |
| 4508 | + argsSc === null ? null : __rpcDesArgs(argsSc); | |
| 4509 | + try { | |
| 4510 | + return await __rpcWalk(entry.target, path, | |
| 4511 | + decoded === null ? null : decoded.args, false); | |
| 4512 | + } finally { | |
| 4513 | + if (decoded !== null) | |
| 4514 | + for (const handle of decoded.received) | |
| 4515 | + __disposeStub(handle); | |
| 4516 | + } | |
| 4517 | + }, true)); | |
| 4518 | + if (__abortedCtxs.size !== 0) { | |
| 4519 | + const aborted = __abortedCtxs.get(entry.ctx); | |
| 4520 | + if (aborted !== undefined) | |
| 4521 | + throw aborted instanceof __ActorAbort | |
| 4522 | + ? aborted.reason : aborted; | |
| 4523 | + } | |
| 4524 | + return __rpcDes(reply); | |
| 4525 | + })(); | |
| 4526 | + if (entry.ctx === undefined) return dispatch; | |
| 4527 | + // Race the op against its hosting context's abort: a hung callee | |
| 4528 | + // never settles, so the settlement check above cannot reach it. | |
| 4529 | + // A late settlement lands on an already-settled promise (no-op). | |
| 4530 | + return new Promise((resolve, reject) => { | |
| 4531 | + const untrack = __opTrack(entry.ctx, reject); | |
| 4532 | + dispatch.then( | |
| 4533 | + (value) => { untrack(); resolve(value); }, | |
| 4534 | + (error) => { untrack(); reject(error); }); | |
| 4535 | + }); | |
| 4536 | +}; | |
| 4537 | +// Resolve a path against a local, already-revived value. A hop | |
| 4538 | +// landing on a same-isolate stub delegates the rest of the path | |
| 4539 | +// to the stub's target; everything else is a plain [[Get]] so | |
| 4540 | +// Durable Object stubs and Proxies participate. | |
| 4541 | +const __walkLocal = (parent, path, args) => { | |
| 4542 | + for (let i = 0; i < path.length; i++) { | |
| 4543 | + const meta = __stubMeta.get(parent); | |
| 4544 | + if (meta) return __stubOp(meta, path.slice(i), args); | |
| 4545 | + const prop = path[i]; | |
| 4546 | + const member = parent == null ? undefined : parent[prop]; | |
| 4547 | + if (i < path.length - 1) { | |
| 4548 | + parent = member; | |
| 4549 | + continue; | |
| 4550 | + } | |
| 4551 | + if (args === null) return member; | |
| 4552 | + if (typeof member !== "function") { | |
| 4553 | + if (member === undefined) throw __rpcNoSuchMethod(prop); | |
| 4554 | + throw new TypeError('"' + prop + '" is not a function.'); | |
| 4555 | + } | |
| 4556 | + // [[Call]] directly: `.apply` on a stub proxy would be a | |
| 4557 | + // remote property access, not an invocation. | |
| 4558 | + return Reflect.apply(member, parent, args); | |
| 4559 | + } | |
| 4560 | + if (args === null) return parent; | |
| 4561 | + const meta = __stubMeta.get(parent); | |
| 4562 | + if (meta) return __stubOp(meta, [], args); | |
| 4563 | + if (typeof parent !== "function") | |
| 4564 | + throw new TypeError("The RPC value is not callable."); | |
| 4565 | + return parent(...args); | |
| 4566 | +}; | |
| 4567 | +// A session is one place pipeline ops resolve: the local value a | |
| 4568 | +// call returned, a same-isolate stub's target, or a named | |
| 4569 | +// entrypoint (whose paths resolve receiver-side in one op). | |
| 4570 | +const __valueSession = (promise) => ({ | |
| 4571 | + root: () => promise, | |
| 4572 | + get: (path) => promise.then((v) => __walkLocal(v, path, null)), | |
| 4573 | + call: (path, args) => | |
| 4574 | + promise.then((v) => __walkLocal(v, path, args)), | |
| 4575 | +}); | |
| 4576 | +const __stubSession = (meta) => ({ | |
| 4577 | + get: (path) => __stubOp(meta, path, null), | |
| 4578 | + call: (path, args) => __stubOp(meta, path, args), | |
| 4579 | +}); | |
| 4580 | +const __entrypointSession = (name, local, script, makeInst, propsSc) => ({ | |
| 4581 | + get: (path) => local | |
| 4582 | + ? (async () => __rpcDes( | |
| 4583 | + await __entrypointOp(name, path, null, true, makeInst)))() | |
| 4584 | + : (async () => __rpcDes( | |
| 4585 | + await __svc_rpc( | |
| 4586 | + script, name, JSON.stringify(path), null, propsSc)))(), | |
| 4587 | + call: (path, args) => (async () => { | |
| 4588 | + const argsSc = __rpcOut(args, local); | |
| 4589 | + if (local) | |
| 4590 | + return __rpcDes(await __entrypointOp( | |
| 4591 | + name, path, argsSc, true, makeInst)); | |
| 4592 | + return __rpcDes( | |
| 4593 | + await __svc_rpc( | |
| 4594 | + script, name, JSON.stringify(path), argsSc, propsSc)); | |
| 4595 | + })(), | |
| 4596 | +}); | |
| 4597 | +// Workerd's JsRpcPromise/JsRpcProperty: awaitable, callable, and | |
| 4598 | +// property access extends a path resolved at the far end, so | |
| 4599 | +// intermediates obey Workerd's receiver rules. `ctx` is the node's | |
| 4600 | +// owning request context -- null marks a context-free node (a | |
| 4601 | +// property path rooted directly at a service binding, which | |
| 4602 | +// starts a fresh session per await); a foreign context awaiting a | |
| 4603 | +// property or calling through the node gets Workerd's | |
| 4604 | +// cross-context error. Depth is capped like Workerd's | |
| 4605 | +// MAX_PROPERTY_DEPTH. | |
| 4606 | +const __makeNode = (session, path, ctx) => { | |
| 4607 | + let promise; | |
| 4608 | + const value = () => promise ??= (() => { | |
| 4609 | + if (path.length === 0) return session.root(); | |
| 4610 | + if (ctx !== null && ctx !== __ctxNow()) | |
| 4611 | + return Promise.reject(__ctxError("Pipeline")); | |
| 4612 | + return session.get(path); | |
| 4613 | + })(); | |
| 4614 | + const brand = | |
| 4615 | + path.length === 0 ? __cf.RpcPromise : __cf.RpcProperty; | |
| 4616 | + return new Proxy(function () {}, { | |
| 4617 | + getPrototypeOf: () => brand.prototype, | |
| 4618 | + get: (_b, p) => { | |
| 4619 | + if (p === "then") | |
| 4620 | + return (onOk, onErr) => value().then(onOk, onErr); | |
| 4621 | + if (p === "catch") return (onErr) => value().catch(onErr); | |
| 4622 | + if (p === "finally") | |
| 4623 | + return (onDone) => value().finally(onDone); | |
| 4624 | + if (typeof p !== "string") return undefined; | |
| 4625 | + if (path.length >= 5120) | |
| 4626 | + throw new TypeError( | |
| 4627 | + "RPC pipelined property chain is too deep."); | |
| 4628 | + return __makeNode(session, [...path, p], ctx); | |
| 4629 | + }, | |
| 4630 | + apply: (_b, _this, args) => { | |
| 4631 | + let call; | |
| 4632 | + if (ctx !== null && ctx !== __ctxNow()) { | |
| 4633 | + call = Promise.reject(__ctxError("JsRpcPromise")); | |
| 4634 | + call.catch(() => {}); | |
| 4635 | + } else { | |
| 4636 | + // Eager, so concurrent calls keep e-order. | |
| 4637 | + call = session.call(path, args); | |
| 4638 | + } | |
| 4639 | + return __makeNode( | |
| 4640 | + __valueSession(call), [], ctx ?? __ctxNow()); | |
| 4641 | + }, | |
| 4642 | + }); | |
| 4643 | +}; | |
| 4644 | +const __makeStub = (entry, callable) => { | |
| 4645 | + const meta = | |
| 4646 | + { entry, callable, disposed: false, ctx: __ctxNow() }; | |
| 4647 | + __ctxRegister(meta); | |
| 4648 | + const stub = new Proxy(function () {}, { | |
| 4649 | + getPrototypeOf: () => __cf.RpcStub.prototype, | |
| 4650 | + get: (_b, prop) => { | |
| 4651 | + if (prop === "then") return undefined; | |
| 4652 | + if (prop === Symbol.dispose) return () => __disposeStub(meta); | |
| 4653 | + if (prop === "dup") return () => { | |
| 4654 | + if (meta.disposed) throw __stubDisposedError(); | |
| 4655 | + entry.refs++; | |
| 4656 | + return __makeStub(entry, callable); | |
| 4657 | + }; | |
| 4658 | + if (typeof prop !== "string") return undefined; | |
| 4659 | + return __makeNode(__stubSession(meta), [prop], __ctxNow()); | |
| 4660 | + }, | |
| 4661 | + apply: (_b, _this, args) => __makeNode( | |
| 4662 | + __valueSession(__stubOp(meta, [], args)), [], __ctxNow()), | |
| 4663 | + }); | |
| 4664 | + __stubMeta.set(stub, meta); | |
| 4665 | + return stub; | |
| 4666 | +}; | |
| 4667 | +// A loopback service stub for one of this worker's own | |
| 4668 | +// entrypoints -- the ctx.exports surface. Calling the stub itself | |
| 4669 | +// returns a new stub carrying per-instance props, delivered to | |
| 4670 | +// the class constructor as ctx.props (Workerd's | |
| 4671 | +// ctx.exports.Name({ props })). | |
| 4672 | +const __svcMeta = new WeakMap(); | |
| 4673 | +const __entrypointStub = (name, props) => { | |
| 4674 | + let inst; | |
| 4675 | + const makeInst = props === undefined ? undefined : () => { | |
| 4676 | + if (inst !== undefined) return inst; | |
| 4677 | + const cls = __cell.entrypoints[name]; | |
| 4678 | + if (typeof cls !== "function") | |
| 4679 | + throw new TypeError( | |
| 4680 | + "The entrypoint " + name + " cannot carry props."); | |
| 4681 | + // Construction gets its own event, like a top-level invocation, and hands | |
| 4682 | + // that event's drain to the enclosing one. This runs inside the event of | |
| 4683 | + // the first method call on the stub, so a ctx.waitUntil() call in the | |
| 4684 | + // constructor drains before that call replies. | |
| 4685 | + inst = __constructEntrypoint(cls, props); | |
| 4686 | + return inst; | |
| 4687 | + }; | |
| 4688 | + const session = __entrypointSession(name, true, null, makeInst); | |
| 4689 | + const stub = new Proxy(function () {}, { | |
| 4690 | + getPrototypeOf: () => __cf.ServiceStub.prototype, | |
| 4691 | + get: (_b, prop) => { | |
| 4692 | + if (prop === "then") return undefined; | |
| 4693 | + if (typeof prop !== "string") return undefined; | |
| 4694 | + if (prop === "getRpcMethodForTestOnly") | |
| 4695 | + return (n) => __makeNode(session, [String(n)], null); | |
| 4696 | + return __makeNode(session, [prop], null); | |
| 4697 | + }, | |
| 4698 | + apply: (_b, _this, args) => | |
| 4699 | + __entrypointStub(name, args[0]?.props), | |
| 4700 | + }); | |
| 4701 | + __svcMeta.set(stub, { name, props }); | |
| 4702 | + __outboundMeta.set(stub, { | |
| 4703 | + script: __cell.script, | |
| 4704 | + entrypoint: name, | |
| 4705 | + props, | |
| 4706 | + }); | |
| 4707 | + return stub; | |
| 4708 | +}; | |
| 4709 | +// ---- stored stubs ---------------------------------------------- | |
| 4710 | +// Durable Object storage accepts only stubs with durable identity: | |
| 4711 | +// loopback service stubs (entrypoint name + props re-mint a fresh | |
| 4712 | +// stub on read) and Durable Object stubs (HMAC'd id + class revive | |
| 4713 | +// in any isolate). A transient handle -- a received RPC stub, a | |
| 4714 | +// function, an RpcTarget -- dies with its isolate; persisting its | |
| 4715 | +// entry id would revive garbage after a restart, so it is refused. | |
| 4716 | +// A stub-bearing row is written as 0x01 + clone(marker tree), off | |
| 4717 | +// the plain-clone fast path (the lift runs only after the plain | |
| 4718 | +// clone already threw, exactly like the RPC envelope). Reads hand | |
| 4719 | +// tagged rows to JS as [sentinel, tree]; the sentinel never leaves | |
| 4720 | +// this script and no user value can decode to it, so revival | |
| 4721 | +// cannot be spoofed by data shaped like a marker. | |
| 4722 | +const __storedSentinel = {}; | |
| 4723 | +const __storedLift = (value) => { | |
| 4724 | + let lifted = false; | |
| 4725 | + const seen = new Map(); | |
| 4726 | + const lift = (v) => { | |
| 4727 | + if (v === null || | |
| 4728 | + (typeof v !== "object" && typeof v !== "function")) return v; | |
| 4729 | + const cached = seen.get(v); | |
| 4730 | + if (cached !== undefined) return cached; | |
| 4731 | + // Ordering mirrors __stubLift: identify proxies by their | |
| 4732 | + // side tables and brands before touching any property -- a | |
| 4733 | + // stub or pipeline proxy answers every property read with a | |
| 4734 | + // fresh RpcProperty node. | |
| 4735 | + if (__stubMeta.has(v) || v instanceof __cf.RpcTarget) | |
| 4736 | + throw new DOMException( | |
| 4737 | + "Durable Object storage can only store stubs with " + | |
| 4738 | + "durable identity: service stubs from ctx.exports and " + | |
| 4739 | + "Durable Object stubs. This value is a transient RPC " + | |
| 4740 | + "handle that would not survive a restart.", | |
| 4741 | + "DataCloneError"); | |
| 4742 | + const svc = __svcMeta.get(v); | |
| 4743 | + if (svc !== undefined) { | |
| 4744 | + lifted = true; | |
| 4745 | + const marker = { "__celld$svc": svc.name }; | |
| 4746 | + seen.set(v, marker); | |
| 4747 | + if (svc.props !== undefined) marker.p = lift(svc.props); | |
| 4748 | + return marker; | |
| 4749 | + } | |
| 4750 | + if (v instanceof __cf.RpcPromise || | |
| 4751 | + v instanceof __cf.RpcProperty) | |
| 4752 | + throw new DOMException( | |
| 4753 | + 'Could not serialize object of type "' + | |
| 4754 | + (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + | |
| 4755 | + '". This type does not support serialization.', | |
| 4756 | + "DataCloneError"); | |
| 4757 | + if (typeof v === "function") return v; // leave to the clone | |
| 4758 | + const doId = __doStubMeta.get(v); | |
| 4759 | + if (doId !== undefined) { | |
| 4760 | + lifted = true; | |
| 4761 | + const marker = { "__celld$do": doId._className, | |
| 4762 | + v: doId._value, n: v.name ?? null }; | |
| 4763 | + seen.set(v, marker); | |
| 4764 | + return marker; | |
| 4765 | + } | |
| 4766 | + if (Array.isArray(v)) { | |
| 4767 | + const out = []; | |
| 4768 | + seen.set(v, out); | |
| 4769 | + for (let i = 0; i < v.length; i++) out[i] = lift(v[i]); | |
| 4770 | + return out; | |
| 4771 | + } | |
| 4772 | + const proto = Object.getPrototypeOf(v); | |
| 4773 | + if (proto !== Object.prototype && proto !== null) | |
| 4774 | + return v; // host/other: leave to the clone | |
| 4775 | + const out = {}; | |
| 4776 | + seen.set(v, out); | |
| 4777 | + for (const key of Object.keys(v)) out[key] = lift(v[key]); | |
| 4778 | + return out; | |
| 4779 | + }; | |
| 4780 | + const tree = lift(value); | |
| 4781 | + return lifted ? tree : null; | |
| 4782 | +}; | |
| 4783 | +// Encode one stub-bearing value for storage. Rethrows the original | |
| 4784 | +// clone error when nothing was liftable, so plain uncloneables | |
| 4785 | +// fail exactly as they always did. | |
| 4786 | +const __storedBytes = (value, error) => { | |
| 4787 | + const tree = __storedLift(value); | |
| 4788 | + if (tree === null) throw error; | |
| 4789 | + return __tagged(1, __sc_encode(tree)); | |
| 4790 | +}; | |
| 4791 | +const __storedRevive = (value) => { | |
| 4792 | + const seen = new Set(); | |
| 4793 | + const revive = (v) => { | |
| 4794 | + if (v === null || typeof v !== "object") return v; | |
| 4795 | + const svcName = v["__celld$svc"]; | |
| 4796 | + if (svcName !== undefined) | |
| 4797 | + return __entrypointStub(svcName, revive(v.p)); | |
| 4798 | + const doClass = v["__celld$do"]; | |
| 4799 | + if (doClass !== undefined) | |
| 4800 | + return __cell.makeNamespace(doClass).get( | |
| 4801 | + new DurableObjectId(doClass, v.v, v.n ?? undefined)); | |
| 4802 | + if (seen.has(v)) return v; | |
| 4803 | + seen.add(v); | |
| 4804 | + if (Array.isArray(v)) { | |
| 4805 | + for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); | |
| 4806 | + return v; | |
| 4807 | + } | |
| 4808 | + const proto = Object.getPrototypeOf(v); | |
| 4809 | + if (proto !== Object.prototype && proto !== null) return v; | |
| 4810 | + for (const key of Object.keys(v)) v[key] = revive(v[key]); | |
| 4811 | + return v; | |
| 4812 | + }; | |
| 4813 | + return revive(value); | |
| 4814 | +}; | |
| 4815 | +const __unwrapStored = (v) => | |
| 4816 | + Array.isArray(v) && v[0] === __storedSentinel | |
| 4817 | + ? __storedRevive(v[1]) : v; | |
| 4818 | +// A map result is wrapped as a whole only when it holds at least | |
| 4819 | +// one tagged row, so the per-entry walk never runs on plain data. | |
| 4820 | +const __unwrapStoredMap = (v) => { | |
| 4821 | + if (!Array.isArray(v) || v[0] !== __storedSentinel) return v; | |
| 4822 | + const map = v[1]; | |
| 4823 | + for (const [key, value] of map) | |
| 4824 | + map.set(key, __unwrapStored(value)); | |
| 4825 | + return map; | |
| 4826 | +}; | |
| 4827 | +// ctx.exports: loopback stubs for every exported entrypoint plus | |
| 4828 | +// this worker's Durable Object namespaces. Built once, on first | |
| 4829 | +// access -- ctx construction itself only carries the getter. | |
| 4830 | +let __ctxExportsCache; | |
| 4831 | +const __ctxExports = () => __ctxExportsCache ??= (() => { | |
| 4832 | + const out = {}; | |
| 4833 | + for (const name of Object.keys(__cell.entrypoints)) | |
| 4834 | + out[name] = __entrypointStub(name, undefined); | |
| 4835 | + for (const name of Object.keys(__cell.objectEntrypoints)) | |
| 4836 | + if (name !== "default") | |
| 4837 | + out[name] = __entrypointStub(name, undefined); | |
| 4838 | + for (const name of Object.keys(__cell.namespaceKeys)) | |
| 4839 | + out[name] = __cell.makeNamespace(name); | |
| 4840 | + return out; | |
| 4841 | +})(); | |
| 4842 | +// ---- RPC envelope ---------------------------------------------- | |
| 4843 | +// Serialize one payload. `lift` marks a same-isolate transport, | |
| 4844 | +// where stub-able values may cross as markers; elsewhere they stay | |
| 4845 | +// a DataCloneError, exactly as before stubs existed. | |
| 4846 | +const __rpcOut = (value, lift) => { | |
| 4847 | + const projected = __rpcProject(value); | |
| 4848 | + try { | |
| 4849 | + return __sc_encode(projected.tree); | |
| 4850 | + } catch (error) { | |
| 4851 | + // A cross-isolate call lifts only a live signal. A same-isolate call can | |
| 4852 | + // also transfer the existing host values and JS capability handles. | |
| 4853 | + const lifted = __stubLift(projected.tree, lift, projected.originals); | |
| 4854 | + if (lifted === null) throw __dataCloneError(error); | |
| 4855 | + try { | |
| 4856 | + return __tagged( | |
| 4857 | + lifted.caps ? 1 : 2, __sc_encode(lifted.tree)); | |
| 4858 | + } catch (error_) { | |
| 4859 | + throw __dataCloneError(error_); | |
| 4860 | + } | |
| 4861 | + } | |
| 4862 | +}; | |
| 4863 | +// A callee exception as tagged bytes: the Error crosses by value | |
| 4864 | +// (V8 serializes Error natively), custom own properties beside it. | |
| 4865 | +const __rpcErrOut = (error) => { | |
| 4866 | + // `name` rides in the props: V8 only round-trips the standard | |
| 4867 | + // Error subclass names, and e.g. DataCloneError must survive. | |
| 4868 | + const props = error instanceof Error | |
| 4869 | + ? { ...error, name: error.name } : {}; | |
| 4870 | + let sc; | |
| 4871 | + try { | |
| 4872 | + sc = __sc_encode([error, props]); | |
| 4873 | + } catch { | |
| 4874 | + const error_ = new Error(String(error?.message ?? error)); | |
| 4875 | + sc = __sc_encode([error_, { name: String(error?.name ?? "Error") }]); | |
| 4876 | + } | |
| 4877 | + return __tagged(0, sc); | |
| 4878 | +}; | |
| 4879 | +// The callee half of one RPC: run `body`, answer tagged bytes. | |
| 4880 | +const __rpcRun = async (body, lift) => { | |
| 4881 | + try { | |
| 4882 | + return __rpcOut(await body(), lift); | |
| 4883 | + } catch (error) { | |
| 4884 | + return __rpcErrOut(error); | |
| 4885 | + } | |
| 4886 | +}; | |
| 4887 | +const __rpcDesArgs = (bytes) => { | |
| 4888 | + if (bytes[0] === 0xff) | |
| 4889 | + return { args: __sc_decode(bytes), received: [] }; | |
| 4890 | + const revived = __stubRevive(__sc_decode(bytes.subarray(1))); | |
| 4891 | + return { args: revived.value, received: revived.handles }; | |
| 4892 | +}; | |
| 4893 | +// The caller half: decode a reply, rebuilding stubs and rethrowing | |
| 4894 | +// callee exceptions as real Errors with the callee's own | |
| 4895 | +// properties, `.remote`, and a local (caller-side) stack. | |
| 4896 | +const __rpcDes = (bytes) => { | |
| 4897 | + if (bytes[0] === 0xff) return __sc_decode(bytes); | |
| 4898 | + if (bytes[0] === 1 || bytes[0] === 2) { | |
| 4899 | + const { value, handles, disposers } = | |
| 4900 | + __stubRevive(__sc_decode(bytes.subarray(1))); | |
| 4901 | + if (value !== null && typeof value === "object" && | |
| 4902 | + !__stubMeta.has(value) && | |
| 4903 | + (handles.length > 0 || disposers.length > 0)) { | |
| 4904 | + Object.defineProperty(value, Symbol.dispose, { | |
| 4905 | + configurable: true, | |
| 4906 | + value: () => { | |
| 4907 | + for (const handle of handles) __disposeStub(handle); | |
| 4908 | + for (const entry of disposers) { | |
| 4909 | + __stubEntries.delete(entry.id); | |
| 4910 | + Promise.resolve().then(() => entry.target()); | |
| 4911 | + } | |
| 4912 | + }, | |
| 4913 | + }); | |
| 4914 | + } | |
| 4915 | + return value; | |
| 4916 | + } | |
| 4917 | + const [error, props] = __sc_decode(bytes.subarray(1)); | |
| 4918 | + if (error instanceof Error) { | |
| 4919 | + Object.assign(error, props); | |
| 4920 | + error.remote = true; | |
| 4921 | + const local = new Error().stack; | |
| 4922 | + error.stack = error.name + ": " + error.message + | |
| 4923 | + local.slice(local.indexOf("\n")); | |
| 4924 | + } | |
| 4925 | + throw error; | |
| 4926 | +}; | |
| 4927 | +// Deprecated Fetcher `get()`/`put()`/`delete()` HTTP helpers, kept by | |
| 4928 | +// the fetcher_has_get_put_delete compat flag (Workerd http.c++): | |
| 4929 | +// shortcuts for fetch() with the corresponding method. | |
| 4930 | +const __fetcherStatus = (res, method) => { | |
| 4931 | + if (res.status >= 200 && res.status < 300) return; | |
| 4932 | + throw new Error("HTTP " + method + " request failed: " + res.status + | |
| 4933 | + " " + (res.statusText || __STATUS_TEXT[res.status] || "")); | |
| 4934 | +}; | |
| 4935 | +const __fetcherHelper = (fetch, prop) => { | |
| 4936 | + if (prop === "get") return async (url, type) => { | |
| 4937 | + const res = await fetch(url, { method: "GET" }); | |
| 4938 | + if (res.status === 404 || res.status === 410) return null; | |
| 4939 | + __fetcherStatus(res, "GET"); | |
| 4940 | + if (type === "stream") | |
| 4941 | + return res.body ?? new ReadableStream({ start(c) { c.close(); } }); | |
| 4942 | + if (type === "arrayBuffer") return res.arrayBuffer(); | |
| 4943 | + if (type === "json") return res.json(); | |
| 4944 | + return res.text(); | |
| 4945 | + }; | |
| 4946 | + if (prop === "put") return async (url, body, options) => { | |
| 4947 | + const { expiration, expirationTtl } = options ?? {}; | |
| 4948 | + if (expiration !== undefined || expirationTtl !== undefined) { | |
| 4949 | + const url_ = new URL(url); | |
| 4950 | + if (expiration !== undefined) | |
| 4951 | + url_.searchParams.append("expiration", expiration); | |
| 4952 | + if (expirationTtl !== undefined) | |
| 4953 | + url_.searchParams.append("expiration_ttl", expirationTtl); | |
| 4954 | + url = url_.toString(); | |
| 4955 | + } | |
| 4956 | + __fetcherStatus(await fetch(url, { method: "PUT", body }), "PUT"); | |
| 4957 | + }; | |
| 4958 | + return async (url) => { | |
| 4959 | + __fetcherStatus(await fetch(url, { method: "DELETE" }), "DELETE"); | |
| 4960 | + }; | |
| 4961 | +}; | |
| 4962 | +function makeNamespace(className) { | |
| 4963 | + const namespaceKey = __cell.namespaceKeys[className]; | |
| 4964 | + if (typeof namespaceKey !== "string") | |
| 4965 | + throw new Error("no Durable Object namespace key for " + className); | |
| 4966 | + return new DurableObjectNamespace(className, namespaceKey); | |
| 4967 | +} | |
| 4968 | +// A named class: SDKs sniff bindings by constructor name (workers-rs | |
| 4969 | +// EnvBinding requires `constructor.name === "DurableObjectNamespace"`). | |
| 4970 | +class DurableObjectNamespace { | |
| 4971 | + constructor(className, namespaceKey) { | |
| 4972 | + Object.defineProperty(this, "_className", { value: className }); | |
| 4973 | + Object.defineProperty(this, "_namespaceKey", { value: namespaceKey }); | |
| 4974 | + } | |
| 4975 | + idFromName(name) { | |
| 4976 | + name = String(name); | |
| 4977 | + return new DurableObjectId( | |
| 4978 | + this._className, __do_id(this._namespaceKey, "name", name), name, | |
| 4979 | + ); | |
| 4980 | + } | |
| 4981 | + idFromString(value) { | |
| 4982 | + return new DurableObjectId( | |
| 4983 | + this._className, __do_id(this._namespaceKey, "validate", String(value)), | |
| 4984 | + ); | |
| 4985 | + } | |
| 4986 | + newUniqueId(options = {}) { | |
| 4987 | + const jurisdiction = options == null ? undefined : options.jurisdiction; | |
| 4988 | + if (jurisdiction != null) | |
| 4989 | + throw new Error("Jurisdiction restrictions are not implemented"); | |
| 4990 | + return new DurableObjectId( | |
| 4991 | + this._className, __do_id(this._namespaceKey, "unique", ""), | |
| 4992 | + ); | |
| 4993 | + } | |
| 4994 | + jurisdiction(value) { | |
| 4995 | + if (value == null) return this; | |
| 4996 | + throw new Error("Jurisdiction restrictions are not implemented"); | |
| 4997 | + } | |
| 4998 | + getByName(name, options) { | |
| 4999 | + return this.get(this.idFromName(name), options); | |
| 5000 | + } | |
| 5001 | + get(id) { | |
| 5002 | + const className = this._className; | |
| 5003 | + if (!(id instanceof DurableObjectId) || id._className !== className) | |
| 5004 | + throw new TypeError("Durable Object ID is not valid for this namespace"); | |
| 5005 | + const scope = id._scope(); | |
| 5006 | + // Emulate production: the actor recovers its name only when it is | |
| 5007 | + // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is | |
| 5008 | + // undefined. The full name still seeds the routing hash, so | |
| 5009 | + // dispatch is unchanged. Short names skip the byte count (< 256 | |
| 5010 | + // chars is always <= 1020 bytes) to keep the hot path alloc-free. | |
| 5011 | + const nm = id.name; | |
| 5012 | + const dispatchName = nm === undefined ? undefined | |
| 5013 | + : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024 | |
| 5014 | + ? nm : undefined; | |
| 5015 | + if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName; | |
| 5016 | + // Fetch and native RPC use the same host routing/activation seam. | |
| 5017 | + // Never expose `.then`: a DO stub is not itself a promise. | |
| 5018 | + const target = { id, name: dispatchName }; | |
| 5019 | + const abortMarker = "__CELLD_ACTOR_ABORT__:"; | |
| 5020 | + const processExitMarker = "__CELLD_PROCESS_EXIT__:"; | |
| 5021 | + let brokenReason = null; | |
| 5022 | + const invoke = async (operation) => { | |
| 5023 | + if (brokenReason !== null) throw new Error(brokenReason); | |
| 5024 | + try { | |
| 5025 | + return await operation(); | |
| 5026 | + } catch (error) { | |
| 5027 | + const routingError = __durableObjectRoutingError(error); | |
| 5028 | + if (routingError !== null) throw routingError; | |
| 5029 | + const message = String(error && error.message || error); | |
| 5030 | + const marker = [abortMarker, processExitMarker] | |
| 5031 | + .find((candidate) => message.includes(candidate)); | |
| 5032 | + if (!marker) throw error; | |
| 5033 | + brokenReason = message.slice(message.indexOf(marker) + marker.length); | |
| 5034 | + throw new Error(brokenReason); | |
| 5035 | + } | |
| 5036 | + }; | |
| 5037 | + const doFetch = async (input, init) => { | |
| 5038 | + const req = new Request(input, init); | |
| 5039 | + const signal = req._signalForSubrequests; | |
| 5040 | + if (signal?.aborted) throw signal.reason; | |
| 5041 | + // A body already backed by a host stream forwards to the cell as its | |
| 5042 | + // stream id, so a proxied upload to a cell on this node costs a chunk | |
| 5043 | + // rather than the whole body (#156). The host keeps it a stream for a | |
| 5044 | + // local cell and collects it only to sign a cross-node frame. A held | |
| 5045 | + // body -- or a stream with no host id -- crosses as its bytes. | |
| 5046 | + const bodyStreamId = | |
| 5047 | + req._bodyBytes === null && req.body && req.body.__celldStreamId !== undefined | |
| 5048 | + ? req.body.__celldStreamId | |
| 5049 | + : undefined; | |
| 5050 | + const body_ = bodyStreamId !== undefined | |
| 5051 | + ? new Uint8Array() | |
| 5052 | + : req._bodyBytes === null | |
| 5053 | + ? await req._consume() | |
| 5054 | + : req._bodyBytes; | |
| 5055 | + if (bodyStreamId !== undefined) { | |
| 5056 | + // The cell reads this upload through the same host stream id, so the | |
| 5057 | + // Worker's wrapper must not also read it: lock it (a late read throws | |
| 5058 | + // instead of racing the cell over one host stream) and mark it used, | |
| 5059 | + // which is what awaiting the old _consume() did and what workerd | |
| 5060 | + // reports as request.bodyUsed after the forward. | |
| 5061 | + req.bodyUsed = true; | |
| 5062 | + req.body.getReader(); | |
| 5063 | + } | |
| 5064 | + // Forward the request's headers to the cell as JSON. When they were | |
| 5065 | + // never materialized -- a Worker that only routes to a cell reads | |
| 5066 | + // none -- pass the raw header string straight through, so the whole | |
| 5067 | + // dispatch never builds a Headers object on either side. | |
| 5068 | + // | |
| 5069 | + // Both branches now carry the same shape. The raw string is the | |
| 5070 | + // wire list the host handed in, so the materialized branch must send | |
| 5071 | + // the header list too, not the iterator; see the note on the | |
| 5072 | + // outbound `fetch`. Reading `.headers` on a forwarded request used | |
| 5073 | + // to change what the cell received. | |
| 5074 | + const headersJson = req._headersJson !== undefined | |
| 5075 | + ? req._headersJson | |
| 5076 | + : JSON.stringify(req.headers.__celldHeaderList); | |
| 5077 | + const r = JSON.parse(await invoke(() => { | |
| 5078 | + if (!signal) return __do_call( | |
| 5079 | + scope, dispatchName ?? null, req.url, req.method, body_, | |
| 5080 | + headersJson, bodyStreamId, | |
| 5081 | + ); | |
| 5082 | + return __awaitCancellableDoCall( | |
| 5083 | + __do_call_cancellable( | |
| 5084 | + scope, dispatchName ?? null, req.url, req.method, body_, | |
| 5085 | + headersJson, bodyStreamId, | |
| 5086 | + ), | |
| 5087 | + signal, | |
| 5088 | + ); | |
| 5089 | + })); | |
| 5090 | + const body = r.streamId !== undefined | |
| 5091 | + ? new CelldHttpBodyStream(r.streamId) | |
| 5092 | + : r.body !== undefined | |
| 5093 | + ? r.body | |
| 5094 | + : Uint8Array.from(r.bodyBytes || []); | |
| 5095 | + // An upgrade the cell answered with. The pair straddles two isolates, | |
| 5096 | + // so the client end cannot be the peer object itself -- it is a new | |
| 5097 | + // socket the host joins to the cell's on `accept()`. A caller that | |
| 5098 | + // returns this response instead of accepting keeps the direct route | |
| 5099 | + // `__wsTarget` already describes, and binds nothing. | |
| 5100 | + return new Response(body, { | |
| 5101 | + status: r.status, | |
| 5102 | + headers: r.headers, | |
| 5103 | + __wsTarget: r.wsTarget, | |
| 5104 | + webSocket: r.status === 101 && r.wsTarget | |
| 5105 | + ? new WebSocket(undefined, [], r.wsTarget) | |
| 5106 | + : undefined, | |
| 5107 | + }); | |
| 5108 | + }; | |
| 5109 | + const stub = new Proxy(target, { get: (_target, prop) => { | |
| 5110 | + if (prop === "then") return undefined; | |
| 5111 | + if (Reflect.has(_target, prop)) return Reflect.get(_target, prop); | |
| 5112 | + if (prop === "fetch") return doFetch; | |
| 5113 | + if (typeof prop !== "string") return undefined; | |
| 5114 | + if (__cell.compat.fetcherGetPutDelete && | |
| 5115 | + (prop === "get" || prop === "put" || prop === "delete")) | |
| 5116 | + return __fetcherHelper(doFetch, prop); | |
| 5117 | + // Every cell RPC goes out through the host, whichever node owns the | |
| 5118 | + // target. Same-process dispatch re-enters this isolate, where the | |
| 5119 | + // abort and exit markers revive; bytes that land elsewhere revive as | |
| 5120 | + // loud foreign stubs. | |
| 5121 | + return async (...args) => invoke( | |
| 5122 | + async () => __rpcDes(await __rpc_call( | |
| 5123 | + scope, dispatchName ?? null, prop, __rpcOut(args, true), | |
| 5124 | + )), | |
| 5125 | + ); | |
| 5126 | + }}); | |
| 5127 | + __doStubMeta.set(stub, id); | |
| 5128 | + return stub; | |
| 5129 | + } | |
| 5130 | +} | |
| 5131 | +const __attachResponseRequestCancellation = ( | |
| 5132 | + response, | |
| 5133 | + requestController, | |
| 5134 | + wrapBody, | |
| 5135 | +) => { | |
| 5136 | + if (!(response instanceof Response) || | |
| 5137 | + response._bodyBytes !== null || | |
| 5138 | + response.body === null) { | |
| 5139 | + return; | |
| 5140 | + } | |
| 5141 | + const requestControllers = Array.isArray( | |
| 5142 | + response.__celldRequestControllers, | |
| 5143 | + ) | |
| 5144 | + ? response.__celldRequestControllers | |
| 5145 | + : [requestController]; | |
| 5146 | + if (requestControllers !== response.__celldRequestControllers) { | |
| 5147 | + Object.defineProperty(response, "__celldRequestControllers", { | |
| 5148 | + value: requestControllers, | |
| 5149 | + }); | |
| 5150 | + } else { | |
| 5151 | + requestControllers.push(requestController); | |
| 5152 | + } | |
| 5153 | + if (!wrapBody || response.__celldCancellationWrapped) return; | |
| 5154 | + const reader = response.body.getReader(); | |
| 5155 | + response.body = new ReadableStream({ | |
| 5156 | + async pull(controller) { | |
| 5157 | + const result = await reader.read(); | |
| 5158 | + if (result.done) controller.close(); | |
| 5159 | + else controller.enqueue(result.value); | |
| 5160 | + }, | |
| 5161 | + async cancel() { | |
| 5162 | + const reason = new Error("The client has disconnected"); | |
| 5163 | + for (const controller of requestControllers) { | |
| 5164 | + if (!controller.signal.aborted) controller.abort(reason); | |
| 5165 | + } | |
| 5166 | + try { | |
| 5167 | + await reader.cancel(reason); | |
| 5168 | + } catch {} | |
| 5169 | + }, | |
| 5170 | + }, { highWaterMark: 0 }); | |
| 5171 | + Object.defineProperty(response, "__celldCancellationWrapped", { | |
| 5172 | + value: true, | |
| 5173 | + }); | |
| 5174 | +}; | |
| 5175 | +// called on the owner node by the /__do/<scope> endpoint: run one object. | |
| 5176 | +// Returns the Response; Rust's read_response unwraps it (don't double-wrap). | |
| 5177 | +// A top-level (non-actor) request whose signal can be aborted by id, so a | |
| 5178 | +// disconnected HTTP or service-binding caller reaches the target's | |
| 5179 | +// `request.signal`. | |
| 5180 | +// A large body, or a body of unknown length, arrives as a stream id and | |
| 5181 | +// not as bytes. The handler then pulls the body off the socket as it | |
| 5182 | +// reads, so the whole body is never resident. `request.body` is a stream | |
| 5183 | +// in both cases. | |
| 5184 | +__celld.__makeIncomingRequest = ( | |
| 5185 | + url, method, body, headersJson, streamId, | |
| 5186 | +) => __makeRequest( | |
| 5187 | + url, method, | |
| 5188 | + streamId === undefined ? body : new CelldHttpBodyStream(streamId), | |
| 5189 | + headersJson, undefined, true); | |
| 5190 | +const __dispatchTo = __celld.__dispatchTo = async ( | |
| 5191 | + scope, url, method, body, headersJson, requestId = null, bodyStreamId = null, | |
| 5192 | +) => { | |
| 5193 | + // A routed body that must not be collected crosses as a host stream id; the | |
| 5194 | + // handler here reads it in parts. A held body arrives as its bytes. | |
| 5195 | + if (bodyStreamId !== null) body = new CelldHttpBodyStream(bodyStreamId); | |
| 5196 | + // Request already allocates a default controller for an absent signal. | |
| 5197 | + // Retain that same allocation so a streamed response can report reader | |
| 5198 | + // cancellation after the handler has returned. | |
| 5199 | + const requestController = new AbortController(); | |
| 5200 | + if (requestId !== null) | |
| 5201 | + __incomingRequestSignals.set( | |
| 5202 | + String(requestId), requestController.signal); | |
| 5203 | + const actorEvent = __beginActorEvent(scope); | |
| 5204 | + try { | |
| 5205 | + const dispatch = (async () => { | |
| 5206 | + const inst = await _readyInstance(scope); | |
| 5207 | + return await __ctxRun(undefined, () => inst.fetch( | |
| 5208 | + __makeRequest( | |
| 5209 | + url, | |
| 5210 | + method, | |
| 5211 | + body, | |
| 5212 | + headersJson, | |
| 5213 | + requestController.signal, | |
| 5214 | + true, | |
| 5215 | + ))); | |
| 5216 | + })(); | |
| 5217 | + // The caller's abandonment reaches the target through | |
| 5218 | + // __do_call_cancel/__abortIncomingRequest, which aborts the fresh incoming | |
| 5219 | + // signal made above; the host dispatcher passes no caller signal here. | |
| 5220 | + const response = await dispatch; | |
| 5221 | + // Not wrapped: the host holds this response and gates it, and the caller | |
| 5222 | + // that would cancel the body reaches it through the routed channel's own | |
| 5223 | + // controller rather than this one. | |
| 5224 | + __attachResponseRequestCancellation(response, requestController, false); | |
| 5225 | + if (response instanceof Response && response.status === 101 && | |
| 5226 | + response.webSocket && !response.webSocket._target) { | |
| 5227 | + const socket = response.webSocket._peer; | |
| 5228 | + const target = { id: response.webSocket._id, scope }; | |
| 5229 | + response.webSocket._target = target; | |
| 5230 | + if (socket) { | |
| 5231 | + socket._target = target; | |
| 5232 | + if (!socket._hibernatable) | |
| 5233 | + __ws_accept_regular(socket._id, scope); | |
| 5234 | + __sockets.set(socket._id, socket); | |
| 5235 | + socket._flushPending(); | |
| 5236 | + } | |
| 5237 | + } | |
| 5238 | + return response; | |
| 5239 | + } finally { | |
| 5240 | + if (requestId !== null) | |
| 5241 | + __incomingRequestSignals.delete(String(requestId)); | |
| 5242 | + __endActorEvent(actorEvent); | |
| 5243 | + } | |
| 5244 | +}; | |
| 5245 | +const __rpcTargetMethod = async (scope, method) => { | |
| 5246 | + const inst = await _readyInstance(scope); | |
| 5247 | + if (!inst.__celldState._rpcOk) | |
| 5248 | + throw new TypeError( | |
| 5249 | + "The receiving Durable Object does not support RPC, because " + | |
| 5250 | + "its class was not declared with `extends DurableObject`. In " + | |
| 5251 | + "order to enable RPC, make sure your class extends the " + | |
| 5252 | + "special class `DurableObject`, which can be imported from " + | |
| 5253 | + "the module \"cloudflare:workers\"."); | |
| 5254 | + const fn = inst[method]; | |
| 5255 | + if (typeof fn !== "function") | |
| 5256 | + throw new TypeError(method + " is not a function"); | |
| 5257 | + return [inst, fn]; | |
| 5258 | +}; | |
| 5259 | +// The byte path always lifts stub-able values into the reply: the | |
| 5260 | +// markers carry the isolate token, so they revive only back in this | |
| 5261 | +// isolate (same-process routed dispatch re-enters it) and fail loudly | |
| 5262 | +// on use anywhere else. Callee exceptions cross in | |
| 5263 | +// the error envelope on every flavor. | |
| 5264 | +__celld.__dispatchRpc = async (scope, method, args) => { | |
| 5265 | + const actorEvent = __beginActorEvent(scope); | |
| 5266 | + try { | |
| 5267 | + // A string is the legacy JSON flavor; bytes are V8 structured clone. | |
| 5268 | + // Answer in kind. | |
| 5269 | + if (typeof args === "string") { | |
| 5270 | + const [inst, fn] = await __rpcTargetMethod(scope, method); | |
| 5271 | + const result = await fn.apply(inst, JSON.parse(args)); | |
| 5272 | + return JSON.stringify(result) ?? "null"; | |
| 5273 | + } | |
| 5274 | + return await __ctxRun(undefined, () => (async () => { | |
| 5275 | + const decoded = __rpcDesArgs(args); | |
| 5276 | + try { | |
| 5277 | + return await __rpcRun(async () => { | |
| 5278 | + // A broken actor (JS-flavored ctx.abort) rejects every | |
| 5279 | + // later call with the reason. One gated field read. | |
| 5280 | + if (__brokenActors.size !== 0) { | |
| 5281 | + const broken = __brokenActors.get(scope); | |
| 5282 | + if (broken !== undefined) throw broken; | |
| 5283 | + } | |
| 5284 | + const [inst, fn] = await __rpcTargetMethod(scope, method); | |
| 5285 | + return fn.apply(inst, decoded.args); | |
| 5286 | + }, true); | |
| 5287 | + } finally { | |
| 5288 | + for (const handle of decoded.received) __disposeStub(handle); | |
| 5289 | + } | |
| 5290 | + })()); | |
| 5291 | + } finally { | |
| 5292 | + __endActorEvent(actorEvent); | |
| 5293 | + } | |
| 5294 | +}; | |
| 5295 | +const __entrypointClass = (name) => { | |
| 5296 | + const cls = __cell.entrypoints[name]; | |
| 5297 | + if (typeof cls !== "function") { | |
| 5298 | + // Workerd getExportedHandler(): distinguish a Durable Object class | |
| 5299 | + // misused as a stateless entrypoint from a name that resolves to | |
| 5300 | + // nothing. Error path only; both lookups are O(1). | |
| 5301 | + if (__cell.classes[name] !== undefined || __cell.doExports[name]) | |
| 5302 | + throw new TypeError( | |
| 5303 | + `The entrypoint name ${name} refers to a Durable Object ` + | |
| 5304 | + "class, but the incoming request is trying to invoke it as " + | |
| 5305 | + "a stateless worker."); | |
| 5306 | + throw new TypeError( | |
| 5307 | + `The entrypoint name ${name} was not found in this worker. ` + | |
| 5308 | + "Ensure the worker exports an entrypoint with that name."); | |
| 5309 | + } | |
| 5310 | + return cls; | |
| 5311 | +}; | |
| 5312 | +// End the construction event immediately: ctx.waitUntil registers into | |
| 5313 | +// whichever event is current at call time, so leaving this event on the | |
| 5314 | +// stack would swallow every later registration in the isolate. The drain that | |
| 5315 | +// the event yields moves to the enclosing event, because a ctx.waitUntil() | |
| 5316 | +// call inside a constructor is otherwise fire-and-forget: the RPC reply can | |
| 5317 | +// answer and the request context can tear down before that work runs. | |
| 5318 | +// __wait_until drops the drain when no event encloses this one, which is the | |
| 5319 | +// isolate-startup case and matches the older behavior. | |
| 5320 | +const __constructEntrypoint = (cls, props) => { | |
| 5321 | + const ctx = __beginEvent(props); | |
| 5322 | + try { | |
| 5323 | + return new cls(ctx, __cell.env); | |
| 5324 | + } finally { | |
| 5325 | + const drain = __endEvent(); | |
| 5326 | + if (drain !== null) __wait_until(drain); | |
| 5327 | + } | |
| 5328 | +}; | |
| 5329 | +// A stateless Worker invocation owns one class instance and its constructor | |
| 5330 | +// context. Reusing either across invocations leaks class fields and request | |
| 5331 | +// authority, while constructing more than once inside one invocation splits | |
| 5332 | +// work that Cloudflare delivers to one receiver. | |
| 5333 | +const __newEntrypointInstance = (name, props) => | |
| 5334 | + __constructEntrypoint(__entrypointClass(name), props); | |
| 5335 | +// `env.NAME.fetch()` where NAME is bound with `entrypoint = "..."` goes | |
| 5336 | +// to that class's fetch, not the module's default export. A plain | |
| 5337 | +// object export (Workerd's non-class entrypoint) dispatches its | |
| 5338 | +// handler functions as fn(arg, env, ctx). | |
| 5339 | +// A missing fetch reports workerd's own text, the same one the loader | |
| 5340 | +// installs for a Worker with no default export, so the two paths agree. | |
| 5341 | +const __noHandler = (name, method) => | |
| 5342 | + method === "fetch" && name === "default" | |
| 5343 | + ? new Error("Handler does not export a fetch() function.") | |
| 5344 | + : new TypeError( | |
| 5345 | + `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); | |
| 5346 | + | |
| 5347 | +const __dispatchEntrypointMethod = async (name, method, arg, props) => { | |
| 5348 | + const handler = __cell.objectEntrypoints[name]; | |
| 5349 | + if (handler !== undefined) { | |
| 5350 | + if (typeof handler[method] !== "function") | |
| 5351 | + throw __noHandler(name, method); | |
| 5352 | + const ctx = __beginEvent(props); | |
| 5353 | + try { | |
| 5354 | + return await __ctxRun(undefined, | |
| 5355 | + () => handler[method](arg, __cell.env, ctx)); | |
| 5356 | + } finally { | |
| 5357 | + __endEvent(); | |
| 5358 | + } | |
| 5359 | + } | |
| 5360 | + // A class entrypoint's methods get env and ctx from its constructor, | |
| 5361 | + // not as arguments. | |
| 5362 | + const inst = __newEntrypointInstance(name, props); | |
| 5363 | + if (typeof inst[method] !== "function") | |
| 5364 | + throw __noHandler(name, method); | |
| 5365 | + return await __ctxRun(undefined, () => inst[method](arg)); | |
| 5366 | +}; | |
| 5367 | +// Invoke a handler inside the event frame that the host already opened. A | |
| 5368 | +// Queue dispatch uses this form because its host driver must receive and keep | |
| 5369 | +// driving the handler's waitUntil aggregate after the settlement is returned. | |
| 5370 | +const __dispatchEntrypointMethodInCurrentEvent = async (name, method, arg) => { | |
| 5371 | + const handler = __cell.objectEntrypoints[name]; | |
| 5372 | + if (handler !== undefined) { | |
| 5373 | + if (typeof handler[method] !== "function") | |
| 5374 | + throw __noHandler(name, method); | |
| 5375 | + return await __ctxRun(undefined, | |
| 5376 | + () => handler[method](arg, __cell.env, __entrypointContext())); | |
| 5377 | + } | |
| 5378 | + const inst = __newEntrypointInstance(name, undefined); | |
| 5379 | + if (typeof inst[method] !== "function") | |
| 5380 | + throw __noHandler(name, method); | |
| 5381 | + return await __ctxRun(undefined, () => inst[method](arg)); | |
| 5382 | +}; | |
| 5383 | +const __dispatchEntrypointFetch = __celld.__dispatchEntrypointFetch = | |
| 5384 | + (name, request, propsSc = null) => | |
| 5385 | + __dispatchEntrypointMethod( | |
| 5386 | + name, "fetch", request, | |
| 5387 | + propsSc === null || propsSc.length === 0 | |
| 5388 | + ? undefined : __sc_decode(propsSc)); | |
| 5389 | +__celld.__dispatchEntrypointScheduled = (name, ctrl) => | |
| 5390 | + __dispatchEntrypointMethod(name, "scheduled", ctrl); | |
| 5391 | +// A queue batch owns mutable settlement state only while its handler runs. | |
| 5392 | +// Keeping a batch alive after dispatch must not keep authority to settle its | |
| 5393 | +// lease, because that lease can have expired and been handed out again. | |
| 5394 | +__celld.__dispatchEntrypointQueue = async (name, incoming) => { | |
| 5395 | + let active = true; | |
| 5396 | + let ackAll = false; | |
| 5397 | + const explicitAcks = new Set(); | |
| 5398 | + const retries = new Map(); | |
| 5399 | + const retryBatch = { retry: false, delaySeconds: undefined }; | |
| 5400 | + const checkActive = () => { | |
| 5401 | + if (!active) | |
| 5402 | + throw new Error("Queue event methods cannot be called after the handler returns."); | |
| 5403 | + }; | |
| 5404 | + const retryDelay = (options) => { | |
| 5405 | + const value = options?.delaySeconds; | |
| 5406 | + if (value === undefined) return undefined; | |
| 5407 | + if (!Number.isInteger(value) || value < -0x8000_0000 || value > 0x7fff_ffff) | |
| 5408 | + throw new TypeError("delaySeconds must be a 32-bit integer"); | |
| 5409 | + return value; | |
| 5410 | + }; | |
| 5411 | + const decode = (message) => { | |
| 5412 | + switch (message.contentType) { | |
| 5413 | + case "text": return new TextDecoder().decode(message.body); | |
| 5414 | + case "bytes": return message.body; | |
| 5415 | + case "json": return JSON.parse(new TextDecoder().decode(message.body)); | |
| 5416 | + case "v8": return __sc_decode(message.body); | |
| 5417 | + default: throw new TypeError(`Unknown queue content type: ${message.contentType}`); | |
| 5418 | + } | |
| 5419 | + }; | |
| 5420 | + const messages = incoming.messages.map((message) => ({ | |
| 5421 | + id: message.id, | |
| 5422 | + timestamp: new Date(message.timestamp), | |
| 5423 | + body: decode(message), | |
| 5424 | + attempts: message.attempts, | |
| 5425 | + ack() { | |
| 5426 | + checkActive(); | |
| 5427 | + if (ackAll || retryBatch.retry || retries.has(message.id)) return; | |
| 5428 | + explicitAcks.add(message.id); | |
| 5429 | + }, | |
| 5430 | + retry(options) { | |
| 5431 | + checkActive(); | |
| 5432 | + if (ackAll || explicitAcks.has(message.id)) return; | |
| 5433 | + const delaySeconds = retryDelay(options); | |
| 5434 | + if (delaySeconds !== undefined || !retries.has(message.id)) | |
| 5435 | + retries.set(message.id, delaySeconds); | |
| 5436 | + }, | |
| 5437 | + })); | |
| 5438 | + const oldest = incoming.metrics.oldestMessageTimestamp; | |
| 5439 | + const batch = { | |
| 5440 | + queue: incoming.queue, | |
| 5441 | + messages, | |
| 5442 | + metadata: { | |
| 5443 | + metrics: { | |
| 5444 | + backlogCount: incoming.metrics.backlogCount, | |
| 5445 | + backlogBytes: incoming.metrics.backlogBytes, | |
| 5446 | + oldestMessageTimestamp: oldest === undefined ? undefined : new Date(oldest), | |
| 5447 | + }, | |
| 5448 | + }, | |
| 5449 | + ackAll() { | |
| 5450 | + checkActive(); | |
| 5451 | + if (!retryBatch.retry) ackAll = true; | |
| 5452 | + }, | |
| 5453 | + retryAll(options) { | |
| 5454 | + checkActive(); | |
| 5455 | + if (ackAll) return; | |
| 5456 | + retryBatch.retry = true; | |
| 5457 | + const delaySeconds = retryDelay(options); | |
| 5458 | + if (delaySeconds !== undefined) retryBatch.delaySeconds = delaySeconds; | |
| 5459 | + }, | |
| 5460 | + }; | |
| 5461 | + let outcome = "ok"; | |
| 5462 | + let errorText; | |
| 5463 | + try { | |
| 5464 | + await __dispatchEntrypointMethodInCurrentEvent(name, "queue", batch); | |
| 5465 | + } catch (error) { | |
| 5466 | + // A handler exception retries the batch but keeps explicit acks that the | |
| 5467 | + // handler made before it threw. The caller needs both facts together. | |
| 5468 | + outcome = "exception"; | |
| 5469 | + try { | |
| 5470 | + errorText = String(error); | |
| 5471 | + } catch { | |
| 5472 | + errorText = "queue handler rejected"; | |
| 5473 | + } | |
| 5474 | + } finally { | |
| 5475 | + active = false; | |
| 5476 | + } | |
| 5477 | + return { | |
| 5478 | + outcome, | |
| 5479 | + error: errorText, | |
| 5480 | + ackAll, | |
| 5481 | + retryBatch, | |
| 5482 | + explicitAcks: [...explicitAcks], | |
| 5483 | + retryMessages: [...retries].map(([msgId, delaySeconds]) => ({ | |
| 5484 | + msgId, | |
| 5485 | + delaySeconds, | |
| 5486 | + })), | |
| 5487 | + }; | |
| 5488 | +}; | |
| 5489 | +// Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class | |
| 5490 | +// handler method is called as fn(arg, env, ctx), the client must send | |
| 5491 | +// exactly one argument, and the handler must not declare more than | |
| 5492 | +// (arg, env, ctx). The messages are Workerd's, verbatim. | |
| 5493 | +const __callObjectEntrypoint = (handler, method, args, props) => { | |
| 5494 | + const fn = handler[method]; | |
| 5495 | + if (typeof fn !== "function") | |
| 5496 | + throw new TypeError( | |
| 5497 | + 'The RPC receiver does not implement the method "' + method + | |
| 5498 | + '".'); | |
| 5499 | + if (fn.length > 3) | |
| 5500 | + throw new TypeError( | |
| 5501 | + 'Cannot call handler function "' + method + '" over RPC ' + | |
| 5502 | + "because it has the wrong number of arguments. A simple " + | |
| 5503 | + "function handler can only be called over RPC if it has " + | |
| 5504 | + "exactly the arguments (arg, env, ctx), where only the first " + | |
| 5505 | + "argument comes from the client. To support multi-argument " + | |
| 5506 | + "RPC functions, use class-based syntax (extending " + | |
| 5507 | + "WorkerEntrypoint) instead."); | |
| 5508 | + if (args.length !== 1) | |
| 5509 | + throw new TypeError( | |
| 5510 | + 'Attempted to call RPC function "' + method + '" with the ' + | |
| 5511 | + "wrong number of arguments. When calling a top-level handler " + | |
| 5512 | + "function that is not declared as part of a class, you must " + | |
| 5513 | + "always send exactly one argument. In order to support " + | |
| 5514 | + "variable numbers of arguments, the server must use " + | |
| 5515 | + "class-based syntax (extending WorkerEntrypoint) instead."); | |
| 5516 | + return fn.call(handler, args[0], __cell.env, __entrypointContext(props)); | |
| 5517 | +}; | |
| 5518 | +let __nextPendingEventId = 1; | |
| 5519 | +const __pendingEvents = new Map(); | |
| 5520 | +const __pendingEventError = () => new Error( | |
| 5521 | + "The Workers runtime canceled this request because it detected that " + | |
| 5522 | + "your Worker's code had hung and would never generate a response. " + | |
| 5523 | + "Refer to: https://developers.cloudflare.com/workers/observability/errors/"); | |
| 5524 | +// The host calls this only when the request has no native operation that can | |
| 5525 | +// resume JavaScript. Reject the entrypoint call itself, so its caller can | |
| 5526 | +// catch the cancellation and continue the enclosing event. | |
| 5527 | +__celld.__cancelPendingEvents = (ids) => { | |
| 5528 | + for (const id of ids) __pendingEvents.get(id)?.(__pendingEventError()); | |
| 5529 | +}; | |
| 5530 | +// One entrypoint op (a call, or a property GET when argsSc is | |
| 5531 | +// null), inside a fresh request context -- the callee owns stubs | |
| 5532 | +// revived from its params, and stubs it mints belong to it. | |
| 5533 | +// `props` is the caller's per-stub props (Workerd's | |
| 5534 | +// getEntrypoint(name, { props })); undefined leaves the entrypoint's | |
| 5535 | +// default empty props. | |
| 5536 | +const __entrypointOp = (name, path, argsSc, local, makeInst, props) => { | |
| 5537 | + const id = __nextCtxId++; | |
| 5538 | + return __ctxRun(id, () => { | |
| 5539 | + const pendingId = __nextPendingEventId++; | |
| 5540 | + let cancel; | |
| 5541 | + const cancellation = new Promise((_, reject) => { cancel = reject; }); | |
| 5542 | + __pendingEvents.set(pendingId, cancel); | |
| 5543 | + __pending_event_begin(pendingId); | |
| 5544 | + const running = (async () => { | |
| 5545 | + const decoded = argsSc === null ? null : __rpcDesArgs(argsSc); | |
| 5546 | + let drain = null; | |
| 5547 | + try { | |
| 5548 | + const reply = await __rpcRun(async () => { | |
| 5549 | + // The handler's synchronous part runs inside its own event so | |
| 5550 | + // ctx.waitUntil and the imported waitUntil have a target. The | |
| 5551 | + // event pops before the first await -- the event stack is | |
| 5552 | + // strictly LIFO and an event held across an await would be | |
| 5553 | + // popped by whichever event settles next -- and its registered | |
| 5554 | + // work drains before a plain reply (below). | |
| 5555 | + __beginEvent(); | |
| 5556 | + let result; | |
| 5557 | + try { | |
| 5558 | + const handler = __cell.objectEntrypoints[name]; | |
| 5559 | + if (handler !== undefined && makeInst === undefined) { | |
| 5560 | + // Simple-handler entrypoints expose single-method calls | |
| 5561 | + // only; property GETs and deeper paths are refused. | |
| 5562 | + if (argsSc === null || path.length !== 1) | |
| 5563 | + throw __rpcNoSuchMethod(path[0]); | |
| 5564 | + result = __callObjectEntrypoint( | |
| 5565 | + handler, path[0], decoded.args, props); | |
| 5566 | + } else { | |
| 5567 | + // A loopback stub with props retains one instance for that RPC | |
| 5568 | + // session. Each ordinary top-level operation constructs once here, | |
| 5569 | + // so neither its fields nor its constructor context reach the next | |
| 5570 | + // invocation. | |
| 5571 | + const inst = makeInst !== undefined ? makeInst() | |
| 5572 | + : __newEntrypointInstance(name, props); | |
| 5573 | + result = __rpcWalk(inst, path, | |
| 5574 | + decoded === null ? null : decoded.args, true); | |
| 5575 | + } | |
| 5576 | + } finally { | |
| 5577 | + drain = __endEvent(); | |
| 5578 | + } | |
| 5579 | + return await result; | |
| 5580 | + }, local); | |
| 5581 | + // Registered work drains before a plain reply. A | |
| 5582 | + // capability-bearing reply (tag 1) must not wait: a returned | |
| 5583 | + // stream's chunks may be produced by that very work, which | |
| 5584 | + // cannot finish until the caller pulls (returnReadableStream's | |
| 5585 | + // waitUntil writer would deadlock behind its own reply). | |
| 5586 | + if (reply[0] !== 1 && drain !== null) await drain; | |
| 5587 | + // ctx.abort() during the call supersedes its result; the raw | |
| 5588 | + // reason rejects the caller (same isolate -- identity holds). | |
| 5589 | + if (__abortedCtxs.size !== 0) { | |
| 5590 | + const reason = __abortedCtxs.get(id); | |
| 5591 | + if (reason !== undefined) throw reason; | |
| 5592 | + } | |
| 5593 | + // A reply that exports no stubs (tag 0xff plain, tag 0 error) | |
| 5594 | + // leaves nothing rooting this context: tear it down now, so a | |
| 5595 | + // dup() the callee leaked reaches its disposal callback | |
| 5596 | + // promptly (Workerd tears the IoContext down at call end | |
| 5597 | + // unless returned capabilities hold it open). | |
| 5598 | + if (reply[0] !== 1) __ctxEnd(id); | |
| 5599 | + return reply; | |
| 5600 | + } finally { | |
| 5601 | + if (decoded !== null) | |
| 5602 | + for (const handle of decoded.received) __disposeStub(handle); | |
| 5603 | + } | |
| 5604 | + })(); | |
| 5605 | + return Promise.race([running, cancellation]).finally(() => { | |
| 5606 | + __pendingEvents.delete(pendingId); | |
| 5607 | + __pending_event_end(pendingId); | |
| 5608 | + }); | |
| 5609 | + }); | |
| 5610 | +}; | |
| 5611 | +// Cross-isolate service callers pass a complete property path. Older host | |
| 5612 | +// callers can still pass one method name, which becomes a one-part path. | |
| 5613 | +// `propsSc` carries getEntrypoint(name, {props}) as structured-clone bytes, | |
| 5614 | +// the same encoding as `argsSc`. It is empty when the caller sent no props, | |
| 5615 | +// which no encoded value can be, so an empty buffer is an unambiguous absent. | |
| 5616 | +__celld.__dispatchEntrypointRpc = | |
| 5617 | + (name, path, argsSc, local = false, propsSc = null) => __entrypointOp( | |
| 5618 | + name, typeof path === "string" ? [path] : path, argsSc, local, | |
| 5619 | + undefined, | |
| 5620 | + propsSc === null || propsSc.length === 0 | |
| 5621 | + ? undefined : __sc_decode(propsSc)); | |
| 5622 | +// WebSocket: the host holds the socket; these deliver events into the DO. | |
| 5623 | +// `ws` is a lightweight stub whose send/close route back to the host task | |
| 5624 | +// by wsId -- so the isolate can be hibernated between messages. | |
| 5625 | +const __wsStub = __celld.__wsStub = (wsId) => ({ | |
| 5626 | + _hibernatable: true, | |
| 5627 | + send: (data) => { | |
| 5628 | + if (data instanceof ArrayBuffer) | |
| 5629 | + __ws_send_binary(wsId, new Uint8Array(data)); | |
| 5630 | + else if (ArrayBuffer.isView(data)) | |
| 5631 | + __ws_send_binary(wsId, | |
| 5632 | + new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); | |
| 5633 | + else | |
| 5634 | + __ws_send(wsId, String(data)); | |
| 5635 | + }, | |
| 5636 | + close: (code = 1000, reason = "") => __ws_close(wsId, code, reason), | |
| 5637 | +}); | |
| 5638 | +__celld.__wsOpen = async (scope, wsId, protocol) => { | |
| 5639 | + const actorEvent = __beginActorEvent(scope); | |
| 5640 | + try { | |
| 5641 | + const inst = await _readyInstance(scope); | |
| 5642 | + const socket = inst.__celldState._socket(wsId); | |
| 5643 | + if (socket.readyState !== WebSocket.READY_STATE_CONNECTING) return; | |
| 5644 | + socket.protocol = protocol; | |
| 5645 | + socket.readyState = WebSocket.READY_STATE_OPEN; | |
| 5646 | + socket.dispatchEvent(new Event("open")); | |
| 5647 | + } finally { | |
| 5648 | + __endActorEvent(actorEvent); | |
| 5649 | + } | |
| 5650 | +}; | |
| 5651 | +__celld.__wsMessage = async (scope, wsId, msg) => { | |
| 5652 | + const actorEvent = __beginActorEvent(scope); | |
| 5653 | + try { | |
| 5654 | + const inst = await _readyInstance(scope); | |
| 5655 | + const socket = inst.__celldState._socket(wsId); | |
| 5656 | + if (!socket._hibernatable && typeof socket._dispatchMessage === "function") | |
| 5657 | + socket._dispatchMessage(msg); | |
| 5658 | + else if (typeof inst.webSocketMessage === "function") | |
| 5659 | + await inst.webSocketMessage(socket, msg); | |
| 5660 | + } finally { | |
| 5661 | + __endActorEvent(actorEvent); | |
| 5662 | + } | |
| 5663 | +}; | |
| 5664 | +__celld.__wsBinary = async (scope, wsId, data) => { | |
| 5665 | + const actorEvent = __beginActorEvent(scope); | |
| 5666 | + try { | |
| 5667 | + const inst = await _readyInstance(scope); | |
| 5668 | + const socket = inst.__celldState._socket(wsId); | |
| 5669 | + const bytes = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); | |
| 5670 | + if (!socket._hibernatable && typeof socket._dispatchMessage === "function") | |
| 5671 | + socket._dispatchMessage(bytes); | |
| 5672 | + else if (typeof inst.webSocketMessage === "function") | |
| 5673 | + await inst.webSocketMessage(socket, bytes); | |
| 5674 | + } finally { | |
| 5675 | + __endActorEvent(actorEvent); | |
| 5676 | + } | |
| 5677 | +}; | |
| 5678 | +__celld.__wsClosed = async (scope, wsId, code, reason, wasClean) => { | |
| 5679 | + const actorEvent = __beginActorEvent(scope); | |
| 5680 | + try { | |
| 5681 | + const inst = await _readyInstance(scope); | |
| 5682 | + const socket = inst.__celldState._socket(wsId); | |
| 5683 | + if (!socket._hibernatable && typeof socket._dispatchClose === "function") | |
| 5684 | + socket._dispatchClose(code, reason, wasClean); | |
| 5685 | + else if (!wasClean && typeof inst.webSocketError === "function") | |
| 5686 | + // A hibernatable socket reports an abnormal closure through | |
| 5687 | + // webSocketError, which celld listed as a handler name and never | |
| 5688 | + // called. | |
| 5689 | + await inst.webSocketError( | |
| 5690 | + socket, | |
| 5691 | + new Error(reason ? `WebSocket closed abnormally: ${reason}` : "WebSocket closed abnormally"), | |
| 5692 | + ); | |
| 5693 | + else if (typeof inst.webSocketClose === "function") | |
| 5694 | + await inst.webSocketClose(socket, code, reason, wasClean); | |
| 5695 | + } finally { | |
| 5696 | + __endActorEvent(actorEvent); | |
| 5697 | + } | |
| 5698 | +}; | |
| 5699 | +// called by celld's scheduler when an alarm is due. Returns a promise. | |
| 5700 | +__celld.__fireAlarm = async (scope, scheduledTime, retryCount) => { | |
| 5701 | + const actorEvent = __beginActorEvent(scope); | |
| 5702 | + try { | |
| 5703 | + const inst = await _readyInstance(scope); | |
| 5704 | + if (typeof inst.alarm !== "function") return; | |
| 5705 | + await inst.alarm({ scheduledTime, retryCount, isRetry: retryCount > 0 }); | |
| 5706 | + } finally { | |
| 5707 | + __endActorEvent(actorEvent); | |
| 5708 | + } | |
| 5709 | +}; | |
| 5710 | +// The reserved cron cell. It is not a user class: celld registers it under | |
| 5711 | +// `.cron` for every deployment that declares `triggers.crons`, and one cell | |
| 5712 | +// per script carries that script's whole schedule. Ownership CAS on that one | |
| 5713 | +// name is what makes a cron trigger fire once per fleet rather than once per | |
| 5714 | +// node -- the same arbiter an alarm already relies on, with nothing added. | |
| 5715 | +// | |
| 5716 | +// The schedule itself is never stored here. `__cell.crons` comes from the | |
| 5717 | +// deployment the cell is running under, so changing a cron expression takes | |
| 5718 | +// effect on the next activation and needs no migration of an armed alarm. | |
| 5719 | +class CelldCronSchedule { | |
| 5720 | + constructor(state) { | |
| 5721 | + this._state = state; | |
| 5722 | + // Failures within one occurrence. Held in memory on purpose: losing the | |
| 5723 | + // count to an eviction only makes the next retry sooner, and every retry | |
| 5724 | + // is capped at the next occurrence anyway, so it need not be durable. | |
| 5725 | + this._retry = 0; | |
| 5726 | + // What a pending retry owes: the occurrence, the expressions of it that | |
| 5727 | + // failed, and the deadline the retry was armed for. A retry deadline is a | |
| 5728 | + // backoff instant and not an occurrence, so nothing about it can be | |
| 5729 | + // recovered from the deadline itself -- without this record the wake | |
| 5730 | + // matches no expression, runs nothing, and drops the failed tick in | |
| 5731 | + // silence. Held in memory beside `_retry` and for the same reason: an | |
| 5732 | + // eviction costs the retry, never the next occurrence. | |
| 5733 | + this._owed = null; | |
| 5734 | + } | |
| 5735 | + // celld calls this once per node after a deployment loads, because a cron | |
| 5736 | + // cell has no client to wake it. Arming is idempotent -- the same schedule | |
| 5737 | + // and the same clock give the same answer -- so it does not matter which | |
| 5738 | + // node wins the cell. | |
| 5739 | + async fetch() { | |
| 5740 | + // A pending retry is a deadline this cell already owes, and re-arming | |
| 5741 | + // would move it to the next occurrence and lose the tick it owes with it. | |
| 5742 | + if (this._owed !== null) return new Response(null, { status: 204 }); | |
| 5743 | + const armed = await this._state.storage.getAlarm(); | |
| 5744 | + // An alarm already due is a tick that is late, not one that is wrong. | |
| 5745 | + // Leaving it alone is what makes a fleet that was down fire the missed | |
| 5746 | + // occurrence once, instead of skipping it by re-arming into the future. | |
| 5747 | + if (armed === null || armed > Date.now()) await this._arm(null, [], false); | |
| 5748 | + return new Response(null, { status: 204 }); | |
| 5749 | + } | |
| 5750 | + async alarm(info) { | |
| 5751 | + const crons = __cell.crons || []; | |
| 5752 | + // A retry wake carries the backoff instant as its deadline, so what to run | |
| 5753 | + // and what time to report both come from the record the failure left. Only | |
| 5754 | + // a deadline that is not a retry is an occurrence to match against. | |
| 5755 | + const owed = this._owed !== null && this._owed.armedFor === info.scheduledTime | |
| 5756 | + ? this._owed | |
| 5757 | + : null; | |
| 5758 | + const occurrence = owed === null ? info.scheduledTime : owed.at; | |
| 5759 | + // One deadline can belong to several expressions, and each is its own | |
| 5760 | + // invocation with its own controller.cron, as on Cloudflare. A retry | |
| 5761 | + // repeats only the expressions that failed, because the ones that | |
| 5762 | + // succeeded already ran for this occurrence. | |
| 5763 | + const due = owed === null | |
| 5764 | + ? __cron_plan(crons, info.scheduledTime, Date.now(), 0, false).matching | |
| 5765 | + : owed.indices; | |
| 5766 | + const failed = []; | |
| 5767 | + for (const index of due) { | |
| 5768 | + let noRetry = false; | |
| 5769 | + const controller = { | |
| 5770 | + // The occurrence, never the instant this attempt started, so a late | |
| 5771 | + // run and a retry both report the minute they were scheduled for. | |
| 5772 | + scheduledTime: occurrence, | |
| 5773 | + cron: crons[index], | |
| 5774 | + noRetry() { noRetry = true; }, | |
| 5775 | + }; | |
| 5776 | + const ctx = __beginEvent(); | |
| 5777 | + try { | |
| 5778 | + if (typeof __cell.selfScheduled !== "function") | |
| 5779 | + throw new Error( | |
| 5780 | + "a cron trigger needs the Worker to export a `scheduled` handler"); | |
| 5781 | + await __cell.selfScheduled(controller, __cell.env, ctx); | |
| 5782 | + } catch (error) { | |
| 5783 | + // Swallowed on purpose: this handler owns the re-arm below, so | |
| 5784 | + // throwing would hand the deadline to the generic alarm retry and | |
| 5785 | + // lose the next occurrence with it. | |
| 5786 | + console.error( | |
| 5787 | + `scheduled handler for cron ${JSON.stringify(crons[index])} failed:`, | |
| 5788 | + error); | |
| 5789 | + if (!noRetry) failed.push(index); | |
| 5790 | + } finally { | |
| 5791 | + const drain = __endEvent(); | |
| 5792 | + // The alarm turn is the only host owner for this scheduled event. | |
| 5793 | + // Dropping its drain lets the actor turn end with waitUntil work still | |
| 5794 | + // pending, so an I/O promise can remain unresolved forever. | |
| 5795 | + if (drain !== null) await drain; | |
| 5796 | + } | |
| 5797 | + } | |
| 5798 | + await this._arm(occurrence, failed, owed !== null); | |
| 5799 | + } | |
| 5800 | + // `occurrence` is the tick just handled, or null when the cell is only | |
| 5801 | + // arming, `failed` holds the expressions of it still owed, and `retried` | |
| 5802 | + // says the deadline just handled was a backoff rather than an occurrence. | |
| 5803 | + async _arm(occurrence, failed, retried) { | |
| 5804 | + const crons = __cell.crons || []; | |
| 5805 | + // The count is failures within one occurrence, so a fresh occurrence | |
| 5806 | + // starts at one however the last one ended. Carrying it across would | |
| 5807 | + // spend `alarm_retry`'s ceiling once and leave every later occurrence | |
| 5808 | + // with no retry at all, which is a budget for the schedule and not for | |
| 5809 | + // the tick. | |
| 5810 | + this._retry = failed.length ? (retried ? this._retry + 1 : 1) : 0; | |
| 5811 | + // A negative first argument means "arming only, nothing fired". | |
| 5812 | + const plan = __cron_plan(crons, -1, Date.now(), this._retry, failed.length > 0); | |
| 5813 | + // The next occurrence beats the backoff whenever it is sooner, and it then | |
| 5814 | + // cancels the retry rather than queueing behind it, so the record the | |
| 5815 | + // retry needed goes when the retry does. | |
| 5816 | + this._owed = plan.armIsRetry | |
| 5817 | + ? { at: occurrence, indices: failed, armedFor: plan.armAt } | |
| 5818 | + : null; | |
| 5819 | + // No expression matches again and nothing is owed: the deployment dropped | |
| 5820 | + // its crons, so the cell retires rather than waking forever. | |
| 5821 | + if (plan.armAt === null) await this._state.storage.deleteAlarm(); | |
| 5822 | + else await this._state.storage.setAlarm(plan.armAt); | |
| 5823 | + } | |
| 5824 | +} | |
| 5825 | +const __cell = __celld.__cell = { | |
| 5826 | + entrypoints: {}, | |
| 5827 | + objectEntrypoints: {}, | |
| 5828 | + doExports: {}, | |
| 5829 | + classes: { ".cron": CelldCronSchedule }, | |
| 5830 | + crons: [], | |
| 5831 | + workflows: {}, | |
| 5832 | + containers: {}, | |
| 5833 | + instances: {}, | |
| 5834 | + facetConfigs: {}, | |
| 5835 | + env: {}, | |
| 5836 | + idNames: {}, | |
| 5837 | + namespaceKeys: {}, | |
| 5838 | + node: "", | |
| 5839 | + deleteAllDeletesAlarm: false, | |
| 5840 | + compat: { jsRpc: false, fetcherGetPutDelete: false, queueJsonMessages: false }, | |
| 5841 | + makeNamespace, | |
| 5842 | + release: __cellRelease, | |
| 5843 | +}; | |
| 5844 | +// ---- KV ------------------------------------------------------------------ | |
| 5845 | +// A KV namespace is a cell of a runtime-supplied Durable Object class, so it | |
| 5846 | +// inherits ownership, fencing, LTX replication and durable acknowledgement | |
| 5847 | +// from the cell it already is. This half is the server; `__makeKvNamespace` | |
| 5848 | +// below is the client the binding hands to a Worker. | |
| 5849 | +// | |
| 5850 | +// Reads here are strongly consistent and the published contract is upstream's: | |
| 5851 | +// a value can be up to 60 seconds old. That gap is deliberate. A node-local | |
| 5852 | +// read cache is the obvious next optimisation and it would make reads | |
| 5853 | +// genuinely stale, and a freshness promise made now could not be withdrawn | |
| 5854 | +// then. Implement strong, promise weak. | |
| 5855 | +// | |
| 5856 | +// Storage is ordinary cell SQL rather than the KV surface, because a namespace | |
| 5857 | +// is read by ordered prefix scan and `list` is the operation that decides the | |
| 5858 | +// schema. `celld_logic::kv` owns every decision about a key, a deadline or a | |
| 5859 | +// limit; nothing here re-derives one. | |
| 5860 | + | |
| 5861 | +// Run one bounded reclamation transaction. A cell supplies only its ordered | |
| 5862 | +// candidate query and its per-row transition, so KV expiry and Queue retention | |
| 5863 | +// share the turn bound and the transaction shape without pretending their SQL | |
| 5864 | +// state machines are the same. | |
| 5865 | +const __cellSweepBatch = (storage, select, reclaim, limit) => { | |
| 5866 | + let processed = 0; | |
| 5867 | + storage.transactionSync(() => { | |
| 5868 | + const rows = select(limit); | |
| 5869 | + if (rows.length > limit) throw new Error("a cell sweep exceeded its row bound"); | |
| 5870 | + for (const row of rows) { | |
| 5871 | + reclaim(row); | |
| 5872 | + processed += 1; | |
| 5873 | + } | |
| 5874 | + }); | |
| 5875 | + return processed; | |
| 5876 | +}; | |
| 5877 | + | |
| 5878 | +const __KV_TABLE = "__kv"; | |
| 5879 | +const __KV_META_TABLE = "__kv_meta"; | |
| 5880 | + | |
| 5881 | +// Upstream's four content types. The wire form is what `get` returns for | |
| 5882 | +// `type: "text"`; the binding converts from there, so the cell stores bytes | |
| 5883 | +// and a tag and never a parsed value. | |
| 5884 | +const __kvError = (message) => new Error("KV_ERROR: " + String(message)); | |
| 5885 | + | |
| 5886 | +// One op for the whole large-value path, following `__d1_run`. Bytes cross as | |
| 5887 | +// a typed view in both directions. Encoding a 25 MiB value as a JSON number | |
| 5888 | +// array creates millions of heap objects and can crash an otherwise valid put. | |
| 5889 | +const __kvBlob = async (request, value) => { | |
| 5890 | + const reply = await __kv_blob(JSON.stringify(request), value); | |
| 5891 | + return reply instanceof Uint8Array | |
| 5892 | + ? { found: true, value: reply } | |
| 5893 | + : JSON.parse(reply); | |
| 5894 | +}; | |
| 5895 | + | |
| 5896 | +// The authenticated operator route still uses JSON for its control envelope. | |
| 5897 | +// A byte array is acceptable for an inline value, but a 25 MiB array creates | |
| 5898 | +// 25 million JavaScript numbers and exhausts the isolate. The raw base64 ops | |
| 5899 | +// accept typed views for this internal wire form; the public atob() and btoa() | |
| 5900 | +// wrappers keep their standard string-only behaviour. | |
| 5901 | +const __kvOperatorValue = (value) => { | |
| 5902 | + const bytes = value instanceof Uint8Array ? value : new Uint8Array(value); | |
| 5903 | + return bytes.byteLength > __kvLimits().maxInlineValueBytes | |
| 5904 | + ? { value: $$btoa(bytes), valueEncoding: "base64" } | |
| 5905 | + : { value: [...bytes] }; | |
| 5906 | +}; | |
| 5907 | + | |
| 5908 | +// Content addressing, so the same value written twice in one ownership epoch | |
| 5909 | +// stores once and a retry after an uncertain failure costs nothing. A later | |
| 5910 | +// epoch deliberately uses a different object. SHA-256 makes an accidental | |
| 5911 | +// collision infeasible. The host adds the active cell scope and epoch to the | |
| 5912 | +// object key, because one activation cannot prove another activation's live | |
| 5913 | +// set and therefore cannot safely collect from a shared digest prefix. | |
| 5914 | +const __kvDigest = async (bytes) => { | |
| 5915 | + const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); | |
| 5916 | + let out = ""; | |
| 5917 | + for (const byte of hash) out += byte.toString(16).padStart(2, "0"); | |
| 5918 | + return out; | |
| 5919 | +}; | |
| 5920 | + | |
| 5921 | +// The least name that sorts after every name with this prefix, or null when no | |
| 5922 | +// such name exists. SQLite compares TEXT byte by byte and UTF-8 byte order is | |
| 5923 | +// code point order, so the successor is the prefix with its final code point | |
| 5924 | +// incremented; a final code point that is already the highest carries into the | |
| 5925 | +// code point before it, and an empty prefix has no upper bound at all. | |
| 5926 | +// | |
| 5927 | +// A lone surrogate has no UTF-8 form, so a prefix that holds one gets no bound | |
| 5928 | +// rather than a bound derived from whatever the host substitutes. Such a | |
| 5929 | +// prefix matches no stored name, and answering it with a wrong range would | |
| 5930 | +// answer it with the wrong keys instead of slowly. | |
| 5931 | +const __kvPrefixUpperBound = (prefix) => { | |
| 5932 | + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(prefix)) { | |
| 5933 | + return null; | |
| 5934 | + } | |
| 5935 | + // Array.from splits on code points, so a surrogate pair stays one element | |
| 5936 | + // and cannot be incremented into a different character. | |
| 5937 | + const points = Array.from(prefix); | |
| 5938 | + while (points.length > 0) { | |
| 5939 | + const code = points.pop().codePointAt(0); | |
| 5940 | + if (code >= 0x10FFFF) continue; | |
| 5941 | + // The surrogate block is unencodable, so step over it in one move. | |
| 5942 | + const next = code + 1 === 0xD800 ? 0xE000 : code + 1; | |
| 5943 | + return points.join("") + String.fromCodePoint(next); | |
| 5944 | + } | |
| 5945 | + return null; | |
| 5946 | +}; | |
| 5947 | + | |
| 5948 | +// Which rows a list visits is not visible in its result, so a lost bound reads | |
| 5949 | +// as a correct answer and is measurable only as latency. The plan is the | |
| 5950 | +// evidence, and a gated test seam reads it from the shipped query rather than | |
| 5951 | +// from a copy that can drift. | |
| 5952 | +const __kvReportListPlan = (sql, query, params) => { | |
| 5953 | + if (typeof __test_kv_list_plan !== "function") return; | |
| 5954 | + const plan = sql.exec(`EXPLAIN QUERY PLAN ${query}`, ...params) | |
| 5955 | + .toArray() | |
| 5956 | + .map((row) => row.detail) | |
| 5957 | + .join("; "); | |
| 5958 | + __test_kv_list_plan(plan); | |
| 5959 | +}; | |
| 5960 | + | |
| 5961 | +class __KvNamespaceCell { | |
| 5962 | + constructor(ctx) { | |
| 5963 | + this.ctx = ctx; | |
| 5964 | + this._ready = false; | |
| 5965 | + // Blob references written to the bucket whose row has not committed yet. A sweep | |
| 5966 | + // must spare these, or it collects bytes a put is about to reference. | |
| 5967 | + this._pending = new Set(); | |
| 5968 | + // Blob writes and the mark-and-sweep protocol share one per-cell queue. | |
| 5969 | + // The pending set is live state, not a snapshot that stays valid across an | |
| 5970 | + // await, so collection cannot overlap a put from its announcement through | |
| 5971 | + // its row commit. Other cells and ordinary reads stay independent. | |
| 5972 | + this._blobProtocolTail = Promise.resolve(); | |
| 5973 | + } | |
| 5974 | + | |
| 5975 | + async _withBlobProtocol(operation) { | |
| 5976 | + const previous = this._blobProtocolTail; | |
| 5977 | + let release; | |
| 5978 | + this._blobProtocolTail = new Promise((resolve) => { | |
| 5979 | + release = resolve; | |
| 5980 | + }); | |
| 5981 | + await previous; | |
| 5982 | + try { | |
| 5983 | + return await operation(); | |
| 5984 | + } finally { | |
| 5985 | + release(); | |
| 5986 | + } | |
| 5987 | + } | |
| 5988 | + | |
| 5989 | + // Schedule collection before a blob can leave the process or a row can drop | |
| 5990 | + // its reference. `setAlarm()` writes cell state, and the following bucket | |
| 5991 | + // egress waits on that write's output gate. A crash can therefore leave an | |
| 5992 | + // orphan only together with the durable wake that will collect it. | |
| 5993 | + async _armBlobSweep() { | |
| 5994 | + this._open().exec( | |
| 5995 | + `INSERT INTO ${__KV_META_TABLE} (name, value) VALUES ('blob-sweep-due', 1) | |
| 5996 | + ON CONFLICT(name) DO UPDATE SET value = excluded.value`, | |
| 5997 | + ); | |
| 5998 | + const now = Date.now(); | |
| 5999 | + const deadline = now + __kvLimits().blobSweepMs; | |
| 6000 | + const armed = await this.ctx.storage.getAlarm(); | |
| 6001 | + // During an alarm event, `getAlarm()` can still report the timestamp that | |
| 6002 | + // caused the current delivery. It is not a future wake and cannot cover a | |
| 6003 | + // reference removed by an event that interleaves with this one. | |
| 6004 | + if (armed === null || armed <= now || armed > deadline) { | |
| 6005 | + await this.ctx.storage.setAlarm(deadline); | |
| 6006 | + } | |
| 6007 | + } | |
| 6008 | + | |
| 6009 | + _blobSweepDue() { | |
| 6010 | + return this._open().exec( | |
| 6011 | + `SELECT 1 AS due FROM ${__KV_META_TABLE} | |
| 6012 | + WHERE name = 'blob-sweep-due' AND value = 1`, | |
| 6013 | + ).toArray().length > 0; | |
| 6014 | + } | |
| 6015 | + | |
| 6016 | + _clearBlobSweepDue() { | |
| 6017 | + this._open().exec( | |
| 6018 | + `DELETE FROM ${__KV_META_TABLE} WHERE name = 'blob-sweep-due'`, | |
| 6019 | + ); | |
| 6020 | + } | |
| 6021 | + | |
| 6022 | + // Created on first touch rather than at construction, so a namespace that is | |
| 6023 | + // only ever read costs no write, and an eviction that drops the isolate does | |
| 6024 | + // not need the table rebuilt before the cell can answer. | |
| 6025 | + _open() { | |
| 6026 | + if (this._ready) return this.ctx.storage.sql; | |
| 6027 | + const sql = this.ctx.storage.sql; | |
| 6028 | + // Recreate the first release's table before the normal open path. The | |
| 6029 | + // migration test then reaches the same `CREATE IF NOT EXISTS` boundary as | |
| 6030 | + // an upgraded cell and starts with a row it must preserve. | |
| 6031 | + if (__kvLimits().legacySchema) { | |
| 6032 | + sql.exec( | |
| 6033 | + `CREATE TABLE IF NOT EXISTS ${__KV_TABLE} ( | |
| 6034 | + name TEXT PRIMARY KEY, | |
| 6035 | + value BLOB, | |
| 6036 | + tag TEXT NOT NULL, | |
| 6037 | + metadata TEXT, | |
| 6038 | + expires_at INTEGER | |
| 6039 | + ) WITHOUT ROWID`, | |
| 6040 | + ); | |
| 6041 | + sql.exec( | |
| 6042 | + `INSERT OR IGNORE INTO ${__KV_TABLE} | |
| 6043 | + (name, value, tag, metadata, expires_at) | |
| 6044 | + VALUES ('before-upgrade', CAST('legacy' AS BLOB), 'text', NULL, NULL)`, | |
| 6045 | + ); | |
| 6046 | + } | |
| 6047 | + sql.exec( | |
| 6048 | + `CREATE TABLE IF NOT EXISTS ${__KV_TABLE} ( | |
| 6049 | + name TEXT PRIMARY KEY, | |
| 6050 | + value BLOB, | |
| 6051 | + blob_id TEXT, | |
| 6052 | + size INTEGER NOT NULL, | |
| 6053 | + tag TEXT NOT NULL, | |
| 6054 | + metadata TEXT, | |
| 6055 | + expires_at INTEGER | |
| 6056 | + ) WITHOUT ROWID`, | |
| 6057 | + ); | |
| 6058 | + // Inline KV shipped before `blob_id` and `size`. `CREATE IF NOT EXISTS` | |
| 6059 | + // does not change that table, so migrate each column independently. A | |
| 6060 | + // crash between the ALTER statements is safe because the next open reads | |
| 6061 | + // the surviving shape and resumes at the missing column. | |
| 6062 | + const columns = new Set( | |
| 6063 | + sql.exec(`PRAGMA table_info(${__KV_TABLE})`).toArray().map((row) => row.name), | |
| 6064 | + ); | |
| 6065 | + if (!columns.has("blob_id")) { | |
| 6066 | + sql.exec(`ALTER TABLE ${__KV_TABLE} ADD COLUMN blob_id TEXT`); | |
| 6067 | + } | |
| 6068 | + if (!columns.has("size")) { | |
| 6069 | + sql.exec( | |
| 6070 | + `ALTER TABLE ${__KV_TABLE} | |
| 6071 | + ADD COLUMN size INTEGER NOT NULL DEFAULT 0`, | |
| 6072 | + ); | |
| 6073 | + sql.exec(`UPDATE ${__KV_TABLE} SET size = LENGTH(value)`); | |
| 6074 | + } | |
| 6075 | + // `list` walks the primary key in order, so the only index worth carrying | |
| 6076 | + // is the sweeper's. Without it the sweep is a full scan of a namespace | |
| 6077 | + // whose whole point is being large. | |
| 6078 | + sql.exec( | |
| 6079 | + `CREATE INDEX IF NOT EXISTS ${__KV_TABLE}_expires | |
| 6080 | + ON ${__KV_TABLE} (expires_at) WHERE expires_at IS NOT NULL`, | |
| 6081 | + ); | |
| 6082 | + // The due bit is durable because the isolate that wrote a blob can die | |
| 6083 | + // before its row commit. In-memory state cannot schedule that orphan's | |
| 6084 | + // collector on the next owner. | |
| 6085 | + sql.exec( | |
| 6086 | + `CREATE TABLE IF NOT EXISTS ${__KV_META_TABLE} ( | |
| 6087 | + name TEXT PRIMARY KEY, | |
| 6088 | + value INTEGER NOT NULL | |
| 6089 | + ) WITHOUT ROWID`, | |
| 6090 | + ); | |
| 6091 | + this._ready = true; | |
| 6092 | + return sql; | |
| 6093 | + } | |
| 6094 | + | |
| 6095 | + // A key past its deadline is invisible from the instant it expires, not from | |
| 6096 | + // whenever the sweeper next runs. The read path filters and the sweep only | |
| 6097 | + // reclaims space, so the two can never disagree about which side of the | |
| 6098 | + // boundary a key is on. | |
| 6099 | + async __kvGet({ keys, withMetadata, withExpiration = false, now }) { | |
| 6100 | + const sql = this._open(); | |
| 6101 | + const out = []; | |
| 6102 | + for (const key of keys) { | |
| 6103 | + const row = sql.exec( | |
| 6104 | + `SELECT value, blob_id, tag, metadata, expires_at FROM ${__KV_TABLE} | |
| 6105 | + WHERE name = ? AND (expires_at IS NULL OR expires_at > ?)`, | |
| 6106 | + key, | |
| 6107 | + now, | |
| 6108 | + ).toArray()[0]; | |
| 6109 | + if (row === undefined) { | |
| 6110 | + out.push({ key, found: false }); | |
| 6111 | + continue; | |
| 6112 | + } | |
| 6113 | + let value = row.value; | |
| 6114 | + if (row.blob_id !== null && row.blob_id !== undefined) { | |
| 6115 | + const blob = await __kvBlob({ mode: "get", reference: row.blob_id }); | |
| 6116 | + // A row naming a blob the bucket does not hold is the failure the | |
| 6117 | + // commit order exists to prevent, so it is reported as itself rather | |
| 6118 | + // than as a missing key: an absent key and a broken one need different | |
| 6119 | + // answers from an operator. | |
| 6120 | + if (!blob.found) { | |
| 6121 | + throw __kvError( | |
| 6122 | + `the value for ${JSON.stringify(key)} is missing from the fleet ` + | |
| 6123 | + `bucket (blob ${row.blob_id})`, | |
| 6124 | + ); | |
| 6125 | + } | |
| 6126 | + value = new Uint8Array(blob.value); | |
| 6127 | + } | |
| 6128 | + const entry = { key, found: true, value, tag: row.tag }; | |
| 6129 | + if (withMetadata) entry.metadata = row.metadata ?? null; | |
| 6130 | + // These fields describe one row snapshot. The operator bulk export must | |
| 6131 | + // not combine a value from this read with an expiration from an earlier | |
| 6132 | + // listing when a concurrent put replaces the key between both calls. | |
| 6133 | + if (withExpiration) entry.expiration = row.expires_at ?? null; | |
| 6134 | + out.push(entry); | |
| 6135 | + } | |
| 6136 | + return out; | |
| 6137 | + } | |
| 6138 | + | |
| 6139 | + // One transaction for the whole batch, so a bulk put is all-or-nothing | |
| 6140 | + // rather than a prefix of itself. Upstream gives no such guarantee, and | |
| 6141 | + // giving a stronger one here costs nothing and cannot surprise a caller. | |
| 6142 | + // Blob first, row second. An orphan blob is bytes the collector reclaims; a | |
| 6143 | + // row naming a blob that was never written is a read that fails forever, and | |
| 6144 | + // no sweep repairs it. The opposite commit order can leave that dangling | |
| 6145 | + // row when a process stops between the two writes. | |
| 6146 | + // | |
| 6147 | + // The blob reference travels in `_pending` until the row commits, so a sweep that | |
| 6148 | + // runs mid-put does not collect bytes that are about to be referenced. That | |
| 6149 | + // costs the put and not the read -- the commit requires the blob, so a | |
| 6150 | + // collected blob means the commit cannot fire -- which is why the model's | |
| 6151 | + // tooth for it is an action property and not an invariant. | |
| 6152 | + async _store(value) { | |
| 6153 | + if (value.byteLength <= __kvLimits().maxInlineValueBytes) { | |
| 6154 | + return { value, blobId: null }; | |
| 6155 | + } | |
| 6156 | + const digest = await __kvDigest(value); | |
| 6157 | + await this._armBlobSweep(); | |
| 6158 | + // The host mints the reference from the epoch installed with this cell. | |
| 6159 | + // JavaScript never guesses that authority or recovers it after an await. | |
| 6160 | + const { reference } = await __kvBlob({ mode: "prepare", digest }); | |
| 6161 | + this._pending.add(reference); | |
| 6162 | + try { | |
| 6163 | + await __kvBlob({ mode: "put", reference }, value); | |
| 6164 | + // Force the collector race at its real seam. The alarm took its mark | |
| 6165 | + // snapshot before this put started and waits briefly after the put | |
| 6166 | + // announces itself. Without blob-protocol serialization, this write | |
| 6167 | + // lands during that wait and must stay here until the stale sweep runs. | |
| 6168 | + if ( | |
| 6169 | + __kvLimits().raceSweepPut && this._testSweepMarked && | |
| 6170 | + !this._testSweepFinished | |
| 6171 | + ) { | |
| 6172 | + await new Promise((resolve) => { | |
| 6173 | + this._testResumePut = resolve; | |
| 6174 | + }); | |
| 6175 | + } | |
| 6176 | + // The crash window the commit order exists for: the blob is in the | |
| 6177 | + // bucket and the row is not written yet. The failed operation no longer | |
| 6178 | + // protects the digest in memory, so the durable wake can reclaim it even | |
| 6179 | + // when this isolate remains resident. | |
| 6180 | + if (__kvLimits().failAfterBlobWrite) { | |
| 6181 | + throw __kvError("CELLD_TEST_KV_FAIL_AFTER_BLOB_WRITE"); | |
| 6182 | + } | |
| 6183 | + return { value: null, blobId: reference }; | |
| 6184 | + } catch (error) { | |
| 6185 | + this._pending.delete(reference); | |
| 6186 | + throw error; | |
| 6187 | + } | |
| 6188 | + } | |
| 6189 | + | |
| 6190 | + async __kvPut({ entries }) { | |
| 6191 | + if ( | |
| 6192 | + __kvLimits().raceSweepPut && | |
| 6193 | + entries.some((entry) => | |
| 6194 | + entry.value.byteLength > __kvLimits().maxInlineValueBytes | |
| 6195 | + ) | |
| 6196 | + ) { | |
| 6197 | + if (!this._testSweepMarked || this._testPutAttempted === undefined) { | |
| 6198 | + throw __kvError("the test blob sweep did not reach its mark snapshot"); | |
| 6199 | + } | |
| 6200 | + this._testPutAttempted(); | |
| 6201 | + this._testPutAttempted = undefined; | |
| 6202 | + } | |
| 6203 | + return this._withBlobProtocol(() => this._putLocked(entries)); | |
| 6204 | + } | |
| 6205 | + | |
| 6206 | + async _putLocked(entries) { | |
| 6207 | + const sql = this._open(); | |
| 6208 | + // An inline replacement can remove the final row reference to an old | |
| 6209 | + // blob, so arm before changing the row. A new large value also arms in | |
| 6210 | + // `_store`, before its own bucket write. | |
| 6211 | + const replacesBlob = entries.some((entry) => | |
| 6212 | + sql.exec( | |
| 6213 | + `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 6214 | + WHERE name = ? AND blob_id IS NOT NULL`, | |
| 6215 | + entry.key, | |
| 6216 | + ).toArray().length > 0 | |
| 6217 | + ); | |
| 6218 | + if (replacesBlob) await this._armBlobSweep(); | |
| 6219 | + const stored = []; | |
| 6220 | + try { | |
| 6221 | + for (const entry of entries) { | |
| 6222 | + stored.push({ entry, ...(await this._store(entry.value)) }); | |
| 6223 | + } | |
| 6224 | + this.ctx.storage.transactionSync(() => { | |
| 6225 | + for (const { entry, value, blobId } of stored) { | |
| 6226 | + sql.exec( | |
| 6227 | + `INSERT INTO ${__KV_TABLE} | |
| 6228 | + (name, value, blob_id, size, tag, metadata, expires_at) | |
| 6229 | + VALUES (?, ?, ?, ?, ?, ?, ?) | |
| 6230 | + ON CONFLICT(name) DO UPDATE SET | |
| 6231 | + value = excluded.value, | |
| 6232 | + blob_id = excluded.blob_id, | |
| 6233 | + size = excluded.size, | |
| 6234 | + tag = excluded.tag, | |
| 6235 | + metadata = excluded.metadata, | |
| 6236 | + expires_at = excluded.expires_at`, | |
| 6237 | + entry.key, | |
| 6238 | + value, | |
| 6239 | + blobId, | |
| 6240 | + entry.value.byteLength, | |
| 6241 | + entry.tag, | |
| 6242 | + entry.metadata ?? null, | |
| 6243 | + entry.expiresAt ?? null, | |
| 6244 | + ); | |
| 6245 | + } | |
| 6246 | + }); | |
| 6247 | + } finally { | |
| 6248 | + // A committed row protects the blob durably. A failed put protects | |
| 6249 | + // nothing, so it must not pin an orphan until this isolate is evicted. | |
| 6250 | + for (const { blobId } of stored) { | |
| 6251 | + if (blobId !== null) this._pending.delete(blobId); | |
| 6252 | + } | |
| 6253 | + } | |
| 6254 | + // Only when something in this batch can expire. A namespace of permanent | |
| 6255 | + // keys arms no alarm and wakes for nothing. | |
| 6256 | + if (entries.some((entry) => entry.expiresAt !== null && entry.expiresAt !== undefined)) { | |
| 6257 | + await this._rearm(); | |
| 6258 | + } | |
| 6259 | + } | |
| 6260 | + | |
| 6261 | + async __kvDelete({ keys }) { | |
| 6262 | + return this._withBlobProtocol(() => this._deleteLocked(keys)); | |
| 6263 | + } | |
| 6264 | + | |
| 6265 | + async _deleteLocked(keys) { | |
| 6266 | + const sql = this._open(); | |
| 6267 | + const removesBlob = keys.some((key) => | |
| 6268 | + sql.exec( | |
| 6269 | + `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 6270 | + WHERE name = ? AND blob_id IS NOT NULL`, | |
| 6271 | + key, | |
| 6272 | + ).toArray().length > 0 | |
| 6273 | + ); | |
| 6274 | + if (removesBlob) await this._armBlobSweep(); | |
| 6275 | + this.ctx.storage.transactionSync(() => { | |
| 6276 | + for (const key of keys) { | |
| 6277 | + sql.exec(`DELETE FROM ${__KV_TABLE} WHERE name = ?`, key); | |
| 6278 | + } | |
| 6279 | + }); | |
| 6280 | + } | |
| 6281 | + | |
| 6282 | + // Arm for the earliest deadline the table holds, or disarm when it holds | |
| 6283 | + // none. Asked from the row rather than held in memory, so the answer does | |
| 6284 | + // not depend on what this activation happens to remember -- an evicted cell | |
| 6285 | + // that wakes for an alarm re-derives the same deadline from the same rows. | |
| 6286 | + // | |
| 6287 | + // What carries the deadline across an eviction is the alarm itself, which is | |
| 6288 | + // durable cell state. This is *not* recomputed when a cell is merely opened, | |
| 6289 | + // so the one gap is a `_rearm` that throws after its put committed: the rows | |
| 6290 | + // are written, the caller sees an error, and nothing is armed until the next | |
| 6291 | + // put with a deadline. That costs space and never correctness, because the | |
| 6292 | + // read path filters an expired key whether or not it was reclaimed. | |
| 6293 | + async _rearm() { | |
| 6294 | + // A test that means to pin the read filter must be able to stop the sweep, | |
| 6295 | + // or it cannot tell which mechanism hid the key -- and a test that cannot | |
| 6296 | + // tell will pass when the filter is broken. This seam exists because that | |
| 6297 | + // is exactly what happened: the first version of the expiry test stayed | |
| 6298 | + // green with the filter removed. | |
| 6299 | + if (__kvLimits().sweepDisabled) return; | |
| 6300 | + const sql = this._open(); | |
| 6301 | + const row = sql.exec( | |
| 6302 | + `SELECT MIN(expires_at) AS next FROM ${__KV_TABLE} WHERE expires_at IS NOT NULL`, | |
| 6303 | + ).toArray()[0]; | |
| 6304 | + const next = row === undefined ? null : row.next; | |
| 6305 | + const blobDue = this._blobSweepDue(); | |
| 6306 | + if ((next === null || next === undefined) && !blobDue) { | |
| 6307 | + await this.ctx.storage.deleteAlarm(); | |
| 6308 | + return; | |
| 6309 | + } | |
| 6310 | + const now = Date.now(); | |
| 6311 | + const deadlines = []; | |
| 6312 | + // Never in the past: a deadline already due is swept on this wake, and | |
| 6313 | + // arming behind `now` would spin. | |
| 6314 | + if (next !== null && next !== undefined) { | |
| 6315 | + deadlines.push(Math.max(next, now + 1)); | |
| 6316 | + } | |
| 6317 | + if (blobDue) deadlines.push(now + __kvLimits().blobSweepMs); | |
| 6318 | + const deadline = Math.min(...deadlines); | |
| 6319 | + const armed = await this.ctx.storage.getAlarm(); | |
| 6320 | + if (armed === null || armed <= now || armed > deadline) { | |
| 6321 | + await this.ctx.storage.setAlarm(deadline); | |
| 6322 | + } | |
| 6323 | + } | |
| 6324 | + | |
| 6325 | + // Reclaiming space, never deciding visibility. A key is invisible from the | |
| 6326 | + // instant it expires because the read path filters, so a late sweep costs | |
| 6327 | + // storage and never correctness -- which is what lets this be bounded and | |
| 6328 | + // re-armed rather than obliged to finish. | |
| 6329 | + // Every reference a row names, plus every reference a put has written and | |
| 6330 | + // not yet committed. The two go in one list because the bucket end cannot | |
| 6331 | + // tell them apart and does not need to: it only needs "do not delete these". | |
| 6332 | + _liveBlobs() { | |
| 6333 | + const rows = this._open().exec( | |
| 6334 | + `SELECT blob_id FROM ${__KV_TABLE} WHERE blob_id IS NOT NULL`, | |
| 6335 | + ).toArray(); | |
| 6336 | + return [...new Set([...rows.map((row) => row.blob_id), ...this._pending])]; | |
| 6337 | + } | |
| 6338 | + | |
| 6339 | + async alarm() { | |
| 6340 | + const removed = await this._withBlobProtocol(async () => { | |
| 6341 | + const now = Date.now(); | |
| 6342 | + // If expiry will remove a blob reference, persist the due bit and a | |
| 6343 | + // future wake before deleting the row. A crash later in this alarm then | |
| 6344 | + // leaves the next owner enough durable state to finish collection. | |
| 6345 | + const expiresBlob = this._open().exec( | |
| 6346 | + `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 6347 | + WHERE expires_at IS NOT NULL AND expires_at <= ? | |
| 6348 | + AND blob_id IS NOT NULL | |
| 6349 | + LIMIT ?`, | |
| 6350 | + now, | |
| 6351 | + __kvLimits().sweepBatchRows, | |
| 6352 | + ).toArray().length > 0; | |
| 6353 | + if (expiresBlob) await this._armBlobSweep(); | |
| 6354 | + | |
| 6355 | + const { removed } = this.__kvSweep({ | |
| 6356 | + now, | |
| 6357 | + limit: __kvLimits().sweepBatchRows, | |
| 6358 | + }); | |
| 6359 | + // The blob sweep runs after the row sweep, on the same wake, so a row | |
| 6360 | + // reclaimed above has already dropped its reference by the time the live | |
| 6361 | + // set is read. A durable due bit distinguishes a GC wake from an inline | |
| 6362 | + // expiry wake and survives isolate eviction or a failed bucket request. | |
| 6363 | + if (this._blobSweepDue() || __kvLimits().raceSweepPut) { | |
| 6364 | + const live = this._liveBlobs(); | |
| 6365 | + if (__kvLimits().raceSweepPut && !this._testSweepFinished) { | |
| 6366 | + const putAttempted = new Promise((resolve) => { | |
| 6367 | + this._testPutAttempted = resolve; | |
| 6368 | + }); | |
| 6369 | + this._testSweepMarked = true; | |
| 6370 | + await putAttempted; | |
| 6371 | + // The fixture bucket is local. This bounded pause lets an | |
| 6372 | + // unprotected put finish its blob write; a protected put is waiting | |
| 6373 | + // for this protocol lock and therefore cannot enter the window. | |
| 6374 | + await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 6375 | + } | |
| 6376 | + let swept = false; | |
| 6377 | + try { | |
| 6378 | + await __kvBlob({ mode: "sweep", live }); | |
| 6379 | + swept = true; | |
| 6380 | + } catch (error) { | |
| 6381 | + // Reclaiming space is not deciding visibility, so a bucket that | |
| 6382 | + // refuses a delete costs storage and never correctness. The next | |
| 6383 | + // wake tries again. | |
| 6384 | + console.error("kv blob sweep failed:", error); | |
| 6385 | + } finally { | |
| 6386 | + if (__kvLimits().raceSweepPut) { | |
| 6387 | + this._testSweepFinished = true; | |
| 6388 | + this._testResumePut?.(); | |
| 6389 | + this._testResumePut = undefined; | |
| 6390 | + } | |
| 6391 | + } | |
| 6392 | + if (swept) this._clearBlobSweepDue(); | |
| 6393 | + } | |
| 6394 | + return removed; | |
| 6395 | + }); | |
| 6396 | + // A full batch means there is more to reclaim, so come back promptly | |
| 6397 | + // rather than waiting for the next natural deadline. | |
| 6398 | + if (removed >= __kvLimits().sweepBatchRows) { | |
| 6399 | + await this.ctx.storage.setAlarm(Date.now() + 1); | |
| 6400 | + return; | |
| 6401 | + } | |
| 6402 | + await this._rearm(); | |
| 6403 | + } | |
| 6404 | + | |
| 6405 | + // Pagination resumes at `name > after`, never at an offset. A caller holds | |
| 6406 | + // no transaction across pages, so an offset would skip or repeat keys the | |
| 6407 | + // moment a concurrent writer inserted or deleted inside the prefix. | |
| 6408 | + // | |
| 6409 | + // One row beyond the limit is read to decide `list_complete`, and discarded. | |
| 6410 | + // Asking the database is the only honest answer: a page that happens to fill | |
| 6411 | + // exactly is indistinguishable from a page that ended. | |
| 6412 | + __kvList({ prefix, limit, after, now }) { | |
| 6413 | + const sql = this._open(); | |
| 6414 | + // Every name a prefix can match is one contiguous run of the primary key, | |
| 6415 | + // so bound the key on both sides. The query used to carry the cursor as | |
| 6416 | + // its only range, and SQLite then walked every earlier row in the | |
| 6417 | + // namespace before it could report that a late prefix matches nothing: an | |
| 6418 | + // empty-result list measured 684/s over 4,849 rows and 43/s over 114,881. | |
| 6419 | + // | |
| 6420 | + // The bounds decide which rows a list visits and the prefix comparison | |
| 6421 | + // still decides which rows match. A prefix whose bounds cannot be derived | |
| 6422 | + // -- one holding a lone surrogate, which no stored name can hold -- is | |
| 6423 | + // therefore answered at the old cost rather than short of keys. | |
| 6424 | + const upper = __kvPrefixUpperBound(prefix); | |
| 6425 | + // A cursor names a key this namespace already returned for this prefix, so | |
| 6426 | + // it is inside the range and replaces the prefix as the start. Carrying | |
| 6427 | + // both would leave SQLite to pick one as the seek and demote the other to | |
| 6428 | + // a filter, and picking the prefix rescans every earlier page. A cursor | |
| 6429 | + // arrives from the caller, so a hand-made one can start below the prefix; | |
| 6430 | + // the comparison below, and not the range, keeps that page correct. | |
| 6431 | + const start = after ? "name > ?" : "name >= ?"; | |
| 6432 | + const params = [after ? after : prefix]; | |
| 6433 | + if (upper !== null) params.push(upper); | |
| 6434 | + // `substr` compares under BINARY, so a prefix matches by bytes and not by | |
| 6435 | + // ASCII case. `LIKE` stood here and folded case, which made `list({prefix: | |
| 6436 | + // "A"})` answer a key named `a` -- upstream compares a byte prefix, and no | |
| 6437 | + // range bound can reproduce a case-folded match anyway. The length counts | |
| 6438 | + // code points, which is what SQLite counts, not UTF-16 units. | |
| 6439 | + if (prefix !== "") params.push(Array.from(prefix).length, prefix); | |
| 6440 | + const query = `SELECT name, metadata, expires_at FROM ${__KV_TABLE} | |
| 6441 | + WHERE ${start} | |
| 6442 | + ${upper === null ? "" : "AND name < ?"} | |
| 6443 | + ${prefix === "" ? "" : "AND substr(name, 1, ?) = ?"} | |
| 6444 | + AND (expires_at IS NULL OR expires_at > ?) | |
| 6445 | + ORDER BY name | |
| 6446 | + LIMIT ?`; | |
| 6447 | + params.push(now, limit + 1); | |
| 6448 | + __kvReportListPlan(sql, query, params); | |
| 6449 | + const rows = sql.exec(query, ...params).toArray(); | |
| 6450 | + const complete = rows.length <= limit; | |
| 6451 | + const page = complete ? rows : rows.slice(0, limit); | |
| 6452 | + return { | |
| 6453 | + keys: page.map((row) => ({ | |
| 6454 | + name: row.name, | |
| 6455 | + metadata: row.metadata ?? null, | |
| 6456 | + expiration: row.expires_at ?? null, | |
| 6457 | + })), | |
| 6458 | + complete, | |
| 6459 | + }; | |
| 6460 | + } | |
| 6461 | + | |
| 6462 | + // The operator's live key and byte counts. `size` stays in the row because | |
| 6463 | + // a bucket-backed value has a NULL inline `value`; `LENGTH(value)` would | |
| 6464 | + // report zero bytes for exactly the values whose size matters most. | |
| 6465 | + __kvMetrics({ now }) { | |
| 6466 | + const sql = this._open(); | |
| 6467 | + const row = sql.exec( | |
| 6468 | + `SELECT COUNT(*) AS count, | |
| 6469 | + COALESCE(SUM(size), 0) AS bytes | |
| 6470 | + FROM ${__KV_TABLE} | |
| 6471 | + WHERE expires_at IS NULL OR expires_at > ?`, | |
| 6472 | + now, | |
| 6473 | + ).toArray()[0]; | |
| 6474 | + return { count: row.count, bytes: row.bytes }; | |
| 6475 | + } | |
| 6476 | + | |
| 6477 | + // Reclaim what the read path already treats as gone. Bounded per call so a | |
| 6478 | + // namespace with a large expired population cannot hold the cell for an | |
| 6479 | + // unbounded time; the caller re-arms while there is more. | |
| 6480 | + __kvSweep({ now, limit }) { | |
| 6481 | + const sql = this._open(); | |
| 6482 | + const removed = __cellSweepBatch( | |
| 6483 | + this.ctx.storage, | |
| 6484 | + (bound) => sql.exec( | |
| 6485 | + `SELECT name FROM ${__KV_TABLE} | |
| 6486 | + WHERE expires_at IS NOT NULL AND expires_at <= ? | |
| 6487 | + ORDER BY expires_at | |
| 6488 | + LIMIT ?`, | |
| 6489 | + now, | |
| 6490 | + bound, | |
| 6491 | + ).toArray(), | |
| 6492 | + (row) => { | |
| 6493 | + sql.exec(`DELETE FROM ${__KV_TABLE} WHERE name = ?`, row.name); | |
| 6494 | + }, | |
| 6495 | + limit, | |
| 6496 | + ); | |
| 6497 | + return { removed }; | |
| 6498 | + } | |
| 6499 | + | |
| 6500 | + // The operator surface, reached only over `/runtime/`, which authenticates | |
| 6501 | + // with the fleet secret. `/do/` refuses every reserved class structurally, | |
| 6502 | + // so adding this handler does not put a namespace on an unauthenticated | |
| 6503 | + // route -- the trap d1.md decision 4 records paying for once, and the reason | |
| 6504 | + // that refusal is one question rather than one per class. | |
| 6505 | + // | |
| 6506 | + // Values cross this boundary as arrays of bytes rather than as text, because | |
| 6507 | + // a namespace holds bytes: a value written from a Worker as an ArrayBuffer | |
| 6508 | + // has no faithful string form, and `celld kv` must be able to read back | |
| 6509 | + // exactly what was written. | |
| 6510 | + async fetch(request) { | |
| 6511 | + let body; | |
| 6512 | + try { | |
| 6513 | + body = await request.json(); | |
| 6514 | + } catch { | |
| 6515 | + return Response.json({ error: "KV_ERROR: invalid request body" }, { status: 400 }); | |
| 6516 | + } | |
| 6517 | + const now = Date.now(); | |
| 6518 | + try { | |
| 6519 | + let result; | |
| 6520 | + switch (body.op) { | |
| 6521 | + case "get": { | |
| 6522 | + // Awaited: `__kvGet` resolves a bucket-backed value, so it is | |
| 6523 | + // async. Destructuring the promise instead threw "object is not | |
| 6524 | + // iterable" on every operator read, and only here -- the binding | |
| 6525 | + // reaches the same method over RPC, which awaits for it. | |
| 6526 | + const [row] = await this.__kvGet({ | |
| 6527 | + keys: [String(body.key)], | |
| 6528 | + withMetadata: true, | |
| 6529 | + withExpiration: true, | |
| 6530 | + now, | |
| 6531 | + }); | |
| 6532 | + result = row.found | |
| 6533 | + ? { | |
| 6534 | + found: true, | |
| 6535 | + ...__kvOperatorValue(row.value), | |
| 6536 | + tag: row.tag, | |
| 6537 | + metadata: row.metadata ?? null, | |
| 6538 | + expiration: row.expiration, | |
| 6539 | + } | |
| 6540 | + : { found: false }; | |
| 6541 | + break; | |
| 6542 | + } | |
| 6543 | + case "put": | |
| 6544 | + case "put-base64": { | |
| 6545 | + // Validated here, through the same helpers the binding calls, so a | |
| 6546 | + // key written by `celld kv` is a key the binding could have written. | |
| 6547 | + // The operator route used to arrive pre-validated by the CLI, which | |
| 6548 | + // put the same bound in two processes -- and they disagreed the first | |
| 6549 | + // time a test shortened one of them. | |
| 6550 | + const key = String(body.key); | |
| 6551 | + __kvCheckKey(key); | |
| 6552 | + const value = body.op === "put-base64" | |
| 6553 | + ? $$atob(String(body.value), true) | |
| 6554 | + : new Uint8Array(body.value); | |
| 6555 | + __kvCheckValue(value.byteLength); | |
| 6556 | + const metadata = body.metadata === undefined ? null : body.metadata; | |
| 6557 | + if (metadata !== null) __kvCheckMetadata(metadata); | |
| 6558 | + // Resolved from the cell's clock, not the caller's, because that is | |
| 6559 | + // the clock the read filter and the sweeper compare against. | |
| 6560 | + const expiresAt = __kvExpiryAt(now, body.expiration, body.expirationTtl); | |
| 6561 | + await this.__kvPut({ | |
| 6562 | + entries: [{ | |
| 6563 | + key, | |
| 6564 | + value, | |
| 6565 | + tag: String(body.tag ?? __KV_TAG_BYTES), | |
| 6566 | + metadata, | |
| 6567 | + expiresAt, | |
| 6568 | + }], | |
| 6569 | + }); | |
| 6570 | + result = { ok: true }; | |
| 6571 | + break; | |
| 6572 | + } | |
| 6573 | + case "delete": | |
| 6574 | + for (const key of body.keys) __kvCheckKey(String(key)); | |
| 6575 | + await this.__kvDelete({ keys: body.keys.map(String) }); | |
| 6576 | + result = { ok: true }; | |
| 6577 | + break; | |
| 6578 | + case "list": | |
| 6579 | + result = this.__kvList({ | |
| 6580 | + prefix: String(body.prefix ?? ""), | |
| 6581 | + limit: Number(body.limit), | |
| 6582 | + after: String(body.after ?? ""), | |
| 6583 | + now, | |
| 6584 | + }); | |
| 6585 | + break; | |
| 6586 | + // What `celld kv info` reports. `stored` counts every row and `live` | |
| 6587 | + // counts only what a read would return, so the difference is exactly | |
| 6588 | + // the population the sweeper still owes -- which is the one number | |
| 6589 | + // that makes reclamation observable from outside the cell. | |
| 6590 | + case "info": { | |
| 6591 | + const live = this.__kvMetrics({ now }); | |
| 6592 | + const total = this._open().exec( | |
| 6593 | + `SELECT COUNT(*) AS count FROM ${__KV_TABLE}`, | |
| 6594 | + ).toArray()[0]; | |
| 6595 | + result = { live: live.count, bytes: live.bytes, stored: total.count }; | |
| 6596 | + break; | |
| 6597 | + } | |
| 6598 | + default: | |
| 6599 | + return Response.json( | |
| 6600 | + { error: `KV_ERROR: unknown operation ${JSON.stringify(body.op)}` }, | |
| 6601 | + { status: 400 }, | |
| 6602 | + ); | |
| 6603 | + } | |
| 6604 | + return Response.json({ result }); | |
| 6605 | + } catch (error) { | |
| 6606 | + return Response.json( | |
| 6607 | + { error: String(error && error.message || error) }, | |
| 6608 | + { status: 400 }, | |
| 6609 | + ); | |
| 6610 | + } | |
| 6611 | + } | |
| 6612 | +} | |
| 6613 | + | |
| 6614 | +__cell.classes.__KvNamespace = __KvNamespaceCell; | |
| 6615 | +// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class is | |
| 6616 | +// the runtime's own, so grant it here rather than making every KV user set a | |
| 6617 | +// compatibility flag to reach a namespace. | |
| 6618 | +__cell.doExports.__KvNamespace = true; | |
| 6619 | + | |
| 6620 | +// The client half. | |
| 6621 | +// | |
| 6622 | +// Every number below is injected from `celld_logic::kv` as `__cell.kvLimits` | |
| 6623 | +// rather than written here, so the binding, `celld kv` and deploy-time | |
| 6624 | +// validation cannot disagree about what a valid key is. No new host op: D1 set | |
| 6625 | +// the bar at one and Workflows came in under it, and a limit is data rather | |
| 6626 | +// than a decision, so shipping the values is enough. What stays in JS is the | |
| 6627 | +// presentation -- the error text is the binding's published contract, in | |
| 6628 | +// upstream's `KV <OP> failed:` shape, and belongs beside the calls that raise | |
| 6629 | +// it. | |
| 6630 | +// | |
| 6631 | +// The cursor codec is the one thing that must byte-match Rust's, and it is | |
| 6632 | +// plain hex: a total function with a single right answer, which two correct | |
| 6633 | +// implementations cannot disagree about. A policy would be a different matter | |
| 6634 | +// and none is duplicated here. | |
| 6635 | +const __kvLimits = () => __cell.kvLimits; | |
| 6636 | + | |
| 6637 | +const __kvCheckKey = (key) => { | |
| 6638 | + if (key.length === 0) throw __kvError("a key must not be empty"); | |
| 6639 | + const bytes = __kvEncoder.encode(key).byteLength; | |
| 6640 | + if (bytes > __kvLimits().maxKeyBytes) { | |
| 6641 | + throw __kvError( | |
| 6642 | + `a key is at most ${__kvLimits().maxKeyBytes} bytes, got ${bytes}`, | |
| 6643 | + ); | |
| 6644 | + } | |
| 6645 | +}; | |
| 6646 | + | |
| 6647 | +// A TTL becomes an absolute deadline here, once, at the call. Resolving it | |
| 6648 | +// again later against a newer clock would extend the life of the key every | |
| 6649 | +// time anything re-read the row -- the reason a workflow persists a sleep | |
| 6650 | +// deadline and not its duration. | |
| 6651 | +const __kvCheckValue = (size) => { | |
| 6652 | + // Upstream's bound, and now the only one. A value above the inline bound is | |
| 6653 | + // no longer refused: it goes to the fleet bucket, which is the split | |
| 6654 | + // Cloudflare's own KV rearchitecture made and for the same reason -- a cell | |
| 6655 | + // replicates every write as LTX, so an inline value is paid for twice. | |
| 6656 | + if (size > __kvLimits().maxValueBytes) { | |
| 6657 | + throw __kvError(`a value is at most ${__kvLimits().maxValueBytes} bytes, got ${size}`); | |
| 6658 | + } | |
| 6659 | +}; | |
| 6660 | + | |
| 6661 | +const __kvCheckMetadata = (metadata) => { | |
| 6662 | + const bytes = __kvEncoder.encode(metadata).byteLength; | |
| 6663 | + if (bytes > __kvLimits().maxMetadataBytes) { | |
| 6664 | + throw __kvError( | |
| 6665 | + `metadata is at most ${__kvLimits().maxMetadataBytes} bytes, got ${bytes}`, | |
| 6666 | + ); | |
| 6667 | + } | |
| 6668 | +}; | |
| 6669 | + | |
| 6670 | +const __kvExpiryAt = (now, expiration, expirationTtl) => { | |
| 6671 | + if (expirationTtl !== undefined && expirationTtl !== null) { | |
| 6672 | + const ms = Math.floor(Number(expirationTtl) * 1000); | |
| 6673 | + if (!Number.isFinite(ms) || ms < __kvLimits().minExpirationTtlMs) { | |
| 6674 | + throw __kvError( | |
| 6675 | + `expirationTtl is at least ${__kvLimits().minExpirationTtlMs / 1000} seconds`, | |
| 6676 | + ); | |
| 6677 | + } | |
| 6678 | + return now + ms; | |
| 6679 | + } | |
| 6680 | + if (expiration !== undefined && expiration !== null) { | |
| 6681 | + const at = Math.floor(Number(expiration) * 1000); | |
| 6682 | + if (!Number.isFinite(at) || at <= now) { | |
| 6683 | + throw __kvError(`expiration ${expiration} is in the past`); | |
| 6684 | + } | |
| 6685 | + return at; | |
| 6686 | + } | |
| 6687 | + return null; | |
| 6688 | +}; | |
| 6689 | + | |
| 6690 | +const __kvCursor = { | |
| 6691 | + encode(key) { | |
| 6692 | + let out = ""; | |
| 6693 | + for (const byte of __kvEncoder.encode(key)) { | |
| 6694 | + out += byte.toString(16).padStart(2, "0"); | |
| 6695 | + } | |
| 6696 | + return out; | |
| 6697 | + }, | |
| 6698 | + decode(cursor) { | |
| 6699 | + // A malformed cursor is refused, never read as "start from the | |
| 6700 | + // beginning": that would hand a paginating caller its first page a second | |
| 6701 | + // time and call it progress. | |
| 6702 | + if (cursor.length % 2 !== 0 || /[^0-9a-f]/.test(cursor)) { | |
| 6703 | + throw __kvError("the list cursor is malformed"); | |
| 6704 | + } | |
| 6705 | + const bytes = new Uint8Array(cursor.length / 2); | |
| 6706 | + for (let at = 0; at < bytes.length; at += 1) { | |
| 6707 | + bytes[at] = Number.parseInt(cursor.slice(at * 2, at * 2 + 2), 16); | |
| 6708 | + } | |
| 6709 | + return __kvDecoder.decode(bytes); | |
| 6710 | + }, | |
| 6711 | +}; | |
| 6712 | + | |
| 6713 | +const __kvListLimit = (requested) => { | |
| 6714 | + const max = __kvLimits().maxListLimit; | |
| 6715 | + if (requested === undefined || requested === null) return max; | |
| 6716 | + const limit = Math.floor(Number(requested)); | |
| 6717 | + // Zero would be a page that never ends. | |
| 6718 | + if (!Number.isFinite(limit) || limit <= 0) return max; | |
| 6719 | + return Math.min(limit, max); | |
| 6720 | +}; | |
| 6721 | + | |
| 6722 | +// Upstream's four content types, and what each one means on the way in and out. | |
| 6723 | +const __KV_TAG_TEXT = "text"; | |
| 6724 | +const __KV_TAG_BYTES = "bytes"; | |
| 6725 | + | |
| 6726 | +const __kvEncoder = new TextEncoder(); | |
| 6727 | +const __kvDecoder = new TextDecoder(); | |
| 6728 | + | |
| 6729 | +// A value becomes bytes plus a tag, once, at the public boundary. Storing the | |
| 6730 | +// tag is what lets `get(key, "text")` and `get(key)` answer differently from | |
| 6731 | +// the same row without the cell parsing anything. | |
| 6732 | +const __kvEncodeValue = (value) => { | |
| 6733 | + if (typeof value === "string") { | |
| 6734 | + return { value: __kvEncoder.encode(value), tag: __KV_TAG_TEXT }; | |
| 6735 | + } | |
| 6736 | + if (value instanceof ArrayBuffer) { | |
| 6737 | + return { value: new Uint8Array(value.slice(0)), tag: __KV_TAG_BYTES }; | |
| 6738 | + } | |
| 6739 | + if (ArrayBuffer.isView(value)) { | |
| 6740 | + // Copied, not referenced. `sendBatch`'s resizable-ArrayBuffer regression | |
| 6741 | + // upstream is the same hazard: a caller may resize or reuse the buffer | |
| 6742 | + // between this call and the write, and a shallow view would then read | |
| 6743 | + // decommitted pages. | |
| 6744 | + return { | |
| 6745 | + value: new Uint8Array( | |
| 6746 | + value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), | |
| 6747 | + ), | |
| 6748 | + tag: __KV_TAG_BYTES, | |
| 6749 | + }; | |
| 6750 | + } | |
| 6751 | + throw __kvError( | |
| 6752 | + "a KV value must be a string, an ArrayBuffer, or a typed array", | |
| 6753 | + ); | |
| 6754 | +}; | |
| 6755 | + | |
| 6756 | +const __kvDecodeValue = (bytes, tag, type) => { | |
| 6757 | + const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); | |
| 6758 | + switch (type) { | |
| 6759 | + case "arrayBuffer": | |
| 6760 | + return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength); | |
| 6761 | + case "json": | |
| 6762 | + return JSON.parse(__kvDecoder.decode(view)); | |
| 6763 | + case "stream": | |
| 6764 | + return new Response(view).body; | |
| 6765 | + case "text": | |
| 6766 | + default: | |
| 6767 | + // A value written as bytes still decodes as text when asked for text, | |
| 6768 | + // which is upstream's behaviour and the reason the tag is advisory | |
| 6769 | + // rather than a type check. | |
| 6770 | + return __kvDecoder.decode(view); | |
| 6771 | + } | |
| 6772 | +}; | |
| 6773 | + | |
| 6774 | +const __kvReadOptions = (options) => { | |
| 6775 | + if (typeof options === "string") return { type: options }; | |
| 6776 | + if (options === null || options === undefined) return { type: "text" }; | |
| 6777 | + return { type: options.type ?? "text", cacheTtl: options.cacheTtl }; | |
| 6778 | +}; | |
| 6779 | + | |
| 6780 | +class KvNamespace { | |
| 6781 | + constructor(id, cellName) { | |
| 6782 | + Object.defineProperty(this, "_id", { value: id }); | |
| 6783 | + Object.defineProperty(this, "_cellName", { value: cellName }); | |
| 6784 | + } | |
| 6785 | + | |
| 6786 | + // Resolved per call rather than cached: a cell can move between calls, and | |
| 6787 | + // `getByName` costs what the Durable Object path already pays. | |
| 6788 | + get _stub() { | |
| 6789 | + return __cell.makeNamespace("__KvNamespace").getByName(this._cellName); | |
| 6790 | + } | |
| 6791 | + | |
| 6792 | + async _read(keys, options, withMetadata) { | |
| 6793 | + const { type } = __kvReadOptions(options); | |
| 6794 | + for (const key of keys) __kvCheckKey(key); | |
| 6795 | + const rows = await this._stub.__kvGet({ | |
| 6796 | + keys, | |
| 6797 | + withMetadata, | |
| 6798 | + now: Date.now(), | |
| 6799 | + }); | |
| 6800 | + return rows.map((row) => { | |
| 6801 | + if (!row.found) return { key: row.key, value: null, metadata: null }; | |
| 6802 | + return { | |
| 6803 | + key: row.key, | |
| 6804 | + value: __kvDecodeValue(row.value, row.tag, type), | |
| 6805 | + metadata: row.metadata === null || row.metadata === undefined | |
| 6806 | + ? null | |
| 6807 | + : JSON.parse(row.metadata), | |
| 6808 | + }; | |
| 6809 | + }); | |
| 6810 | + } | |
| 6811 | + | |
| 6812 | + // `get(key)` answers a value; `get([keys])` answers a Map with a null hole | |
| 6813 | + // for a key that is not there. Upstream's bulk form is a Map and not an | |
| 6814 | + // object, which matters: an object would collide a key named `__proto__` | |
| 6815 | + // with the prototype chain. | |
| 6816 | + async get(key, options) { | |
| 6817 | + if (Array.isArray(key)) { | |
| 6818 | + const rows = await this._read(__kvBulkKeys(key), options, false); | |
| 6819 | + return new Map(rows.map((row) => [row.key, row.value])); | |
| 6820 | + } | |
| 6821 | + const [row] = await this._read([String(key)], options, false); | |
| 6822 | + return row.value; | |
| 6823 | + } | |
| 6824 | + | |
| 6825 | + async getWithMetadata(key, options) { | |
| 6826 | + if (Array.isArray(key)) { | |
| 6827 | + const rows = await this._read(__kvBulkKeys(key), options, true); | |
| 6828 | + return new Map( | |
| 6829 | + rows.map((row) => [row.key, { value: row.value, metadata: row.metadata }]), | |
| 6830 | + ); | |
| 6831 | + } | |
| 6832 | + const [row] = await this._read([String(key)], options, true); | |
| 6833 | + return { | |
| 6834 | + value: row.value, | |
| 6835 | + metadata: row.metadata, | |
| 6836 | + // Null, and honestly so: celld has no read cache, and reporting a HIT | |
| 6837 | + // from a runtime that never cached anything would be a lie in a field | |
| 6838 | + // applications read. | |
| 6839 | + cacheStatus: null, | |
| 6840 | + }; | |
| 6841 | + } | |
| 6842 | + | |
| 6843 | + async put(key, value, options) { | |
| 6844 | + const name = String(key); | |
| 6845 | + __kvCheckKey(name); | |
| 6846 | + const encoded = __kvEncodeValue(value); | |
| 6847 | + __kvCheckValue(encoded.value.byteLength); | |
| 6848 | + const metadata = options && options.metadata !== undefined | |
| 6849 | + ? JSON.stringify(options.metadata) | |
| 6850 | + : null; | |
| 6851 | + if (metadata !== null) __kvCheckMetadata(metadata); | |
| 6852 | + const expiresAt = __kvExpiryAt( | |
| 6853 | + Date.now(), | |
| 6854 | + options && options.expiration, | |
| 6855 | + options && options.expirationTtl, | |
| 6856 | + ); | |
| 6857 | + await this._stub.__kvPut({ | |
| 6858 | + entries: [{ key: name, value: encoded.value, tag: encoded.tag, metadata, expiresAt }], | |
| 6859 | + }); | |
| 6860 | + } | |
| 6861 | + | |
| 6862 | + async delete(key) { | |
| 6863 | + const name = String(key); | |
| 6864 | + __kvCheckKey(name); | |
| 6865 | + await this._stub.__kvDelete({ keys: [name] }); | |
| 6866 | + } | |
| 6867 | + | |
| 6868 | + // Upstream takes one key or an array, and caps the array at the same 100 a | |
| 6869 | + // bulk get takes. | |
| 6870 | + async deleteBulk(keys) { | |
| 6871 | + const names = Array.isArray(keys) ? __kvBulkKeys(keys) : [String(keys)]; | |
| 6872 | + for (const name of names) __kvCheckKey(name); | |
| 6873 | + await this._stub.__kvDelete({ keys: names }); | |
| 6874 | + } | |
| 6875 | + | |
| 6876 | + async list(options) { | |
| 6877 | + const prefix = options && options.prefix ? String(options.prefix) : ""; | |
| 6878 | + const limit = __kvListLimit(options && options.limit); | |
| 6879 | + const after = options && options.cursor ? __kvCursor.decode(String(options.cursor)) : ""; | |
| 6880 | + const page = await this._stub.__kvList({ prefix, limit, after, now: Date.now() }); | |
| 6881 | + const keys = page.keys.map((entry) => { | |
| 6882 | + const key = { name: entry.name }; | |
| 6883 | + if (entry.metadata !== null) key.metadata = JSON.parse(entry.metadata); | |
| 6884 | + // Upstream reports an expiration in seconds. | |
| 6885 | + if (entry.expiration !== null) key.expiration = Math.floor(entry.expiration / 1000); | |
| 6886 | + return key; | |
| 6887 | + }); | |
| 6888 | + if (page.complete) return { keys, list_complete: true, cacheStatus: null }; | |
| 6889 | + return { | |
| 6890 | + keys, | |
| 6891 | + list_complete: false, | |
| 6892 | + cursor: __kvCursor.encode(keys[keys.length - 1].name), | |
| 6893 | + cacheStatus: null, | |
| 6894 | + }; | |
| 6895 | + } | |
| 6896 | +} | |
| 6897 | + | |
| 6898 | +// The bulk ceiling belongs to the binding, and a CLI chunks beneath it rather | |
| 6899 | +// than inheriting it. An empty array is refused because upstream refuses it: | |
| 6900 | +// answering an empty Map would look like "none of these keys exist". | |
| 6901 | +const __kvBulkKeys = (keys) => { | |
| 6902 | + if (keys.length === 0) throw __kvError("a bulk get needs at least one key"); | |
| 6903 | + if (keys.length > __kvLimits().maxBulkKeys) { | |
| 6904 | + throw __kvError( | |
| 6905 | + `a bulk get takes at most ${__kvLimits().maxBulkKeys} keys, got ${keys.length}`, | |
| 6906 | + ); | |
| 6907 | + } | |
| 6908 | + return keys.map(String); | |
| 6909 | +}; | |
| 6910 | + | |
| 6911 | +const __makeKvNamespace = __celld.__makeKvNamespace = | |
| 6912 | + (id, cellName) => new KvNamespace(id, cellName); | |
| 6913 | + | |
| 6914 | +// ---- Queues -------------------------------------------------------------- | |
| 6915 | +// A Queue is one runtime-supplied Durable Object. The producer binding writes | |
| 6916 | +// bytes and a content tag through RPC, and the cell owns the durable order, | |
| 6917 | +// deadlines, leases, and alarms. `celld_logic::queue` owns every transition | |
| 6918 | +// that can invalidate a lease or choose a deadline; this code supplies SQL and | |
| 6919 | +// the Cloudflare-compatible presentation. | |
| 6920 | + | |
| 6921 | +const __QUEUE_MESSAGES = "__queue_messages"; | |
| 6922 | +const __QUEUE_META = "__queue_meta"; | |
| 6923 | +const __QUEUE_STATS = "__queue_stats"; | |
| 6924 | +const __QUEUE_TRANSFER_RECEIPTS = "__queue_transfer_receipts"; | |
| 6925 | +const __queueEncoder = new TextEncoder(); | |
| 6926 | + | |
| 6927 | +// Independent send() calls share the same economics as sendBatch() without | |
| 6928 | +// changing the public promise boundary. The first call opens a four-millisecond | |
| 6929 | +// owner-local group by default; later cell events append their already-copied | |
| 6930 | +// entries, and park on their own promise. One event commits the bounded group, | |
| 6931 | +// and every response still trails that commit through the ordinary output | |
| 6932 | +// gate. The three caps bound heap retention and keep the persisted transaction | |
| 6933 | +// inside the public sendBatch limits. | |
| 6934 | +const __QUEUE_PRODUCER_GROUP_CALLS = 64; | |
| 6935 | +const __QUEUE_PRODUCER_GROUP_MESSAGES = 100; | |
| 6936 | +const __QUEUE_PRODUCER_GROUP_BYTES = 256_000; | |
| 6937 | + | |
| 6938 | +const __queueError = (message) => new Error("QUEUE_ERROR: " + String(message)); | |
| 6939 | +// A Queue message id is a UUIDv7 (RFC 9562): 48 bits of enqueue time, a | |
| 6940 | +// 12-bit sequence inside that millisecond, and 62 random bits. It keeps the | |
| 6941 | +// UUID shape a consumer can parse, and it sorts in enqueue order, so the | |
| 6942 | +// UNIQUE index on `id` appends. A random v4 id made every grouped send | |
| 6943 | +// transaction dirty one index leaf per message (about 1.6 WAL frames per | |
| 6944 | +// 64-byte message) and turned every passive checkpoint into a random write | |
| 6945 | +// across the whole backlog, which is what made a deep Queue's checkpoint | |
| 6946 | +// cost grow with its backlog. The sequence never moves backwards inside one | |
| 6947 | +// process, so a clock step only widens the gap between consecutive ids. | |
| 6948 | +let __queueIdMs = 0; | |
| 6949 | +let __queueIdSeq = 0; | |
| 6950 | +function __queueMessageId(now) { | |
| 6951 | + if (now > __queueIdMs) { | |
| 6952 | + __queueIdMs = now; | |
| 6953 | + __queueIdSeq = 0; | |
| 6954 | + } else { | |
| 6955 | + __queueIdSeq += 1; | |
| 6956 | + if (__queueIdSeq > 0xfff) { | |
| 6957 | + __queueIdMs += 1; | |
| 6958 | + __queueIdSeq = 0; | |
| 6959 | + } | |
| 6960 | + } | |
| 6961 | + const bytes = new Uint8Array(16); | |
| 6962 | + crypto.getRandomValues(bytes); | |
| 6963 | + const ms = __queueIdMs; | |
| 6964 | + bytes[0] = Math.floor(ms / 0x10000000000) & 0xff; | |
| 6965 | + bytes[1] = Math.floor(ms / 0x100000000) & 0xff; | |
| 6966 | + bytes[2] = (ms >>> 24) & 0xff; | |
| 6967 | + bytes[3] = (ms >>> 16) & 0xff; | |
| 6968 | + bytes[4] = (ms >>> 8) & 0xff; | |
| 6969 | + bytes[5] = ms & 0xff; | |
| 6970 | + bytes[6] = 0x70 | (__queueIdSeq >> 8); | |
| 6971 | + bytes[7] = __queueIdSeq & 0xff; | |
| 6972 | + bytes[8] = (bytes[8] & 0x3f) | 0x80; | |
| 6973 | + let hex = ""; | |
| 6974 | + for (let i = 0; i < 16; i++) hex += bytes[i].toString(16).padStart(2, "0"); | |
| 6975 | + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${ | |
| 6976 | + hex.slice(16, 20) | |
| 6977 | + }-${hex.slice(20)}`; | |
| 6978 | +} | |
| 6979 | +const __queueLimits = () => __cell.queueLimits; | |
| 6980 | +const __queuePolicy = (request) => | |
| 6981 | + JSON.parse(__queue_policy(JSON.stringify(request))); | |
| 6982 | + | |
| 6983 | +const __queueDelay = (value, fallback = 0) => { | |
| 6984 | + if (value === undefined || value === null) return fallback; | |
| 6985 | + const seconds = Number(value); | |
| 6986 | + if (!Number.isInteger(seconds) || seconds < 0 || | |
| 6987 | + seconds > __queueLimits().maxDelaySeconds) { | |
| 6988 | + throw __queueError( | |
| 6989 | + `delaySeconds must be an integer from 0 to ${__queueLimits().maxDelaySeconds}`, | |
| 6990 | + ); | |
| 6991 | + } | |
| 6992 | + return seconds; | |
| 6993 | +}; | |
| 6994 | + | |
| 6995 | +const __queueBytes = (value) => { | |
| 6996 | + if (value instanceof ArrayBuffer) { | |
| 6997 | + return new Uint8Array(value.slice(0)); | |
| 6998 | + } | |
| 6999 | + if (ArrayBuffer.isView(value)) { | |
| 7000 | + return new Uint8Array( | |
| 7001 | + value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), | |
| 7002 | + ); | |
| 7003 | + } | |
| 7004 | + throw __queueError("a bytes message must be an ArrayBuffer or a typed array"); | |
| 7005 | +}; | |
| 7006 | + | |
| 7007 | +// Encode before entering the cell. The copy makes `sendBatch()` immune to a | |
| 7008 | +// caller resizing or reusing a backing buffer while the durable write awaits. | |
| 7009 | +const __queueEncode = (body, requestedType) => { | |
| 7010 | + const contentType = requestedType ?? | |
| 7011 | + (__cell.compat.queueJsonMessages ? "json" : "v8"); | |
| 7012 | + let bytes; | |
| 7013 | + switch (contentType) { | |
| 7014 | + case "text": | |
| 7015 | + bytes = __queueEncoder.encode(String(body)); | |
| 7016 | + break; | |
| 7017 | + case "bytes": | |
| 7018 | + bytes = __queueBytes(body); | |
| 7019 | + break; | |
| 7020 | + case "json": { | |
| 7021 | + let json; | |
| 7022 | + try { | |
| 7023 | + json = JSON.stringify(body); | |
| 7024 | + } catch (error) { | |
| 7025 | + throw __queueError("the JSON message body cannot be serialized", error); | |
| 7026 | + } | |
| 7027 | + if (json === undefined) { | |
| 7028 | + throw __queueError("the JSON message body cannot be undefined"); | |
| 7029 | + } | |
| 7030 | + bytes = __queueEncoder.encode(json); | |
| 7031 | + break; | |
| 7032 | + } | |
| 7033 | + case "v8": | |
| 7034 | + try { | |
| 7035 | + bytes = __sc_encode(body); | |
| 7036 | + } catch (error) { | |
| 7037 | + throw __queueError("the message body cannot be cloned", error); | |
| 7038 | + } | |
| 7039 | + break; | |
| 7040 | + default: | |
| 7041 | + throw __queueError( | |
| 7042 | + `contentType must be "text", "bytes", "json", or "v8", got ${JSON.stringify(contentType)}`, | |
| 7043 | + ); | |
| 7044 | + } | |
| 7045 | + if (bytes.byteLength > __queueLimits().maxMessageBytes) { | |
| 7046 | + throw __queueError( | |
| 7047 | + `a message is at most ${__queueLimits().maxMessageBytes} bytes, got ${bytes.byteLength}`, | |
| 7048 | + ); | |
| 7049 | + } | |
| 7050 | + return { body: bytes, contentType, size: bytes.byteLength }; | |
| 7051 | +}; | |
| 7052 | + | |
| 7053 | +// A lease-scoped read must seek, not walk the backlog. The plan is the only | |
| 7054 | +// evidence that says which, and it is cheap to ask for, so a gated test seam | |
| 7055 | +// reads it from the shipped query rather than from a copy that can drift. | |
| 7056 | +const __queueReportLeaseLookupPlan = (sql, query, leaseId) => { | |
| 7057 | + if (typeof __test_queue_lease_lookup_plan !== "function") return; | |
| 7058 | + const plan = sql.exec(`EXPLAIN QUERY PLAN ${query}`, leaseId) | |
| 7059 | + .toArray() | |
| 7060 | + .map((row) => row.detail) | |
| 7061 | + .join("; "); | |
| 7062 | + __test_queue_lease_lookup_plan(plan); | |
| 7063 | +}; | |
| 7064 | + | |
| 7065 | +const __queueMetricsView = (metrics) => ({ | |
| 7066 | + backlogCount: metrics.backlogCount, | |
| 7067 | + backlogBytes: metrics.backlogBytes, | |
| 7068 | + oldestMessageTimestamp: metrics.oldestMessageTimestamp === null || | |
| 7069 | + metrics.oldestMessageTimestamp === undefined | |
| 7070 | + ? undefined | |
| 7071 | + : new Date(metrics.oldestMessageTimestamp), | |
| 7072 | +}); | |
| 7073 | + | |
| 7074 | +class __QueueCell { | |
| 7075 | + constructor(ctx) { | |
| 7076 | + this.ctx = ctx; | |
| 7077 | + this.queue = ctx.id.name; | |
| 7078 | + this._ready = false; | |
| 7079 | + this._producerGroup = null; | |
| 7080 | + } | |
| 7081 | + | |
| 7082 | + _open() { | |
| 7083 | + if (this._ready) return this.ctx.storage.sql; | |
| 7084 | + const sql = this.ctx.storage.sql; | |
| 7085 | + sql.exec( | |
| 7086 | + `CREATE TABLE IF NOT EXISTS ${__QUEUE_MESSAGES} ( | |
| 7087 | + seq INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 7088 | + id TEXT NOT NULL UNIQUE, | |
| 7089 | + body BLOB NOT NULL, | |
| 7090 | + content_type TEXT NOT NULL, | |
| 7091 | + size INTEGER NOT NULL, | |
| 7092 | + enqueued_at INTEGER NOT NULL, | |
| 7093 | + visible_at INTEGER NOT NULL, | |
| 7094 | + attempts INTEGER NOT NULL DEFAULT 0, | |
| 7095 | + lease_id TEXT, | |
| 7096 | + lease_generation INTEGER NOT NULL DEFAULT 0, | |
| 7097 | + leased_until INTEGER, | |
| 7098 | + purge_on_settle INTEGER NOT NULL DEFAULT 0, | |
| 7099 | + dlq_target TEXT, | |
| 7100 | + dlq_transfer_id TEXT, | |
| 7101 | + transfer_kind TEXT, | |
| 7102 | + dead_letter_source TEXT, | |
| 7103 | + CHECK ((dlq_target IS NULL AND transfer_kind IS NULL) | |
| 7104 | + OR (dlq_target IS NOT NULL | |
| 7105 | + AND transfer_kind IN ('dead-letter', 'redrive'))) | |
| 7106 | + )`, | |
| 7107 | + ); | |
| 7108 | + sql.exec( | |
| 7109 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_visible | |
| 7110 | + ON ${__QUEUE_MESSAGES} (visible_at, seq)`, | |
| 7111 | + ); | |
| 7112 | + // Rearming is on every producer acknowledgement and settlement. Each | |
| 7113 | + // scheduling lookup must therefore stop at one deadline or one batch; | |
| 7114 | + // an aggregate over the backlog makes a large Queue quadratic to fill. | |
| 7115 | + sql.exec( | |
| 7116 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_ready | |
| 7117 | + ON ${__QUEUE_MESSAGES} (visible_at, seq) | |
| 7118 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7119 | + AND lease_id IS NULL`, | |
| 7120 | + ); | |
| 7121 | + sql.exec( | |
| 7122 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_enqueued | |
| 7123 | + ON ${__QUEUE_MESSAGES} (enqueued_at, seq)`, | |
| 7124 | + ); | |
| 7125 | + sql.exec( | |
| 7126 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_retained | |
| 7127 | + ON ${__QUEUE_MESSAGES} (enqueued_at, seq) | |
| 7128 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL`, | |
| 7129 | + ); | |
| 7130 | + sql.exec( | |
| 7131 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease | |
| 7132 | + ON ${__QUEUE_MESSAGES} (leased_until, seq) | |
| 7133 | + WHERE lease_id IS NOT NULL`, | |
| 7134 | + ); | |
| 7135 | + sql.exec( | |
| 7136 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_moving | |
| 7137 | + ON ${__QUEUE_MESSAGES} (seq) | |
| 7138 | + WHERE dlq_target IS NOT NULL`, | |
| 7139 | + ); | |
| 7140 | + // Dispatch and settlement both select a whole batch by its lease. Without | |
| 7141 | + // this index SQLite answers them by walking every row: the dispatch | |
| 7142 | + // readback scans `_visible` and the settlement scan walks the table, so | |
| 7143 | + // each delivered batch costs two passes over the backlog. The `_lease` | |
| 7144 | + // index cannot serve them because it is keyed on `leased_until`. | |
| 7145 | + // The partial predicate keeps only leased rows, which `max_concurrency` | |
| 7146 | + // times `max_batch_size` bounds, and an inserted message has a null | |
| 7147 | + // `lease_id`, so `send` pays nothing for it. | |
| 7148 | + sql.exec( | |
| 7149 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease_batch | |
| 7150 | + ON ${__QUEUE_MESSAGES} (lease_id, visible_at, seq) | |
| 7151 | + WHERE lease_id IS NOT NULL`, | |
| 7152 | + ); | |
| 7153 | + // The live-row index catches an impossible duplicate while a received | |
| 7154 | + // message remains queued. The receipt below is the durable deduplication | |
| 7155 | + // record after a consumer or purge removes that message. | |
| 7156 | + sql.exec( | |
| 7157 | + `CREATE UNIQUE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_dlq_transfer | |
| 7158 | + ON ${__QUEUE_MESSAGES} (dlq_transfer_id) | |
| 7159 | + WHERE dlq_transfer_id IS NOT NULL AND dlq_target IS NULL`, | |
| 7160 | + ); | |
| 7161 | + sql.exec( | |
| 7162 | + `CREATE TABLE IF NOT EXISTS ${__QUEUE_META} ( | |
| 7163 | + name TEXT PRIMARY KEY, | |
| 7164 | + value TEXT NOT NULL | |
| 7165 | + ) WITHOUT ROWID`, | |
| 7166 | + ); | |
| 7167 | + // The producer result and operator metrics are on hot paths. SQLite | |
| 7168 | + // triggers keep the three values in the same transaction as every row | |
| 7169 | + // transition, so a caller cannot observe a new message with old totals. | |
| 7170 | + sql.exec( | |
| 7171 | + `CREATE TABLE IF NOT EXISTS ${__QUEUE_STATS} ( | |
| 7172 | + id INTEGER PRIMARY KEY CHECK (id = 1), | |
| 7173 | + stored_count INTEGER NOT NULL, | |
| 7174 | + backlog_count INTEGER NOT NULL, | |
| 7175 | + backlog_bytes INTEGER NOT NULL, | |
| 7176 | + oldest_message_timestamp INTEGER | |
| 7177 | + )`, | |
| 7178 | + ); | |
| 7179 | + sql.exec( | |
| 7180 | + `INSERT INTO ${__QUEUE_STATS} | |
| 7181 | + (id, stored_count, backlog_count, backlog_bytes, | |
| 7182 | + oldest_message_timestamp) | |
| 7183 | + SELECT 1, | |
| 7184 | + COUNT(*), | |
| 7185 | + COALESCE(SUM(purge_on_settle = 0), 0), | |
| 7186 | + COALESCE(SUM(CASE WHEN purge_on_settle = 0 THEN size ELSE 0 END), 0), | |
| 7187 | + MIN(CASE WHEN purge_on_settle = 0 THEN enqueued_at END) | |
| 7188 | + FROM ${__QUEUE_MESSAGES} | |
| 7189 | + WHERE true | |
| 7190 | + ON CONFLICT(id) DO NOTHING`, | |
| 7191 | + ); | |
| 7192 | + sql.exec( | |
| 7193 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_insert | |
| 7194 | + AFTER INSERT ON ${__QUEUE_MESSAGES} | |
| 7195 | + BEGIN | |
| 7196 | + UPDATE ${__QUEUE_STATS} | |
| 7197 | + SET stored_count = stored_count + 1 | |
| 7198 | + WHERE id = 1; | |
| 7199 | + END`, | |
| 7200 | + ); | |
| 7201 | + sql.exec( | |
| 7202 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_delete | |
| 7203 | + AFTER DELETE ON ${__QUEUE_MESSAGES} | |
| 7204 | + BEGIN | |
| 7205 | + UPDATE ${__QUEUE_STATS} | |
| 7206 | + SET stored_count = stored_count - 1 | |
| 7207 | + WHERE id = 1; | |
| 7208 | + END`, | |
| 7209 | + ); | |
| 7210 | + sql.exec( | |
| 7211 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_insert | |
| 7212 | + AFTER INSERT ON ${__QUEUE_MESSAGES} | |
| 7213 | + WHEN new.purge_on_settle = 0 | |
| 7214 | + BEGIN | |
| 7215 | + UPDATE ${__QUEUE_STATS} | |
| 7216 | + SET backlog_count = backlog_count + 1, | |
| 7217 | + backlog_bytes = backlog_bytes + new.size, | |
| 7218 | + oldest_message_timestamp = CASE | |
| 7219 | + WHEN oldest_message_timestamp IS NULL | |
| 7220 | + OR new.enqueued_at < oldest_message_timestamp | |
| 7221 | + THEN new.enqueued_at ELSE oldest_message_timestamp END | |
| 7222 | + WHERE id = 1; | |
| 7223 | + END`, | |
| 7224 | + ); | |
| 7225 | + sql.exec( | |
| 7226 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_delete | |
| 7227 | + AFTER DELETE ON ${__QUEUE_MESSAGES} | |
| 7228 | + WHEN old.purge_on_settle = 0 | |
| 7229 | + BEGIN | |
| 7230 | + UPDATE ${__QUEUE_STATS} | |
| 7231 | + SET backlog_count = backlog_count - 1, | |
| 7232 | + backlog_bytes = backlog_bytes - old.size, | |
| 7233 | + oldest_message_timestamp = CASE | |
| 7234 | + WHEN backlog_count <= 1 THEN NULL | |
| 7235 | + WHEN oldest_message_timestamp = old.enqueued_at | |
| 7236 | + THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} | |
| 7237 | + WHERE purge_on_settle = 0) | |
| 7238 | + ELSE oldest_message_timestamp END | |
| 7239 | + WHERE id = 1; | |
| 7240 | + END`, | |
| 7241 | + ); | |
| 7242 | + sql.exec( | |
| 7243 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_exclude | |
| 7244 | + AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} | |
| 7245 | + WHEN old.purge_on_settle = 0 AND new.purge_on_settle != 0 | |
| 7246 | + BEGIN | |
| 7247 | + UPDATE ${__QUEUE_STATS} | |
| 7248 | + SET backlog_count = backlog_count - 1, | |
| 7249 | + backlog_bytes = backlog_bytes - old.size, | |
| 7250 | + oldest_message_timestamp = CASE | |
| 7251 | + WHEN backlog_count <= 1 THEN NULL | |
| 7252 | + WHEN oldest_message_timestamp = old.enqueued_at | |
| 7253 | + THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} | |
| 7254 | + WHERE purge_on_settle = 0) | |
| 7255 | + ELSE oldest_message_timestamp END | |
| 7256 | + WHERE id = 1; | |
| 7257 | + END`, | |
| 7258 | + ); | |
| 7259 | + sql.exec( | |
| 7260 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_include | |
| 7261 | + AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} | |
| 7262 | + WHEN old.purge_on_settle != 0 AND new.purge_on_settle = 0 | |
| 7263 | + BEGIN | |
| 7264 | + UPDATE ${__QUEUE_STATS} | |
| 7265 | + SET backlog_count = backlog_count + 1, | |
| 7266 | + backlog_bytes = backlog_bytes + new.size, | |
| 7267 | + oldest_message_timestamp = CASE | |
| 7268 | + WHEN oldest_message_timestamp IS NULL | |
| 7269 | + OR new.enqueued_at < oldest_message_timestamp | |
| 7270 | + THEN new.enqueued_at ELSE oldest_message_timestamp END | |
| 7271 | + WHERE id = 1; | |
| 7272 | + END`, | |
| 7273 | + ); | |
| 7274 | + sql.exec( | |
| 7275 | + `CREATE TABLE IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS} ( | |
| 7276 | + transfer_id TEXT PRIMARY KEY, | |
| 7277 | + message_id TEXT NOT NULL, | |
| 7278 | + dead_letter_source TEXT, | |
| 7279 | + expires_at INTEGER NOT NULL | |
| 7280 | + ) WITHOUT ROWID`, | |
| 7281 | + ); | |
| 7282 | + sql.exec( | |
| 7283 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS}_expires | |
| 7284 | + ON ${__QUEUE_TRANSFER_RECEIPTS} (expires_at, transfer_id)`, | |
| 7285 | + ); | |
| 7286 | + this._ready = true; | |
| 7287 | + return sql; | |
| 7288 | + } | |
| 7289 | + | |
| 7290 | + _meta(name) { | |
| 7291 | + return this._open().exec( | |
| 7292 | + `SELECT value FROM ${__QUEUE_META} WHERE name = ?`, name, | |
| 7293 | + ).toArray()[0]?.value; | |
| 7294 | + } | |
| 7295 | + | |
| 7296 | + _setMeta(name, value) { | |
| 7297 | + if (value === null || value === undefined) { | |
| 7298 | + this._open().exec(`DELETE FROM ${__QUEUE_META} WHERE name = ?`, name); | |
| 7299 | + return; | |
| 7300 | + } | |
| 7301 | + this._open().exec( | |
| 7302 | + `INSERT INTO ${__QUEUE_META} (name, value) VALUES (?, ?) | |
| 7303 | + ON CONFLICT(name) DO UPDATE SET value = excluded.value`, | |
| 7304 | + name, | |
| 7305 | + String(value), | |
| 7306 | + ); | |
| 7307 | + } | |
| 7308 | + | |
| 7309 | + _paused() { | |
| 7310 | + return this._meta("paused") === "1"; | |
| 7311 | + } | |
| 7312 | + | |
| 7313 | + _metrics(now = Date.now(), waitingOnly = false) { | |
| 7314 | + const expiresBefore = now - __queueLimits().retentionMs; | |
| 7315 | + const sql = this._open(); | |
| 7316 | + const stats = sql.exec( | |
| 7317 | + `SELECT backlog_count, backlog_bytes, oldest_message_timestamp | |
| 7318 | + FROM ${__QUEUE_STATS} WHERE id = 1`, | |
| 7319 | + ).toArray()[0]; | |
| 7320 | + // Retention is a clock transition, not a row transition. Until the | |
| 7321 | + // bounded sweep catches up, use the exact query only at that boundary; | |
| 7322 | + // the normal hot path remains one materialized row at every depth. | |
| 7323 | + if (stats.oldest_message_timestamp !== null && | |
| 7324 | + stats.oldest_message_timestamp <= expiresBefore) { | |
| 7325 | + const row = sql.exec( | |
| 7326 | + `SELECT COUNT(*) AS backlog_count, | |
| 7327 | + COALESCE(SUM(size), 0) AS backlog_bytes, | |
| 7328 | + MIN(enqueued_at) AS oldest_message_timestamp | |
| 7329 | + FROM ${__QUEUE_MESSAGES} | |
| 7330 | + WHERE purge_on_settle = 0 AND enqueued_at > ? | |
| 7331 | + AND (? = 0 OR (lease_id IS NULL AND dlq_target IS NULL | |
| 7332 | + AND visible_at <= ?))`, | |
| 7333 | + expiresBefore, | |
| 7334 | + waitingOnly ? 1 : 0, | |
| 7335 | + now, | |
| 7336 | + ).toArray()[0]; | |
| 7337 | + return { | |
| 7338 | + backlogCount: row.backlog_count, | |
| 7339 | + backlogBytes: row.backlog_bytes, | |
| 7340 | + oldestMessageTimestamp: row.oldest_message_timestamp ?? null, | |
| 7341 | + }; | |
| 7342 | + } | |
| 7343 | + if (!waitingOnly) { | |
| 7344 | + if (typeof __test_queue_metrics_materialized === "function") { | |
| 7345 | + __test_queue_metrics_materialized(); | |
| 7346 | + } | |
| 7347 | + return { | |
| 7348 | + backlogCount: stats.backlog_count, | |
| 7349 | + backlogBytes: stats.backlog_bytes, | |
| 7350 | + oldestMessageTimestamp: stats.oldest_message_timestamp ?? null, | |
| 7351 | + }; | |
| 7352 | + } | |
| 7353 | + const blocked = sql.exec( | |
| 7354 | + `SELECT COALESCE(SUM(blocked_count), 0) AS blocked_count, | |
| 7355 | + COALESCE(SUM(blocked_bytes), 0) AS blocked_bytes | |
| 7356 | + FROM ( | |
| 7357 | + SELECT COUNT(*) AS blocked_count, | |
| 7358 | + COALESCE(SUM(size), 0) AS blocked_bytes | |
| 7359 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 7360 | + WHERE purge_on_settle = 0 AND lease_id IS NOT NULL | |
| 7361 | + UNION ALL | |
| 7362 | + SELECT COUNT(*) AS blocked_count, | |
| 7363 | + COALESCE(SUM(size), 0) AS blocked_bytes | |
| 7364 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving | |
| 7365 | + WHERE purge_on_settle = 0 AND dlq_target IS NOT NULL | |
| 7366 | + UNION ALL | |
| 7367 | + SELECT COUNT(*) AS blocked_count, | |
| 7368 | + COALESCE(SUM(size), 0) AS blocked_bytes | |
| 7369 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 7370 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7371 | + AND lease_id IS NULL AND visible_at > ? | |
| 7372 | + )`, | |
| 7373 | + now, | |
| 7374 | + ).toArray()[0]; | |
| 7375 | + const unleasedOldest = sql.exec( | |
| 7376 | + `SELECT enqueued_at | |
| 7377 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained | |
| 7378 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7379 | + AND lease_id IS NULL AND visible_at <= ? | |
| 7380 | + ORDER BY enqueued_at, seq | |
| 7381 | + LIMIT 1`, | |
| 7382 | + now, | |
| 7383 | + ).toArray()[0]?.enqueued_at ?? null; | |
| 7384 | + return { | |
| 7385 | + backlogCount: stats.backlog_count - blocked.blocked_count, | |
| 7386 | + backlogBytes: stats.backlog_bytes - blocked.blocked_bytes, | |
| 7387 | + oldestMessageTimestamp: unleasedOldest, | |
| 7388 | + }; | |
| 7389 | + } | |
| 7390 | + | |
| 7391 | + async _rearm(now = Date.now(), waitForWake = false) { | |
| 7392 | + const sql = this._open(); | |
| 7393 | + const consumer = __cell.queueConsumers?.[this.queue]; | |
| 7394 | + const paused = this._paused(); | |
| 7395 | + const active = sql.exec( | |
| 7396 | + `SELECT COUNT(DISTINCT lease_id) AS count | |
| 7397 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 7398 | + WHERE lease_id IS NOT NULL AND leased_until > ?`, | |
| 7399 | + now, | |
| 7400 | + ).toArray()[0].count; | |
| 7401 | + const concurrency = consumer | |
| 7402 | + ? consumer.maxConcurrency ?? __queueLimits().maxConcurrency | |
| 7403 | + : 0; | |
| 7404 | + const hasCapacity = !paused && consumer !== undefined && __queuePolicy({ | |
| 7405 | + op: "capacity", | |
| 7406 | + active, | |
| 7407 | + maximum: concurrency, | |
| 7408 | + }); | |
| 7409 | + // We need only enough ready rows to distinguish a partial batch from a | |
| 7410 | + // full one. The two indexed arms cover a new row and an expired lease, | |
| 7411 | + // and the outer LIMIT keeps the work independent of backlog depth. | |
| 7412 | + let ready = []; | |
| 7413 | + if (hasCapacity) { | |
| 7414 | + const visibleReady = sql.exec( | |
| 7415 | + `SELECT visible_at AS ready_at, seq | |
| 7416 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 7417 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7418 | + AND lease_id IS NULL AND visible_at <= ? | |
| 7419 | + ORDER BY visible_at, seq | |
| 7420 | + LIMIT ?`, | |
| 7421 | + now, | |
| 7422 | + consumer.maxBatchSize, | |
| 7423 | + ).toArray(); | |
| 7424 | + const expiredReady = sql.exec( | |
| 7425 | + `SELECT leased_until AS ready_at, seq | |
| 7426 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 7427 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7428 | + AND lease_id IS NOT NULL AND leased_until <= ? | |
| 7429 | + ORDER BY leased_until, seq | |
| 7430 | + LIMIT ?`, | |
| 7431 | + now, | |
| 7432 | + consumer.maxBatchSize, | |
| 7433 | + ).toArray(); | |
| 7434 | + ready = [...visibleReady, ...expiredReady] | |
| 7435 | + .sort((left, right) => left.ready_at - right.ready_at || left.seq - right.seq) | |
| 7436 | + .slice(0, consumer.maxBatchSize); | |
| 7437 | + } | |
| 7438 | + if (typeof __test_queue_rearm_bounded === "function") { | |
| 7439 | + __test_queue_rearm_bounded( | |
| 7440 | + ready.length <= (consumer?.maxBatchSize ?? 0), | |
| 7441 | + ready.length > 0, | |
| 7442 | + ); | |
| 7443 | + } | |
| 7444 | + const earliestVisible = hasCapacity | |
| 7445 | + ? sql.exec( | |
| 7446 | + `SELECT visible_at | |
| 7447 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 7448 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7449 | + AND lease_id IS NULL AND visible_at > ? | |
| 7450 | + ORDER BY visible_at, seq | |
| 7451 | + LIMIT 1`, | |
| 7452 | + now, | |
| 7453 | + ).toArray()[0]?.visible_at ?? null | |
| 7454 | + : null; | |
| 7455 | + const earliestLeaseExpiry = paused | |
| 7456 | + ? null | |
| 7457 | + : sql.exec( | |
| 7458 | + `SELECT leased_until | |
| 7459 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 7460 | + WHERE lease_id IS NOT NULL | |
| 7461 | + ORDER BY leased_until | |
| 7462 | + LIMIT 1`, | |
| 7463 | + ).toArray()[0]?.leased_until ?? null; | |
| 7464 | + const nextSweep = sql.exec( | |
| 7465 | + `SELECT enqueued_at + ? AS next_sweep | |
| 7466 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained | |
| 7467 | + WHERE dlq_target IS NULL AND purge_on_settle = 0 | |
| 7468 | + ORDER BY enqueued_at, seq | |
| 7469 | + LIMIT 1`, | |
| 7470 | + __queueLimits().retentionMs, | |
| 7471 | + ).toArray()[0]?.next_sweep ?? null; | |
| 7472 | + const dlqPending = sql.exec( | |
| 7473 | + `SELECT 1 AS pending | |
| 7474 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving | |
| 7475 | + WHERE dlq_target IS NOT NULL | |
| 7476 | + LIMIT 1`, | |
| 7477 | + ).toArray().length !== 0; | |
| 7478 | + const receiptSweep = sql.exec( | |
| 7479 | + `SELECT expires_at AS next_sweep | |
| 7480 | + FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7481 | + ORDER BY expires_at, transfer_id | |
| 7482 | + LIMIT 1`, | |
| 7483 | + ).toArray()[0]?.next_sweep ?? null; | |
| 7484 | + // A queue without an attached consumer only wakes to reclaim retention. | |
| 7485 | + // Consumer attachment will nudge the cell when the fleet catalog gains a | |
| 7486 | + // registration; spinning on an already-visible row cannot make progress. | |
| 7487 | + let batchDeadline = null; | |
| 7488 | + if (ready.length > 0) { | |
| 7489 | + batchDeadline = ready.length >= consumer.maxBatchSize | |
| 7490 | + ? now | |
| 7491 | + : ready[0].ready_at + consumer.maxBatchTimeoutMs; | |
| 7492 | + } | |
| 7493 | + if (dlqPending) { | |
| 7494 | + batchDeadline = batchDeadline === null ? now : Math.min(batchDeadline, now); | |
| 7495 | + } | |
| 7496 | + const sweepDeadlines = [nextSweep, receiptSweep] | |
| 7497 | + .filter((deadline) => deadline !== null && deadline !== undefined); | |
| 7498 | + const armAt = __queuePolicy({ | |
| 7499 | + op: "rearm", | |
| 7500 | + now, | |
| 7501 | + batchDeadline, | |
| 7502 | + earliestVisible, | |
| 7503 | + // A live handler can settle after delivery pauses. Do not reclaim its | |
| 7504 | + // lease while paused; resume re-arms the expired deadline immediately | |
| 7505 | + // and only then can a new generation replace it. | |
| 7506 | + earliestLeaseExpiry, | |
| 7507 | + nextSweep: sweepDeadlines.length === 0 ? null : Math.min(...sweepDeadlines), | |
| 7508 | + }); | |
| 7509 | + if (armAt !== null && !Number.isFinite(armAt)) { | |
| 7510 | + throw __queueError("the Queue sweep deadline is invalid"); | |
| 7511 | + } | |
| 7512 | + if (armAt === null) await this.ctx.storage.deleteAlarm(); | |
| 7513 | + else if (waitForWake) { | |
| 7514 | + await __queue_alarm_set_wait(this.ctx.storage._scope, armAt); | |
| 7515 | + } else await this.ctx.storage.setAlarm(armAt); | |
| 7516 | + } | |
| 7517 | + | |
| 7518 | + _newProducerGroup() { | |
| 7519 | + const group = { | |
| 7520 | + calls: [], | |
| 7521 | + entries: [], | |
| 7522 | + bytes: 0, | |
| 7523 | + flushing: false, | |
| 7524 | + timer: null, | |
| 7525 | + }; | |
| 7526 | + this._producerGroup = group; | |
| 7527 | + group.timer = setTimeout(() => { | |
| 7528 | + void this._flushProducerGroup(group); | |
| 7529 | + }, __queueLimits().producerGroupMs); | |
| 7530 | + return group; | |
| 7531 | + } | |
| 7532 | + | |
| 7533 | + async _flushProducerGroup(group) { | |
| 7534 | + if (group.flushing) return; | |
| 7535 | + group.flushing = true; | |
| 7536 | + if (this._producerGroup === group) this._producerGroup = null; | |
| 7537 | + if (group.timer !== null) { | |
| 7538 | + clearTimeout(group.timer); | |
| 7539 | + group.timer = null; | |
| 7540 | + } | |
| 7541 | + | |
| 7542 | + const now = Date.now(); | |
| 7543 | + try { | |
| 7544 | + const sql = this._open(); | |
| 7545 | + this.ctx.storage.transactionSync(() => { | |
| 7546 | + for (const entry of group.entries) { | |
| 7547 | + sql.exec( | |
| 7548 | + `INSERT INTO ${__QUEUE_MESSAGES} | |
| 7549 | + (id, body, content_type, size, enqueued_at, visible_at) | |
| 7550 | + VALUES (?, ?, ?, ?, ?, ?)`, | |
| 7551 | + __queueMessageId(now), | |
| 7552 | + entry.body, | |
| 7553 | + entry.contentType, | |
| 7554 | + entry.size, | |
| 7555 | + now, | |
| 7556 | + now + entry.delaySeconds * 1000, | |
| 7557 | + ); | |
| 7558 | + } | |
| 7559 | + }); | |
| 7560 | + await this._rearm(now, true); | |
| 7561 | + const metrics = this._metrics(now); | |
| 7562 | + if (typeof __test_queue_producer_group === "function") { | |
| 7563 | + __test_queue_producer_group(group.calls.length, group.entries.length); | |
| 7564 | + } | |
| 7565 | + for (const call of group.calls) call.resolve(metrics); | |
| 7566 | + } catch (error) { | |
| 7567 | + for (const call of group.calls) call.reject(error); | |
| 7568 | + } | |
| 7569 | + } | |
| 7570 | + | |
| 7571 | + __queueSend({ entries }) { | |
| 7572 | + const bytes = entries.reduce((total, entry) => total + entry.size, 0); | |
| 7573 | + return new Promise((resolve, reject) => { | |
| 7574 | + let group = this._producerGroup; | |
| 7575 | + if (group !== null && | |
| 7576 | + (group.calls.length + 1 > __QUEUE_PRODUCER_GROUP_CALLS || | |
| 7577 | + group.entries.length + entries.length > __QUEUE_PRODUCER_GROUP_MESSAGES || | |
| 7578 | + group.bytes + bytes > __QUEUE_PRODUCER_GROUP_BYTES)) { | |
| 7579 | + void this._flushProducerGroup(group); | |
| 7580 | + group = null; | |
| 7581 | + } | |
| 7582 | + if (group === null) group = this._newProducerGroup(); | |
| 7583 | + group.calls.push({ resolve, reject }); | |
| 7584 | + group.entries.push(...entries); | |
| 7585 | + group.bytes += bytes; | |
| 7586 | + if (group.calls.length === __QUEUE_PRODUCER_GROUP_CALLS || | |
| 7587 | + group.entries.length === __QUEUE_PRODUCER_GROUP_MESSAGES || | |
| 7588 | + group.bytes === __QUEUE_PRODUCER_GROUP_BYTES) { | |
| 7589 | + void this._flushProducerGroup(group); | |
| 7590 | + } | |
| 7591 | + }); | |
| 7592 | + } | |
| 7593 | + | |
| 7594 | + __queueMetrics() { | |
| 7595 | + return this._metrics(); | |
| 7596 | + } | |
| 7597 | + | |
| 7598 | + // Retention decides visibility through `_metrics` immediately, while this | |
| 7599 | + // bounded sweep only reclaims space. A live lease is marked instead of | |
| 7600 | + // deleted, so its handler can finish but settlement or expiry removes it | |
| 7601 | + // without a redelivery. | |
| 7602 | + _sweep(now) { | |
| 7603 | + const sql = this._open(); | |
| 7604 | + const cutoff = now - __queueLimits().retentionMs; | |
| 7605 | + const messages = __cellSweepBatch( | |
| 7606 | + this.ctx.storage, | |
| 7607 | + (limit) => sql.exec( | |
| 7608 | + `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} | |
| 7609 | + WHERE enqueued_at <= ? | |
| 7610 | + AND (purge_on_settle = 0 | |
| 7611 | + OR lease_id IS NULL OR leased_until <= ?) | |
| 7612 | + ORDER BY enqueued_at, seq | |
| 7613 | + LIMIT ?`, | |
| 7614 | + cutoff, | |
| 7615 | + now, | |
| 7616 | + limit, | |
| 7617 | + ).toArray(), | |
| 7618 | + (row) => { | |
| 7619 | + if (row.lease_id !== null && row.leased_until > now) { | |
| 7620 | + sql.exec( | |
| 7621 | + `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 WHERE seq = ?`, | |
| 7622 | + row.seq, | |
| 7623 | + ); | |
| 7624 | + } else { | |
| 7625 | + sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); | |
| 7626 | + } | |
| 7627 | + }, | |
| 7628 | + __queueLimits().sweepBatchRows, | |
| 7629 | + ); | |
| 7630 | + const remaining = __queueLimits().sweepBatchRows - messages; | |
| 7631 | + if (remaining === 0) return messages; | |
| 7632 | + const receipts = __cellSweepBatch( | |
| 7633 | + this.ctx.storage, | |
| 7634 | + (limit) => sql.exec( | |
| 7635 | + `SELECT transfer_id FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7636 | + WHERE expires_at <= ? | |
| 7637 | + ORDER BY expires_at, transfer_id | |
| 7638 | + LIMIT ?`, | |
| 7639 | + now, | |
| 7640 | + limit, | |
| 7641 | + ).toArray(), | |
| 7642 | + (row) => { | |
| 7643 | + sql.exec( | |
| 7644 | + `DELETE FROM ${__QUEUE_TRANSFER_RECEIPTS} WHERE transfer_id = ?`, | |
| 7645 | + row.transfer_id, | |
| 7646 | + ); | |
| 7647 | + }, | |
| 7648 | + remaining, | |
| 7649 | + ); | |
| 7650 | + return messages + receipts; | |
| 7651 | + } | |
| 7652 | + | |
| 7653 | + _candidateRows(now, limit) { | |
| 7654 | + return this._open().exec( | |
| 7655 | + `SELECT seq, id, body, content_type, size, enqueued_at, visible_at, | |
| 7656 | + attempts, lease_id, lease_generation, leased_until, | |
| 7657 | + purge_on_settle | |
| 7658 | + FROM ${__QUEUE_MESSAGES} | |
| 7659 | + WHERE dlq_target IS NULL AND ((purge_on_settle = 1 | |
| 7660 | + AND (lease_id IS NULL OR leased_until <= ?)) | |
| 7661 | + OR (purge_on_settle = 0 AND visible_at <= ? | |
| 7662 | + AND (lease_id IS NULL OR leased_until <= ?))) | |
| 7663 | + ORDER BY visible_at, seq | |
| 7664 | + LIMIT ?`, | |
| 7665 | + now, | |
| 7666 | + now, | |
| 7667 | + now, | |
| 7668 | + limit, | |
| 7669 | + ).toArray(); | |
| 7670 | + } | |
| 7671 | + | |
| 7672 | + async _leaseBatch(now, consumer) { | |
| 7673 | + const sql = this._open(); | |
| 7674 | + const active = sql.exec( | |
| 7675 | + `SELECT COUNT(DISTINCT lease_id) AS count | |
| 7676 | + FROM ${__QUEUE_MESSAGES} | |
| 7677 | + WHERE lease_id IS NOT NULL AND leased_until > ?`, | |
| 7678 | + now, | |
| 7679 | + ).toArray()[0].count; | |
| 7680 | + const concurrency = consumer.maxConcurrency ?? __queueLimits().maxConcurrency; | |
| 7681 | + if (!__queuePolicy({ op: "capacity", active, maximum: concurrency })) return null; | |
| 7682 | + | |
| 7683 | + // Read extra rows so expired purge markers cannot hide a deliverable | |
| 7684 | + // batch. Policy chooses at most `maxBatchSize` rows and returns every | |
| 7685 | + // purge deletion that precedes them in this bounded scan. | |
| 7686 | + const rows = this._candidateRows(now, consumer.maxBatchSize + 256); | |
| 7687 | + const deliverable = rows.filter((row) => row.purge_on_settle === 0); | |
| 7688 | + if (deliverable.length === 0) { | |
| 7689 | + if (rows.length > 0) { | |
| 7690 | + this.ctx.storage.transactionSync(() => { | |
| 7691 | + for (const row of rows) { | |
| 7692 | + sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); | |
| 7693 | + } | |
| 7694 | + }); | |
| 7695 | + } | |
| 7696 | + return null; | |
| 7697 | + } | |
| 7698 | + const readySince = Math.min(...deliverable.map((row) => | |
| 7699 | + row.lease_id === null ? row.visible_at : row.leased_until | |
| 7700 | + )); | |
| 7701 | + if (deliverable.length < consumer.maxBatchSize && | |
| 7702 | + readySince + consumer.maxBatchTimeoutMs > now) { | |
| 7703 | + return null; | |
| 7704 | + } | |
| 7705 | + | |
| 7706 | + const plan = __queuePolicy({ | |
| 7707 | + op: "batch", | |
| 7708 | + now, | |
| 7709 | + maxBatchSize: consumer.maxBatchSize, | |
| 7710 | + rows: rows.map((row) => ({ | |
| 7711 | + seq: row.seq, | |
| 7712 | + visibleAt: row.visible_at, | |
| 7713 | + leaseGeneration: String(row.lease_generation), | |
| 7714 | + leasedUntil: row.leased_until, | |
| 7715 | + purgeOnSettle: row.purge_on_settle !== 0, | |
| 7716 | + })), | |
| 7717 | + }); | |
| 7718 | + if (plan.leases.length === 0 && plan.deletePurged.length === 0) return null; | |
| 7719 | + const rowBySeq = new Map(rows.map((row) => [row.seq, row])); | |
| 7720 | + const reclaimed = plan.leases.filter((lease) => lease.reclaimed); | |
| 7721 | + const expiryPolicy = __queuePolicy({ | |
| 7722 | + op: "expiry", | |
| 7723 | + now, | |
| 7724 | + entries: reclaimed.map((lease) => { | |
| 7725 | + const row = rowBySeq.get(lease.seq); | |
| 7726 | + return { | |
| 7727 | + priorFailures: row.attempts, | |
| 7728 | + maxRetries: consumer.maxRetries, | |
| 7729 | + configuredSeconds: consumer.retryDelaySeconds ?? null, | |
| 7730 | + purgeOnSettle: row.purge_on_settle !== 0, | |
| 7731 | + }; | |
| 7732 | + }), | |
| 7733 | + }); | |
| 7734 | + const expiryBySeq = new Map( | |
| 7735 | + reclaimed.map((lease, index) => [lease.seq, expiryPolicy[index]]), | |
| 7736 | + ); | |
| 7737 | + const installs = plan.leases.filter((lease) => { | |
| 7738 | + const expiry = expiryBySeq.get(lease.seq); | |
| 7739 | + return expiry === undefined || | |
| 7740 | + (expiry.action.kind === "retry" && expiry.action.at <= now); | |
| 7741 | + }); | |
| 7742 | + const exhaustedTransfers = new Map( | |
| 7743 | + reclaimed | |
| 7744 | + .filter((lease) => | |
| 7745 | + expiryBySeq.get(lease.seq).action.kind === "exhausted" && | |
| 7746 | + consumer.deadLetterQueue !== undefined | |
| 7747 | + ) | |
| 7748 | + .map((lease) => [lease.seq, crypto.randomUUID()]), | |
| 7749 | + ); | |
| 7750 | + const leaseId = crypto.randomUUID(); | |
| 7751 | + const leasedUntil = Math.min( | |
| 7752 | + Number.MAX_SAFE_INTEGER, | |
| 7753 | + now + __cell.queueLeaseDurationMs, | |
| 7754 | + ); | |
| 7755 | + this.ctx.storage.transactionSync(() => { | |
| 7756 | + for (const seq of plan.deletePurged) { | |
| 7757 | + sql.exec( | |
| 7758 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7759 | + WHERE seq = ? AND purge_on_settle = 1 | |
| 7760 | + AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 7761 | + seq, | |
| 7762 | + now, | |
| 7763 | + ); | |
| 7764 | + } | |
| 7765 | + for (const lease of reclaimed) { | |
| 7766 | + const expiry = expiryBySeq.get(lease.seq); | |
| 7767 | + if (expiry.action.kind === "delete-purged") { | |
| 7768 | + sql.exec( | |
| 7769 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7770 | + WHERE seq = ? AND leased_until <= ?`, | |
| 7771 | + lease.seq, | |
| 7772 | + now, | |
| 7773 | + ); | |
| 7774 | + } else if (expiry.action.kind === "exhausted") { | |
| 7775 | + if (consumer.deadLetterQueue === undefined) { | |
| 7776 | + sql.exec( | |
| 7777 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7778 | + WHERE seq = ? AND leased_until <= ?`, | |
| 7779 | + lease.seq, | |
| 7780 | + now, | |
| 7781 | + ); | |
| 7782 | + } else { | |
| 7783 | + sql.exec( | |
| 7784 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 7785 | + SET attempts = ?, lease_id = NULL, leased_until = NULL, | |
| 7786 | + dlq_target = ?, dlq_transfer_id = ?, | |
| 7787 | + transfer_kind = 'dead-letter' | |
| 7788 | + WHERE seq = ? AND leased_until <= ?`, | |
| 7789 | + expiry.attempt, | |
| 7790 | + consumer.deadLetterQueue, | |
| 7791 | + exhaustedTransfers.get(lease.seq), | |
| 7792 | + lease.seq, | |
| 7793 | + now, | |
| 7794 | + ); | |
| 7795 | + } | |
| 7796 | + } else if (expiry.action.at > now) { | |
| 7797 | + sql.exec( | |
| 7798 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 7799 | + SET attempts = ?, visible_at = ?, lease_id = NULL, | |
| 7800 | + leased_until = NULL | |
| 7801 | + WHERE seq = ? AND leased_until <= ?`, | |
| 7802 | + expiry.attempt, | |
| 7803 | + expiry.action.at, | |
| 7804 | + lease.seq, | |
| 7805 | + now, | |
| 7806 | + ); | |
| 7807 | + } | |
| 7808 | + } | |
| 7809 | + for (const lease of installs) { | |
| 7810 | + const generation = Number(lease.generation); | |
| 7811 | + if (!Number.isSafeInteger(generation)) { | |
| 7812 | + throw __queueError(`message ${lease.seq} exhausted its safe lease generation`); | |
| 7813 | + } | |
| 7814 | + sql.exec( | |
| 7815 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 7816 | + SET lease_id = ?, lease_generation = ?, leased_until = ?, | |
| 7817 | + attempts = attempts + ? | |
| 7818 | + WHERE seq = ? AND lease_generation = ? | |
| 7819 | + AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 7820 | + leaseId, | |
| 7821 | + generation, | |
| 7822 | + leasedUntil, | |
| 7823 | + lease.reclaimed ? 1 : 0, | |
| 7824 | + lease.seq, | |
| 7825 | + generation - 1, | |
| 7826 | + now, | |
| 7827 | + ); | |
| 7828 | + } | |
| 7829 | + }); | |
| 7830 | + if (installs.length === 0) return null; | |
| 7831 | + const leasedQuery = | |
| 7832 | + `SELECT seq, id, body, content_type, enqueued_at, attempts, | |
| 7833 | + lease_generation | |
| 7834 | + FROM ${__QUEUE_MESSAGES} | |
| 7835 | + WHERE lease_id = ? | |
| 7836 | + ORDER BY visible_at, seq`; | |
| 7837 | + __queueReportLeaseLookupPlan(sql, leasedQuery, leaseId); | |
| 7838 | + const leased = sql.exec(leasedQuery, leaseId).toArray(); | |
| 7839 | + if (leased.length !== installs.length) { | |
| 7840 | + throw __queueError("the Queue lease transaction changed fewer rows than its plan"); | |
| 7841 | + } | |
| 7842 | + return { | |
| 7843 | + leaseId, | |
| 7844 | + leases: leased.map((row) => ({ | |
| 7845 | + message_id: row.id, | |
| 7846 | + seq: row.seq, | |
| 7847 | + generation: row.lease_generation, | |
| 7848 | + })), | |
| 7849 | + messages: leased.map((row) => ({ | |
| 7850 | + id: row.id, | |
| 7851 | + timestampMs: row.enqueued_at, | |
| 7852 | + // SQLite answers a BLOB as an ArrayBuffer. The raw base64 op accepts | |
| 7853 | + // typed views, so normalize here; otherwise it encodes the text | |
| 7854 | + // "[object ArrayBuffer]" and every consumer decoder sees corrupt data. | |
| 7855 | + bodyBase64: $$btoa( | |
| 7856 | + row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), | |
| 7857 | + ), | |
| 7858 | + contentType: row.content_type, | |
| 7859 | + attempts: row.attempts + 1, | |
| 7860 | + })), | |
| 7861 | + // Miniflare removes every dispatched batch from its backlog before it | |
| 7862 | + // invokes the consumer. Exclude every lease here for the same contract; | |
| 7863 | + // the operator aggregate still includes durable in-flight messages. | |
| 7864 | + metrics: this._metrics(now, true), | |
| 7865 | + }; | |
| 7866 | + } | |
| 7867 | + | |
| 7868 | + // The target deduplicates the stable transfer identity. The source can | |
| 7869 | + // therefore repeat this call after a stop between the target commit and the | |
| 7870 | + // source delete without creating a second message. | |
| 7871 | + async __queueDlqAcceptBatch({ transfers }) { | |
| 7872 | + if (!Array.isArray(transfers) || transfers.length === 0 || | |
| 7873 | + transfers.length > __queueLimits().maxBatchMessages) { | |
| 7874 | + throw __queueError("a Queue transfer batch has an invalid size"); | |
| 7875 | + } | |
| 7876 | + for (const transfer of transfers) { | |
| 7877 | + if (transfer.deadLetterSource !== null && | |
| 7878 | + typeof transfer.deadLetterSource !== "string") { | |
| 7879 | + throw __queueError("a Queue transfer has an invalid dead-letter source"); | |
| 7880 | + } | |
| 7881 | + } | |
| 7882 | + const now = Date.now(); | |
| 7883 | + const sql = this._open(); | |
| 7884 | + this.ctx.storage.transactionSync(() => { | |
| 7885 | + for (const { transferId, entry, deadLetterSource } of transfers) { | |
| 7886 | + const accepted = sql.exec( | |
| 7887 | + `SELECT message_id, dead_letter_source | |
| 7888 | + FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7889 | + WHERE transfer_id = ?`, | |
| 7890 | + transferId, | |
| 7891 | + ).toArray()[0]; | |
| 7892 | + if (accepted !== undefined && (accepted.message_id !== entry.id || | |
| 7893 | + accepted.dead_letter_source !== deadLetterSource)) { | |
| 7894 | + throw __queueError("a DLQ transfer collided with another message identity"); | |
| 7895 | + } | |
| 7896 | + if (accepted !== undefined) continue; | |
| 7897 | + sql.exec( | |
| 7898 | + `INSERT INTO ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7899 | + (transfer_id, message_id, dead_letter_source, expires_at) | |
| 7900 | + VALUES (?, ?, ?, ?)`, | |
| 7901 | + transferId, | |
| 7902 | + entry.id, | |
| 7903 | + deadLetterSource, | |
| 7904 | + now + __queueLimits().retentionMs, | |
| 7905 | + ); | |
| 7906 | + sql.exec( | |
| 7907 | + `INSERT INTO ${__QUEUE_MESSAGES} | |
| 7908 | + (id, body, content_type, size, enqueued_at, visible_at, | |
| 7909 | + attempts, dlq_transfer_id, dead_letter_source) | |
| 7910 | + VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)`, | |
| 7911 | + entry.id, | |
| 7912 | + entry.body, | |
| 7913 | + entry.contentType, | |
| 7914 | + entry.size, | |
| 7915 | + now, | |
| 7916 | + now, | |
| 7917 | + transferId, | |
| 7918 | + deadLetterSource, | |
| 7919 | + ); | |
| 7920 | + } | |
| 7921 | + }); | |
| 7922 | + await this._rearm(now); | |
| 7923 | + return this._metrics(now); | |
| 7924 | + } | |
| 7925 | + | |
| 7926 | + async _driveDlq(limit = 100) { | |
| 7927 | + const now = Date.now(); | |
| 7928 | + const pending = this._open().exec( | |
| 7929 | + `SELECT seq, id, body, content_type, size, dlq_target, dlq_transfer_id, | |
| 7930 | + transfer_kind | |
| 7931 | + FROM ${__QUEUE_MESSAGES} | |
| 7932 | + WHERE dlq_target IS NOT NULL | |
| 7933 | + AND enqueued_at > ? | |
| 7934 | + ORDER BY seq | |
| 7935 | + LIMIT ?`, | |
| 7936 | + now - __queueLimits().retentionMs, | |
| 7937 | + limit, | |
| 7938 | + ).toArray(); | |
| 7939 | + const groups = new Map(); | |
| 7940 | + for (const row of pending) { | |
| 7941 | + let group = groups.get(row.dlq_target); | |
| 7942 | + if (group === undefined) groups.set(row.dlq_target, group = []); | |
| 7943 | + group.push(row); | |
| 7944 | + } | |
| 7945 | + for (const [targetName, rows] of groups) { | |
| 7946 | + const target = __cell.makeNamespace("__Queue").getByName(targetName); | |
| 7947 | + await target.__queueDlqAcceptBatch({ | |
| 7948 | + transfers: rows.map((row) => ({ | |
| 7949 | + transferId: row.dlq_transfer_id, | |
| 7950 | + // A dead-letter transfer records where redrive returns the message. | |
| 7951 | + // A redrive returns it to ordinary queue state, so the source marker | |
| 7952 | + // must not follow it and make a later redrive bounce it backwards. | |
| 7953 | + deadLetterSource: row.transfer_kind === "dead-letter" ? this.queue : null, | |
| 7954 | + entry: { | |
| 7955 | + id: row.id, | |
| 7956 | + body: row.body, | |
| 7957 | + contentType: row.content_type, | |
| 7958 | + size: row.size, | |
| 7959 | + }, | |
| 7960 | + })), | |
| 7961 | + }); | |
| 7962 | + if (typeof __test_queue_dlq_accepted === "function") { | |
| 7963 | + __test_queue_dlq_accepted(); | |
| 7964 | + } | |
| 7965 | + // The target committed every receipt before this reply. Delete the | |
| 7966 | + // corresponding source marks together; a stop before this transaction | |
| 7967 | + // leaves the whole group replayable through those stable receipts. | |
| 7968 | + this.ctx.storage.transactionSync(() => { | |
| 7969 | + for (const row of rows) { | |
| 7970 | + this._open().exec( | |
| 7971 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7972 | + WHERE seq = ? AND dlq_target = ? AND dlq_transfer_id = ? | |
| 7973 | + AND transfer_kind = ?`, | |
| 7974 | + row.seq, | |
| 7975 | + row.dlq_target, | |
| 7976 | + row.dlq_transfer_id, | |
| 7977 | + row.transfer_kind, | |
| 7978 | + ); | |
| 7979 | + } | |
| 7980 | + }); | |
| 7981 | + } | |
| 7982 | + return pending.length; | |
| 7983 | + } | |
| 7984 | + | |
| 7985 | + async alarm() { | |
| 7986 | + const now = Date.now(); | |
| 7987 | + try { | |
| 7988 | + await this._driveDlq(); | |
| 7989 | + } catch (error) { | |
| 7990 | + // The durable source mark is the retry record. An alarm stays armed at | |
| 7991 | + // `now`, and the target's transfer identity makes a replay idempotent. | |
| 7992 | + console.error("Queue DLQ transfer failed:", error); | |
| 7993 | + } | |
| 7994 | + const swept = this._sweep(now); | |
| 7995 | + const consumer = this._paused() | |
| 7996 | + ? undefined | |
| 7997 | + : __cell.queueConsumers?.[this.queue]; | |
| 7998 | + // Install every lease that the configured concurrency admits before the | |
| 7999 | + // first consumer can settle. One lease per alarm serialized full batches | |
| 8000 | + // because the next alarm depended on a later scheduler turn, so a queue | |
| 8001 | + // with maxConcurrency > 1 still used only one handler under backlog. | |
| 8002 | + // `_leaseBatch` counts the durable lease IDs on every iteration, which | |
| 8003 | + // makes the configured concurrency the structural bound for this loop. | |
| 8004 | + const batches = []; | |
| 8005 | + if (consumer !== undefined) { | |
| 8006 | + while (true) { | |
| 8007 | + const batch = await this._leaseBatch(now, consumer); | |
| 8008 | + if (batch === null) break; | |
| 8009 | + batches.push(batch); | |
| 8010 | + } | |
| 8011 | + } | |
| 8012 | + try { | |
| 8013 | + // `_leaseBatch` can exhaust an expired lease and create a new durable | |
| 8014 | + // DLQ mark. Drive that mark in the same wake; the first call above is | |
| 8015 | + // for a mark recovered from an earlier stopped process. | |
| 8016 | + await this._driveDlq(); | |
| 8017 | + } catch (error) { | |
| 8018 | + console.error("Queue DLQ transfer failed:", error); | |
| 8019 | + } | |
| 8020 | + await this._rearm(now); | |
| 8021 | + if (swept >= __queueLimits().sweepBatchRows && batches.length === 0) { | |
| 8022 | + await this.ctx.storage.setAlarm(now + 1); | |
| 8023 | + return; | |
| 8024 | + } | |
| 8025 | + for (const batch of batches) { | |
| 8026 | + // This await covers only the output-gated handoff to the host. The | |
| 8027 | + // consumer runs after this alarm returns, and settlement comes back as | |
| 8028 | + // an independent cell event. All admitted leases are durable before the | |
| 8029 | + // first handoff, so a fast settlement cannot make this turn exceed the | |
| 8030 | + // configured concurrency. | |
| 8031 | + await __queue_dispatch( | |
| 8032 | + consumer.script, | |
| 8033 | + this.queue, | |
| 8034 | + JSON.stringify(batch), | |
| 8035 | + ); | |
| 8036 | + } | |
| 8037 | + } | |
| 8038 | + | |
| 8039 | + _matchingLease(body) { | |
| 8040 | + if (typeof body.leaseId !== "string" || !Array.isArray(body.leases)) return null; | |
| 8041 | + const matchQuery = | |
| 8042 | + `SELECT seq, id, attempts, lease_generation, purge_on_settle | |
| 8043 | + FROM ${__QUEUE_MESSAGES} | |
| 8044 | + WHERE lease_id = ? | |
| 8045 | + ORDER BY seq`; | |
| 8046 | + __queueReportLeaseLookupPlan(this._open(), matchQuery, body.leaseId); | |
| 8047 | + const rows = this._open().exec(matchQuery, body.leaseId).toArray(); | |
| 8048 | + for (const lease of body.leases) { | |
| 8049 | + if (typeof lease?.message_id !== "string" || | |
| 8050 | + !Number.isSafeInteger(lease.seq) || | |
| 8051 | + !Number.isSafeInteger(lease.generation)) return null; | |
| 8052 | + } | |
| 8053 | + const matches = __queuePolicy({ | |
| 8054 | + op: "settlement", | |
| 8055 | + current: rows.map((row) => ({ | |
| 8056 | + seq: String(row.seq), | |
| 8057 | + messageId: row.id, | |
| 8058 | + generation: String(row.lease_generation), | |
| 8059 | + })), | |
| 8060 | + submitted: body.leases.map((lease) => ({ | |
| 8061 | + seq: String(lease.seq), | |
| 8062 | + messageId: lease.message_id, | |
| 8063 | + generation: String(lease.generation), | |
| 8064 | + })), | |
| 8065 | + }); | |
| 8066 | + return matches ? rows : null; | |
| 8067 | + } | |
| 8068 | + | |
| 8069 | + async _settle(body) { | |
| 8070 | + const rows = this._matchingLease(body); | |
| 8071 | + if (rows === null) return false; | |
| 8072 | + const consumer = __cell.queueConsumers?.[this.queue]; | |
| 8073 | + if (consumer === undefined) return false; | |
| 8074 | + const explicitAcks = new Set(body.explicitAcks ?? []); | |
| 8075 | + const retryMessages = new Map( | |
| 8076 | + (body.retryMessages ?? []).map((retry) => [retry.msgId, retry.delaySeconds]), | |
| 8077 | + ); | |
| 8078 | + const retryBatch = body.retryBatch?.retry === true; | |
| 8079 | + const batchDelay = body.retryBatch?.delaySeconds; | |
| 8080 | + const exception = body.outcome === "exception"; | |
| 8081 | + // An explicit ack-all survives a later handler exception, so it must | |
| 8082 | + // override every batch-level and message-level retry signal. | |
| 8083 | + const ackAll = body.ackAll === true; | |
| 8084 | + const decisions = rows.map((row) => { | |
| 8085 | + const retry = !ackAll && !explicitAcks.has(row.id) && ( | |
| 8086 | + retryMessages.has(row.id) || retryBatch || exception | |
| 8087 | + ); | |
| 8088 | + return { row, retry }; | |
| 8089 | + }); | |
| 8090 | + const retrying = decisions.filter((decision) => | |
| 8091 | + decision.retry && decision.row.purge_on_settle === 0 | |
| 8092 | + ); | |
| 8093 | + const retryPolicy = __queuePolicy({ | |
| 8094 | + op: "retries", | |
| 8095 | + now: Date.now(), | |
| 8096 | + entries: retrying.map(({ row }) => ({ | |
| 8097 | + attempt: row.attempts + 1, | |
| 8098 | + maxRetries: consumer.maxRetries, | |
| 8099 | + explicitSeconds: retryMessages.has(row.id) | |
| 8100 | + ? retryMessages.get(row.id) | |
| 8101 | + : retryBatch ? batchDelay : null, | |
| 8102 | + configuredSeconds: consumer.retryDelaySeconds ?? null, | |
| 8103 | + })), | |
| 8104 | + }); | |
| 8105 | + const retryById = new Map( | |
| 8106 | + retrying.map(({ row }, index) => [row.id, retryPolicy[index]]), | |
| 8107 | + ); | |
| 8108 | + const dlqTransferById = new Map( | |
| 8109 | + retrying | |
| 8110 | + .filter(({ row }) => | |
| 8111 | + retryById.get(row.id).exhausted && consumer.deadLetterQueue !== undefined | |
| 8112 | + ) | |
| 8113 | + .map(({ row }) => [row.id, crypto.randomUUID()]), | |
| 8114 | + ); | |
| 8115 | + const sql = this._open(); | |
| 8116 | + this.ctx.storage.transactionSync(() => { | |
| 8117 | + for (const { row, retry } of decisions) { | |
| 8118 | + const policy = retryById.get(row.id); | |
| 8119 | + if (row.purge_on_settle !== 0 || !retry || | |
| 8120 | + (policy.exhausted && consumer.deadLetterQueue === undefined)) { | |
| 8121 | + sql.exec( | |
| 8122 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 8123 | + WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 8124 | + row.seq, | |
| 8125 | + body.leaseId, | |
| 8126 | + row.lease_generation, | |
| 8127 | + ); | |
| 8128 | + continue; | |
| 8129 | + } | |
| 8130 | + if (policy.exhausted) { | |
| 8131 | + sql.exec( | |
| 8132 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 8133 | + SET attempts = attempts + 1, lease_id = NULL, | |
| 8134 | + leased_until = NULL, dlq_target = ?, dlq_transfer_id = ?, | |
| 8135 | + transfer_kind = 'dead-letter' | |
| 8136 | + WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 8137 | + consumer.deadLetterQueue, | |
| 8138 | + dlqTransferById.get(row.id), | |
| 8139 | + row.seq, | |
| 8140 | + body.leaseId, | |
| 8141 | + row.lease_generation, | |
| 8142 | + ); | |
| 8143 | + continue; | |
| 8144 | + } | |
| 8145 | + sql.exec( | |
| 8146 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 8147 | + SET attempts = attempts + 1, visible_at = ?, | |
| 8148 | + lease_id = NULL, leased_until = NULL | |
| 8149 | + WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 8150 | + policy.at, | |
| 8151 | + row.seq, | |
| 8152 | + body.leaseId, | |
| 8153 | + row.lease_generation, | |
| 8154 | + ); | |
| 8155 | + } | |
| 8156 | + }); | |
| 8157 | + try { | |
| 8158 | + await this._driveDlq(); | |
| 8159 | + } catch (error) { | |
| 8160 | + // Settlement is durable once the source mark commits. A failed transfer | |
| 8161 | + // is alarm work now, not a reason to put the message back in delivery. | |
| 8162 | + console.error("Queue DLQ transfer deferred:", error); | |
| 8163 | + } | |
| 8164 | + await this._rearm(); | |
| 8165 | + return true; | |
| 8166 | + } | |
| 8167 | + | |
| 8168 | + async _purge() { | |
| 8169 | + const now = Date.now(); | |
| 8170 | + const sql = this._open(); | |
| 8171 | + let deleted = 0; | |
| 8172 | + let leased = 0; | |
| 8173 | + this.ctx.storage.transactionSync(() => { | |
| 8174 | + let after = 0; | |
| 8175 | + while (true) { | |
| 8176 | + // Purge is necessarily proportional to the stored backlog, but its | |
| 8177 | + // policy envelope stays bounded instead of materializing the Queue in | |
| 8178 | + // V8 or Rust. One SQLite transaction keeps the visibility change | |
| 8179 | + // atomic across all chunks. | |
| 8180 | + const rows = sql.exec( | |
| 8181 | + `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} | |
| 8182 | + WHERE seq > ? | |
| 8183 | + ORDER BY seq | |
| 8184 | + LIMIT 256`, | |
| 8185 | + after, | |
| 8186 | + ).toArray(); | |
| 8187 | + if (rows.length === 0) break; | |
| 8188 | + after = rows[rows.length - 1].seq; | |
| 8189 | + const plan = __queuePolicy({ | |
| 8190 | + op: "purge", | |
| 8191 | + now, | |
| 8192 | + rows: rows.map((row) => ({ | |
| 8193 | + seq: String(row.seq), | |
| 8194 | + leaseIdPresent: row.lease_id !== null, | |
| 8195 | + leasedUntil: row.leased_until, | |
| 8196 | + })), | |
| 8197 | + }); | |
| 8198 | + for (const seq of plan.delete) { | |
| 8199 | + sql.exec( | |
| 8200 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 8201 | + WHERE seq = ? | |
| 8202 | + AND (lease_id IS NULL OR leased_until IS NULL OR leased_until <= ?)`, | |
| 8203 | + Number(seq), | |
| 8204 | + now, | |
| 8205 | + ); | |
| 8206 | + deleted += 1; | |
| 8207 | + } | |
| 8208 | + for (const seq of plan.markForSettle) { | |
| 8209 | + sql.exec( | |
| 8210 | + `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 | |
| 8211 | + WHERE seq = ? AND lease_id IS NOT NULL AND leased_until > ?`, | |
| 8212 | + Number(seq), | |
| 8213 | + now, | |
| 8214 | + ); | |
| 8215 | + leased += 1; | |
| 8216 | + } | |
| 8217 | + } | |
| 8218 | + }); | |
| 8219 | + await this._rearm(now); | |
| 8220 | + return { deleted, leased, metrics: this._metrics(now) }; | |
| 8221 | + } | |
| 8222 | + | |
| 8223 | + async _setPaused(paused) { | |
| 8224 | + this._setMeta("paused", paused ? "1" : null); | |
| 8225 | + await this._rearm(); | |
| 8226 | + return { paused, ...this._metrics() }; | |
| 8227 | + } | |
| 8228 | + | |
| 8229 | + _operatorLimit(value, fallback) { | |
| 8230 | + const limit = value ?? fallback; | |
| 8231 | + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { | |
| 8232 | + throw __queueError("limit must be an integer from 1 through 100"); | |
| 8233 | + } | |
| 8234 | + return limit; | |
| 8235 | + } | |
| 8236 | + | |
| 8237 | + _peek(limit) { | |
| 8238 | + const now = Date.now(); | |
| 8239 | + const cutoff = now - __queueLimits().retentionMs; | |
| 8240 | + const rows = this._open().exec( | |
| 8241 | + `SELECT id, body, content_type, size, enqueued_at, visible_at, attempts, | |
| 8242 | + lease_id, leased_until, purge_on_settle, dlq_target, | |
| 8243 | + dead_letter_source | |
| 8244 | + FROM ${__QUEUE_MESSAGES} | |
| 8245 | + WHERE enqueued_at > ? | |
| 8246 | + ORDER BY visible_at, seq | |
| 8247 | + LIMIT ?`, | |
| 8248 | + cutoff, | |
| 8249 | + limit, | |
| 8250 | + ).toArray(); | |
| 8251 | + return { | |
| 8252 | + messages: rows.map((row) => ({ | |
| 8253 | + id: row.id, | |
| 8254 | + bodyBase64: $$btoa( | |
| 8255 | + row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), | |
| 8256 | + ), | |
| 8257 | + contentType: row.content_type, | |
| 8258 | + size: row.size, | |
| 8259 | + enqueuedAt: row.enqueued_at, | |
| 8260 | + visibleAt: row.visible_at, | |
| 8261 | + attempts: row.attempts, | |
| 8262 | + state: row.dlq_target !== null | |
| 8263 | + ? "moving" | |
| 8264 | + : row.purge_on_settle !== 0 | |
| 8265 | + ? "purging" | |
| 8266 | + : row.lease_id !== null && row.leased_until > now | |
| 8267 | + ? "leased" | |
| 8268 | + : row.visible_at <= now | |
| 8269 | + ? "visible" | |
| 8270 | + : "delayed", | |
| 8271 | + leasedUntil: row.lease_id !== null && row.leased_until > now | |
| 8272 | + ? row.leased_until | |
| 8273 | + : null, | |
| 8274 | + transferTarget: row.dlq_target, | |
| 8275 | + deadLetterSource: row.dead_letter_source, | |
| 8276 | + })), | |
| 8277 | + }; | |
| 8278 | + } | |
| 8279 | + | |
| 8280 | + async _redrive(limit) { | |
| 8281 | + // Finish an interrupted move before selecting more work. A transfer mark | |
| 8282 | + // is durable, so selecting it a second time would invent another identity | |
| 8283 | + // where replaying the existing identity is sufficient. | |
| 8284 | + await this._driveDlq(100); | |
| 8285 | + const now = Date.now(); | |
| 8286 | + const cutoff = now - __queueLimits().retentionMs; | |
| 8287 | + const candidates = this._open().exec( | |
| 8288 | + `SELECT seq, dead_letter_source | |
| 8289 | + FROM ${__QUEUE_MESSAGES} | |
| 8290 | + WHERE dead_letter_source IS NOT NULL | |
| 8291 | + AND dlq_target IS NULL | |
| 8292 | + AND purge_on_settle = 0 | |
| 8293 | + AND enqueued_at > ? | |
| 8294 | + AND (lease_id IS NULL OR leased_until <= ?) | |
| 8295 | + ORDER BY visible_at, seq | |
| 8296 | + LIMIT ?`, | |
| 8297 | + cutoff, | |
| 8298 | + now, | |
| 8299 | + limit, | |
| 8300 | + ).toArray(); | |
| 8301 | + const transfers = candidates.map((row) => ({ | |
| 8302 | + ...row, | |
| 8303 | + transferId: crypto.randomUUID(), | |
| 8304 | + })); | |
| 8305 | + this.ctx.storage.transactionSync(() => { | |
| 8306 | + for (const transfer of transfers) { | |
| 8307 | + this._open().exec( | |
| 8308 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 8309 | + SET dlq_target = ?, dlq_transfer_id = ?, transfer_kind = 'redrive', | |
| 8310 | + lease_id = NULL, leased_until = NULL | |
| 8311 | + WHERE seq = ? AND dead_letter_source = ? AND dlq_target IS NULL | |
| 8312 | + AND purge_on_settle = 0 | |
| 8313 | + AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 8314 | + transfer.dead_letter_source, | |
| 8315 | + transfer.transferId, | |
| 8316 | + transfer.seq, | |
| 8317 | + transfer.dead_letter_source, | |
| 8318 | + now, | |
| 8319 | + ); | |
| 8320 | + } | |
| 8321 | + }); | |
| 8322 | + // Arm before the cross-cell call. If the process stops after the durable | |
| 8323 | + // mark, the alarm replays the same transfer identity. | |
| 8324 | + await this._rearm(now); | |
| 8325 | + await this._driveDlq(100); | |
| 8326 | + await this._rearm(); | |
| 8327 | + return { redriven: transfers.length, metrics: this._metrics() }; | |
| 8328 | + } | |
| 8329 | + | |
| 8330 | + async fetch(request) { | |
| 8331 | + const path = new URL(request.url).pathname; | |
| 8332 | + if (request.method !== "POST") { | |
| 8333 | + return new Response("Queue route not found", { status: 404 }); | |
| 8334 | + } | |
| 8335 | + let body; | |
| 8336 | + try { | |
| 8337 | + body = await request.json(); | |
| 8338 | + } catch { | |
| 8339 | + return new Response("invalid Queue request", { status: 400 }); | |
| 8340 | + } | |
| 8341 | + try { | |
| 8342 | + if (path === "/__qSettle") { | |
| 8343 | + return await this._settle(body) | |
| 8344 | + ? new Response(null, { status: 204 }) | |
| 8345 | + : new Response("stale Queue settlement", { status: 409 }); | |
| 8346 | + } | |
| 8347 | + if (body.op === "info") { | |
| 8348 | + const metrics = this._metrics(); | |
| 8349 | + const stored = this._open().exec( | |
| 8350 | + `SELECT stored_count FROM ${__QUEUE_STATS} WHERE id = 1`, | |
| 8351 | + ).toArray()[0].stored_count; | |
| 8352 | + return Response.json({ result: { ...metrics, stored, paused: this._paused() } }); | |
| 8353 | + } | |
| 8354 | + if (body.op === "purge") { | |
| 8355 | + return Response.json({ result: await this._purge() }); | |
| 8356 | + } | |
| 8357 | + if (body.op === "pause") { | |
| 8358 | + return Response.json({ result: await this._setPaused(true) }); | |
| 8359 | + } | |
| 8360 | + if (body.op === "resume") { | |
| 8361 | + return Response.json({ result: await this._setPaused(false) }); | |
| 8362 | + } | |
| 8363 | + if (body.op === "peek") { | |
| 8364 | + return Response.json({ | |
| 8365 | + result: this._peek(this._operatorLimit(body.limit, 10)), | |
| 8366 | + }); | |
| 8367 | + } | |
| 8368 | + if (body.op === "redrive") { | |
| 8369 | + return Response.json({ | |
| 8370 | + result: await this._redrive(this._operatorLimit(body.limit, 100)), | |
| 8371 | + }); | |
| 8372 | + } | |
| 8373 | + return Response.json( | |
| 8374 | + { error: `QUEUE_ERROR: unknown operation ${JSON.stringify(body.op)}` }, | |
| 8375 | + { status: 400 }, | |
| 8376 | + ); | |
| 8377 | + } catch (error) { | |
| 8378 | + return Response.json( | |
| 8379 | + { error: String(error?.message ?? error) }, | |
| 8380 | + { status: 400 }, | |
| 8381 | + ); | |
| 8382 | + } | |
| 8383 | + } | |
| 8384 | +} | |
| 8385 | + | |
| 8386 | +__cell.classes.__Queue = __QueueCell; | |
| 8387 | +__cell.doExports.__Queue = true; | |
| 8388 | + | |
| 8389 | +class Queue { | |
| 8390 | + constructor(queue, cellName, deliveryDelay) { | |
| 8391 | + Object.defineProperties(this, { | |
| 8392 | + _queue: { value: queue }, | |
| 8393 | + _cellName: { value: cellName }, | |
| 8394 | + _deliveryDelay: { value: deliveryDelay }, | |
| 8395 | + }); | |
| 8396 | + } | |
| 8397 | + | |
| 8398 | + get _stub() { | |
| 8399 | + return __cell.makeNamespace("__Queue").getByName(this._cellName); | |
| 8400 | + } | |
| 8401 | + | |
| 8402 | + async _send(entries) { | |
| 8403 | + const metrics = await this._stub.__queueSend({ entries }); | |
| 8404 | + return { metadata: { metrics: __queueMetricsView(metrics) } }; | |
| 8405 | + } | |
| 8406 | + | |
| 8407 | + send(body, options = {}) { | |
| 8408 | + const encoded = __queueEncode(body, options.contentType); | |
| 8409 | + return this._send([{ | |
| 8410 | + ...encoded, | |
| 8411 | + delaySeconds: __queueDelay(options.delaySeconds, this._deliveryDelay), | |
| 8412 | + }]); | |
| 8413 | + } | |
| 8414 | + | |
| 8415 | + sendBatch(messages, options = {}) { | |
| 8416 | + if (messages === null || messages === undefined || | |
| 8417 | + typeof messages[Symbol.iterator] !== "function") { | |
| 8418 | + throw __queueError("sendBatch() needs an iterable of messages"); | |
| 8419 | + } | |
| 8420 | + const entries = []; | |
| 8421 | + let bytes = 0; | |
| 8422 | + const batchDelay = __queueDelay(options.delaySeconds, this._deliveryDelay); | |
| 8423 | + for (const message of messages) { | |
| 8424 | + if (entries.length >= __queueLimits().maxBatchMessages) { | |
| 8425 | + throw __queueError( | |
| 8426 | + `a batch has at most ${__queueLimits().maxBatchMessages} messages`, | |
| 8427 | + ); | |
| 8428 | + } | |
| 8429 | + if (message === null || typeof message !== "object" || !("body" in message)) { | |
| 8430 | + throw __queueError("each batch entry needs a body"); | |
| 8431 | + } | |
| 8432 | + const encoded = __queueEncode(message.body, message.contentType); | |
| 8433 | + bytes += encoded.size; | |
| 8434 | + if (bytes > __queueLimits().maxBatchBytes) { | |
| 8435 | + throw __queueError( | |
| 8436 | + `a batch is at most ${__queueLimits().maxBatchBytes} bytes, got ${bytes}`, | |
| 8437 | + ); | |
| 8438 | + } | |
| 8439 | + entries.push({ | |
| 8440 | + ...encoded, | |
| 8441 | + delaySeconds: __queueDelay(message.delaySeconds, batchDelay), | |
| 8442 | + }); | |
| 8443 | + } | |
| 8444 | + if (entries.length === 0) { | |
| 8445 | + throw __queueError("sendBatch() needs at least one message"); | |
| 8446 | + } | |
| 8447 | + return this._send(entries); | |
| 8448 | + } | |
| 8449 | + | |
| 8450 | + async metrics() { | |
| 8451 | + return __queueMetricsView(await this._stub.__queueMetrics()); | |
| 8452 | + } | |
| 8453 | +} | |
| 8454 | + | |
| 8455 | +__celld.__makeQueue = (queue, cellName, deliveryDelay) => | |
| 8456 | + new Queue(queue, cellName, deliveryDelay); | |
| 8457 | + | |
| 8458 | +// ---- D1 ----------------------------------------------------------------- | |
| 8459 | +// A D1 database is a cell of a runtime-supplied Durable Object class, so it | |
| 8460 | +// inherits ownership, fencing, LTX replication, RPO=0 acknowledgement and | |
| 8461 | +// pressure shedding from the cell it already is. This half is the server; | |
| 8462 | +// `__makeD1Database` below is the client the binding hands to a Worker. | |
| 8463 | +// | |
| 8464 | +// Everything SQL goes through the one `__d1_run` op. The engine owns the | |
| 8465 | +// statement walk, the row and byte caps, and the meta snapshot, all inside | |
| 8466 | +// one execution -- the previous shape assembled these from the general | |
| 8467 | +// SqlStorage ops, and every seam between them was a contract only convention | |
| 8468 | +// enforced. | |
| 8469 | + | |
| 8470 | +// The error families applications match on. A message that already carries | |
| 8471 | +// one must pass through unwrapped: wrapping again would bury the family the | |
| 8472 | +// application is matching under a second D1_ERROR prefix. | |
| 8473 | +const __d1IsFamilyError = (message) => | |
| 8474 | + /^D1_([A-Z]+_)*(ERROR|NOTFOUND): /.test(String(message)); | |
| 8475 | + | |
| 8476 | +const __d1Error = (message, cause) => { | |
| 8477 | + const error = new Error("D1_ERROR: " + String(message)); | |
| 8478 | + error.cause = cause !== undefined ? cause : new Error(String(message)); | |
| 8479 | + return error; | |
| 8480 | +}; | |
| 8481 | + | |
| 8482 | +// A typed refusal from the engine: `{family, message}` becomes the Error the | |
| 8483 | +// application sees, with `.cause` carrying the bare message as upstream does. | |
| 8484 | +const __d1Failure = (failure) => { | |
| 8485 | + const error = new Error(failure.family + ": " + failure.message); | |
| 8486 | + error.cause = new Error(failure.message); | |
| 8487 | + return error; | |
| 8488 | +}; | |
| 8489 | + | |
| 8490 | +const __d1Run = (scope, request) => { | |
| 8491 | + const response = JSON.parse(__d1_run(scope, JSON.stringify(request))); | |
| 8492 | + if (response.error) throw __d1Failure(response.error); | |
| 8493 | + return response.ok; | |
| 8494 | +}; | |
| 8495 | + | |
| 8496 | +class __D1DatabaseCell { | |
| 8497 | + constructor(ctx) { | |
| 8498 | + this.ctx = ctx; | |
| 8499 | + } | |
| 8500 | + // Takes an array so that `batch()` can ride this same method, and the | |
| 8501 | + // same turn, when it lands. | |
| 8502 | + __d1Query(statements) { | |
| 8503 | + const scope = this.ctx.storage.sql._scope; | |
| 8504 | + return statements.map((statement) => | |
| 8505 | + __d1Run(scope, { | |
| 8506 | + mode: "prepared", | |
| 8507 | + sql: String(statement.sql), | |
| 8508 | + params: statement.params || [], | |
| 8509 | + first: !!statement.first, | |
| 8510 | + }) | |
| 8511 | + ); | |
| 8512 | + } | |
| 8513 | + __d1Batch(statements) { | |
| 8514 | + return __d1Run(this.ctx.storage.sql._scope, { | |
| 8515 | + mode: "batch", | |
| 8516 | + statements: statements.map((statement) => ({ | |
| 8517 | + sql: String(statement.sql), | |
| 8518 | + params: statement.params || [], | |
| 8519 | + })), | |
| 8520 | + }); | |
| 8521 | + } | |
| 8522 | + // The CLI's way in. `celld d1` signs each request with the fleet secret | |
| 8523 | + // and sends it to a live node's `/runtime/<scope>` route, which verifies the | |
| 8524 | + // signature and then forwards to the owner over the same dispatch `/do/` | |
| 8525 | + // uses -- so the CLI needs no ownership logic and the database is reached | |
| 8526 | + // the way a Worker reaches it. The unauthenticated `/do/` route refuses a | |
| 8527 | + // D1 scope outright: this cell answers arbitrary SQL, and its scope is an | |
| 8528 | + // HMAC over names that sit in the project's config, so the scope itself | |
| 8529 | + // is no secret. | |
| 8530 | + async fetch(request) { | |
| 8531 | + let body; | |
| 8532 | + try { | |
| 8533 | + body = await request.json(); | |
| 8534 | + } catch { | |
| 8535 | + return Response.json({ error: "D1_ERROR: invalid request body" }, { status: 400 }); | |
| 8536 | + } | |
| 8537 | + try { | |
| 8538 | + let result; | |
| 8539 | + if (body.migrate !== undefined) { | |
| 8540 | + result = this.__d1Migrate( | |
| 8541 | + String(body.migrate.name), | |
| 8542 | + String(body.migrate.sql), | |
| 8543 | + String(body.migrate.table || "d1_migrations"), | |
| 8544 | + ); | |
| 8545 | + } else if (body.exec !== undefined) { | |
| 8546 | + // The CLI asks for rows; the Worker binding's exec() never does. | |
| 8547 | + result = __d1Run(this.ctx.storage.sql._scope, { | |
| 8548 | + mode: "exec", | |
| 8549 | + sql: String(body.exec.sql), | |
| 8550 | + rows: !!body.exec.rows, | |
| 8551 | + }); | |
| 8552 | + } else { | |
| 8553 | + result = this.__d1Query(body.statements || []); | |
| 8554 | + } | |
| 8555 | + return Response.json({ result }); | |
| 8556 | + } catch (error) { | |
| 8557 | + return Response.json({ error: String(error && error.message || error) }, { status: 400 }); | |
| 8558 | + } | |
| 8559 | + } | |
| 8560 | + __d1Exec(source) { | |
| 8561 | + const result = __d1Run(this.ctx.storage.sql._scope, { | |
| 8562 | + mode: "exec", | |
| 8563 | + sql: String(source), | |
| 8564 | + rows: false, | |
| 8565 | + }); | |
| 8566 | + return { count: result.count, duration: result.duration }; | |
| 8567 | + } | |
| 8568 | + // Apply one migration and record it. The engine runs the file, the | |
| 8569 | + // bookkeeping insert (the name is a bound parameter, so a file name never | |
| 8570 | + // reaches SQL text) and the BEGIN IMMEDIATE .. COMMIT bracket in one | |
| 8571 | + // request, so a migration that fails part-way rolls back whole and the | |
| 8572 | + // operator fixes the file and re-runs. Without the transaction the | |
| 8573 | + // statements that DID land are exactly the ones a re-run trips over. | |
| 8574 | + __d1Migrate(name, source, table) { | |
| 8575 | + return __d1Run(this.ctx.storage.sql._scope, { | |
| 8576 | + mode: "migrate", | |
| 8577 | + name, | |
| 8578 | + sql: source, | |
| 8579 | + table, | |
| 8580 | + }); | |
| 8581 | + } | |
| 8582 | +} | |
| 8583 | + | |
| 8584 | +__cell.classes.__D1Database = __D1DatabaseCell; | |
| 8585 | +// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class | |
| 8586 | +// is the runtime's own, so grant it here instead of making every D1 user set | |
| 8587 | +// a compatibility flag to reach their database. | |
| 8588 | +__cell.doExports.__D1Database = true; | |
| 8589 | + | |
| 8590 | +// Validate and encode bind values once, at the public boundary, exactly as | |
| 8591 | +// upstream does (workerd d1-api.ts). Byte-shaped values become byte arrays -- | |
| 8592 | +// the wire format for a BLOB bind -- and anything unsupported throws | |
| 8593 | +// D1_TYPE_ERROR here, before any SQL runs. The first version deferred this | |
| 8594 | +// to a JSON round-trip whose fallthrough was SQL NULL, so a Uint8Array bind | |
| 8595 | +// stored NULL and nothing said so. | |
| 8596 | +const __d1BindValue = (value) => { | |
| 8597 | + const kind = typeof value; | |
| 8598 | + if (kind === "number") { | |
| 8599 | + // A non-finite number has no JSON form, so it crosses as null and | |
| 8600 | + // stores SQL NULL. Upstream does the same (bind(NaN) selects typeof | |
| 8601 | + // "null"); making it explicit here turns the conversion from an | |
| 8602 | + // accident of JSON.stringify into a pinned decision. | |
| 8603 | + return Number.isFinite(value) ? value : null; | |
| 8604 | + } | |
| 8605 | + if (kind === "string") return value; | |
| 8606 | + if (kind === "boolean") return value ? 1 : 0; | |
| 8607 | + if (kind === "object") { | |
| 8608 | + if (value === null) return value; | |
| 8609 | + if ( | |
| 8610 | + Array.isArray(value) && | |
| 8611 | + value.every((byte) => typeof byte === "number" && byte >= 0 && byte < 256) | |
| 8612 | + ) { | |
| 8613 | + return value; | |
| 8614 | + } | |
| 8615 | + if (value instanceof ArrayBuffer) { | |
| 8616 | + return Array.from(new Uint8Array(value)); | |
| 8617 | + } | |
| 8618 | + // A typed view binds its ELEMENT values, each truncated to a byte -- | |
| 8619 | + // Int8Array([-1]) stores 0xff, Float32Array([1.5]) stores 0x01 -- not | |
| 8620 | + // its underlying byte window, so Uint16Array([65, 66]) stores 2 bytes | |
| 8621 | + // and not 4. Upstream behaves this way (verified against workerd's D1; | |
| 8622 | + // the differential suite pins it), and the bare Array.from that | |
| 8623 | + // preceded this produced elements the engine then refused as bytes. | |
| 8624 | + if (ArrayBuffer.isView(value)) return Array.from(Uint8Array.from(value)); | |
| 8625 | + } | |
| 8626 | + const error = new Error( | |
| 8627 | + `D1_TYPE_ERROR: Type '${kind}' not supported for value '${value}'`, | |
| 8628 | + ); | |
| 8629 | + error.cause = new Error(`Type '${kind}' not supported for value '${value}'`); | |
| 8630 | + throw error; | |
| 8631 | +}; | |
| 8632 | + | |
| 8633 | +class D1PreparedStatement { | |
| 8634 | + constructor(database, sql, params) { | |
| 8635 | + Object.defineProperty(this, "_database", { value: database }); | |
| 8636 | + Object.defineProperty(this, "_sql", { value: sql }); | |
| 8637 | + Object.defineProperty(this, "_params", { value: params }); | |
| 8638 | + } | |
| 8639 | + bind(...values) { | |
| 8640 | + return new D1PreparedStatement( | |
| 8641 | + this._database, | |
| 8642 | + this._sql, | |
| 8643 | + values.map(__d1BindValue), | |
| 8644 | + ); | |
| 8645 | + } | |
| 8646 | + async _run(first) { | |
| 8647 | + const results = await this._database._query([ | |
| 8648 | + { sql: this._sql, params: this._params, first }, | |
| 8649 | + ]); | |
| 8650 | + return results[0]; | |
| 8651 | + } | |
| 8652 | + async all() { | |
| 8653 | + const result = await this._run(); | |
| 8654 | + return { | |
| 8655 | + success: true, | |
| 8656 | + meta: result.meta, | |
| 8657 | + results: result.rows.map((row) => __d1Shape(result.columns, row)), | |
| 8658 | + }; | |
| 8659 | + } | |
| 8660 | + async run() { | |
| 8661 | + return await this.all(); | |
| 8662 | + } | |
| 8663 | + async first(column) { | |
| 8664 | + // `first: true` keeps one row on the cell side, so only that row crosses | |
| 8665 | + // the isolate boundary and the row cap cannot fire for a first(). | |
| 8666 | + const result = await this._run(true); | |
| 8667 | + if (result.rows.length === 0) return null; | |
| 8668 | + const row = __d1Shape(result.columns, result.rows[0]); | |
| 8669 | + if (column === undefined) return row; | |
| 8670 | + // The check runs on the shaped object, as upstream's does, so a column | |
| 8671 | + // named like an Object.prototype member behaves the same here as there. | |
| 8672 | + if (row[column] === undefined) { | |
| 8673 | + const error = new Error( | |
| 8674 | + `D1_COLUMN_NOTFOUND: Column not found (${column})`, | |
| 8675 | + ); | |
| 8676 | + error.cause = new Error("Column not found"); | |
| 8677 | + throw error; | |
| 8678 | + } | |
| 8679 | + return row[column]; | |
| 8680 | + } | |
| 8681 | + async raw(options) { | |
| 8682 | + const result = await this._run(); | |
| 8683 | + return options && options.columnNames | |
| 8684 | + ? [result.columns, ...result.rows] | |
| 8685 | + : result.rows; | |
| 8686 | + } | |
| 8687 | +} | |
| 8688 | + | |
| 8689 | +// Object.fromEntries, not property assignment: assigning to a column named | |
| 8690 | +// `__proto__` would walk the prototype chain and silently drop the value, | |
| 8691 | +// while fromEntries defines an own property whatever the name. | |
| 8692 | +const __d1Shape = (columns, row) => | |
| 8693 | + Object.fromEntries(row.map((value, index) => [columns[index], value])); | |
| 8694 | + | |
| 8695 | +const __d1PublicResult = (result) => ({ | |
| 8696 | + success: true, | |
| 8697 | + meta: result.meta, | |
| 8698 | + results: result.rows.map((row) => __d1Shape(result.columns, row)), | |
| 8699 | +}); | |
| 8700 | + | |
| 8701 | +// celld has one primary and no replicas, so every completed query satisfies | |
| 8702 | +// every earlier session constraint. One stable opaque token states that fact | |
| 8703 | +// without pretending an isolate-local counter is a durable database position. | |
| 8704 | +const __d1PrimaryBookmark = "celld:primary"; | |
| 8705 | + | |
| 8706 | +class D1DatabaseSession { | |
| 8707 | + constructor(database, constraintOrBookmark) { | |
| 8708 | + Object.defineProperty(this, "_database", { value: database }); | |
| 8709 | + const value = constraintOrBookmark == null | |
| 8710 | + ? "first-unconstrained" | |
| 8711 | + : String(constraintOrBookmark).trim(); | |
| 8712 | + if (!value) { | |
| 8713 | + throw new Error("D1_SESSION_ERROR: invalid bookmark or constraint"); | |
| 8714 | + } | |
| 8715 | + Object.defineProperty(this, "_bookmark", { | |
| 8716 | + value: value === "first-primary" || value === "first-unconstrained" ? null : value, | |
| 8717 | + writable: true, | |
| 8718 | + }); | |
| 8719 | + } | |
| 8720 | + _advanceBookmark() { | |
| 8721 | + this._bookmark = __d1PrimaryBookmark; | |
| 8722 | + } | |
| 8723 | + async _query(statements) { | |
| 8724 | + const results = await this._database._query(statements); | |
| 8725 | + this._advanceBookmark(); | |
| 8726 | + return results; | |
| 8727 | + } | |
| 8728 | + prepare(sql) { | |
| 8729 | + return new D1PreparedStatement(this, String(sql), []); | |
| 8730 | + } | |
| 8731 | + async batch(statements) { | |
| 8732 | + const results = await this._database._batch(statements); | |
| 8733 | + this._advanceBookmark(); | |
| 8734 | + return results; | |
| 8735 | + } | |
| 8736 | + getBookmark() { | |
| 8737 | + return this._bookmark; | |
| 8738 | + } | |
| 8739 | +} | |
| 8740 | + | |
| 8741 | +// Named so SDKs that sniff a binding by `constructor.name` recognise it. | |
| 8742 | +class D1Database { | |
| 8743 | + constructor(databaseName) { | |
| 8744 | + Object.defineProperty(this, "_databaseName", { value: databaseName }); | |
| 8745 | + } | |
| 8746 | + // Resolved per call rather than cached: a cell can move between calls, and | |
| 8747 | + // `getByName` is the same cost the Durable Object path already pays. | |
| 8748 | + get _stub() { | |
| 8749 | + return __cell.makeNamespace("__D1Database").getByName(this._databaseName); | |
| 8750 | + } | |
| 8751 | + async _query(statements) { | |
| 8752 | + try { | |
| 8753 | + return await this._stub.__d1Query(statements); | |
| 8754 | + } catch (error) { | |
| 8755 | + if (__d1IsFamilyError(error && error.message)) throw error; | |
| 8756 | + throw __d1Error(String(error && error.message || error), error); | |
| 8757 | + } | |
| 8758 | + } | |
| 8759 | + async _batch(statements) { | |
| 8760 | + try { | |
| 8761 | + const encoded = statements.map((statement) => ({ | |
| 8762 | + sql: statement._sql, | |
| 8763 | + params: statement._params, | |
| 8764 | + })); | |
| 8765 | + const results = await this._stub.__d1Batch(encoded); | |
| 8766 | + return results.map(__d1PublicResult); | |
| 8767 | + } catch (error) { | |
| 8768 | + if (__d1IsFamilyError(error && error.message)) throw error; | |
| 8769 | + throw __d1Error(String(error && error.message || error), error); | |
| 8770 | + } | |
| 8771 | + } | |
| 8772 | + prepare(sql) { | |
| 8773 | + return new D1PreparedStatement(this, String(sql), []); | |
| 8774 | + } | |
| 8775 | + async exec(sql) { | |
| 8776 | + try { | |
| 8777 | + return await this._stub.__d1Exec(String(sql)); | |
| 8778 | + } catch (error) { | |
| 8779 | + if (__d1IsFamilyError(error && error.message)) throw error; | |
| 8780 | + throw __d1Error(String(error && error.message || error), error); | |
| 8781 | + } | |
| 8782 | + } | |
| 8783 | + async batch(statements) { | |
| 8784 | + return await this._batch(statements); | |
| 8785 | + } | |
| 8786 | + withSession(constraintOrBookmark) { | |
| 8787 | + return new D1DatabaseSession(this, constraintOrBookmark); | |
| 8788 | + } | |
| 8789 | + async dump() { | |
| 8790 | + throw __d1Error( | |
| 8791 | + "dump() is not implemented in celld; the database is a SQLite file in " + | |
| 8792 | + "your own bucket", | |
| 8793 | + ); | |
| 8794 | + } | |
| 8795 | +} | |
| 8796 | + | |
| 8797 | +const __makeD1Database = __celld.__makeD1Database = | |
| 8798 | + (databaseName) => new D1Database(databaseName); | |
| 8799 | +// ---- Workflows ---------------------------------------------------------- | |
| 8800 | +// A workflow instance is one cell of the runtime-supplied `__Workflow` class, | |
| 8801 | +// named `<workflow_name>/<instance_id>` through getByName, so it inherits | |
| 8802 | +// ownership, fencing, LTX replication and the output gate from the cell it | |
| 8803 | +// already is. Execution is replay: `run()` re-executes from the top on every | |
| 8804 | +// resume and only steps are memoized, in `ctx.storage` KV under `__wf.*`. | |
| 8805 | +// This half is the server; `__makeWorkflow` below is the client the binding | |
| 8806 | +// hands to a Worker. The public contract is in docs/cloudflare-compat.md. | |
| 8807 | + | |
| 8808 | +// Upstream's limit for a step return, an event payload, and the params. The | |
| 8809 | +// error is distinct and names the step, because "too large" and "the isolate | |
| 8810 | +// died" must not read the same (the D1 row-cap precedent). | |
| 8811 | +const __WF_VALUE_CAP = 1 << 20; | |
| 8812 | +// Workflow names, instance ids, and event types all share this charset. | |
| 8813 | +// `/` is outside it, which is what makes the `<name>/<id>` cell-name join | |
| 8814 | +// unambiguous. | |
| 8815 | +const __WF_NAME_RE = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/; | |
| 8816 | +const __wfError = (message) => new Error("WORKFLOW_ERROR: " + message); | |
| 8817 | +// The suspension primitive: a blocked step returns a promise that never | |
| 8818 | +// settles in this invocation, so user code simply stops progressing. A | |
| 8819 | +// sentinel thrown through user code was rejected because `Promise.all` in | |
| 8820 | +// `run()` would observe it as a rejection and user try/catch would eat it. | |
| 8821 | +const __wfNever = new Promise(() => {}); | |
| 8822 | +const __wfTerminal = (status) => | |
| 8823 | + status === "complete" || status === "errored" || status === "terminated"; | |
| 8824 | +// Upstream's hard bounds: 10,000 retries per step, 365 days for any sleep or | |
| 8825 | +// event wait, one second under a waitForEvent timeout. Enforced loudly at the | |
| 8826 | +// call site -- a config outside them would otherwise misbehave only after | |
| 8827 | +// the instance is minutes or days into its run. | |
| 8828 | +const __WF_RETRY_LIMIT_CAP = 10000; | |
| 8829 | +const __WF_STEP_NAME_LIMIT = 256; | |
| 8830 | +const __WF_MAX_WAIT_MS = 365 * 86400000; | |
| 8831 | +const __WF_MIN_EVENT_TIMEOUT_MS = 1000; | |
| 8832 | +// celld has no account plans, so it exposes the larger published retention | |
| 8833 | +// ceiling as one stable application limit. Both an omitted policy and an | |
| 8834 | +// omitted member of a partial policy use this value. | |
| 8835 | +const __WF_RETENTION_MAX_MS = 30 * 86400000; | |
| 8836 | +const __WF_LOCATION_HINTS = new Set([ | |
| 8837 | + "wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", | |
| 8838 | + "oc", "afr", "me", | |
| 8839 | +]); | |
| 8840 | +// How long run() can stay pending on non-step work while no step runs and | |
| 8841 | +// none is blocked before the instance fails. Upstream permits un-stepped | |
| 8842 | +// awaits between steps (they are merely non-durable), so erroring at the | |
| 8843 | +// first quiescent macrotask would kill any run() whose external await | |
| 8844 | +// outlives one turn of the loop. Sixty seconds is long enough for any | |
| 8845 | +// sane un-stepped await and short enough that a truly never-settling | |
| 8846 | +// promise fails the instance instead of wedging the alarm handler. | |
| 8847 | +const __WF_STALL_GRACE_MS = 60000; | |
| 8848 | +const __WF_UNITS = { | |
| 8849 | + second: 1000, | |
| 8850 | + minute: 60000, | |
| 8851 | + hour: 3600000, | |
| 8852 | + day: 86400000, | |
| 8853 | + week: 604800000, | |
| 8854 | + // Upstream does not document its month/year arithmetic; fixed 30/365-day | |
| 8855 | + // units are used so one expression cannot mean two durations depending on | |
| 8856 | + // when it runs. | |
| 8857 | + month: 30 * 86400000, | |
| 8858 | + year: 365 * 86400000, | |
| 8859 | +}; | |
| 8860 | +const __wfDuration = (value, what) => { | |
| 8861 | + if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value; | |
| 8862 | + if (typeof value !== "string") { | |
| 8863 | + throw __wfError( | |
| 8864 | + `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + | |
| 8865 | + 'or "<n> <second|minute|hour|day|week|month|year>[s]"', | |
| 8866 | + ); | |
| 8867 | + } | |
| 8868 | + const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week|month|year)s?\s*$/ | |
| 8869 | + .exec(value); | |
| 8870 | + if (!match) { | |
| 8871 | + throw __wfError( | |
| 8872 | + `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + | |
| 8873 | + 'or "<n> <second|minute|hour|day|week|month|year>[s]"', | |
| 8874 | + ); | |
| 8875 | + } | |
| 8876 | + return Number(match[1]) * __WF_UNITS[match[2]]; | |
| 8877 | +}; | |
| 8878 | +const __wfRetentionDuration = (value, what) => { | |
| 8879 | + const durationMs = __wfDuration(value, what); | |
| 8880 | + if (durationMs > __WF_RETENTION_MAX_MS) { | |
| 8881 | + throw __wfError( | |
| 8882 | + `${what} is ${durationMs} ms, above celld's 30-day retention limit`, | |
| 8883 | + ); | |
| 8884 | + } | |
| 8885 | + return durationMs; | |
| 8886 | +}; | |
| 8887 | +const __wfOwnObject = (value) => | |
| 8888 | + value !== null && typeof value === "object" && !Array.isArray(value); | |
| 8889 | +const __wfUnknownKey = (value, allowed) => | |
| 8890 | + Object.keys(value).find((key) => !allowed.includes(key)); | |
| 8891 | +const __wfStepName = (name) => { | |
| 8892 | + // The pinned workers-sdk validator has no minimum length. An empty name is | |
| 8893 | + // therefore valid, although rejecting it looks safer at first glance. A | |
| 8894 | + // non-empty check made celld reject Worker code that the upstream runtime | |
| 8895 | + // accepts, so keep only the upstream length and control-character bounds. | |
| 8896 | + if ( | |
| 8897 | + typeof name !== "string" || name.length > __WF_STEP_NAME_LIMIT || | |
| 8898 | + /[\x00-\x1f]/.test(name) | |
| 8899 | + ) { | |
| 8900 | + throw __wfError( | |
| 8901 | + `invalid step name ${JSON.stringify(name)}: use at most ` + | |
| 8902 | + `${__WF_STEP_NAME_LIMIT} characters and no control characters`, | |
| 8903 | + ); | |
| 8904 | + } | |
| 8905 | +}; | |
| 8906 | +const __wfEventType = (type) => { | |
| 8907 | + if (typeof type !== "string" || type.length > 100 || !__WF_NAME_RE.test(type)) { | |
| 8908 | + throw __wfError( | |
| 8909 | + `invalid event type ${JSON.stringify(type)}: use at most 100 letters, ` + | |
| 8910 | + "digits, hyphens, or underscores", | |
| 8911 | + ); | |
| 8912 | + } | |
| 8913 | +}; | |
| 8914 | +const __wfSleepDuration = (duration, name) => { | |
| 8915 | + const durationMs = __wfDuration( | |
| 8916 | + duration, | |
| 8917 | + `the duration of sleep ${JSON.stringify(name)}`, | |
| 8918 | + ); | |
| 8919 | + if (durationMs > __WF_MAX_WAIT_MS) { | |
| 8920 | + throw __wfError( | |
| 8921 | + `sleep ${JSON.stringify(name)} is ${durationMs} ms, above the upstream ` + | |
| 8922 | + "limit of 365 days", | |
| 8923 | + ); | |
| 8924 | + } | |
| 8925 | + return durationMs; | |
| 8926 | +}; | |
| 8927 | +const __wfSleepUntil = (timestamp, name) => { | |
| 8928 | + const at = timestamp instanceof Date ? timestamp.getTime() : timestamp; | |
| 8929 | + if (typeof at !== "number" || !Number.isFinite(at)) { | |
| 8930 | + throw __wfError( | |
| 8931 | + `invalid sleepUntil timestamp for ${JSON.stringify(name)}: use a Date ` + | |
| 8932 | + "or a UNIX timestamp in milliseconds", | |
| 8933 | + ); | |
| 8934 | + } | |
| 8935 | + const delay = at - Date.now(); | |
| 8936 | + if (delay > __WF_MAX_WAIT_MS) { | |
| 8937 | + throw __wfError( | |
| 8938 | + `sleepUntil ${JSON.stringify(name)} is ${delay} ms away, above the ` + | |
| 8939 | + "upstream limit of 365 days", | |
| 8940 | + ); | |
| 8941 | + } | |
| 8942 | + return at; | |
| 8943 | +}; | |
| 8944 | +const __wfWaitOptions = (options, name) => { | |
| 8945 | + if (!__wfOwnObject(options)) { | |
| 8946 | + throw __wfError(`invalid waitForEvent options for ${JSON.stringify(name)}`); | |
| 8947 | + } | |
| 8948 | + __wfEventType(options.type); | |
| 8949 | + const timeout = options.timeout ?? "24 hours"; | |
| 8950 | + const timeoutMs = __wfDuration( | |
| 8951 | + timeout, | |
| 8952 | + `the timeout of waitForEvent ${JSON.stringify(name)}`, | |
| 8953 | + ); | |
| 8954 | + if (timeoutMs < __WF_MIN_EVENT_TIMEOUT_MS || timeoutMs > __WF_MAX_WAIT_MS) { | |
| 8955 | + throw __wfError( | |
| 8956 | + `the timeout of waitForEvent ${JSON.stringify(name)} is ${timeoutMs} ms; ` + | |
| 8957 | + "upstream allows 1 second to 365 days", | |
| 8958 | + ); | |
| 8959 | + } | |
| 8960 | + return { type: options.type, timeout, timeoutMs }; | |
| 8961 | +}; | |
| 8962 | +const __wfEventOptions = (options) => { | |
| 8963 | + if (!__wfOwnObject(options)) { | |
| 8964 | + throw __wfError("sendEvent() needs an event object"); | |
| 8965 | + } | |
| 8966 | + __wfEventType(options.type); | |
| 8967 | + if (options.payload !== undefined) __wfCheckValue(options.payload, "the event payload"); | |
| 8968 | + return { type: options.type, payload: options.payload }; | |
| 8969 | +}; | |
| 8970 | +const __wfRetentionOptions = (retention, what) => { | |
| 8971 | + if (retention === undefined) { | |
| 8972 | + return { | |
| 8973 | + successMs: __WF_RETENTION_MAX_MS, | |
| 8974 | + errorMs: __WF_RETENTION_MAX_MS, | |
| 8975 | + }; | |
| 8976 | + } | |
| 8977 | + if (!__wfOwnObject(retention)) { | |
| 8978 | + throw __wfError(`${what} option retention must be an object`); | |
| 8979 | + } | |
| 8980 | + const unknown = __wfUnknownKey(retention, ["successRetention", "errorRetention"]); | |
| 8981 | + if (unknown !== undefined) { | |
| 8982 | + throw __wfError( | |
| 8983 | + `${what} option retention has an unknown field ${JSON.stringify(unknown)}`, | |
| 8984 | + ); | |
| 8985 | + } | |
| 8986 | + return { | |
| 8987 | + successMs: retention.successRetention === undefined | |
| 8988 | + ? __WF_RETENTION_MAX_MS | |
| 8989 | + : __wfRetentionDuration( | |
| 8990 | + retention.successRetention, | |
| 8991 | + `${what} successRetention`, | |
| 8992 | + ), | |
| 8993 | + errorMs: retention.errorRetention === undefined | |
| 8994 | + ? __WF_RETENTION_MAX_MS | |
| 8995 | + : __wfRetentionDuration(retention.errorRetention, `${what} errorRetention`), | |
| 8996 | + }; | |
| 8997 | +}; | |
| 8998 | +const __wfLocationHint = (hint, what) => { | |
| 8999 | + if (hint !== undefined && !__WF_LOCATION_HINTS.has(hint)) { | |
| 9000 | + throw __wfError( | |
| 9001 | + `${what} has invalid locationHint ${JSON.stringify(hint)}`, | |
| 9002 | + ); | |
| 9003 | + } | |
| 9004 | + return hint; | |
| 9005 | +}; | |
| 9006 | +const __wfRestartOptions = (options) => { | |
| 9007 | + if (options === undefined) return {}; | |
| 9008 | + if (!__wfOwnObject(options)) { | |
| 9009 | + throw __wfError("restart() options must be an object"); | |
| 9010 | + } | |
| 9011 | + const unknown = __wfUnknownKey(options, ["from"]); | |
| 9012 | + if (unknown !== undefined) { | |
| 9013 | + throw __wfError(`restart() has an unknown option ${JSON.stringify(unknown)}`); | |
| 9014 | + } | |
| 9015 | + if (options.from === undefined) return {}; | |
| 9016 | + const from = options.from; | |
| 9017 | + if (!__wfOwnObject(from)) { | |
| 9018 | + throw __wfError("restart() option from must be an object"); | |
| 9019 | + } | |
| 9020 | + const fromUnknown = __wfUnknownKey(from, ["name", "count", "type"]); | |
| 9021 | + if (fromUnknown !== undefined) { | |
| 9022 | + throw __wfError( | |
| 9023 | + `restart() option from has an unknown field ${JSON.stringify(fromUnknown)}`, | |
| 9024 | + ); | |
| 9025 | + } | |
| 9026 | + __wfStepName(from.name); | |
| 9027 | + const count = from.count ?? 1; | |
| 9028 | + if (!Number.isInteger(count) || count < 1) { | |
| 9029 | + throw __wfError("restart() option from.count must be a positive integer"); | |
| 9030 | + } | |
| 9031 | + const type = from.type ?? "do"; | |
| 9032 | + if (!["do", "sleep", "waitForEvent"].includes(type)) { | |
| 9033 | + throw __wfError( | |
| 9034 | + 'restart() option from.type must be "do", "sleep", or "waitForEvent"', | |
| 9035 | + ); | |
| 9036 | + } | |
| 9037 | + return { from: { name: from.name, count, type } }; | |
| 9038 | +}; | |
| 9039 | +const __wfStepConfig = (config, name) => { | |
| 9040 | + if (!__wfOwnObject(config)) { | |
| 9041 | + throw __wfError(`invalid config for step ${JSON.stringify(name)}: use an object`); | |
| 9042 | + } | |
| 9043 | + let unknown = __wfUnknownKey(config, ["retries", "timeout", "sensitive"]); | |
| 9044 | + if (unknown !== undefined) { | |
| 9045 | + throw __wfError( | |
| 9046 | + `invalid config for step ${JSON.stringify(name)}: unknown option ` + | |
| 9047 | + JSON.stringify(unknown), | |
| 9048 | + ); | |
| 9049 | + } | |
| 9050 | + const retries = config.retries; | |
| 9051 | + if (retries !== undefined) { | |
| 9052 | + if (!__wfOwnObject(retries)) { | |
| 9053 | + throw __wfError(`invalid retries config for step ${JSON.stringify(name)}`); | |
| 9054 | + } | |
| 9055 | + unknown = __wfUnknownKey(retries, ["limit", "delay", "backoff"]); | |
| 9056 | + if (unknown !== undefined) { | |
| 9057 | + throw __wfError( | |
| 9058 | + `invalid retries config for step ${JSON.stringify(name)}: unknown option ` + | |
| 9059 | + JSON.stringify(unknown), | |
| 9060 | + ); | |
| 9061 | + } | |
| 9062 | + if ( | |
| 9063 | + typeof retries.limit !== "number" || !Number.isFinite(retries.limit) || | |
| 9064 | + retries.limit < 0 | |
| 9065 | + ) { | |
| 9066 | + throw __wfError( | |
| 9067 | + `invalid retries config for step ${JSON.stringify(name)}: ` + | |
| 9068 | + "limit must be a non-negative number", | |
| 9069 | + ); | |
| 9070 | + } | |
| 9071 | + if (retries.limit > __WF_RETRY_LIMIT_CAP) { | |
| 9072 | + throw __wfError( | |
| 9073 | + `invalid retries config for step ${JSON.stringify(name)}: limit is above ` + | |
| 9074 | + String(__WF_RETRY_LIMIT_CAP), | |
| 9075 | + ); | |
| 9076 | + } | |
| 9077 | + if (typeof retries.delay !== "function") { | |
| 9078 | + __wfDuration(retries.delay, `the retries config delay of step ${JSON.stringify(name)}`); | |
| 9079 | + } | |
| 9080 | + if ( | |
| 9081 | + retries.backoff !== undefined && | |
| 9082 | + !["constant", "linear", "exponential"].includes(retries.backoff) | |
| 9083 | + ) { | |
| 9084 | + throw __wfError( | |
| 9085 | + `invalid retries config for step ${JSON.stringify(name)}: ` + | |
| 9086 | + "backoff must be constant, linear, or exponential", | |
| 9087 | + ); | |
| 9088 | + } | |
| 9089 | + } | |
| 9090 | + if (config.timeout !== undefined) { | |
| 9091 | + const timeout = __wfDuration( | |
| 9092 | + config.timeout, | |
| 9093 | + `the config timeout of step ${JSON.stringify(name)}`, | |
| 9094 | + ); | |
| 9095 | + if (timeout === 0) { | |
| 9096 | + throw __wfError( | |
| 9097 | + `invalid config timeout for step ${JSON.stringify(name)}: use a value above zero`, | |
| 9098 | + ); | |
| 9099 | + } | |
| 9100 | + } | |
| 9101 | + if (config.sensitive !== undefined && config.sensitive !== "output") { | |
| 9102 | + throw __wfError( | |
| 9103 | + `invalid config sensitive value for step ${JSON.stringify(name)}: use "output"`, | |
| 9104 | + ); | |
| 9105 | + } | |
| 9106 | + return { | |
| 9107 | + ...config, | |
| 9108 | + ...(retries === undefined ? {} : { retries: { ...retries } }), | |
| 9109 | + }; | |
| 9110 | +}; | |
| 9111 | +// Serialization is checked with the same encoder storage and RPC use, so a | |
| 9112 | +// value that passes here cannot fail later at the isolate boundary. The | |
| 9113 | +// thrown errors are permanent: retrying cannot make a value cloneable or | |
| 9114 | +// shrink it. | |
| 9115 | +const __wfEncodeValue = (value, what) => { | |
| 9116 | + try { | |
| 9117 | + return __sc_encode(value); | |
| 9118 | + } catch (error) { | |
| 9119 | + const failure = __wfError( | |
| 9120 | + `${what} is not serializable: ${String(error && error.message || error)}. ` + | |
| 9121 | + "It must survive structured clone; a ReadableStream return is not implemented in celld.", | |
| 9122 | + ); | |
| 9123 | + failure.__wfPermanent = true; | |
| 9124 | + throw failure; | |
| 9125 | + } | |
| 9126 | +}; | |
| 9127 | +const __wfCheckEncodedValue = (bytes, what) => { | |
| 9128 | + if (bytes.byteLength > __WF_VALUE_CAP) { | |
| 9129 | + const failure = __wfError( | |
| 9130 | + `${what} is ${bytes.byteLength} bytes, above the 1 MiB limit; ` + | |
| 9131 | + "store large output externally and return a reference", | |
| 9132 | + ); | |
| 9133 | + failure.__wfPermanent = true; | |
| 9134 | + throw failure; | |
| 9135 | + } | |
| 9136 | +}; | |
| 9137 | +const __wfCheckValue = (value, what) => | |
| 9138 | + __wfCheckEncodedValue(__wfEncodeValue(value, what), what); | |
| 9139 | +const __wfErrorRecord = (error) => ({ | |
| 9140 | + name: String(error && error.name || "Error"), | |
| 9141 | + message: String(error && error.message || error), | |
| 9142 | +}); | |
| 9143 | +// A permanently failed step rejects on every replay, so user try/catch | |
| 9144 | +// around step.do keeps working after a resume, not only on the attempt that | |
| 9145 | +// failed live. | |
| 9146 | +const __wfReviveError = (record) => { | |
| 9147 | + const error = new Error(record.message); | |
| 9148 | + error.name = record.name; | |
| 9149 | + return error; | |
| 9150 | +}; | |
| 9151 | +const __wfLedgerPrefix = (generation) => `__wf.${generation}.`; | |
| 9152 | +const __wfEventPrefix = (generation) => | |
| 9153 | + __wfLedgerPrefix(generation) + "event."; | |
| 9154 | +const __wfEventKey = (generation, sequence) => | |
| 9155 | + __wfEventPrefix(generation) + String(sequence).padStart(9, "0"); | |
| 9156 | +const __wfRetentionMs = (meta, status) => | |
| 9157 | + status === "complete" | |
| 9158 | + ? (meta.retention?.successMs ?? __WF_RETENTION_MAX_MS) | |
| 9159 | + : (meta.retention?.errorMs ?? __WF_RETENTION_MAX_MS); | |
| 9160 | +const __wfFinishRetention = (meta, transaction) => { | |
| 9161 | + meta.endedMs = Date.now(); | |
| 9162 | + meta.expiresMs = meta.endedMs + __wfRetentionMs(meta, meta.status); | |
| 9163 | + transaction.setAlarm(meta.expiresMs); | |
| 9164 | +}; | |
| 9165 | +// A ledger record replays only through the kind of call that wrote it. A | |
| 9166 | +// `do` renamed into a `sleep`, or two calls reordered under one name, would | |
| 9167 | +// otherwise read fields the other kind never wrote and continue on | |
| 9168 | +// undefined -- a deadline of NaN, a value of nothing -- instead of failing. | |
| 9169 | +const __wfKindCheck = (record, kind, name) => { | |
| 9170 | + if (record === undefined || record.kind === kind) return record; | |
| 9171 | + const failure = __wfError( | |
| 9172 | + `step ${JSON.stringify(name)} replays as ${kind} but its ledger record ` + | |
| 9173 | + `was written by ${record.kind}; a step keeps one kind across replays`, | |
| 9174 | + ); | |
| 9175 | + failure.__wfPermanent = true; | |
| 9176 | + throw failure; | |
| 9177 | +}; | |
| 9178 | +// Each step callback runs under an async-context frame naming its step (the | |
| 9179 | +// same CPED-backed frame __ctxRun uses, so it survives the callback's | |
| 9180 | +// awaits). A step started inside another step's callback would wedge | |
| 9181 | +// quiescence: the outer callback cannot settle while it awaits the blocked | |
| 9182 | +// inner step, so `running` never reaches zero and the instance can neither | |
| 9183 | +// suspend nor finish. The frame is what lets the inner call refuse loudly | |
| 9184 | +// at the nesting site instead. | |
| 9185 | +const __wfStepKey = Symbol("celld.wfStep"); | |
| 9186 | +const __wfEnclosingStep = () => { | |
| 9187 | + const frame = __als_get(); | |
| 9188 | + return frame === undefined ? undefined : frame.get(__wfStepKey); | |
| 9189 | +}; | |
| 9190 | +const __wfEnterStep = (name, fn) => { | |
| 9191 | + const prior = __als_get(); | |
| 9192 | + const frame = new Map(prior); | |
| 9193 | + frame.set(__wfStepKey, name); | |
| 9194 | + __als_set(frame); | |
| 9195 | + try { | |
| 9196 | + return fn(); | |
| 9197 | + } finally { | |
| 9198 | + __als_set(prior); | |
| 9199 | + } | |
| 9200 | +}; | |
| 9201 | + | |
| 9202 | +// Race an attempt against its deadline. The abandoned callback keeps | |
| 9203 | +// running -- there is no cancellation to send it -- but its result is | |
| 9204 | +// discarded and the timeout counts as a failed attempt, as upstream. | |
| 9205 | +const __wfTimeout = (promise, ms, name, attempt) => | |
| 9206 | + new Promise((resolve, reject) => { | |
| 9207 | + const timer = setTimeout( | |
| 9208 | + () => | |
| 9209 | + reject(new Error( | |
| 9210 | + `step ${JSON.stringify(name)} timed out after ${ms} ms (attempt ${attempt})`, | |
| 9211 | + )), | |
| 9212 | + ms, | |
| 9213 | + ); | |
| 9214 | + promise.then( | |
| 9215 | + (value) => { clearTimeout(timer); resolve(value); }, | |
| 9216 | + (error) => { clearTimeout(timer); reject(error); }, | |
| 9217 | + ); | |
| 9218 | + }); | |
| 9219 | + | |
| 9220 | +// Storage failures belong to the engine even when workflow code catches the | |
| 9221 | +// rejected step promise. Record them outside the Error object, so user code | |
| 9222 | +// cannot suppress a retry or forge one by returning a marked exception. | |
| 9223 | +const __wfTrackStorageFailures = (storage, driver) => { | |
| 9224 | + const tracked = Object.create(storage); | |
| 9225 | + for (const name of ["get", "put", "transactionSync"]) { | |
| 9226 | + Object.defineProperty(tracked, name, { | |
| 9227 | + value(...args) { | |
| 9228 | + try { | |
| 9229 | + const result = storage[name](...args); | |
| 9230 | + if (result !== null && typeof result === "object" && | |
| 9231 | + typeof result.then === "function") { | |
| 9232 | + return result.catch((error) => { | |
| 9233 | + driver.storageFailure ??= error; | |
| 9234 | + throw error; | |
| 9235 | + }); | |
| 9236 | + } | |
| 9237 | + return result; | |
| 9238 | + } catch (error) { | |
| 9239 | + driver.storageFailure ??= error; | |
| 9240 | + throw error; | |
| 9241 | + } | |
| 9242 | + }, | |
| 9243 | + }); | |
| 9244 | + } | |
| 9245 | + return tracked; | |
| 9246 | +}; | |
| 9247 | + | |
| 9248 | +// The WorkflowStep the driver hands to run(). Each method resolves its step | |
| 9249 | +// record by (name, occurrence count) -- the count is assigned synchronously | |
| 9250 | +// at call time, so `Promise.all` of two same-named steps gets deterministic | |
| 9251 | +// distinct keys in call order, and a repeated name in a loop cannot collide. | |
| 9252 | +const __wfMakeStep = (driver) => { | |
| 9253 | + const storage = driver.storage; | |
| 9254 | + // The shared step frame. `body` resolves to {value} or {block: at, kind}; | |
| 9255 | + // a blocked step leaves its promise unsettled forever in this invocation. | |
| 9256 | + // The running counter covers the whole body, ledger reads included, so | |
| 9257 | + // quiescence cannot fire between a step's read and its decision. | |
| 9258 | + const frame = (name, body) => { | |
| 9259 | + // A stale replay -- one whose invocation already suspended -- can wake | |
| 9260 | + // later if user code raced a step against an un-stepped await. It goes | |
| 9261 | + // quiet instead of executing an attempt beside the fresh replay. | |
| 9262 | + if (driver.finished) return __wfNever; | |
| 9263 | + const enclosing = __wfEnclosingStep(); | |
| 9264 | + if (enclosing !== undefined) { | |
| 9265 | + const failure = __wfError( | |
| 9266 | + `step ${JSON.stringify(name)} cannot start inside the callback of ` + | |
| 9267 | + `step ${JSON.stringify(enclosing)}; a step callback must not use ` + | |
| 9268 | + "the step API", | |
| 9269 | + ); | |
| 9270 | + failure.__wfPermanent = true; | |
| 9271 | + return Promise.reject(failure); | |
| 9272 | + } | |
| 9273 | + const count = (driver.counts.get(name) ?? 0) + 1; | |
| 9274 | + driver.counts.set(name, count); | |
| 9275 | + const ordinal = ++driver.ordinal; | |
| 9276 | + const key = driver.ledgerPrefix + `step.${count}.${name}`; | |
| 9277 | + // Step activity restarts the stall clock: a pending grace timer was | |
| 9278 | + // armed against a run() that looked stuck, and this call is progress. | |
| 9279 | + driver.clearStall(); | |
| 9280 | + driver.running += 1; | |
| 9281 | + return new Promise((resolve, reject) => { | |
| 9282 | + (async () => { | |
| 9283 | + const meta = await storage.get("__wf.meta"); | |
| 9284 | + if ( | |
| 9285 | + meta === undefined || meta.generation !== driver.generation || | |
| 9286 | + __wfTerminal(meta.status) || meta.status === "paused" || | |
| 9287 | + meta.status === "waitingForPause" | |
| 9288 | + ) { | |
| 9289 | + return { pause: true }; | |
| 9290 | + } | |
| 9291 | + return await body(key, count, ordinal); | |
| 9292 | + })().then( | |
| 9293 | + (result) => { | |
| 9294 | + driver.running -= 1; | |
| 9295 | + driver.clearStall(); | |
| 9296 | + if (result.pause === true) { | |
| 9297 | + driver.pauseRequested = true; | |
| 9298 | + driver.check(); | |
| 9299 | + return; | |
| 9300 | + } | |
| 9301 | + if (result.block !== undefined) { | |
| 9302 | + if (!driver.finished) { | |
| 9303 | + driver.blocked.push({ at: result.block, kind: result.kind }); | |
| 9304 | + } | |
| 9305 | + driver.check(); | |
| 9306 | + return; | |
| 9307 | + } | |
| 9308 | + driver.check(); | |
| 9309 | + resolve(result.value); | |
| 9310 | + }, | |
| 9311 | + (error) => { | |
| 9312 | + driver.running -= 1; | |
| 9313 | + driver.clearStall(); | |
| 9314 | + driver.check(); | |
| 9315 | + reject(error); | |
| 9316 | + }, | |
| 9317 | + ); | |
| 9318 | + }); | |
| 9319 | + }; | |
| 9320 | + const doStep = (name, configOrCallback, callbackOrRollback, maybeRollback) => { | |
| 9321 | + const hasConfig = typeof configOrCallback !== "function"; | |
| 9322 | + let config = hasConfig ? (configOrCallback ?? {}) : {}; | |
| 9323 | + const callback = hasConfig ? callbackOrRollback : configOrCallback; | |
| 9324 | + const rollback = hasConfig ? maybeRollback : callbackOrRollback; | |
| 9325 | + try { | |
| 9326 | + __wfStepName(name); | |
| 9327 | + config = __wfStepConfig(config, name); | |
| 9328 | + } catch (error) { | |
| 9329 | + return Promise.reject(error); | |
| 9330 | + } | |
| 9331 | + if (rollback !== undefined) { | |
| 9332 | + return Promise.reject(__wfError( | |
| 9333 | + "step rollbackOptions are not implemented in celld; remove the rollback handler", | |
| 9334 | + )); | |
| 9335 | + } | |
| 9336 | + if (config.sensitive !== undefined) { | |
| 9337 | + return Promise.reject(__wfError( | |
| 9338 | + "sensitive step output is not implemented in celld; remove `sensitive`", | |
| 9339 | + )); | |
| 9340 | + } | |
| 9341 | + if (typeof callback !== "function") { | |
| 9342 | + return Promise.reject(__wfError("step.do needs a callback function")); | |
| 9343 | + } | |
| 9344 | + return frame(name, async (key, count, ordinal) => { | |
| 9345 | + const record = __wfKindCheck(await storage.get(key), "do", name); | |
| 9346 | + if (record !== undefined && record.status === "completed") { | |
| 9347 | + return { value: record.value }; | |
| 9348 | + } | |
| 9349 | + if (record !== undefined && record.status === "failed") { | |
| 9350 | + throw __wfReviveError(record.error); | |
| 9351 | + } | |
| 9352 | + // A pending retry whose backoff has not elapsed blocks without | |
| 9353 | + // executing; the deadline was persisted when the attempt failed, so a | |
| 9354 | + // replay cannot reset the backoff. | |
| 9355 | + if (record !== undefined && record.nextAt > Date.now()) { | |
| 9356 | + return { block: record.nextAt, kind: "retry" }; | |
| 9357 | + } | |
| 9358 | + const attempt = (record === undefined ? 0 : record.attempt) + 1; | |
| 9359 | + const historyOrdinal = record?.ordinal ?? ordinal; | |
| 9360 | + const retries = config.retries ?? | |
| 9361 | + { limit: 5, delay: 10000, backoff: "exponential" }; | |
| 9362 | + const timeout = config.timeout ?? "10 minutes"; | |
| 9363 | + const timeoutMs = __wfDuration( | |
| 9364 | + timeout, | |
| 9365 | + `the timeout of step ${JSON.stringify(name)}`, | |
| 9366 | + ); | |
| 9367 | + // Upstream omits a dynamic delay from the step context. Copying the | |
| 9368 | + // config verbatim would expose the callback to itself as retry policy, | |
| 9369 | + // while callers expect only the serializable limit and backoff fields. | |
| 9370 | + const contextRetries = typeof retries.delay === "function" | |
| 9371 | + ? { limit: retries.limit, ...(retries.backoff === undefined | |
| 9372 | + ? {} | |
| 9373 | + : { backoff: retries.backoff }) } | |
| 9374 | + : retries; | |
| 9375 | + const context = { | |
| 9376 | + step: { name, count }, | |
| 9377 | + attempt, | |
| 9378 | + config: { retries: contextRetries, timeout }, | |
| 9379 | + }; | |
| 9380 | + try { | |
| 9381 | + // Persist the history entry before the callback starts. A concurrent | |
| 9382 | + // selected restart can therefore name an in-flight occurrence, and | |
| 9383 | + // its new generation fences the callback's eventual old-ledger write. | |
| 9384 | + await storage.put(key, { | |
| 9385 | + kind: "do", | |
| 9386 | + status: "running", | |
| 9387 | + attempt: attempt - 1, | |
| 9388 | + ordinal: historyOrdinal, | |
| 9389 | + }); | |
| 9390 | + const value = await __wfTimeout( | |
| 9391 | + __wfEnterStep(name, async () => callback(context)), | |
| 9392 | + timeoutMs, | |
| 9393 | + name, | |
| 9394 | + attempt, | |
| 9395 | + ); | |
| 9396 | + if (value !== undefined) { | |
| 9397 | + __wfCheckValue(value, `the return value of step ${JSON.stringify(name)}`); | |
| 9398 | + } | |
| 9399 | + await storage.put(key, { | |
| 9400 | + kind: "do", | |
| 9401 | + status: "completed", | |
| 9402 | + value, | |
| 9403 | + ordinal: historyOrdinal, | |
| 9404 | + }); | |
| 9405 | + return { value }; | |
| 9406 | + } catch (error) { | |
| 9407 | + // NonRetryableError skips retries by contract; a value-cap or | |
| 9408 | + // serialization failure is marked permanent above because another | |
| 9409 | + // attempt returns the same value. | |
| 9410 | + const permanent = error instanceof NonRetryableError || | |
| 9411 | + (error !== null && typeof error === "object" && | |
| 9412 | + (error.name === "NonRetryableError" || error.__wfPermanent === true)) || | |
| 9413 | + attempt > retries.limit; | |
| 9414 | + if (permanent) { | |
| 9415 | + await storage.put(key, { | |
| 9416 | + kind: "do", | |
| 9417 | + status: "failed", | |
| 9418 | + error: __wfErrorRecord(error), | |
| 9419 | + ordinal: historyOrdinal, | |
| 9420 | + }); | |
| 9421 | + throw error; | |
| 9422 | + } | |
| 9423 | + // Upstream documents the backoff names, not the arithmetic; the | |
| 9424 | + // simplest reading is used and recorded in the design page. When | |
| 9425 | + // `retries` is given without `backoff`, celld uses constant -- the | |
| 9426 | + // documented exponential default is the whole-config-omitted case. | |
| 9427 | + const dynamic = typeof retries.delay === "function"; | |
| 9428 | + const delay = dynamic | |
| 9429 | + ? await __wfEnterStep(name, () => retries.delay({ ctx: context, error })) | |
| 9430 | + : retries.delay; | |
| 9431 | + const base = __wfDuration( | |
| 9432 | + delay, | |
| 9433 | + `the retry delay of step ${JSON.stringify(name)}`, | |
| 9434 | + ); | |
| 9435 | + // A delay callback replaces the fixed base duration, not the backoff | |
| 9436 | + // policy. Skipping this factor makes a dynamic exponential or linear | |
| 9437 | + // policy retry earlier than the same policy with a fixed base. | |
| 9438 | + const factor = retries.backoff === "exponential" | |
| 9439 | + ? 2 ** (attempt - 1) | |
| 9440 | + : retries.backoff === "linear" | |
| 9441 | + ? attempt | |
| 9442 | + : 1; | |
| 9443 | + const nextAt = Date.now() + base * factor; | |
| 9444 | + await storage.put(key, { | |
| 9445 | + kind: "do", | |
| 9446 | + status: "retrying", | |
| 9447 | + attempt, | |
| 9448 | + nextAt, | |
| 9449 | + ordinal: historyOrdinal, | |
| 9450 | + }); | |
| 9451 | + return { block: nextAt, kind: "retry" }; | |
| 9452 | + } | |
| 9453 | + }); | |
| 9454 | + }; | |
| 9455 | + const sleepUntilDeadline = (name, key, ordinal, deadline) => (async () => { | |
| 9456 | + const record = __wfKindCheck(await storage.get(key), "sleep", name); | |
| 9457 | + if (record !== undefined && record.status === "completed") { | |
| 9458 | + return { value: undefined }; | |
| 9459 | + } | |
| 9460 | + const historyOrdinal = record?.ordinal ?? ordinal; | |
| 9461 | + let at = record === undefined ? undefined : record.deadline; | |
| 9462 | + if (at === undefined) { | |
| 9463 | + // The absolute deadline is computed once and persisted. Recomputing | |
| 9464 | + // from "now" on replay would extend the sleep by however long the | |
| 9465 | + // instance was down, so a crash could postpone a deadline forever. | |
| 9466 | + at = deadline(); | |
| 9467 | + if (at - Date.now() > __WF_MAX_WAIT_MS) { | |
| 9468 | + throw __wfError( | |
| 9469 | + `sleep ${JSON.stringify(name)} ends ${at - Date.now()} ms from now, ` + | |
| 9470 | + "above the upstream limit of 365 days", | |
| 9471 | + ); | |
| 9472 | + } | |
| 9473 | + await storage.put(key, { | |
| 9474 | + kind: "sleep", | |
| 9475 | + status: "sleeping", | |
| 9476 | + deadline: at, | |
| 9477 | + ordinal: historyOrdinal, | |
| 9478 | + }); | |
| 9479 | + } | |
| 9480 | + if (at <= Date.now()) { | |
| 9481 | + await storage.put(key, { | |
| 9482 | + kind: "sleep", | |
| 9483 | + status: "completed", | |
| 9484 | + ordinal: historyOrdinal, | |
| 9485 | + }); | |
| 9486 | + return { value: undefined }; | |
| 9487 | + } | |
| 9488 | + return { block: at, kind: "sleep" }; | |
| 9489 | + })(); | |
| 9490 | + return { | |
| 9491 | + do: doStep, | |
| 9492 | + sleep: (name, duration) => { | |
| 9493 | + let durationMs; | |
| 9494 | + try { | |
| 9495 | + __wfStepName(name); | |
| 9496 | + durationMs = __wfSleepDuration(duration, name); | |
| 9497 | + } catch (error) { | |
| 9498 | + return Promise.reject(error); | |
| 9499 | + } | |
| 9500 | + return frame(name, (key, _count, ordinal) => | |
| 9501 | + sleepUntilDeadline( | |
| 9502 | + name, | |
| 9503 | + key, | |
| 9504 | + ordinal, | |
| 9505 | + () => Date.now() + durationMs, | |
| 9506 | + )); | |
| 9507 | + }, | |
| 9508 | + sleepUntil: (name, timestamp) => { | |
| 9509 | + let at; | |
| 9510 | + try { | |
| 9511 | + __wfStepName(name); | |
| 9512 | + at = __wfSleepUntil(timestamp, name); | |
| 9513 | + } catch (error) { | |
| 9514 | + return Promise.reject(error); | |
| 9515 | + } | |
| 9516 | + return frame(name, (key, _count, ordinal) => | |
| 9517 | + sleepUntilDeadline(name, key, ordinal, () => { | |
| 9518 | + // A replay uses the persisted deadline after it has passed. Check | |
| 9519 | + // the moving future bound only while the deadline is first installed, | |
| 9520 | + // or every successful sleep would fail on the resume that completes it. | |
| 9521 | + if (at - Date.now() < 0) { | |
| 9522 | + throw __wfError( | |
| 9523 | + `sleepUntil ${JSON.stringify(name)} needs a future timestamp`, | |
| 9524 | + ); | |
| 9525 | + } | |
| 9526 | + return at; | |
| 9527 | + })); | |
| 9528 | + }, | |
| 9529 | + waitForEvent: (name, options) => { | |
| 9530 | + let checked; | |
| 9531 | + try { | |
| 9532 | + __wfStepName(name); | |
| 9533 | + checked = __wfWaitOptions(options, name); | |
| 9534 | + } catch (error) { | |
| 9535 | + return Promise.reject(error); | |
| 9536 | + } | |
| 9537 | + return frame(name, async (key, _count, ordinal) => { | |
| 9538 | + let record = __wfKindCheck(await storage.get(key), "event", name); | |
| 9539 | + if (record !== undefined && record.status === "completed") { | |
| 9540 | + return { value: record.value }; | |
| 9541 | + } | |
| 9542 | + if (record !== undefined && record.status === "failed") { | |
| 9543 | + throw __wfReviveError(record.error); | |
| 9544 | + } | |
| 9545 | + if (record === undefined) { | |
| 9546 | + record = { | |
| 9547 | + kind: "event", | |
| 9548 | + status: "waiting", | |
| 9549 | + type: checked.type, | |
| 9550 | + deadline: Date.now() + checked.timeoutMs, | |
| 9551 | + ordinal, | |
| 9552 | + }; | |
| 9553 | + await storage.put(key, record); | |
| 9554 | + } | |
| 9555 | + // The deadline is checked before the buffer: an event that arrived | |
| 9556 | + // after the persisted deadline must time the step out, not succeed | |
| 9557 | + // because the replay that noticed it ran late. | |
| 9558 | + if (record.deadline <= Date.now()) { | |
| 9559 | + const error = new Error( | |
| 9560 | + `waitForEvent ${JSON.stringify(name)} timed out waiting for an event ` + | |
| 9561 | + `of type ${JSON.stringify(record.type)}`, | |
| 9562 | + ); | |
| 9563 | + await storage.put(key, { | |
| 9564 | + kind: "event", | |
| 9565 | + status: "failed", | |
| 9566 | + error: __wfErrorRecord(error), | |
| 9567 | + ordinal: record.ordinal, | |
| 9568 | + }); | |
| 9569 | + throw error; | |
| 9570 | + } | |
| 9571 | + // Delivered events persist until a matching step consumes one, in | |
| 9572 | + // arrival order -- the zero-padded sequence key makes list order | |
| 9573 | + // arrival order -- so an event sent before the step is reached is | |
| 9574 | + // buffered, not lost. | |
| 9575 | + const consumed = storage.transactionSync((transaction) => { | |
| 9576 | + const current = __wfKindCheck(transaction.kv.get(key), "event", name); | |
| 9577 | + if (current !== undefined && current.status === "completed") { | |
| 9578 | + return { value: current.value }; | |
| 9579 | + } | |
| 9580 | + if (current !== undefined && current.status === "failed") { | |
| 9581 | + throw __wfReviveError(current.error); | |
| 9582 | + } | |
| 9583 | + for (const [eventKey, event] of transaction.kv.list({ | |
| 9584 | + prefix: __wfEventPrefix(driver.generation), | |
| 9585 | + })) { | |
| 9586 | + if (event.type !== current.type) continue; | |
| 9587 | + const value = { | |
| 9588 | + payload: event.payload, | |
| 9589 | + timestamp: new Date(event.timestampMs), | |
| 9590 | + type: event.type, | |
| 9591 | + }; | |
| 9592 | + // The delete and completed ledger record are one SQLite commit. | |
| 9593 | + // A crash can therefore expose both or neither, so an | |
| 9594 | + // acknowledged event cannot disappear between them. | |
| 9595 | + transaction.kv.delete(eventKey); | |
| 9596 | + /*__CELLD_TEST_WORKFLOW_EVENT_CONSUMED__*/ | |
| 9597 | + transaction.kv.put(key, { | |
| 9598 | + kind: "event", | |
| 9599 | + status: "completed", | |
| 9600 | + value, | |
| 9601 | + ordinal: current.ordinal, | |
| 9602 | + }); | |
| 9603 | + return { value }; | |
| 9604 | + } | |
| 9605 | + }); | |
| 9606 | + if (consumed !== undefined) return consumed; | |
| 9607 | + return { block: record.deadline, kind: "event" }; | |
| 9608 | + }); | |
| 9609 | + }, | |
| 9610 | + }; | |
| 9611 | +}; | |
| 9612 | + | |
| 9613 | +const __WorkflowCell = (() => { | |
| 9614 | + class StorageTransaction { | |
| 9615 | + constructor(storage, transaction) { | |
| 9616 | + this.kv = transaction.kv; | |
| 9617 | + this._scope = storage._scope; | |
| 9618 | + } | |
| 9619 | + setAlarm(t) { | |
| 9620 | + __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); | |
| 9621 | + } | |
| 9622 | + deleteAlarm() { | |
| 9623 | + __alarm_delete(this._scope); | |
| 9624 | + } | |
| 9625 | + } | |
| 9626 | + const transactionSync = (storage, callback) => | |
| 9627 | + storage.transactionSync((transaction) => | |
| 9628 | + callback(new StorageTransaction(storage, transaction)) | |
| 9629 | + ); | |
| 9630 | + const clearInstance = (transaction) => { | |
| 9631 | + for (const [key] of transaction.kv.list({ prefix: "__wf." })) { | |
| 9632 | + transaction.kv.delete(key); | |
| 9633 | + } | |
| 9634 | + transaction.deleteAlarm(); | |
| 9635 | + }; | |
| 9636 | + const expireTerminal = (transaction, meta, now) => { | |
| 9637 | + if (!__wfTerminal(meta.status)) return false; | |
| 9638 | + if (meta.expiresMs === undefined) { | |
| 9639 | + meta.endedMs = now; | |
| 9640 | + meta.expiresMs = now + __wfRetentionMs(meta, meta.status); | |
| 9641 | + transaction.kv.put("__wf.meta", meta); | |
| 9642 | + } | |
| 9643 | + if (meta.expiresMs > now) return false; | |
| 9644 | + clearInstance(transaction); | |
| 9645 | + return true; | |
| 9646 | + }; | |
| 9647 | + | |
| 9648 | + // The adapter stays in this closure because Workflow needs synchronous | |
| 9649 | + // alarm writes inside transactionSync(). The public async alarm API runs | |
| 9650 | + // after that commit, while a global helper would let application code | |
| 9651 | + // split metadata from its wake or invoke the raw operation after commit. | |
| 9652 | + return class __WorkflowCell { | |
| 9653 | + constructor(state) { | |
| 9654 | + this._state = state; | |
| 9655 | + } | |
| 9656 | + async __wfCreate({ | |
| 9657 | + workflowName, | |
| 9658 | + instanceId, | |
| 9659 | + params, | |
| 9660 | + retention, | |
| 9661 | + locationHint, | |
| 9662 | + skipExisting = false, | |
| 9663 | + }) { | |
| 9664 | + const storage = this._state.storage; | |
| 9665 | + if (params !== undefined) __wfCheckValue(params, "the workflow params"); | |
| 9666 | + const result = transactionSync(storage, (transaction) => { | |
| 9667 | + let meta = transaction.kv.get("__wf.meta"); | |
| 9668 | + if (meta !== undefined && expireTerminal(transaction, meta, Date.now())) { | |
| 9669 | + meta = undefined; | |
| 9670 | + } | |
| 9671 | + if (meta !== undefined && skipExisting) return { id: instanceId, created: false }; | |
| 9672 | + if (meta !== undefined) { | |
| 9673 | + throw __wfError( | |
| 9674 | + `instance ${JSON.stringify(instanceId)} already exists with status ` + | |
| 9675 | + JSON.stringify(meta.status), | |
| 9676 | + ); | |
| 9677 | + } | |
| 9678 | + const generation = crypto.randomUUID(); | |
| 9679 | + transaction.kv.put("__wf.meta", { | |
| 9680 | + workflowName, | |
| 9681 | + instanceId, | |
| 9682 | + params, | |
| 9683 | + retention, | |
| 9684 | + ...(locationHint === undefined ? {} : { locationHint }), | |
| 9685 | + generation, | |
| 9686 | + createdMs: Date.now(), | |
| 9687 | + status: "queued", | |
| 9688 | + }); | |
| 9689 | + // The metadata and alarm are one SQLite commit. A committed creation | |
| 9690 | + // therefore always has the wake that can start or recover its drive. | |
| 9691 | + transaction.setAlarm(Date.now()); | |
| 9692 | + /*__CELLD_TEST_WORKFLOW_META_CREATED__*/ | |
| 9693 | + return { id: instanceId, created: true }; | |
| 9694 | + }); | |
| 9695 | + return result; | |
| 9696 | + } | |
| 9697 | + async __wfStatus() { | |
| 9698 | + const meta = transactionSync(this._state.storage, (transaction) => { | |
| 9699 | + const current = transaction.kv.get("__wf.meta"); | |
| 9700 | + if (current === undefined) return undefined; | |
| 9701 | + return expireTerminal(transaction, current, Date.now()) ? undefined : current; | |
| 9702 | + }); | |
| 9703 | + // A cell exists on first address like any cell, so an absent ledger is | |
| 9704 | + // the only honest "no such instance" signal. Inventing an instance here | |
| 9705 | + // would turn every typo into an empty workflow. | |
| 9706 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9707 | + const status = { status: meta.status, rollback: null }; | |
| 9708 | + if (meta.error !== undefined) status.error = meta.error; | |
| 9709 | + if (meta.output !== undefined) status.output = meta.output; | |
| 9710 | + return status; | |
| 9711 | + } | |
| 9712 | + async __wfDelete() { | |
| 9713 | + const storage = this._state.storage; | |
| 9714 | + const deleted = transactionSync(storage, (transaction) => { | |
| 9715 | + const meta = transaction.kv.get("__wf.meta"); | |
| 9716 | + if (meta === undefined) return false; | |
| 9717 | + if (expireTerminal(transaction, meta, Date.now())) return false; | |
| 9718 | + clearInstance(transaction); | |
| 9719 | + return true; | |
| 9720 | + }); | |
| 9721 | + // Throw after the transaction commits. An expiry discovered here must | |
| 9722 | + // keep its cleanup even though delete() reports that the instance is gone. | |
| 9723 | + if (!deleted) throw __wfError("instance does not exist"); | |
| 9724 | + // A callback can still be awaiting application I/O when deletion lands. | |
| 9725 | + // Reset the object after the deletion commit so that callback cannot | |
| 9726 | + // recreate an old-generation ledger entry after delete() reports success. | |
| 9727 | + this._state.abort(new Error("WORKFLOW_INSTANCE_DELETED")); | |
| 9728 | + } | |
| 9729 | + async __wfPause() { | |
| 9730 | + const storage = this._state.storage; | |
| 9731 | + transactionSync(storage, (transaction) => { | |
| 9732 | + const meta = transaction.kv.get("__wf.meta"); | |
| 9733 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9734 | + if (__wfTerminal(meta.status) || meta.status === "paused" || | |
| 9735 | + meta.status === "waitingForPause") return; | |
| 9736 | + if (meta.status === "running") { | |
| 9737 | + meta.status = "waitingForPause"; | |
| 9738 | + // A drive lost after this commit must re-enter and finish the pause. | |
| 9739 | + transaction.setAlarm(Date.now()); | |
| 9740 | + } else { | |
| 9741 | + meta.status = "paused"; | |
| 9742 | + meta.pausedMs = Date.now(); | |
| 9743 | + transaction.deleteAlarm(); | |
| 9744 | + } | |
| 9745 | + transaction.kv.put("__wf.meta", meta); | |
| 9746 | + }); | |
| 9747 | + } | |
| 9748 | + async __wfResume() { | |
| 9749 | + const storage = this._state.storage; | |
| 9750 | + transactionSync(storage, (transaction) => { | |
| 9751 | + const meta = transaction.kv.get("__wf.meta"); | |
| 9752 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9753 | + if (meta.status === "waitingForPause") { | |
| 9754 | + meta.status = "running"; | |
| 9755 | + transaction.kv.put("__wf.meta", meta); | |
| 9756 | + transaction.setAlarm(Date.now()); | |
| 9757 | + return; | |
| 9758 | + } | |
| 9759 | + if (meta.status !== "paused") { | |
| 9760 | + throw __wfError( | |
| 9761 | + `cannot resume an instance with status ${JSON.stringify(meta.status)}`, | |
| 9762 | + ); | |
| 9763 | + } | |
| 9764 | + const offset = Math.max(0, Date.now() - (meta.pausedMs ?? Date.now())); | |
| 9765 | + for (const [key, record] of transaction.kv.list({ | |
| 9766 | + prefix: __wfLedgerPrefix(meta.generation) + "step.", | |
| 9767 | + })) { | |
| 9768 | + if (record.status === "retrying") record.nextAt += offset; | |
| 9769 | + if (record.status === "sleeping" || record.status === "waiting") { | |
| 9770 | + record.deadline += offset; | |
| 9771 | + } | |
| 9772 | + transaction.kv.put(key, record); | |
| 9773 | + } | |
| 9774 | + delete meta.pausedMs; | |
| 9775 | + meta.status = "queued"; | |
| 9776 | + transaction.kv.put("__wf.meta", meta); | |
| 9777 | + transaction.setAlarm(Date.now()); | |
| 9778 | + }); | |
| 9779 | + } | |
| 9780 | + async __wfRestart(options) { | |
| 9781 | + const checked = __wfRestartOptions(options); | |
| 9782 | + const storage = this._state.storage; | |
| 9783 | + transactionSync(storage, (transaction) => { | |
| 9784 | + const meta = transaction.kv.get("__wf.meta"); | |
| 9785 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9786 | + const oldPrefix = __wfLedgerPrefix(meta.generation); | |
| 9787 | + let targetOrdinal; | |
| 9788 | + if (checked.from !== undefined) { | |
| 9789 | + const expectedKind = checked.from.type === "waitForEvent" | |
| 9790 | + ? "event" | |
| 9791 | + : checked.from.type; | |
| 9792 | + let occurrence = 0; | |
| 9793 | + const history = [...transaction.kv.list({ prefix: oldPrefix + "step." })] | |
| 9794 | + .filter(([, record]) => Number.isInteger(record.ordinal)) | |
| 9795 | + .sort((left, right) => left[1].ordinal - right[1].ordinal); | |
| 9796 | + // The ledger key is `<prefix>step.<per-name-count>.<name>`. Derive | |
| 9797 | + // the name from it because a record stores replay state, not identity. | |
| 9798 | + for (const [key, record] of history) { | |
| 9799 | + const marker = oldPrefix + "step."; | |
| 9800 | + const suffix = key.slice(marker.length); | |
| 9801 | + const dot = suffix.indexOf("."); | |
| 9802 | + const name = dot < 0 ? "" : suffix.slice(dot + 1); | |
| 9803 | + if (record.kind !== expectedKind || name !== checked.from.name) continue; | |
| 9804 | + occurrence += 1; | |
| 9805 | + if (occurrence === checked.from.count) { | |
| 9806 | + targetOrdinal = record.ordinal; | |
| 9807 | + break; | |
| 9808 | + } | |
| 9809 | + } | |
| 9810 | + if (targetOrdinal === undefined) { | |
| 9811 | + throw __wfError( | |
| 9812 | + `restart() could not find ${checked.from.type} step ` + | |
| 9813 | + `${JSON.stringify(checked.from.name)} occurrence ${checked.from.count}`, | |
| 9814 | + ); | |
| 9815 | + } | |
| 9816 | + } | |
| 9817 | + const generation = crypto.randomUUID(); | |
| 9818 | + const newPrefix = __wfLedgerPrefix(generation); | |
| 9819 | + if (targetOrdinal !== undefined) { | |
| 9820 | + for (const [key, record] of transaction.kv.list({ prefix: oldPrefix + "step." })) { | |
| 9821 | + if (Number.isInteger(record.ordinal) && record.ordinal < targetOrdinal) { | |
| 9822 | + transaction.kv.put(newPrefix + key.slice(oldPrefix.length), record); | |
| 9823 | + } | |
| 9824 | + } | |
| 9825 | + } | |
| 9826 | + for (const [key] of transaction.kv.list({ prefix: oldPrefix })) { | |
| 9827 | + transaction.kv.delete(key); | |
| 9828 | + } | |
| 9829 | + meta.generation = generation; | |
| 9830 | + meta.status = "queued"; | |
| 9831 | + delete meta.pausedMs; | |
| 9832 | + delete meta.output; | |
| 9833 | + delete meta.error; | |
| 9834 | + transaction.kv.put("__wf.meta", meta); | |
| 9835 | + transaction.setAlarm(Date.now()); | |
| 9836 | + }); | |
| 9837 | + } | |
| 9838 | + async __wfTerminate() { | |
| 9839 | + const storage = this._state.storage; | |
| 9840 | + transactionSync(storage, (transaction) => { | |
| 9841 | + const meta = transaction.kv.get("__wf.meta"); | |
| 9842 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9843 | + if (__wfTerminal(meta.status)) { | |
| 9844 | + throw __wfError( | |
| 9845 | + `cannot terminate an instance with status ${JSON.stringify(meta.status)}`, | |
| 9846 | + ); | |
| 9847 | + } | |
| 9848 | + meta.status = "terminated"; | |
| 9849 | + __wfFinishRetention(meta, transaction); | |
| 9850 | + transaction.kv.put("__wf.meta", meta); | |
| 9851 | + /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 9852 | + }); | |
| 9853 | + } | |
| 9854 | + async __wfSendEvent(options) { | |
| 9855 | + const storage = this._state.storage; | |
| 9856 | + // The binding validates first to avoid an unnecessary cell call. Repeat | |
| 9857 | + // the check here because this RPC owns the durable event invariant: no | |
| 9858 | + // current or future internal caller can bypass validation before storage. | |
| 9859 | + const { type, payload } = __wfEventOptions(options); | |
| 9860 | + transactionSync(storage, (transaction) => { | |
| 9861 | + const meta = transaction.kv.get("__wf.meta"); | |
| 9862 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9863 | + if (__wfTerminal(meta.status)) { | |
| 9864 | + throw __wfError( | |
| 9865 | + `cannot send an event to an instance with status ${JSON.stringify(meta.status)}`, | |
| 9866 | + ); | |
| 9867 | + } | |
| 9868 | + const sequenceKey = __wfLedgerPrefix(meta.generation) + "eventSeq"; | |
| 9869 | + const sequence = transaction.kv.get(sequenceKey) ?? 0; | |
| 9870 | + transaction.kv.put(sequenceKey, sequence + 1); | |
| 9871 | + transaction.kv.put(__wfEventKey(meta.generation, sequence), { | |
| 9872 | + type, | |
| 9873 | + payload, | |
| 9874 | + timestampMs: Date.now(), | |
| 9875 | + }); | |
| 9876 | + // Allocation, the event body, and the nudge are one commit. Parallel | |
| 9877 | + // writers cannot reuse a sequence and a crash cannot expose a partial | |
| 9878 | + // acknowledged send. | |
| 9879 | + if (meta.status !== "paused" && meta.status !== "waitingForPause") { | |
| 9880 | + transaction.setAlarm(Date.now()); | |
| 9881 | + } | |
| 9882 | + }); | |
| 9883 | + } | |
| 9884 | + async alarm() { | |
| 9885 | + const storage = this._state.storage; | |
| 9886 | + // One drive at a time. A sendEvent nudge (setAlarm(now)) landing | |
| 9887 | + // mid-fire replaces the firing alarm in the core, and the replacement | |
| 9888 | + // can dispatch a second alarm() into this isolate while the first drive | |
| 9889 | + // still awaits user code. Two concurrent replays would both see the | |
| 9890 | + // same incomplete steps and double-execute their callbacks. The guard | |
| 9891 | + // is isolate-local and that is sufficient: every drive for a cell runs | |
| 9892 | + // in its owner's isolate, and a takeover starts a fresh isolate with no | |
| 9893 | + // drive in flight. The nudge is not lost -- the in-flight drive folds | |
| 9894 | + // `_wfNudge` into the minimum it re-arms, and if it suspended before | |
| 9895 | + // seeing the flag, the re-arm below starts a fresh drive immediately. | |
| 9896 | + // A failed drive is not re-raised here: the engine already retries the | |
| 9897 | + // alarm that fired it. | |
| 9898 | + if (this._wfDriving !== undefined) { | |
| 9899 | + this._wfNudge = Date.now(); | |
| 9900 | + await this._wfDriving.catch(() => {}); | |
| 9901 | + if (this._wfNudge !== undefined) { | |
| 9902 | + this._wfNudge = undefined; | |
| 9903 | + const meta = await storage.get("__wf.meta"); | |
| 9904 | + if ( | |
| 9905 | + meta !== undefined && !__wfTerminal(meta.status) && | |
| 9906 | + meta.status !== "paused" && meta.status !== "waitingForPause" | |
| 9907 | + ) { | |
| 9908 | + await storage.setAlarm(Date.now()); | |
| 9909 | + } | |
| 9910 | + } | |
| 9911 | + return; | |
| 9912 | + } | |
| 9913 | + const meta = await storage.get("__wf.meta"); | |
| 9914 | + // A terminal instance's pending alarm can still fire. It owns retention: | |
| 9915 | + // remove expired state, or restore the expiry wake after a stale nudge. | |
| 9916 | + if (meta === undefined) { | |
| 9917 | + await storage.deleteAlarm(); | |
| 9918 | + return; | |
| 9919 | + } | |
| 9920 | + if (__wfTerminal(meta.status)) { | |
| 9921 | + transactionSync(storage, (transaction) => { | |
| 9922 | + const current = transaction.kv.get("__wf.meta"); | |
| 9923 | + if (current === undefined) { | |
| 9924 | + transaction.deleteAlarm(); | |
| 9925 | + return; | |
| 9926 | + } | |
| 9927 | + if (!expireTerminal(transaction, current, Date.now())) { | |
| 9928 | + transaction.setAlarm(current.expiresMs); | |
| 9929 | + } | |
| 9930 | + }); | |
| 9931 | + return; | |
| 9932 | + } | |
| 9933 | + if (meta.status === "paused") { | |
| 9934 | + await storage.deleteAlarm(); | |
| 9935 | + return; | |
| 9936 | + } | |
| 9937 | + if (meta.status === "waitingForPause") { | |
| 9938 | + transactionSync(storage, (transaction) => { | |
| 9939 | + const current = transaction.kv.get("__wf.meta"); | |
| 9940 | + if (current === undefined || current.generation !== meta.generation || | |
| 9941 | + current.status !== "waitingForPause") return; | |
| 9942 | + current.status = "paused"; | |
| 9943 | + current.pausedMs = Date.now(); | |
| 9944 | + transaction.kv.put("__wf.meta", current); | |
| 9945 | + transaction.deleteAlarm(); | |
| 9946 | + }); | |
| 9947 | + return; | |
| 9948 | + } | |
| 9949 | + // The fired alarm stays armed while the drive runs. The engine consumes | |
| 9950 | + // it only when this handler returns cleanly, and retries it when the | |
| 9951 | + // handler fails -- that retry is the crash safety net. Deleting it here | |
| 9952 | + // would commit the deletion durably mid-drive (durability is per SQLite | |
| 9953 | + // commit, and replication ships frames per commit), so a SIGKILL before | |
| 9954 | + // the suspend-time re-arm would strand a "running" instance with no | |
| 9955 | + // alarm and no wake entry. The suspend path re-arms explicitly, and a | |
| 9956 | + // terminal drive deletes. | |
| 9957 | + const driving = this._drive(meta); | |
| 9958 | + this._wfDriving = driving; | |
| 9959 | + try { | |
| 9960 | + await driving; | |
| 9961 | + } finally { | |
| 9962 | + this._wfDriving = undefined; | |
| 9963 | + } | |
| 9964 | + } | |
| 9965 | + async _drive(meta) { | |
| 9966 | + const storage = this._state.storage; | |
| 9967 | + // The drive owns `status`, `output`, and `error`; every other piece of | |
| 9968 | + // instance state belongs to the RPCs (sendEvent's sequence lives in its | |
| 9969 | + // own key for the same reason). The gate is open at every await, so a | |
| 9970 | + // terminate can land mid-drive: re-reading before each write, and | |
| 9971 | + // writing nothing once the status is terminal, is what makes "terminate | |
| 9972 | + // wins the race" true rather than asserted. Writing back the meta this | |
| 9973 | + // drive entered with would resurrect a terminated instance as "waiting" | |
| 9974 | + // and re-arm the alarm its terminate deleted. | |
| 9975 | + const settle = (mutate) => transactionSync(storage, (transaction) => { | |
| 9976 | + const current = transaction.kv.get("__wf.meta"); | |
| 9977 | + if (current === undefined || __wfTerminal(current.status) || | |
| 9978 | + current.generation !== meta.generation) return false; | |
| 9979 | + mutate(current, transaction); | |
| 9980 | + transaction.kv.put("__wf.meta", current); | |
| 9981 | + return true; | |
| 9982 | + }); | |
| 9983 | + const className = __cell.workflows[meta.workflowName]; | |
| 9984 | + const cls = className === undefined ? undefined : __cf.exports[className]; | |
| 9985 | + if (typeof cls !== "function" || | |
| 9986 | + typeof (cls.prototype && cls.prototype.run) !== "function") { | |
| 9987 | + // Deploy cannot see inside the bundle, so a missing export fails | |
| 9988 | + // here, loudly, with the class and the config key named. | |
| 9989 | + settle((current, transaction) => { | |
| 9990 | + current.status = "errored"; | |
| 9991 | + current.error = { | |
| 9992 | + name: "Error", | |
| 9993 | + message: className === undefined | |
| 9994 | + ? `workflow ${JSON.stringify(meta.workflowName)} is not declared ` + | |
| 9995 | + "in this deployment's `workflows`" | |
| 9996 | + : `workflow class ${JSON.stringify(className)} is not a module ` + | |
| 9997 | + "export with a run() method; export it and extend " + | |
| 9998 | + "WorkflowEntrypoint", | |
| 9999 | + }; | |
| 10000 | + __wfFinishRetention(current, transaction); | |
| 10001 | + /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 10002 | + }); | |
| 10003 | + return; | |
| 10004 | + } | |
| 10005 | + const driver = { | |
| 10006 | + storage: undefined, | |
| 10007 | + storageFailure: undefined, | |
| 10008 | + generation: meta.generation, | |
| 10009 | + ledgerPrefix: __wfLedgerPrefix(meta.generation), | |
| 10010 | + counts: new Map(), | |
| 10011 | + ordinal: 0, | |
| 10012 | + running: 0, | |
| 10013 | + blocked: [], | |
| 10014 | + pauseRequested: false, | |
| 10015 | + finished: false, | |
| 10016 | + checkQueued: false, | |
| 10017 | + stallTimer: undefined, | |
| 10018 | + clearStall() { | |
| 10019 | + if (this.stallTimer !== undefined) { | |
| 10020 | + clearTimeout(this.stallTimer); | |
| 10021 | + this.stallTimer = undefined; | |
| 10022 | + } | |
| 10023 | + }, | |
| 10024 | + }; | |
| 10025 | + driver.storage = __wfTrackStorageFailures(storage, driver); | |
| 10026 | + const outcome = new Promise((resolve) => { | |
| 10027 | + driver.finish = (result) => { | |
| 10028 | + if (driver.finished) return; | |
| 10029 | + driver.finished = true; | |
| 10030 | + driver.clearStall(); | |
| 10031 | + resolve(result); | |
| 10032 | + }; | |
| 10033 | + }); | |
| 10034 | + // Quiescence: when a step is blocked, no step callback is executing, | |
| 10035 | + // and a macrotask has passed, nothing can progress, so the invocation | |
| 10036 | + // suspends. The macrotask lets every microtask chain a completed step | |
| 10037 | + // unblocked drain first; checking on the spot would suspend an instance | |
| 10038 | + // whose next step is one `await` away from starting. | |
| 10039 | + driver.check = () => { | |
| 10040 | + if (driver.checkQueued || driver.finished) return; | |
| 10041 | + driver.checkQueued = true; | |
| 10042 | + setTimeout(() => { | |
| 10043 | + driver.checkQueued = false; | |
| 10044 | + if (driver.finished || driver.running !== 0) return; | |
| 10045 | + if (driver.pauseRequested) { | |
| 10046 | + driver.finish({ kind: "pause" }); | |
| 10047 | + return; | |
| 10048 | + } | |
| 10049 | + if (driver.blocked.length > 0) { | |
| 10050 | + driver.finish({ kind: "suspend" }); | |
| 10051 | + return; | |
| 10052 | + } | |
| 10053 | + // No step runs, none is blocked, and run() has not settled: it | |
| 10054 | + // awaits something that is not a step. Upstream permits that -- an | |
| 10055 | + // un-stepped `await fetch()` between steps is legal, merely | |
| 10056 | + // non-durable -- so this is not yet an error; but a promise that | |
| 10057 | + // never settles would wedge the alarm handler in silence, with the | |
| 10058 | + // instance "running" forever. A grace timer splits the two: if the | |
| 10059 | + // same nothing-can-progress state still holds when it fires, the | |
| 10060 | + // instance fails loudly. The timer is a plain in-isolate timeout, | |
| 10061 | + // not a durable alarm, on purpose: an eviction or a restart replays | |
| 10062 | + // run() from the top anyway, so losing the timer loses nothing -- | |
| 10063 | + // the replay re-enters the same stall and re-arms its own grace. | |
| 10064 | + if (driver.stallTimer !== undefined) return; | |
| 10065 | + driver.stallTimer = setTimeout(() => { | |
| 10066 | + driver.stallTimer = undefined; | |
| 10067 | + if (driver.finished || driver.running !== 0 || driver.blocked.length > 0) { | |
| 10068 | + return; | |
| 10069 | + } | |
| 10070 | + driver.finish({ | |
| 10071 | + kind: "error", | |
| 10072 | + error: __wfError( | |
| 10073 | + "run() has been awaiting something that is not a step for " + | |
| 10074 | + (__WF_STALL_GRACE_MS / 1000) + " seconds while no step is " + | |
| 10075 | + "running or blocked; a replay cannot resume this wait, so " + | |
| 10076 | + "wrap long async work in step.do", | |
| 10077 | + ), | |
| 10078 | + }); | |
| 10079 | + }, __WF_STALL_GRACE_MS); | |
| 10080 | + }, 0); | |
| 10081 | + }; | |
| 10082 | + if ( | |
| 10083 | + meta.status !== "running" && | |
| 10084 | + !(await settle((current) => { | |
| 10085 | + current.status = "running"; | |
| 10086 | + })) | |
| 10087 | + ) { | |
| 10088 | + return; | |
| 10089 | + } | |
| 10090 | + const step = __wfMakeStep(driver); | |
| 10091 | + const event = { | |
| 10092 | + payload: meta.params, | |
| 10093 | + timestamp: new Date(meta.createdMs), | |
| 10094 | + instanceId: meta.instanceId, | |
| 10095 | + workflowName: meta.workflowName, | |
| 10096 | + }; | |
| 10097 | + // ExecutionContext-shaped, as the WorkflowEntrypoint constructor | |
| 10098 | + // documents upstream. | |
| 10099 | + const ctx = { | |
| 10100 | + waitUntil: __registerWaitUntil, | |
| 10101 | + passThroughOnException() {}, | |
| 10102 | + }; | |
| 10103 | + (async () => new cls(ctx, __cell.env).run(event, step))().then( | |
| 10104 | + (value) => driver.finish({ kind: "complete", value }), | |
| 10105 | + (error) => driver.finish({ kind: "error", error }), | |
| 10106 | + ); | |
| 10107 | + /*__CELLD_TEST_WORKFLOW_AFTER_RUN_STARTED__*/ | |
| 10108 | + let result = await outcome; | |
| 10109 | + // The workflow can catch a rejected step promise, but it cannot turn an | |
| 10110 | + // engine storage failure into a successful run. Preserve the alarm so | |
| 10111 | + // the runtime retries over the last committed ledger prefix. | |
| 10112 | + if (driver.storageFailure !== undefined) { | |
| 10113 | + throw driver.storageFailure; | |
| 10114 | + } | |
| 10115 | + const currentMeta = await storage.get("__wf.meta"); | |
| 10116 | + if ( | |
| 10117 | + result.kind === "pause" || | |
| 10118 | + (currentMeta !== undefined && | |
| 10119 | + currentMeta.generation === meta.generation && | |
| 10120 | + currentMeta.status === "waitingForPause") | |
| 10121 | + ) { | |
| 10122 | + /*__CELLD_TEST_WORKFLOW_BEFORE_PAUSE_SETTLE__*/ | |
| 10123 | + settle((current, transaction) => { | |
| 10124 | + // A resume can cancel waitingForPause after this drive selected its | |
| 10125 | + // pause result. Preserve that newer running state and its alarm, or | |
| 10126 | + // this stale settlement strands an acknowledged resume as paused. | |
| 10127 | + if (current.status !== "waitingForPause") return; | |
| 10128 | + current.status = "paused"; | |
| 10129 | + current.pausedMs = Date.now(); | |
| 10130 | + transaction.deleteAlarm(); | |
| 10131 | + }); | |
| 10132 | + return; | |
| 10133 | + } | |
| 10134 | + if (result.kind === "suspend") { | |
| 10135 | + let at = Math.min(...driver.blocked.map((entry) => entry.at)); | |
| 10136 | + // A nudge that landed mid-drive must not wait out the pending | |
| 10137 | + // deadline. It is visible in one of two places: getAlarm(), when the | |
| 10138 | + // nudge re-armed and no second alarm dispatched yet, or `_wfNudge`, | |
| 10139 | + // when a second alarm() already entered and parked on the drive | |
| 10140 | + // guard -- its dispatch consumed the armed alarm, so getAlarm() | |
| 10141 | + // alone would miss it. | |
| 10142 | + const nudge = await storage.getAlarm(); | |
| 10143 | + if (nudge !== null) at = Math.min(at, nudge); | |
| 10144 | + if (this._wfNudge !== undefined) { | |
| 10145 | + at = Math.min(at, this._wfNudge); | |
| 10146 | + this._wfNudge = undefined; | |
| 10147 | + } | |
| 10148 | + settle((current, transaction) => { | |
| 10149 | + current.status = "waiting"; | |
| 10150 | + transaction.setAlarm(at); | |
| 10151 | + }); | |
| 10152 | + // The explicit re-arm replaces the alarm that fired this drive. | |
| 10153 | + // Durability is per SQLite commit, not per turn: a crash can persist | |
| 10154 | + // any prefix of this invocation's ledger writes, and the unconsumed | |
| 10155 | + // fired alarm is what re-drives the replay over whatever prefix | |
| 10156 | + // survived. A terminated instance re-arms nothing; its leftover | |
| 10157 | + // alarm fires once, sees the terminal status, and retires itself. | |
| 10158 | + return; | |
| 10159 | + } | |
| 10160 | + if (result.kind === "complete") { | |
| 10161 | + try { | |
| 10162 | + if (result.value !== undefined) { | |
| 10163 | + __wfCheckValue(result.value, "the run() return value"); | |
| 10164 | + } | |
| 10165 | + } catch (error) { | |
| 10166 | + result = { kind: "error", error }; | |
| 10167 | + } | |
| 10168 | + if (result.kind === "complete") { | |
| 10169 | + // Keep settlement outside the value-validation catch. A storage | |
| 10170 | + // failure must escape the alarm handler so the engine retries the | |
| 10171 | + // still-armed drive; converting it to a user error would consume the | |
| 10172 | + // alarm and make a transient commit failure terminal. | |
| 10173 | + settle((current, transaction) => { | |
| 10174 | + current.status = "complete"; | |
| 10175 | + if (result.value !== undefined) current.output = result.value; | |
| 10176 | + // The terminal commit installs the expiry wake with the retained | |
| 10177 | + // state, so a crash can expose neither without the other. | |
| 10178 | + __wfFinishRetention(current, transaction); | |
| 10179 | + /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 10180 | + }); | |
| 10181 | + return; | |
| 10182 | + } | |
| 10183 | + } | |
| 10184 | + settle((current, transaction) => { | |
| 10185 | + current.status = "errored"; | |
| 10186 | + current.error = __wfErrorRecord(result.error); | |
| 10187 | + __wfFinishRetention(current, transaction); | |
| 10188 | + /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 10189 | + }); | |
| 10190 | + } | |
| 10191 | + }; | |
| 10192 | +})(); | |
| 10193 | +__cell.classes.__Workflow = __WorkflowCell; | |
| 10194 | +// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class | |
| 10195 | +// is the runtime's own, so grant it here, as __D1Database does. | |
| 10196 | +__cell.doExports.__Workflow = true; | |
| 10197 | + | |
| 10198 | +class NonRetryableError extends Error { | |
| 10199 | + constructor(message, name = "NonRetryableError") { | |
| 10200 | + super(message); | |
| 10201 | + this.name = name; | |
| 10202 | + } | |
| 10203 | +} | |
| 10204 | +// Backing object for the `cloudflare:workflows` builtin module. | |
| 10205 | +__celld.__cfWorkflows = { NonRetryableError }; | |
| 10206 | + | |
| 10207 | +const __wfValidInstanceId = (id) => | |
| 10208 | + typeof id === "string" && id.length >= 1 && id.length <= 100 && | |
| 10209 | + __WF_NAME_RE.test(id); | |
| 10210 | +const __wfCreateOptions = (options, what, validateParams = true) => { | |
| 10211 | + if (!__wfOwnObject(options)) { | |
| 10212 | + throw __wfError(`${what} needs an object`); | |
| 10213 | + } | |
| 10214 | + const retention = __wfRetentionOptions(options.retention, what); | |
| 10215 | + const locationHint = __wfLocationHint(options.locationHint, what); | |
| 10216 | + const id = options.id === undefined ? crypto.randomUUID() : options.id; | |
| 10217 | + if (!__wfValidInstanceId(id)) { | |
| 10218 | + throw __wfError( | |
| 10219 | + `invalid instance id ${JSON.stringify(id)}: use letters, digits, ` + | |
| 10220 | + "\"-\" and \"_\" (not starting with \"-\"), at most 100 characters", | |
| 10221 | + ); | |
| 10222 | + } | |
| 10223 | + if (validateParams && options.params !== undefined) { | |
| 10224 | + // The cell repeats this serialization check because it owns the durable | |
| 10225 | + // create invariant. A single create rejects before it addresses the cell. | |
| 10226 | + __wfCheckValue(options.params, "the workflow params"); | |
| 10227 | + } | |
| 10228 | + return { id, params: options.params, retention, locationHint }; | |
| 10229 | +}; | |
| 10230 | + | |
| 10231 | +// Named so SDKs that sniff a binding by `constructor.name` recognise it. | |
| 10232 | +class WorkflowInstance { | |
| 10233 | + constructor(workflowName, id) { | |
| 10234 | + Object.defineProperty(this, "_workflowName", { value: workflowName }); | |
| 10235 | + this.id = id; | |
| 10236 | + } | |
| 10237 | + // Resolved per call rather than cached: a cell can move between calls. | |
| 10238 | + get _stub() { | |
| 10239 | + // The reserved class is script-scoped (`deploy::workflow_class`), because | |
| 10240 | + // a workflow instance is: two co-hosted scripts must not share one entry | |
| 10241 | + // in the deployment's flat class registry. `__cell.script` is injected | |
| 10242 | + // before any binding runs, so this resolves at call time. | |
| 10243 | + return __cell.makeNamespace("__Workflow." + __cell.script) | |
| 10244 | + .getByName(this._workflowName + "/" + this.id); | |
| 10245 | + } | |
| 10246 | + async status() { | |
| 10247 | + return await this._stub.__wfStatus(); | |
| 10248 | + } | |
| 10249 | + async terminate(options) { | |
| 10250 | + if (options && options.rollback) { | |
| 10251 | + throw __wfError( | |
| 10252 | + "terminate({rollback: true}) is not implemented in celld; step " + | |
| 10253 | + "rollbackOptions are not implemented, so no handler could run", | |
| 10254 | + ); | |
| 10255 | + } | |
| 10256 | + await this._stub.__wfTerminate(); | |
| 10257 | + } | |
| 10258 | + async sendEvent(options) { | |
| 10259 | + await this._stub.__wfSendEvent(__wfEventOptions(options)); | |
| 10260 | + } | |
| 10261 | + async pause() { | |
| 10262 | + await this._stub.__wfPause(); | |
| 10263 | + } | |
| 10264 | + async resume() { | |
| 10265 | + await this._stub.__wfResume(); | |
| 10266 | + } | |
| 10267 | + async restart(options) { | |
| 10268 | + await this._stub.__wfRestart(__wfRestartOptions(options)); | |
| 10269 | + } | |
| 10270 | + async delete() { | |
| 10271 | + try { | |
| 10272 | + await this._stub.__wfDelete(); | |
| 10273 | + } catch (error) { | |
| 10274 | + // The deletion commit resets an active Workflow cell so an in-flight | |
| 10275 | + // callback cannot put old ledger state back. That reset rejects this | |
| 10276 | + // RPC with its private completion marker; it is the successful path. | |
| 10277 | + if (!String(error && error.message || error).includes("WORKFLOW_INSTANCE_DELETED")) { | |
| 10278 | + throw error; | |
| 10279 | + } | |
| 10280 | + } | |
| 10281 | + } | |
| 10282 | +} | |
| 10283 | + | |
| 10284 | +class Workflow { | |
| 10285 | + constructor(workflowName) { | |
| 10286 | + Object.defineProperty(this, "_workflowName", { value: workflowName }); | |
| 10287 | + } | |
| 10288 | + async _create(options, skipExisting) { | |
| 10289 | + const { id, params, retention, locationHint } = options; | |
| 10290 | + const instance = new WorkflowInstance(this._workflowName, id); | |
| 10291 | + const result = await instance._stub.__wfCreate({ | |
| 10292 | + workflowName: this._workflowName, | |
| 10293 | + instanceId: id, | |
| 10294 | + params, | |
| 10295 | + retention, | |
| 10296 | + locationHint, | |
| 10297 | + skipExisting, | |
| 10298 | + }); | |
| 10299 | + return result.created ? instance : undefined; | |
| 10300 | + } | |
| 10301 | + async create(options = {}) { | |
| 10302 | + return await this._create(__wfCreateOptions(options, "create()"), false); | |
| 10303 | + } | |
| 10304 | + async createBatch(batch) { | |
| 10305 | + if (!Array.isArray(batch)) { | |
| 10306 | + throw __wfError("createBatch() needs an array of create options"); | |
| 10307 | + } | |
| 10308 | + if (batch.length > 100) { | |
| 10309 | + throw __wfError( | |
| 10310 | + `createBatch() accepts at most 100 instances, got ${batch.length}`, | |
| 10311 | + ); | |
| 10312 | + } | |
| 10313 | + if (batch.length === 0) { | |
| 10314 | + throw __wfError("createBatch() needs at least one instance"); | |
| 10315 | + } | |
| 10316 | + // Cloudflare rejects a structural error in any item before it creates the | |
| 10317 | + // first instance, but it filters a params clone failure per item. Keep | |
| 10318 | + // these two gates separate so a bad ID stays atomic while a clone failure | |
| 10319 | + // does not suppress the valid items around it. | |
| 10320 | + const optionsList = batch.map((options, index) => | |
| 10321 | + __wfCreateOptions(options, `createBatch() item ${index}`, false)); | |
| 10322 | + const creatable = []; | |
| 10323 | + for (const options of optionsList) { | |
| 10324 | + let encoded; | |
| 10325 | + try { | |
| 10326 | + if (options.params !== undefined) { | |
| 10327 | + encoded = __wfEncodeValue(options.params, "the workflow params"); | |
| 10328 | + } | |
| 10329 | + } catch { | |
| 10330 | + continue; | |
| 10331 | + } | |
| 10332 | + if (encoded !== undefined) { | |
| 10333 | + __wfCheckEncodedValue(encoded, "the workflow params"); | |
| 10334 | + } | |
| 10335 | + creatable.push(options); | |
| 10336 | + } | |
| 10337 | + const created = []; | |
| 10338 | + for (const options of creatable) { | |
| 10339 | + const instance = await this._create(options, true); | |
| 10340 | + if (instance !== undefined) created.push(instance); | |
| 10341 | + } | |
| 10342 | + return created; | |
| 10343 | + } | |
| 10344 | + async get(id) { | |
| 10345 | + if (!__wfValidInstanceId(id)) { | |
| 10346 | + throw __wfError(`invalid instance id ${JSON.stringify(id)}`); | |
| 10347 | + } | |
| 10348 | + const instance = new WorkflowInstance(this._workflowName, id); | |
| 10349 | + // The cell exists on first address like any cell, but get() must not | |
| 10350 | + // mint an instance for a typo: an id with no ledger rejects here. | |
| 10351 | + await instance._stub.__wfStatus(); | |
| 10352 | + return instance; | |
| 10353 | + } | |
| 10354 | + async deleteBatch(instanceIds) { | |
| 10355 | + if (!Array.isArray(instanceIds)) { | |
| 10356 | + throw __wfError("deleteBatch() needs an array of instance ids"); | |
| 10357 | + } | |
| 10358 | + if (instanceIds.length < 1 || instanceIds.length > 100) { | |
| 10359 | + throw __wfError( | |
| 10360 | + `deleteBatch() accepts 1 to 100 instance ids, got ${instanceIds.length}`, | |
| 10361 | + ); | |
| 10362 | + } | |
| 10363 | + for (const id of instanceIds) { | |
| 10364 | + if (!__wfValidInstanceId(id)) { | |
| 10365 | + throw __wfError(`invalid instance id ${JSON.stringify(id)}`); | |
| 10366 | + } | |
| 10367 | + } | |
| 10368 | + const uniqueIds = [...new Set(instanceIds)]; | |
| 10369 | + const settled = await Promise.allSettled(uniqueIds.map(async (id) => { | |
| 10370 | + const instance = new WorkflowInstance(this._workflowName, id); | |
| 10371 | + await instance.delete(); | |
| 10372 | + })); | |
| 10373 | + const results = new Map(uniqueIds.map((id, index) => [id, settled[index]])); | |
| 10374 | + const output = { deleted: [], errors: [] }; | |
| 10375 | + for (const id of instanceIds) { | |
| 10376 | + const result = results.get(id); | |
| 10377 | + if (result.status === "fulfilled") { | |
| 10378 | + output.deleted.push({ id }); | |
| 10379 | + continue; | |
| 10380 | + } | |
| 10381 | + const notFound = String(result.reason && result.reason.message || result.reason) | |
| 10382 | + .includes("instance does not exist"); | |
| 10383 | + output.errors.push({ | |
| 10384 | + id, | |
| 10385 | + code: notFound ? 10400 : 10001, | |
| 10386 | + message: notFound | |
| 10387 | + ? "workflows.api.error.instance.not_found" | |
| 10388 | + : "workflows.api.error.internal_server", | |
| 10389 | + }); | |
| 10390 | + } | |
| 10391 | + return output; | |
| 10392 | + } | |
| 10393 | +} | |
| 10394 | + | |
| 10395 | +const __makeWorkflow = __celld.__makeWorkflow = | |
| 10396 | + (workflowName) => new Workflow(workflowName); | |
| 10397 | +// `cloudflare:workers` module surface. The DO base class sets ctx/env the | |
| 10398 | +// way `class X extends DurableObject` expects; env aliases the cell env. | |
| 10399 | +const __cf = __celld.__cf = { | |
| 10400 | + DurableObject: class DurableObject { | |
| 10401 | + constructor(ctx, env) { this.ctx = ctx; this.env = env; } | |
| 10402 | + }, | |
| 10403 | + // The enumerable function-valued brand makes V8's structured clone | |
| 10404 | + // fail on every RpcTarget instance, forcing it off the silent | |
| 10405 | + // plain-clone path and into the stub lift (Workerd rejects these | |
| 10406 | + // from plain serialization outright). | |
| 10407 | + RpcTarget: class RpcTarget { | |
| 10408 | + constructor() { | |
| 10409 | + Object.defineProperty(this, "__celldRpcTarget", { | |
| 10410 | + value: __rpcNoClone, enumerable: true, | |
| 10411 | + }); | |
| 10412 | + } | |
| 10413 | + }, | |
| 10414 | + // Named entrypoint for `[[services]]` with `entrypoint = "Name"`. | |
| 10415 | + WorkerEntrypoint: class WorkerEntrypoint { | |
| 10416 | + constructor(ctx, env) { this.ctx = ctx; this.env = env; } | |
| 10417 | + }, | |
| 10418 | + // Base class for `workflows` classes. The reserved workflow cell | |
| 10419 | + // instantiates a subclass on every replay with an ExecutionContext-shaped | |
| 10420 | + // ctx -- never the cell's own DurableObjectState, which would hand user | |
| 10421 | + // code the ledger that replays it. | |
| 10422 | + WorkflowEntrypoint: class WorkflowEntrypoint { | |
| 10423 | + constructor(ctx, env) { this.ctx = ctx; this.env = env; } | |
| 10424 | + }, | |
| 10425 | + // `new RpcStub(target)` wraps any local object or function in a | |
| 10426 | + // loopback stub; the constructor returns the proxy, so instanceof | |
| 10427 | + // works through __makeStub's getPrototypeOf trap. | |
| 10428 | + RpcStub: class RpcStub { | |
| 10429 | + constructor(target) { | |
| 10430 | + if (target === null || | |
| 10431 | + (typeof target !== "object" && typeof target !== "function")) | |
| 10432 | + throw new TypeError( | |
| 10433 | + "RpcStub requires an object or function."); | |
| 10434 | + return __makeStub( | |
| 10435 | + __newEntry(target), typeof target === "function"); | |
| 10436 | + } | |
| 10437 | + }, | |
| 10438 | + RpcPromise: class RpcPromise extends Promise {}, | |
| 10439 | + RpcProperty: class RpcProperty {}, | |
| 10440 | + ServiceStub: class ServiceStub {}, | |
| 10441 | + // `import { waitUntil } from "cloudflare:workers"`: register into | |
| 10442 | + // the current event; outside any event this is Workerd's | |
| 10443 | + // global-scope error. | |
| 10444 | + waitUntil(promise) { | |
| 10445 | + if (__event_depth() === 0) | |
| 10446 | + throw new Error( | |
| 10447 | + "Disallowed operation called within global scope."); | |
| 10448 | + __registerWaitUntil(promise); | |
| 10449 | + }, | |
| 10450 | + exports: {}, | |
| 10451 | + get env() { return __cell.env; }, | |
| 10452 | +}; | |
| 10453 | +// Proxy standing in for unsupported node:*/cloudflare:* builtins. Property | |
| 10454 | +// walks stay inert -- real bundles reference these at module scope, and | |
| 10455 | +// evaluation must not crash on a builtin the fetch path never exercises -- | |
| 10456 | +// but a call or construct throws: the compat contract is "reject at first | |
| 10457 | +// use", and the old silent pass-through turned a missing builtin into a | |
| 10458 | +// wrong result far from the cause. Memoized by dotted path so repeated | |
| 10459 | +// reads keep identity (`mod.foo === mod.foo`). | |
| 10460 | +const __stubCache = new Map(); | |
| 10461 | +const __nodeStubFor = __celld.__nodeStubFor = (path) => { | |
| 10462 | + let stub = __stubCache.get(path); | |
| 10463 | + if (stub) return stub; | |
| 10464 | + stub = new Proxy(function () {}, { | |
| 10465 | + get: (_t, p) => { | |
| 10466 | + // Never masquerade as a thenable. `await` probes `.then`; returning | |
| 10467 | + // a callable here creates a promise that can never settle. | |
| 10468 | + if (p === "then") return undefined; | |
| 10469 | + // coerce cleanly in string/number contexts so evaluation never throws | |
| 10470 | + if (p === Symbol.toPrimitive || p === "toString" || p === "valueOf") | |
| 10471 | + return () => ""; | |
| 10472 | + if (p === Symbol.toStringTag) return "NodeStub"; | |
| 10473 | + if (p === Symbol.iterator) return function* () {}; | |
| 10474 | + if (typeof p !== "string") return undefined; | |
| 10475 | + return __nodeStubFor(path + "." + p); | |
| 10476 | + }, | |
| 10477 | + apply() { throw new Error(path + " is not implemented in celld"); }, | |
| 10478 | + construct() { throw new Error(path + " is not implemented in celld"); }, | |
| 10479 | + }); | |
| 10480 | + __stubCache.set(path, stub); | |
| 10481 | + return stub; | |
| 10482 | +}; | |
| 10483 | +__celld.__nodeStub = __nodeStubFor("node builtin"); | |
| 10484 | +if (!globalThis.Event) { | |
| 10485 | + globalThis.Event = class Event { | |
| 10486 | + // Private fields: stored in the object itself, so an Event costs no | |
| 10487 | + // side allocation and no defineProperty call at construction. The | |
| 10488 | + // public members are accessors because the DOM standard makes them | |
| 10489 | + // read-only; EventTarget drives them through _begin/_end. | |
| 10490 | + #type; #bubbles; #cancelable; #composed; | |
| 10491 | + #defaultPrevented = false; | |
| 10492 | + #eventPhase = 0; | |
| 10493 | + #target; #currentTarget; #path; | |
| 10494 | + #stop = false; #stopImmediate = false; #dispatching = false; | |
| 10495 | + // Workerd: events the runtime delivers are trusted; events a | |
| 10496 | + // script constructs and dispatches itself are not. | |
| 10497 | + #trusted = false; | |
| 10498 | + constructor(type, init = {}) { | |
| 10499 | + if (arguments.length === 0) | |
| 10500 | + throw new TypeError( | |
| 10501 | + "Failed to construct 'Event': 1 argument required, but only " + | |
| 10502 | + "0 present."); | |
| 10503 | + if (init !== undefined && init !== null && | |
| 10504 | + typeof init !== "object") | |
| 10505 | + throw new TypeError( | |
| 10506 | + "Failed to construct 'Event': The provided value is not of " + | |
| 10507 | + "type 'EventInit'."); | |
| 10508 | + const options = init || {}; | |
| 10509 | + // Template interpolation, not String(): it must throw for a | |
| 10510 | + // Symbol, which String() would happily format. | |
| 10511 | + this.#type = `${type}`; | |
| 10512 | + this.#bubbles = !!options.bubbles; | |
| 10513 | + this.#cancelable = !!options.cancelable; | |
| 10514 | + this.#composed = !!options.composed; | |
| 10515 | + } | |
| 10516 | + get type() { return this.#type; } | |
| 10517 | + get bubbles() { return this.#bubbles; } | |
| 10518 | + get cancelable() { return this.#cancelable; } | |
| 10519 | + get composed() { return this.#composed; } | |
| 10520 | + get defaultPrevented() { return this.#defaultPrevented; } | |
| 10521 | + get eventPhase() { return this.#eventPhase; } | |
| 10522 | + get target() { return this.#target; } | |
| 10523 | + get currentTarget() { return this.#currentTarget; } | |
| 10524 | + get isTrusted() { return this.#trusted; } | |
| 10525 | + get timeStamp() { return 0; } | |
| 10526 | + get returnValue() { return !this.#defaultPrevented; } | |
| 10527 | + // The one writable member, per the DOM standard. | |
| 10528 | + get cancelBubble() { return this.#stop; } | |
| 10529 | + set cancelBubble(value) { if (value) this.#stop = true; } | |
| 10530 | + composedPath() { return this.#path ? this.#path.slice() : []; } | |
| 10531 | + preventDefault() { | |
| 10532 | + if (this.#cancelable) this.#defaultPrevented = true; | |
| 10533 | + } | |
| 10534 | + stopPropagation() { this.#stop = true; } | |
| 10535 | + stopImmediatePropagation() { | |
| 10536 | + this.#stop = true; | |
| 10537 | + this.#stopImmediate = true; | |
| 10538 | + } | |
| 10539 | + // Internal dispatch hooks used by EventTarget. | |
| 10540 | + get _dispatching() { return this.#dispatching; } | |
| 10541 | + get _stopImmediate() { return this.#stopImmediate; } | |
| 10542 | + _trust() { this.#trusted = true; } | |
| 10543 | + _begin(target) { | |
| 10544 | + this.#dispatching = true; | |
| 10545 | + this.#target = target; | |
| 10546 | + this.#currentTarget = target; | |
| 10547 | + this.#eventPhase = 2; // AT_TARGET | |
| 10548 | + this.#path = [target]; | |
| 10549 | + this.#stop = false; | |
| 10550 | + this.#stopImmediate = false; | |
| 10551 | + } | |
| 10552 | + // Workerd leaves currentTarget set after dispatch (the DOM standard | |
| 10553 | + // nulls it); only the phase is reset. | |
| 10554 | + _end() { | |
| 10555 | + this.#eventPhase = 0; | |
| 10556 | + this.#dispatching = false; | |
| 10557 | + } | |
| 10558 | + }; | |
| 10559 | + { | |
| 10560 | + const phases = { | |
| 10561 | + NONE: 0, CAPTURING_PHASE: 1, AT_TARGET: 2, BUBBLING_PHASE: 3, | |
| 10562 | + }; | |
| 10563 | + for (const [name, value] of Object.entries(phases)) { | |
| 10564 | + const d = { value, writable: false, enumerable: true, | |
| 10565 | + configurable: false }; | |
| 10566 | + Object.defineProperty(globalThis.Event, name, d); | |
| 10567 | + Object.defineProperty(globalThis.Event.prototype, name, d); | |
| 10568 | + } | |
| 10569 | + } | |
| 10570 | +} | |
| 10571 | +if (!globalThis.CustomEvent) { | |
| 10572 | + globalThis.CustomEvent = class CustomEvent extends Event { | |
| 10573 | + constructor(type, init = {}) { | |
| 10574 | + super(type, init); | |
| 10575 | + this.detail = init.detail === undefined ? null : init.detail; | |
| 10576 | + } | |
| 10577 | + }; | |
| 10578 | +} | |
| 10579 | +if (!globalThis.ExtendableEvent) { | |
| 10580 | + // Exists as a type but is not constructable from user code. | |
| 10581 | + globalThis.ExtendableEvent = class ExtendableEvent extends Event { | |
| 10582 | + constructor() { | |
| 10583 | + throw new TypeError("Illegal constructor"); | |
| 10584 | + } | |
| 10585 | + }; | |
| 10586 | +} | |
| 10587 | +// An event-handler IDL attribute occupies one listener-list position. Replacing | |
| 10588 | +// its callback must retain that position, or listeners added after `onabort` | |
| 10589 | +// run before it and observe an order that differs from the web platform. | |
| 10590 | +const __eventHandlerEntry = Symbol("eventHandlerEntry"); | |
| 10591 | +const __getEventHandler = (target, type) => | |
| 10592 | + (target._listeners.get(type) || []) | |
| 10593 | + .find((entry) => entry[__eventHandlerEntry])?.callback ?? null; | |
| 10594 | +const __setEventHandler = (target, type, callback) => { | |
| 10595 | + const list = target._listeners.get(type) || []; | |
| 10596 | + const entry = list.find((item) => item[__eventHandlerEntry]); | |
| 10597 | + if (typeof callback !== "function") { | |
| 10598 | + if (entry) list.splice(list.indexOf(entry), 1); | |
| 10599 | + return; | |
| 10600 | + } | |
| 10601 | + if (entry) { | |
| 10602 | + entry.callback = callback; | |
| 10603 | + } else { | |
| 10604 | + list.push({ callback, once: false, [__eventHandlerEntry]: true }); | |
| 10605 | + target._listeners.set(type, list); | |
| 10606 | + } | |
| 10607 | +}; | |
| 10608 | +if (!globalThis.EventTarget) { | |
| 10609 | + globalThis.EventTarget = class EventTarget { | |
| 10610 | + constructor() { this._listeners = new Map(); } | |
| 10611 | + addEventListener(type, callback, options = {}) { | |
| 10612 | + if (callback === null || callback === undefined) return; | |
| 10613 | + if (typeof callback !== "function" && | |
| 10614 | + typeof callback.handleEvent !== "function") | |
| 10615 | + throw new TypeError( | |
| 10616 | + "Failed to execute 'addEventListener' on 'EventTarget': " + | |
| 10617 | + "parameter 2 is not of type 'EventListener'."); | |
| 10618 | + const object = typeof options === "object" && options !== null; | |
| 10619 | + // Capture and passive are accepted for portability but must be | |
| 10620 | + // false: Cells dispatches only at the target, so honouring them | |
| 10621 | + // would silently change ordering. | |
| 10622 | + if (object ? options.capture || options.passive : !!options) | |
| 10623 | + throw new TypeError( | |
| 10624 | + "Cells does not support the 'capture' or 'passive' options " + | |
| 10625 | + "on addEventListener()."); | |
| 10626 | + const signal = object ? options.signal : undefined; | |
| 10627 | + if (signal && signal.aborted) return; | |
| 10628 | + const key = String(type); | |
| 10629 | + const list = this._listeners.get(key) || []; | |
| 10630 | + if (list.some((e) => e.callback === callback)) return; | |
| 10631 | + list.push({ callback, once: object && !!options.once }); | |
| 10632 | + this._listeners.set(key, list); | |
| 10633 | + if (signal) | |
| 10634 | + signal.addEventListener("abort", () => | |
| 10635 | + this.removeEventListener(key, callback), { once: true }); | |
| 10636 | + } | |
| 10637 | + removeEventListener(type, callback, options = {}) { | |
| 10638 | + const object = typeof options === "object" && options !== null; | |
| 10639 | + if (object ? options.capture : !!options) | |
| 10640 | + throw new TypeError( | |
| 10641 | + "Cells does not support the 'capture' option on " + | |
| 10642 | + "removeEventListener()."); | |
| 10643 | + const list = this._listeners.get(String(type)); | |
| 10644 | + if (!list) return; | |
| 10645 | + const index = list.findIndex((e) => e.callback === callback); | |
| 10646 | + if (index >= 0) list.splice(index, 1); | |
| 10647 | + } | |
| 10648 | + dispatchEvent(event) { | |
| 10649 | + if (!(event instanceof Event)) | |
| 10650 | + throw new TypeError("argument is not an Event"); | |
| 10651 | + if (event._dispatching) | |
| 10652 | + throw new DOMException( | |
| 10653 | + "The event is already being dispatched.", | |
| 10654 | + "InvalidStateError"); | |
| 10655 | + event._begin(this); | |
| 10656 | + // Copy: a listener may add or remove listeners mid-dispatch. | |
| 10657 | + for (const item of (this._listeners.get(event.type) || []).slice()) { | |
| 10658 | + if (event._stopImmediate) break; | |
| 10659 | + if (item.once) | |
| 10660 | + this.removeEventListener(event.type, item.callback); | |
| 10661 | + if (typeof item.callback === "function") | |
| 10662 | + item.callback.call(this, event); | |
| 10663 | + else item.callback.handleEvent(event); | |
| 10664 | + } | |
| 10665 | + const handler = this["on" + event.type]; | |
| 10666 | + const hasEventHandler = (this._listeners.get(event.type) || []) | |
| 10667 | + .some((item) => item[__eventHandlerEntry]); | |
| 10668 | + if (!hasEventHandler && !event._stopImmediate && | |
| 10669 | + typeof handler === "function") | |
| 10670 | + handler.call(this, event); | |
| 10671 | + event._end(); | |
| 10672 | + return !event.defaultPrevented; | |
| 10673 | + } | |
| 10674 | + }; | |
| 10675 | +} | |
| 10676 | +// The global scope is itself an EventTarget. | |
| 10677 | +if (typeof globalThis.addEventListener !== "function") { | |
| 10678 | + const globalTarget = new EventTarget(); | |
| 10679 | + for (const name of | |
| 10680 | + ["addEventListener", "removeEventListener", "dispatchEvent"]) | |
| 10681 | + globalThis[name] = globalTarget[name].bind(globalTarget); | |
| 10682 | +} | |
| 10683 | +if (!globalThis.MessageEvent) { | |
| 10684 | + globalThis.MessageEvent = class MessageEvent extends Event { | |
| 10685 | + constructor(type, init = {}) { | |
| 10686 | + super(type, init); | |
| 10687 | + this.data = init.data; | |
| 10688 | + this.origin = String(init.origin || ""); | |
| 10689 | + this.lastEventId = String(init.lastEventId || ""); | |
| 10690 | + } | |
| 10691 | + }; | |
| 10692 | +} | |
| 10693 | +if (!globalThis.CloseEvent) { | |
| 10694 | + globalThis.CloseEvent = class CloseEvent extends Event { | |
| 10695 | + constructor(type, init = {}) { | |
| 10696 | + super(type, init); | |
| 10697 | + this.code = Number(init.code || 0); | |
| 10698 | + // `reason` is a USVString: a lone surrogate becomes U+FFFD rather than | |
| 10699 | + // travelling as an unpaired code unit. | |
| 10700 | + this.reason = String(init.reason || "").toWellFormed | |
| 10701 | + ? String(init.reason || "").toWellFormed() | |
| 10702 | + : String(init.reason || "").replace( | |
| 10703 | + /[\uD800-\uDFFF]/g, | |
| 10704 | + (unit, index, whole) => { | |
| 10705 | + const code = unit.charCodeAt(0); | |
| 10706 | + const next = whole.charCodeAt(index + 1); | |
| 10707 | + const prev = whole.charCodeAt(index - 1); | |
| 10708 | + const paired = code <= 0xDBFF | |
| 10709 | + ? next >= 0xDC00 && next <= 0xDFFF | |
| 10710 | + : prev >= 0xD800 && prev <= 0xDBFF; | |
| 10711 | + return paired ? unit : "\uFFFD"; | |
| 10712 | + }, | |
| 10713 | + ); | |
| 10714 | + this.wasClean = !!init.wasClean; | |
| 10715 | + } | |
| 10716 | + }; | |
| 10717 | +} | |
| 10718 | +if (!globalThis.DOMException) { | |
| 10719 | + globalThis.DOMException = class DOMException extends Error { | |
| 10720 | + constructor(message = "", name = "Error") { super(message); this.name = name; } | |
| 10721 | + }; | |
| 10722 | + // WebIDL legacy code constants, enumerable on both the interface | |
| 10723 | + // object and its prototype, in spec order. | |
| 10724 | + { | |
| 10725 | + const codes = [ | |
| 10726 | + ["INDEX_SIZE_ERR", 1], ["DOMSTRING_SIZE_ERR", 2], | |
| 10727 | + ["HIERARCHY_REQUEST_ERR", 3], ["WRONG_DOCUMENT_ERR", 4], | |
| 10728 | + ["INVALID_CHARACTER_ERR", 5], ["NO_DATA_ALLOWED_ERR", 6], | |
| 10729 | + ["NO_MODIFICATION_ALLOWED_ERR", 7], ["NOT_FOUND_ERR", 8], | |
| 10730 | + ["NOT_SUPPORTED_ERR", 9], ["INUSE_ATTRIBUTE_ERR", 10], | |
| 10731 | + ["INVALID_STATE_ERR", 11], ["SYNTAX_ERR", 12], | |
| 10732 | + ["INVALID_MODIFICATION_ERR", 13], ["NAMESPACE_ERR", 14], | |
| 10733 | + ["INVALID_ACCESS_ERR", 15], ["VALIDATION_ERR", 16], | |
| 10734 | + ["TYPE_MISMATCH_ERR", 17], ["SECURITY_ERR", 18], | |
| 10735 | + ["NETWORK_ERR", 19], ["ABORT_ERR", 20], | |
| 10736 | + ["URL_MISMATCH_ERR", 21], ["QUOTA_EXCEEDED_ERR", 22], | |
| 10737 | + ["TIMEOUT_ERR", 23], ["INVALID_NODE_TYPE_ERR", 24], | |
| 10738 | + ["DATA_CLONE_ERR", 25], | |
| 10739 | + ]; | |
| 10740 | + for (const [name, value] of codes) { | |
| 10741 | + const d = { value, writable: false, enumerable: true, | |
| 10742 | + configurable: false }; | |
| 10743 | + Object.defineProperty(globalThis.DOMException, name, d); | |
| 10744 | + Object.defineProperty(globalThis.DOMException.prototype, name, d); | |
| 10745 | + } | |
| 10746 | + // The legacy `code` member maps the error name to its constant, per | |
| 10747 | + // WebIDL; names outside the table (and every modern name) are 0. | |
| 10748 | + const legacy = { | |
| 10749 | + IndexSizeError: 1, HierarchyRequestError: 3, WrongDocumentError: 4, | |
| 10750 | + InvalidCharacterError: 5, NoModificationAllowedError: 7, | |
| 10751 | + NotFoundError: 8, NotSupportedError: 9, InUseAttributeError: 10, | |
| 10752 | + InvalidStateError: 11, SyntaxError: 12, InvalidModificationError: 13, | |
| 10753 | + NamespaceError: 14, InvalidAccessError: 15, TypeMismatchError: 17, | |
| 10754 | + SecurityError: 18, NetworkError: 19, AbortError: 20, | |
| 10755 | + URLMismatchError: 21, QuotaExceededError: 22, TimeoutError: 23, | |
| 10756 | + InvalidNodeTypeError: 24, DataCloneError: 25, | |
| 10757 | + }; | |
| 10758 | + Object.defineProperty(globalThis.DOMException.prototype, "code", { | |
| 10759 | + get() { return legacy[this.name] ?? 0; }, | |
| 10760 | + enumerable: true, configurable: true, | |
| 10761 | + }); | |
| 10762 | + } | |
| 10763 | +} | |
| 10764 | +if (!globalThis.AbortSignal) { | |
| 10765 | + const __abortBrand = Symbol("abortSignal"); | |
| 10766 | + globalThis.AbortSignal = class AbortSignal extends EventTarget { | |
| 10767 | + // The Headers/Blob clone-poisoning brand: V8's structured | |
| 10768 | + // clone throws on functions, so a live signal reaches the | |
| 10769 | + // RPC lift instead of silently flattening to plain data. | |
| 10770 | + constructor() { | |
| 10771 | + // Per spec AbortSignal has no constructor: it is only reachable | |
| 10772 | + // through AbortController, AbortSignal.abort/timeout/any. The internal | |
| 10773 | + // paths pass the brand to get past this. | |
| 10774 | + if (arguments[0] !== __abortBrand) { | |
| 10775 | + throw new TypeError("Illegal constructor"); | |
| 10776 | + } | |
| 10777 | + super(); | |
| 10778 | + this.aborted = false; | |
| 10779 | + this.reason = undefined; | |
| 10780 | + this.__celldHost = __rpcNoClone; | |
| 10781 | + } | |
| 10782 | + throwIfAborted() { if (this.aborted) throw this.reason; } | |
| 10783 | + static abort(reason = new DOMException("This operation was aborted", "AbortError")) { | |
| 10784 | + const c = new AbortController(); c.abort(reason); return c.signal; | |
| 10785 | + } | |
| 10786 | + static timeout(ms) { | |
| 10787 | + const c = new AbortController(); | |
| 10788 | + setTimeout(() => c.abort(new DOMException( | |
| 10789 | + "The operation was aborted due to timeout", "TimeoutError", | |
| 10790 | + )), ms); | |
| 10791 | + return c.signal; | |
| 10792 | + } | |
| 10793 | + static any(signals) { | |
| 10794 | + const c = new AbortController(); | |
| 10795 | + for (const signal of signals) { | |
| 10796 | + if (signal.aborted) { c.abort(signal.reason); break; } | |
| 10797 | + signal.addEventListener("abort", () => c.abort(signal.reason), { once: true }); | |
| 10798 | + } | |
| 10799 | + return c.signal; | |
| 10800 | + } | |
| 10801 | + }; | |
| 10802 | + Object.defineProperty(globalThis.AbortSignal.prototype, "onabort", { | |
| 10803 | + configurable: true, | |
| 10804 | + enumerable: true, | |
| 10805 | + get() { | |
| 10806 | + if (!(this instanceof globalThis.AbortSignal)) | |
| 10807 | + throw new TypeError("Illegal invocation"); | |
| 10808 | + return __getEventHandler(this, "abort"); | |
| 10809 | + }, | |
| 10810 | + set(value) { | |
| 10811 | + if (!(this instanceof globalThis.AbortSignal)) | |
| 10812 | + throw new TypeError("Illegal invocation"); | |
| 10813 | + __setEventHandler(this, "abort", value); | |
| 10814 | + }, | |
| 10815 | + }); | |
| 10816 | + globalThis.AbortController = class AbortController { | |
| 10817 | + constructor() { this.signal = new AbortSignal(__abortBrand); } | |
| 10818 | + abort(reason = new DOMException("This operation was aborted", "AbortError")) { | |
| 10819 | + __abortSignal(this.signal, reason); | |
| 10820 | + } | |
| 10821 | + }; | |
| 10822 | +} | |
| 10823 | +if (!globalThis.Blob) { | |
| 10824 | + // Same clone-poisoning brand as Headers: an enumerable | |
| 10825 | + // function-valued property makes V8's structured clone throw, so | |
| 10826 | + // a Blob reaches the RPC lift instead of silently flattening. | |
| 10827 | + const __blobNoClone = () => {}; | |
| 10828 | + globalThis.Blob = class Blob { | |
| 10829 | + constructor(parts = [], options = {}) { | |
| 10830 | + // size is assigned before type so both land in the order the | |
| 10831 | + // inspect output below reports them. | |
| 10832 | + if (options && options.endings !== undefined) | |
| 10833 | + throw new Error( | |
| 10834 | + "The 'endings' field on 'Options' is not implemented."); | |
| 10835 | + this.size = 0; | |
| 10836 | + // A type outside U+0020..U+007E is not a valid MIME type and is | |
| 10837 | + // dropped rather than stored. | |
| 10838 | + const rawType = String(options.type || ""); | |
| 10839 | + this.type = /^[\u0020-\u007e]*$/.test(rawType) | |
| 10840 | + ? rawType.toLowerCase() : ""; | |
| 10841 | + this.__celldHost = __blobNoClone; | |
| 10842 | + // Two passes. First convert every part in order -- string | |
| 10843 | + // conversion runs user code (Symbol.toPrimitive), which may | |
| 10844 | + // resize a backing buffer. Buffers and views are carried through | |
| 10845 | + // as-is so a length-tracking view is measured *after* those side | |
| 10846 | + // effects, matching Workerd. Then allocate once and copy. | |
| 10847 | + // | |
| 10848 | + // The previous shape pushed every byte into a plain array with a | |
| 10849 | + // spread, costing roughly 8x the memory and exceeding the | |
| 10850 | + // argument limit on multi-megabyte parts. | |
| 10851 | + const sources = []; | |
| 10852 | + for (const part of parts) { | |
| 10853 | + if (part instanceof Blob) sources.push(part._bytes); | |
| 10854 | + else if (part instanceof ArrayBuffer || | |
| 10855 | + ArrayBuffer.isView(part)) sources.push(part); | |
| 10856 | + else sources.push(new TextEncoder().encode(String(part))); | |
| 10857 | + } | |
| 10858 | + const chunks = sources.map((source) => | |
| 10859 | + source instanceof Uint8Array ? source | |
| 10860 | + : source instanceof ArrayBuffer ? new Uint8Array(source) | |
| 10861 | + : new Uint8Array( | |
| 10862 | + source.buffer, source.byteOffset, source.byteLength)); | |
| 10863 | + let total = 0; | |
| 10864 | + for (const chunk of chunks) total += chunk.byteLength; | |
| 10865 | + const LIMIT = 134217728; | |
| 10866 | + if (total > LIMIT) | |
| 10867 | + throw new RangeError( | |
| 10868 | + `Blob size ${total} exceeds limit ${LIMIT}`); | |
| 10869 | + const bytes = new Uint8Array(total); | |
| 10870 | + let offset = 0; | |
| 10871 | + for (const chunk of chunks) { | |
| 10872 | + bytes.set(chunk, offset); | |
| 10873 | + offset += chunk.byteLength; | |
| 10874 | + } | |
| 10875 | + // Non-enumerable: the backing store is not part of the object's | |
| 10876 | + // observable shape (inspect, JSON, spread). | |
| 10877 | + Object.defineProperty(this, "_bytes", { | |
| 10878 | + value: bytes, writable: true, configurable: true, | |
| 10879 | + }); | |
| 10880 | + this.size = total; | |
| 10881 | + } | |
| 10882 | + async arrayBuffer() { return this._bytes.slice().buffer; } | |
| 10883 | + async bytes() { return this._bytes.slice(); } | |
| 10884 | + async text() { return new TextDecoder().decode(this._bytes); } | |
| 10885 | + stream() { | |
| 10886 | + const bytes = this._bytes; | |
| 10887 | + return new ReadableStream({ | |
| 10888 | + start(controller) { | |
| 10889 | + if (bytes.byteLength) controller.enqueue(bytes.slice()); | |
| 10890 | + controller.close(); | |
| 10891 | + }, | |
| 10892 | + }); | |
| 10893 | + } | |
| 10894 | + [Symbol.for("nodejs.util.inspect.custom")]() { | |
| 10895 | + return `Blob { size: ${this.size}, type: '${this.type}' }`; | |
| 10896 | + } | |
| 10897 | + slice(start = 0, end = this.size, type = "") { | |
| 10898 | + const norm = (n, fallback) => { | |
| 10899 | + n = n === undefined ? fallback : Number(n); | |
| 10900 | + return n < 0 ? Math.max(this.size + n, 0) : Math.min(n, this.size); | |
| 10901 | + }; | |
| 10902 | + const a = norm(start, 0), b = norm(end, this.size); | |
| 10903 | + return new Blob( | |
| 10904 | + [this._bytes.subarray(a, Math.max(a, b))], { type }); | |
| 10905 | + } | |
| 10906 | + get [Symbol.toStringTag]() { return "Blob"; } | |
| 10907 | + }; | |
| 10908 | +} | |
| 10909 | +if (!globalThis.File) { | |
| 10910 | + // WebIDL-ish per Workerd: name is required, name/lastModified are | |
| 10911 | + // brand-checked prototype getters (enumerable, matching the | |
| 10912 | + // workers_api_getters_setters_on_prototype flag), and lastModified | |
| 10913 | + // coerces via ToNumber (throws for BigInt), NaN becoming 0. | |
| 10914 | + globalThis.File = class File extends Blob { | |
| 10915 | + #name; | |
| 10916 | + #lastModified; | |
| 10917 | + constructor(parts, name, options = {}) { | |
| 10918 | + if (arguments.length < 2) | |
| 10919 | + throw new TypeError( | |
| 10920 | + "Failed to construct 'File': 2 arguments required, but " + | |
| 10921 | + `only ${arguments.length} present.`); | |
| 10922 | + super(parts, options); | |
| 10923 | + this.#name = String(name); | |
| 10924 | + const lm = options == null ? undefined : options.lastModified; | |
| 10925 | + if (lm === undefined) this.#lastModified = Date.now(); | |
| 10926 | + else { | |
| 10927 | + const n = +lm; // ToNumber: throws for BigInt, like WebIDL | |
| 10928 | + this.#lastModified = Number.isFinite(n) ? Math.trunc(n) : 0; | |
| 10929 | + } | |
| 10930 | + } | |
| 10931 | + get name() { return this.#name; } | |
| 10932 | + get lastModified() { return this.#lastModified; } | |
| 10933 | + get [Symbol.toStringTag]() { return "File"; } | |
| 10934 | + [Symbol.for("nodejs.util.inspect.custom")]() { | |
| 10935 | + return `File { name: '${this.name}', ` + | |
| 10936 | + `lastModified: ${this.lastModified}, size: ${this.size}, ` + | |
| 10937 | + `type: '${this.type}' }`; | |
| 10938 | + } | |
| 10939 | + }; | |
| 10940 | + for (const key of ["name", "lastModified"]) { | |
| 10941 | + const desc = | |
| 10942 | + Object.getOwnPropertyDescriptor(File.prototype, key); | |
| 10943 | + desc.enumerable = true; | |
| 10944 | + Object.defineProperty(File.prototype, key, desc); | |
| 10945 | + } | |
| 10946 | +} | |
| 10947 | +if (!globalThis.FormData) { | |
| 10948 | +// Byte offsets the multipart scanner compares against. A part body is | |
| 10949 | +// arbitrary bytes, so every framing decision below is made on bytes. | |
| 10950 | +const __CR = 13, __LF = 10, __DASH = 45; | |
| 10951 | +const __bytesIndexOf = (haystack, needle, from) => { | |
| 10952 | + const last = haystack.length - needle.length; | |
| 10953 | + outer: for (let i = from; i <= last; i++) { | |
| 10954 | + for (let j = 0; j < needle.length; j++) | |
| 10955 | + if (haystack[i + j] !== needle[j]) continue outer; | |
| 10956 | + return i; | |
| 10957 | + } | |
| 10958 | + return -1; | |
| 10959 | +}; | |
| 10960 | +// A boundary delimiter is a delimiter only at the start of a line (RFC 2046 | |
| 10961 | +// section 5.1.1). Searching for the bytes anywhere would let a binary part | |
| 10962 | +// that happens to contain `--<boundary>` split itself, which is a corrupt | |
| 10963 | +// upload rather than a parse error, so the caller never learns of it. | |
| 10964 | +const __delimiterIndex = (bytes, delimiter, from) => { | |
| 10965 | + for (let at = from;;) { | |
| 10966 | + const found = __bytesIndexOf(bytes, delimiter, at); | |
| 10967 | + if (found < 0) return -1; | |
| 10968 | + if (found === 0 || bytes[found - 1] === __LF) return found; | |
| 10969 | + at = found + 1; | |
| 10970 | + } | |
| 10971 | +}; | |
| 10972 | +// A `Content-Disposition` parameter, anchored to the start of a parameter: | |
| 10973 | +// the parameter name must follow the header name or a `;`. An unanchored | |
| 10974 | +// pattern found the `name=` inside `filename=`, so a part whose header wrote | |
| 10975 | +// the filename first landed under the filename. The grammar does not | |
| 10976 | +// constrain the parameter order, and both orders occur in the wild. Hoisted | |
| 10977 | +// because the previous shape compiled a regex per parameter per part. | |
| 10978 | +const __CD_NAME = | |
| 10979 | + /(?:^|;)\s*name\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i; | |
| 10980 | +const __CD_FILENAME = | |
| 10981 | + /(?:^|;)\s*filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i; | |
| 10982 | +// Body -> FormData for multipart/form-data and | |
| 10983 | +// application/x-www-form-urlencoded. Kept out of the class so V8 only | |
| 10984 | +// pre-parses it; the body is compiled on first actual formData() call. | |
| 10985 | +// | |
| 10986 | +// `bytes` is the undecoded body. A file part must reach `File` as the bytes | |
| 10987 | +// that arrived: decoding the body first and slicing part bodies out of the | |
| 10988 | +// string replaced every non-UTF-8 sequence with U+FFFD, and the re-encode in | |
| 10989 | +// the `Blob` constructor then wrote those replacement bytes into the file. | |
| 10990 | +__celld.__parseFormData = (bytes, contentType) => { | |
| 10991 | + const ct = String(contentType || ""); | |
| 10992 | + if (/^\s*application\/x-www-form-urlencoded/i.test(ct)) { | |
| 10993 | + // This form is decoded as UTF-8, so a declared charset that is not UTF-8 | |
| 10994 | + // cannot be honoured. Refuse rather than mis-decode. | |
| 10995 | + const charset = /;\s*charset\s*=\s*"?([^";]+)/i.exec(ct); | |
| 10996 | + if (charset && !/^utf-?8$/i.test(charset[1].trim())) | |
| 10997 | + throw new TypeError( | |
| 10998 | + `Unsupported charset "${charset[1].trim()}". FormData can only ` + | |
| 10999 | + "parse UTF-8 encoded bodies."); | |
| 11000 | + const form = new FormData(); | |
| 11001 | + for (const [key, value] of new URLSearchParams( | |
| 11002 | + new TextDecoder().decode(bytes))) | |
| 11003 | + form.append(key, value); | |
| 11004 | + return form; | |
| 11005 | + } | |
| 11006 | + if (!/^\s*multipart\/form-data/i.test(ct)) | |
| 11007 | + throw new TypeError( | |
| 11008 | + "Unrecognized Content-Type header value. FormData can only " + | |
| 11009 | + "parse the following MIME types: multipart/form-data, " + | |
| 11010 | + "application/x-www-form-urlencoded"); | |
| 11011 | + const found = /boundary\s*=\s*(?:"([^"]*)"|([^;]+))/i.exec(ct); | |
| 11012 | + if (!found) | |
| 11013 | + throw new TypeError( | |
| 11014 | + "No boundary was found in the multipart/form-data " + | |
| 11015 | + "Content-Type header."); | |
| 11016 | + const boundary = (found[1] !== undefined ? found[1] : found[2]).trim(); | |
| 11017 | + const form = new FormData(); | |
| 11018 | + const delimiter = new TextEncoder().encode("--" + boundary); | |
| 11019 | + // Walk the delimiters rather than splitting on them, so that a body whose | |
| 11020 | + // framing is truncated or corrupt is refused instead of silently yielding | |
| 11021 | + // the parts that happened to parse. Only the framing is checked; a part's | |
| 11022 | + // own bytes are carried through unexamined. The preamble before the first | |
| 11023 | + // delimiter and the epilogue after the closing one are ignored. | |
| 11024 | + let cursor = __delimiterIndex(bytes, delimiter, 0); | |
| 11025 | + if (cursor < 0) | |
| 11026 | + throw new TypeError( | |
| 11027 | + "No boundary delimiter was found in the multipart/form-data body."); | |
| 11028 | + cursor += delimiter.length; | |
| 11029 | + for (;;) { | |
| 11030 | + // What follows a delimiter decides everything: "--" closes the body, a | |
| 11031 | + // line break opens another part, and anything else is malformed. | |
| 11032 | + if (bytes[cursor] === __DASH && bytes[cursor + 1] === __DASH) break; | |
| 11033 | + const lineBreak = bytes[cursor] === __CR && bytes[cursor + 1] === __LF | |
| 11034 | + ? 2 | |
| 11035 | + : bytes[cursor] === __LF ? 1 : 0; | |
| 11036 | + if (lineBreak === 0) | |
| 11037 | + throw new TypeError( | |
| 11038 | + "A boundary delimiter must be followed by CRLF, LF, or \"--\"."); | |
| 11039 | + cursor += lineBreak; | |
| 11040 | + const partStart = cursor; | |
| 11041 | + const next = __delimiterIndex(bytes, delimiter, partStart); | |
| 11042 | + if (next < 0) | |
| 11043 | + throw new TypeError( | |
| 11044 | + "The multipart/form-data body ended without a closing boundary " + | |
| 11045 | + "delimiter."); | |
| 11046 | + // The line break before a delimiter belongs to the delimiter, not to the | |
| 11047 | + // part it terminates. | |
| 11048 | + let chunkEnd = next; | |
| 11049 | + if (chunkEnd > partStart && bytes[chunkEnd - 1] === __LF) { | |
| 11050 | + chunkEnd -= 1; | |
| 11051 | + if (chunkEnd > partStart && bytes[chunkEnd - 1] === __CR) chunkEnd -= 1; | |
| 11052 | + } | |
| 11053 | + cursor = next + delimiter.length; | |
| 11054 | + // The headers end at the first blank line. Either line break can be CRLF | |
| 11055 | + // or a bare LF, which accepted inputs can contain. | |
| 11056 | + let headerEnd = -1, bodyStart = -1; | |
| 11057 | + for (let i = partStart; i < chunkEnd; i++) { | |
| 11058 | + const first = bytes[i] === __CR && bytes[i + 1] === __LF | |
| 11059 | + ? 2 | |
| 11060 | + : bytes[i] === __LF ? 1 : 0; | |
| 11061 | + if (first === 0) continue; | |
| 11062 | + const after = i + first; | |
| 11063 | + const second = bytes[after] === __CR && bytes[after + 1] === __LF | |
| 11064 | + ? 2 | |
| 11065 | + : bytes[after] === __LF ? 1 : 0; | |
| 11066 | + if (second === 0) continue; | |
| 11067 | + headerEnd = i; | |
| 11068 | + bodyStart = after + second; | |
| 11069 | + break; | |
| 11070 | + } | |
| 11071 | + if (headerEnd < 0) | |
| 11072 | + throw new TypeError( | |
| 11073 | + "A FormData part's headers must be terminated by a blank line."); | |
| 11074 | + // Part headers are text. Decoding this slice as UTF-8 keeps a non-ASCII | |
| 11075 | + // name or filename intact and cannot reach the part body. | |
| 11076 | + const rawHeaders = new TextDecoder().decode( | |
| 11077 | + bytes.subarray(partStart, headerEnd)); | |
| 11078 | + const body = bytes.subarray(bodyStart, chunkEnd); | |
| 11079 | + let disposition = null; | |
| 11080 | + let type = ""; | |
| 11081 | + for (const line of rawHeaders.split(/\r?\n/)) { | |
| 11082 | + const colon = line.indexOf(":"); | |
| 11083 | + if (colon < 0) continue; | |
| 11084 | + const name = line.slice(0, colon).trim().toLowerCase(); | |
| 11085 | + const value = line.slice(colon + 1).trim(); | |
| 11086 | + if (name === "content-disposition") disposition = value; | |
| 11087 | + else if (name === "content-type") type = value; | |
| 11088 | + } | |
| 11089 | + if (disposition === null) | |
| 11090 | + throw new TypeError( | |
| 11091 | + "Content-Disposition header is required for each FormData " + | |
| 11092 | + "part."); | |
| 11093 | + const kind = disposition.split(";")[0].trim(); | |
| 11094 | + if (kind.toLowerCase() !== "form-data") | |
| 11095 | + throw new TypeError( | |
| 11096 | + "Content-Disposition header for FormData part must have the " + | |
| 11097 | + "value \"form-data\", possibly followed by parameters. Got: " + | |
| 11098 | + "\"" + kind + "\""); | |
| 11099 | + const param = (pattern) => { | |
| 11100 | + const m = pattern.exec(disposition); | |
| 11101 | + if (!m) return undefined; | |
| 11102 | + const raw = m[1] !== undefined ? m[1] : (m[2] || "").trim(); | |
| 11103 | + if (/\\$/.test(raw.replace(/\\\\/g, ""))) | |
| 11104 | + throw new TypeError( | |
| 11105 | + "Name or filename can't end with backslash"); | |
| 11106 | + return raw.replace(/\\(.)/g, "$1"); | |
| 11107 | + }; | |
| 11108 | + const name = param(__CD_NAME); | |
| 11109 | + if (name === undefined) | |
| 11110 | + throw new TypeError( | |
| 11111 | + "Content-Disposition header for FormData part must have a " + | |
| 11112 | + "name parameter."); | |
| 11113 | + const filename = param(__CD_FILENAME); | |
| 11114 | + // A part without a filename is an entry value, which the spec defines as a | |
| 11115 | + // string, so this one part is decoded as UTF-8. A file part keeps its | |
| 11116 | + // bytes. | |
| 11117 | + if (filename === undefined) | |
| 11118 | + form.append(name, new TextDecoder().decode(body)); | |
| 11119 | + else | |
| 11120 | + form.append( | |
| 11121 | + name, new File([body], filename, { type: type || "" })); | |
| 11122 | + } | |
| 11123 | + return form; | |
| 11124 | +}; | |
| 11125 | + // Spec entry conversion: strings stay strings; a Blob becomes a | |
| 11126 | + // File named "blob" (or `filename`); a File is renamed only when a | |
| 11127 | + // filename is supplied. | |
| 11128 | + const __formDataValue = (value, filename) => { | |
| 11129 | + if (!(value instanceof Blob)) return String(value); | |
| 11130 | + if (value instanceof File && filename === undefined) return value; | |
| 11131 | + return new File( | |
| 11132 | + [value], | |
| 11133 | + filename === undefined ? "blob" : String(filename), | |
| 11134 | + { | |
| 11135 | + type: value.type, | |
| 11136 | + lastModified: | |
| 11137 | + value instanceof File ? value.lastModified : undefined, | |
| 11138 | + }, | |
| 11139 | + ); | |
| 11140 | + }; | |
| 11141 | + globalThis.FormData = class FormData { | |
| 11142 | + constructor() { this._entries = []; } | |
| 11143 | + append(name, value, filename) { | |
| 11144 | + this._entries.push( | |
| 11145 | + [String(name), __formDataValue(value, filename)]); | |
| 11146 | + } | |
| 11147 | + set(name, value, filename) { | |
| 11148 | + value = __formDataValue(value, filename); | |
| 11149 | + const key = String(name); | |
| 11150 | + // Spec: replace the first match in place, keeping its position, | |
| 11151 | + // and drop any later matches. | |
| 11152 | + const first = this._entries.findIndex(([k]) => k === key); | |
| 11153 | + if (first < 0) { this._entries.push([key, value]); return; } | |
| 11154 | + this._entries[first] = [key, value]; | |
| 11155 | + for (let i = this._entries.length - 1; i > first; i--) | |
| 11156 | + if (this._entries[i][0] === key) this._entries.splice(i, 1); | |
| 11157 | + } | |
| 11158 | + get(name) { | |
| 11159 | + const row = this._entries.find(([key]) => key === String(name)); | |
| 11160 | + return row ? row[1] : null; | |
| 11161 | + } | |
| 11162 | + getAll(name) { | |
| 11163 | + return this._entries.filter(([key]) => key === String(name)).map(([, value]) => value); | |
| 11164 | + } | |
| 11165 | + has(name) { return this._entries.some(([key]) => key === String(name)); } | |
| 11166 | + delete(name) { | |
| 11167 | + const key = String(name); | |
| 11168 | + // Splice in place: the iterators below read the live list, so the | |
| 11169 | + // array identity must survive a delete during iteration. | |
| 11170 | + for (let i = this._entries.length - 1; i >= 0; i--) | |
| 11171 | + if (this._entries[i][0] === key) this._entries.splice(i, 1); | |
| 11172 | + } | |
| 11173 | + // Iteration is live: the iterator holds an index and re-reads the | |
| 11174 | + // entry list, so entries appended during iteration are visited and | |
| 11175 | + // an exhausted iterator resumes if entries are added later. A | |
| 11176 | + // generator cannot do this -- once it returns it is done forever. | |
| 11177 | + _iterate(pick) { | |
| 11178 | + const self = this; | |
| 11179 | + let index = 0; | |
| 11180 | + const iterator = { | |
| 11181 | + next() { | |
| 11182 | + if (index >= self._entries.length) | |
| 11183 | + return { value: undefined, done: true }; | |
| 11184 | + return { value: pick(self._entries[index++]), done: false }; | |
| 11185 | + }, | |
| 11186 | + [Symbol.iterator]() { return iterator; }, | |
| 11187 | + }; | |
| 11188 | + return iterator; | |
| 11189 | + } | |
| 11190 | + entries() { return this._iterate((e) => [e[0], e[1]]); } | |
| 11191 | + keys() { return this._iterate((e) => e[0]); } | |
| 11192 | + values() { return this._iterate((e) => e[1]); } | |
| 11193 | + [Symbol.iterator]() { return this.entries(); } | |
| 11194 | + forEach(callback, thisArg) { | |
| 11195 | + if (typeof callback !== "function") | |
| 11196 | + throw new TypeError( | |
| 11197 | + "Failed to execute 'forEach' on 'FormData': parameter 1 is " + | |
| 11198 | + "not of type 'Function'."); | |
| 11199 | + for (const [key, value] of this.entries()) | |
| 11200 | + callback.call(thisArg, value, key, this); | |
| 11201 | + } | |
| 11202 | + }; | |
| 11203 | +} | |
| 11204 | +// Node's Buffer lives in src/js/node_buffer.js, compiled | |
| 11205 | +// lazily (LAZY_GLOBALS / LAZY_MODULES) on first use. | |
| 11206 | +if (!globalThis.ErrorEvent) { | |
| 11207 | + globalThis.ErrorEvent = class ErrorEvent extends Event { | |
| 11208 | + constructor(type, init = {}) { | |
| 11209 | + super(type, init); | |
| 11210 | + this.message = String(init.message ?? ""); | |
| 11211 | + this.filename = String(init.filename ?? ""); | |
| 11212 | + this.lineno = Number(init.lineno ?? 0); | |
| 11213 | + this.colno = Number(init.colno ?? 0); | |
| 11214 | + this.error = init.error; | |
| 11215 | + } | |
| 11216 | + }; | |
| 11217 | +} | |
| 11218 | +// Web API globals a real bundle references at module scope but that the | |
| 11219 | +// prelude doesn't provide. Stub as empty classes (guarded so we never | |
| 11220 | +// clobber a real prelude implementation). Enough to LOAD; every name in | |
| 11221 | +// this first list has a real implementation elsewhere, so the empty class | |
| 11222 | +// only exists for the load-order window. | |
| 11223 | +for (const n of ["WebSocket", "EventTarget", "Event", "MessageEvent", | |
| 11224 | + "CloseEvent", "ErrorEvent", "SubtleCrypto", "TransformStream", | |
| 11225 | + "ReadableStream", "WritableStream", "ReadableStreamDefaultReader", | |
| 11226 | + "WritableStreamDefaultWriter", | |
| 11227 | + "ByteLengthQueuingStrategy", "CountQueuingStrategy", | |
| 11228 | + "TextEncoderStream", "TextDecoderStream"]) { | |
| 11229 | + if (!globalThis[n]) globalThis[n] = class {}; | |
| 11230 | +} | |
| 11231 | +// These have no implementation anywhere in celld. An empty class would | |
| 11232 | +// let `new BroadcastChannel(...)` hand back an inert object that fails | |
| 11233 | +// far from the cause; the compat contract is "reject at first use", so | |
| 11234 | +// the name loads but construction throws. (EventSource, MessageChannel, | |
| 11235 | +// and MessagePort are real; their scripts run after the harness.) | |
| 11236 | +for (const n of ["BroadcastChannel", "FileReader"]) { | |
| 11237 | + if (!globalThis[n]) globalThis[n] = class { | |
| 11238 | + constructor() { | |
| 11239 | + throw new Error(n + " is not implemented in celld"); | |
| 11240 | + } | |
| 11241 | + }; | |
| 11242 | +} | |
| 11243 | +const __sockets = __celld.__sockets = new Map(); | |
| 11244 | +globalThis.WebSocket = class WebSocket extends EventTarget { | |
| 11245 | + // The spec names, which workerd exposes and real bundles use. celld only | |
| 11246 | + // had the READY_STATE_* aliases, which no other runtime defines. | |
| 11247 | + static CONNECTING = 0; | |
| 11248 | + static OPEN = 1; | |
| 11249 | + static CLOSING = 2; | |
| 11250 | + static CLOSED = 3; | |
| 11251 | + static READY_STATE_CONNECTING = 0; | |
| 11252 | + static READY_STATE_OPEN = 1; | |
| 11253 | + static READY_STATE_CLOSING = 2; | |
| 11254 | + static READY_STATE_CLOSED = 3; | |
| 11255 | + constructor(id, protocols = [], boundTarget = null) { | |
| 11256 | + super(); | |
| 11257 | + const dialed = typeof id === "string"; | |
| 11258 | + // A socket bound to a Durable Object's socket behaves like a dialed one | |
| 11259 | + // in every way that matters here: the host carries its frames, so every | |
| 11260 | + // operation goes out through `__ws_*` on this id rather than to a peer | |
| 11261 | + // in this heap. | |
| 11262 | + const outbound = dialed || boundTarget !== null; | |
| 11263 | + this._outbound = outbound; | |
| 11264 | + this._boundTarget = boundTarget; | |
| 11265 | + this._bound = false; | |
| 11266 | + this._pendingClose = null; | |
| 11267 | + this._id = outbound ? __ws_alloc() : Number(id); | |
| 11268 | + this._attachment = undefined; | |
| 11269 | + this._target = null; | |
| 11270 | + this._accepted = false; | |
| 11271 | + this._hibernatable = false; | |
| 11272 | + this._pending = []; | |
| 11273 | + // The other end of an in-isolate upgrade (a WebSocketPair served | |
| 11274 | + // over a same-script service binding); frames route to it | |
| 11275 | + // directly instead of through the host connection. | |
| 11276 | + this._loopback = null; | |
| 11277 | + this.readyState = outbound ? 0 : 1; | |
| 11278 | + this._binaryType = __cell.compat?.websocketStandardBinaryType | |
| 11279 | + ? "blob" | |
| 11280 | + : "arraybuffer"; | |
| 11281 | + // A server-side socket has no URL, and reports null rather than an empty | |
| 11282 | + // string -- workerd's inspect output pins this. A socket that came back | |
| 11283 | + // from an upgrade has none either: nothing in this isolate dialed it. | |
| 11284 | + this.url = dialed ? id : null; | |
| 11285 | + this.protocol = ""; | |
| 11286 | + this.extensions = ""; | |
| 11287 | + if (boundTarget !== null) { | |
| 11288 | + // The caller drives this socket itself, exactly as a Worker drives one | |
| 11289 | + // it opened. The host pipe is not built until `accept()`, so a | |
| 11290 | + // response passed straight back out is left alone. | |
| 11291 | + this._polled = true; | |
| 11292 | + this._target = boundTarget; | |
| 11293 | + } | |
| 11294 | + if (dialed) { | |
| 11295 | + // workerd validates the URL in the constructor and throws | |
| 11296 | + // synchronously; letting the connector reject later would surface a | |
| 11297 | + // scheme mistake as a network failure instead of a TypeError. | |
| 11298 | + let parsed; | |
| 11299 | + try { | |
| 11300 | + parsed = new URL(id); | |
| 11301 | + } catch { | |
| 11302 | + throw new DOMException( | |
| 11303 | + "WebSocket Constructor: The url is invalid.", | |
| 11304 | + "SyntaxError"); | |
| 11305 | + } | |
| 11306 | + if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") { | |
| 11307 | + throw new DOMException( | |
| 11308 | + "WebSocket Constructor: The url scheme must be ws or wss.", | |
| 11309 | + "SyntaxError"); | |
| 11310 | + } | |
| 11311 | + // A Durable Object socket is pushed events by the host so it can revive | |
| 11312 | + // a hibernated cell. A Worker socket has no cell: the isolate polls it, | |
| 11313 | + // and it lives and dies with the request, which is the lifetime | |
| 11314 | + // Cloudflare gives one too. | |
| 11315 | + const scope = __currentActorScope(); | |
| 11316 | + this._polled = !scope; | |
| 11317 | + const requested = typeof protocols === "string" | |
| 11318 | + ? [protocols] | |
| 11319 | + : Array.from(protocols, String); | |
| 11320 | + for (const value of requested) { | |
| 11321 | + // RFC 6455 subprotocols are HTTP tokens; a space or separator would | |
| 11322 | + // otherwise be smuggled into the Sec-WebSocket-Protocol header. | |
| 11323 | + if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) { | |
| 11324 | + throw new DOMException( | |
| 11325 | + `WebSocket Constructor: The subprotocol '${value}' is invalid.`, | |
| 11326 | + "SyntaxError"); | |
| 11327 | + } | |
| 11328 | + } | |
| 11329 | + if (new Set(requested).size !== requested.length) { | |
| 11330 | + throw new DOMException( | |
| 11331 | + "WebSocket Constructor: The subprotocols must be unique.", | |
| 11332 | + "SyntaxError"); | |
| 11333 | + } | |
| 11334 | + __sockets.set(this._id, this); | |
| 11335 | + const connection = __ws_connect(this._id, scope, id, JSON.stringify(requested)); | |
| 11336 | + __registerWaitUntil(connection); | |
| 11337 | + if (this._polled) this._startPump(); | |
| 11338 | + connection.then((protocol) => { | |
| 11339 | + if (this.readyState === WebSocket.READY_STATE_CLOSING) { | |
| 11340 | + if (this._pendingClose) { | |
| 11341 | + const [code, reason] = this._pendingClose; | |
| 11342 | + __ws_close(this._id, code, reason); | |
| 11343 | + } | |
| 11344 | + return; | |
| 11345 | + } | |
| 11346 | + if (this.readyState !== WebSocket.READY_STATE_CONNECTING) return; | |
| 11347 | + this.protocol = protocol; | |
| 11348 | + this.readyState = WebSocket.READY_STATE_OPEN; | |
| 11349 | + this.dispatchEvent(new Event("open")); | |
| 11350 | + }, (error) => { | |
| 11351 | + this.readyState = WebSocket.READY_STATE_CLOSED; | |
| 11352 | + __sockets.delete(this._id); | |
| 11353 | + this.dispatchEvent(new ErrorEvent("error", { message: String(error?.message || error), error })); | |
| 11354 | + this._dispatchClose(1006, "", false); | |
| 11355 | + }); | |
| 11356 | + } | |
| 11357 | + } | |
| 11358 | + // The pump ends only when the socket closes, so it must NOT be registered | |
| 11359 | + // as waitUntil work: that would hold the request open for as long as the | |
| 11360 | + // socket lives, and the host reclaims an abandoned socket only once the | |
| 11361 | + // request has retired. Its `__ws_next` ops are driven while the request | |
| 11362 | + // runs and normally resolve with the host's 1001 "request ended" close. | |
| 11363 | + // They resolve as 1006 only if the sender disappears without a close frame. | |
| 11364 | + _startPump() { | |
| 11365 | + if (this._pumping) return; | |
| 11366 | + this._pumping = true; | |
| 11367 | + this._pump().catch(() => {}); | |
| 11368 | + } | |
| 11369 | + // Drain the host queue for an isolate-polled socket. Each `__ws_next` is an | |
| 11370 | + // ordinary async op the request owns; a request that retires with the | |
| 11371 | + // socket still open closes it, which ends this loop with a close frame. | |
| 11372 | + async _pump() { | |
| 11373 | + for (;;) { | |
| 11374 | + const frame = await __ws_next(this._id); | |
| 11375 | + const tag = frame[0]; | |
| 11376 | + const body = frame.subarray(1); | |
| 11377 | + if (tag === 0) { | |
| 11378 | + this._dispatchMessage(new TextDecoder().decode(body)); | |
| 11379 | + } else if (tag === 1) { | |
| 11380 | + this._dispatchMessage( | |
| 11381 | + body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength), | |
| 11382 | + ); | |
| 11383 | + } else if (tag === 2) { | |
| 11384 | + if (this.readyState === WebSocket.READY_STATE_CONNECTING) { | |
| 11385 | + this.protocol = new TextDecoder().decode(body); | |
| 11386 | + this.readyState = WebSocket.READY_STATE_OPEN; | |
| 11387 | + this.dispatchEvent(new Event("open")); | |
| 11388 | + } | |
| 11389 | + } else { | |
| 11390 | + const info = JSON.parse(new TextDecoder().decode(body)); | |
| 11391 | + this._dispatchClose(info.code, info.reason, info.wasClean); | |
| 11392 | + return; | |
| 11393 | + } | |
| 11394 | + } | |
| 11395 | + } | |
| 11396 | + // Deliver whatever this end queued before it had somewhere to send. | |
| 11397 | + _flushToPeer() { | |
| 11398 | + const peer = this._loopback; | |
| 11399 | + if (!peer) return; | |
| 11400 | + for (const frame of this._pending.splice(0)) { | |
| 11401 | + if (frame[0] === "send") { | |
| 11402 | + queueMicrotask(() => peer._dispatchMessage(frame[1])); | |
| 11403 | + } else if (frame[0] === "send-binary") { | |
| 11404 | + const data = frame[1]; | |
| 11405 | + const bytes = data instanceof ArrayBuffer | |
| 11406 | + ? data | |
| 11407 | + : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); | |
| 11408 | + queueMicrotask(() => peer._dispatchMessage(bytes)); | |
| 11409 | + } else { | |
| 11410 | + queueMicrotask(() => peer._dispatchClose(frame[1], frame[2], true)); | |
| 11411 | + } | |
| 11412 | + } | |
| 11413 | + } | |
| 11414 | + get binaryType() { return this._binaryType; } | |
| 11415 | + // The spec ignores an unrecognised value rather than throwing. | |
| 11416 | + set binaryType(value) { | |
| 11417 | + if (value === "blob" || value === "arraybuffer") this._binaryType = value; | |
| 11418 | + } | |
| 11419 | + accept() { | |
| 11420 | + this._accepted = true; | |
| 11421 | + // A pair used directly, without being returned through a 101 response, | |
| 11422 | + // still has to carry frames once both ends are accepted. celld only | |
| 11423 | + // linked a pair on the upgrade path, so such a pair queued forever. | |
| 11424 | + if (this._peer && this._peer._accepted && !this._loopback) { | |
| 11425 | + this._loopback = this._peer; | |
| 11426 | + this._peer._loopback = this; | |
| 11427 | + this._flushToPeer(); | |
| 11428 | + this._peer._flushToPeer(); | |
| 11429 | + } | |
| 11430 | + // A socket obtained from a `fetch()` upgrade is already connected and | |
| 11431 | + // delivers nothing until it is accepted; this is where it starts. | |
| 11432 | + if (this._outbound && this.readyState === WebSocket.READY_STATE_CONNECTING) { | |
| 11433 | + // Bind before the pump: the op registers this socket's queue on this | |
| 11434 | + // thread, so the first `__ws_next` cannot run ahead of it. | |
| 11435 | + if (this._boundTarget !== null && !this._bound) { | |
| 11436 | + this._bound = true; | |
| 11437 | + __ws_bind_target( | |
| 11438 | + this._id, | |
| 11439 | + JSON.stringify(this._boundTarget), | |
| 11440 | + __currentActorScope(), | |
| 11441 | + ); | |
| 11442 | + } | |
| 11443 | + this.readyState = WebSocket.READY_STATE_OPEN; | |
| 11444 | + if (this._polled) this._startPump(); | |
| 11445 | + } | |
| 11446 | + } | |
| 11447 | + send(data) { | |
| 11448 | + if (this.readyState !== WebSocket.READY_STATE_OPEN) | |
| 11449 | + throw new DOMException("WebSocket is not open", "InvalidStateError"); | |
| 11450 | + const binary = data instanceof ArrayBuffer || ArrayBuffer.isView(data); | |
| 11451 | + const text = binary ? null : String(data); | |
| 11452 | + if (this._loopback) { | |
| 11453 | + const peer = this._loopback; | |
| 11454 | + const message = binary | |
| 11455 | + ? (data instanceof ArrayBuffer ? data.slice(0) : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)) | |
| 11456 | + : text; | |
| 11457 | + queueMicrotask(() => peer._dispatchMessage(message)); | |
| 11458 | + return; | |
| 11459 | + } | |
| 11460 | + // The pending queue belongs to an inbound pair socket that has been | |
| 11461 | + // accepted but not yet bound to a host transport. An outbound socket is | |
| 11462 | + // already bound -- queueing here would silently swallow its frames. | |
| 11463 | + if (!this._outbound && this._accepted && !this._target) { | |
| 11464 | + this._pending.push([binary ? "send-binary" : "send", binary ? data : text]); | |
| 11465 | + return; | |
| 11466 | + } | |
| 11467 | + if (binary) { | |
| 11468 | + const bytes = data instanceof ArrayBuffer | |
| 11469 | + ? new Uint8Array(data) | |
| 11470 | + : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); | |
| 11471 | + __ws_send_binary(this._id, bytes); | |
| 11472 | + } else { | |
| 11473 | + __ws_send(this._id, text); | |
| 11474 | + } | |
| 11475 | + } | |
| 11476 | + close(code = 1000, reason = "") { | |
| 11477 | + // WHATWG: an application may send 1000 or 3000-4999. Everything else is | |
| 11478 | + // reserved for the protocol itself. | |
| 11479 | + const wanted = Number(code); | |
| 11480 | + if (wanted !== 1000 && !(wanted >= 3000 && wanted <= 4999)) { | |
| 11481 | + throw new DOMException( | |
| 11482 | + `WebSocket close code ${code} is not permitted`, | |
| 11483 | + "InvalidAccessError"); | |
| 11484 | + } | |
| 11485 | + // RFC 6455 5.5: the close frame body is at most 125 bytes, two of which | |
| 11486 | + // are the code. Measured in UTF-8, so a multibyte reason can exceed the | |
| 11487 | + // cap at well under 123 characters. | |
| 11488 | + if (new TextEncoder().encode(String(reason)).length > 123) { | |
| 11489 | + throw new DOMException( | |
| 11490 | + "WebSocket close reason must not exceed 123 bytes", | |
| 11491 | + "SyntaxError"); | |
| 11492 | + } | |
| 11493 | + // Outbound sockets follow the WebSocket spec: closing a closed socket is a | |
| 11494 | + // no-op. Inbound sockets must NOT take that shortcut -- a Durable Object | |
| 11495 | + // answers a peer-initiated close from inside `webSocketClose`, by which | |
| 11496 | + // point `_dispatchClose` has already marked this side closed, and its | |
| 11497 | + // reply carries the reason the client is entitled to see. | |
| 11498 | + if (this._outbound && this.readyState === WebSocket.READY_STATE_CLOSED) { | |
| 11499 | + return; | |
| 11500 | + } | |
| 11501 | + const connecting = this.readyState === WebSocket.READY_STATE_CONNECTING; | |
| 11502 | + this.readyState = WebSocket.READY_STATE_CLOSING; | |
| 11503 | + if (this._outbound && connecting) { | |
| 11504 | + this._pendingClose = [code, reason]; | |
| 11505 | + return; | |
| 11506 | + } | |
| 11507 | + if (this._outbound) { | |
| 11508 | + __ws_close(this._id, code, reason); | |
| 11509 | + return; | |
| 11510 | + } | |
| 11511 | + this.readyState = 3; | |
| 11512 | + if (this._loopback) { | |
| 11513 | + const peer = this._loopback; | |
| 11514 | + queueMicrotask(() => peer._dispatchClose(code, reason, true)); | |
| 11515 | + return; | |
| 11516 | + } | |
| 11517 | + if (this._accepted && !this._target) { | |
| 11518 | + this._pending.push(["close", code, reason]); | |
| 11519 | + return; | |
| 11520 | + } | |
| 11521 | + __ws_close(this._id, code, reason); | |
| 11522 | + } | |
| 11523 | + _flushPending() { | |
| 11524 | + const pending = this._pending.splice(0); | |
| 11525 | + for (const frame of pending) { | |
| 11526 | + if (frame[0] === "send") __ws_send(this._id, frame[1]); | |
| 11527 | + else if (frame[0] === "send-binary") { | |
| 11528 | + const data = frame[1]; | |
| 11529 | + const bytes = data instanceof ArrayBuffer | |
| 11530 | + ? new Uint8Array(data) | |
| 11531 | + : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); | |
| 11532 | + __ws_send_binary(this._id, bytes); | |
| 11533 | + } | |
| 11534 | + else __ws_close(this._id, frame[1], frame[2]); | |
| 11535 | + } | |
| 11536 | + } | |
| 11537 | + serializeAttachment(value) { | |
| 11538 | + // Structured clone, not JSON: Cloudflare accepts anything cloneable | |
| 11539 | + // here, so a Date must come back a Date and a Map a Map. | |
| 11540 | + this._attachment = value; | |
| 11541 | + __ws_attachment_set(this._id, __sc_encode(value)); | |
| 11542 | + } | |
| 11543 | + deserializeAttachment() { return this._attachment; } | |
| 11544 | + _dispatchMessage(data) { | |
| 11545 | + if (this._binaryType === "blob" && data instanceof ArrayBuffer) { | |
| 11546 | + data = new Blob([data]); | |
| 11547 | + } | |
| 11548 | + const event = new MessageEvent("message", { data }); | |
| 11549 | + event._trust(); | |
| 11550 | + this.dispatchEvent(event); | |
| 11551 | + } | |
| 11552 | + _dispatchClose(code, reason, wasClean) { | |
| 11553 | + if (this.readyState === WebSocket.READY_STATE_CLOSED) return; | |
| 11554 | + this.readyState = WebSocket.READY_STATE_CLOSED; | |
| 11555 | + __sockets.delete(this._id); | |
| 11556 | + // An abnormal closure fires `error` before `close`. Code written against | |
| 11557 | + // the standard onerror never ran otherwise, which matters most for an | |
| 11558 | + // outbound socket: its peer is a remote server that can simply vanish. | |
| 11559 | + // An abnormal closure fires `error` before `close`. Code written against | |
| 11560 | + // the standard onerror never ran otherwise, which matters most for an | |
| 11561 | + // outbound socket: its peer is a remote server that can simply vanish. | |
| 11562 | + // An abnormal closure fires `error` before `close`. Code written against | |
| 11563 | + // the standard onerror never ran otherwise, which matters most for an | |
| 11564 | + // outbound socket: its peer is a remote server that can simply vanish. | |
| 11565 | + if (!wasClean) { | |
| 11566 | + this.dispatchEvent(new ErrorEvent("error", { | |
| 11567 | + message: reason | |
| 11568 | + ? `WebSocket closed abnormally: ${reason}` | |
| 11569 | + : "WebSocket closed abnormally", | |
| 11570 | + })); | |
| 11571 | + } | |
| 11572 | + const event = new CloseEvent("close", { code, reason, wasClean }); | |
| 11573 | + event._trust(); | |
| 11574 | + this.dispatchEvent(event); | |
| 11575 | + } | |
| 11576 | +}; | |
| 11577 | +const __makeSocket = __celld.__makeSocket = (id) => new WebSocket(id); | |
| 11578 | +const __socketFromRow = __celld.__socketFromRow = (row) => { | |
| 11579 | + let ws = __sockets.get(Number(row.id)); | |
| 11580 | + if (!ws) { | |
| 11581 | + ws = __makeSocket(row.id); | |
| 11582 | + __sockets.set(Number(row.id), ws); | |
| 11583 | + } | |
| 11584 | + ws._tags = row.tags || []; | |
| 11585 | + ws._hibernatable = true; | |
| 11586 | + if (row.attachment != null) { | |
| 11587 | + try { | |
| 11588 | + ws._attachment = __sc_decode(new Uint8Array(row.attachment)); | |
| 11589 | + } catch { | |
| 11590 | + ws._attachment = undefined; | |
| 11591 | + } | |
| 11592 | + } | |
| 11593 | + return ws; | |
| 11594 | +}; | |
| 11595 | +// Workerd's api::WebSocketRequestResponsePair (websocket.h): an immutable | |
| 11596 | +// request/response pair for state.setWebSocketAutoResponse. | |
| 11597 | +globalThis.WebSocketRequestResponsePair = | |
| 11598 | + class WebSocketRequestResponsePair { | |
| 11599 | + #request; | |
| 11600 | + #response; | |
| 11601 | + constructor(request, response) { | |
| 11602 | + this.#request = String(request); | |
| 11603 | + this.#response = String(response); | |
| 11604 | + } | |
| 11605 | + get request() { return this.#request; } | |
| 11606 | + get response() { return this.#response; } | |
| 11607 | + }; | |
| 11608 | +globalThis.WebSocketPair = function WebSocketPair() { | |
| 11609 | + const id = __ws_alloc(); | |
| 11610 | + const client = __makeSocket(id); | |
| 11611 | + const server = __makeSocket(id); | |
| 11612 | + client._peer = server; | |
| 11613 | + server._peer = client; | |
| 11614 | + // Indexed AND iterable: `const [client, server] = new WebSocketPair()` is | |
| 11615 | + // the form most Cloudflare code uses. | |
| 11616 | + return { | |
| 11617 | + 0: client, | |
| 11618 | + 1: server, | |
| 11619 | + length: 2, | |
| 11620 | + [Symbol.iterator]() { | |
| 11621 | + return [client, server][Symbol.iterator](); | |
| 11622 | + }, | |
| 11623 | + }; | |
| 11624 | +}; | |
| 11625 | +// Cloudflare exposes the time of the last I/O, not a clock that advances | |
| 11626 | +// while JavaScript runs. Keep Date and performance on one turn timestamp so | |
| 11627 | +// neither becomes a timing side channel and the two APIs cannot disagree. | |
| 11628 | +const __NativeDate = Date; | |
| 11629 | +let __ioTimestamp = 0; | |
| 11630 | +const __CloudflareDate = function Date(...args) { | |
| 11631 | + if (new.target) { | |
| 11632 | + return Reflect.construct( | |
| 11633 | + __NativeDate, | |
| 11634 | + args.length === 0 ? [__ioTimestamp] : args, | |
| 11635 | + new.target, | |
| 11636 | + ); | |
| 11637 | + } | |
| 11638 | + return new __NativeDate(__ioTimestamp).toString(); | |
| 11639 | +}; | |
| 11640 | +Object.defineProperties(__CloudflareDate, { | |
| 11641 | + length: { value: 7 }, | |
| 11642 | + prototype: { value: __NativeDate.prototype }, | |
| 11643 | + now: { | |
| 11644 | + value: () => __ioTimestamp, | |
| 11645 | + writable: true, | |
| 11646 | + configurable: true, | |
| 11647 | + }, | |
| 11648 | + parse: { | |
| 11649 | + value: __NativeDate.parse, | |
| 11650 | + writable: true, | |
| 11651 | + configurable: true, | |
| 11652 | + }, | |
| 11653 | + UTC: { | |
| 11654 | + value: __NativeDate.UTC, | |
| 11655 | + writable: true, | |
| 11656 | + configurable: true, | |
| 11657 | + }, | |
| 11658 | +}); | |
| 11659 | +Object.defineProperty(__NativeDate.prototype, "constructor", { | |
| 11660 | + value: __CloudflareDate, | |
| 11661 | + writable: true, | |
| 11662 | + configurable: true, | |
| 11663 | +}); | |
| 11664 | +globalThis.Date = __CloudflareDate; | |
| 11665 | +globalThis.performance = { | |
| 11666 | + now: () => __ioTimestamp, | |
| 11667 | + timeOrigin: 0, | |
| 11668 | + mark() {}, | |
| 11669 | + measure() {}, | |
| 11670 | +}; | |
| 11671 | +__celld.__advanceIoTime = (timestamp) => { | |
| 11672 | + __ioTimestamp = timestamp; | |
| 11673 | +}; | |
| 11674 | +if (!globalThis.navigator) globalThis.navigator = { | |
| 11675 | + userAgent: "Cloudflare-Workers", hardwareConcurrency: 1, | |
| 11676 | + language: "en", languages: ["en"], | |
| 11677 | +}; | |
| 11678 | +if (!globalThis.queueMicrotask) | |
| 11679 | + globalThis.queueMicrotask = (f) => Promise.resolve().then(f); | |
| 11680 | +if (!globalThis.scheduler) | |
| 11681 | + globalThis.scheduler = { | |
| 11682 | + wait: (ms) => new Promise((resolve) => setTimeout(resolve, Number(ms) || 0)), | |
| 11683 | + }; | |
| 11684 | +if (!globalThis.structuredClone) { | |
| 11685 | + const hostBrand = Symbol("Cells.structuredCloneHost"); | |
| 11686 | + const deserializers = { | |
| 11687 | + Blob: (data) => new Blob([data.bytes], { type: data.mimeType }), | |
| 11688 | + File: (data) => new File([data.bytes], data.name, { | |
| 11689 | + type: data.mimeType, | |
| 11690 | + lastModified: data.lastModified, | |
| 11691 | + }), | |
| 11692 | + CryptoKey: (data) => new CryptoKey( | |
| 11693 | + data.keyType, data.algorithm, data.extractable, data.usages, data.material), | |
| 11694 | + DOMException: (data) => { | |
| 11695 | + const exception = new DOMException(data.message, data.name); | |
| 11696 | + if (data.stack !== undefined) | |
| 11697 | + Object.defineProperty(exception, "stack", { | |
| 11698 | + value: data.stack, configurable: true, writable: true, | |
| 11699 | + }); | |
| 11700 | + return exception; | |
| 11701 | + }, | |
| 11702 | + }; | |
| 11703 | + const defineHostType = (prototype, serialize) => { | |
| 11704 | + if (!Object.prototype.hasOwnProperty.call(prototype, hostBrand)) | |
| 11705 | + Object.defineProperty(prototype, hostBrand, { value: serialize }); | |
| 11706 | + }; | |
| 11707 | + const defineUnsupportedType = (constructor) => { | |
| 11708 | + if (typeof constructor === "function") | |
| 11709 | + defineHostType(constructor.prototype, null); | |
| 11710 | + }; | |
| 11711 | + | |
| 11712 | + defineHostType(Blob.prototype, function() { | |
| 11713 | + return { | |
| 11714 | + type: "Blob", bytes: this._bytes, | |
| 11715 | + mimeType: this.type, | |
| 11716 | + }; | |
| 11717 | + }); | |
| 11718 | + defineHostType(File.prototype, function() { | |
| 11719 | + return { | |
| 11720 | + type: "File", bytes: this._bytes, | |
| 11721 | + mimeType: this.type, name: this.name, | |
| 11722 | + lastModified: this.lastModified, | |
| 11723 | + }; | |
| 11724 | + }); | |
| 11725 | + defineHostType(DOMException.prototype, function() { | |
| 11726 | + return { | |
| 11727 | + type: "DOMException", message: this.message, | |
| 11728 | + name: this.name, stack: this.stack, | |
| 11729 | + }; | |
| 11730 | + }); | |
| 11731 | + | |
| 11732 | + globalThis.structuredClone = function(value, options) { | |
| 11733 | + if (arguments.length < 1) | |
| 11734 | + throw new TypeError( | |
| 11735 | + "Failed to execute 'structuredClone': 1 argument required"); | |
| 11736 | + const transfer = options?.transfer === undefined | |
| 11737 | + ? [] : Array.from(options.transfer); | |
| 11738 | + const seen = new Set(); | |
| 11739 | + for (let index = 0; index < transfer.length; index++) { | |
| 11740 | + const item = transfer[index]; | |
| 11741 | + if (!(item instanceof ArrayBuffer)) | |
| 11742 | + throw new DOMException( | |
| 11743 | + `Value at index ${index} is not transferable`, "DataCloneError"); | |
| 11744 | + if (item.detached) | |
| 11745 | + throw new DOMException( | |
| 11746 | + `ArrayBuffer at index ${index} is already detached`, | |
| 11747 | + "DataCloneError"); | |
| 11748 | + if (seen.has(item)) | |
| 11749 | + throw new DOMException( | |
| 11750 | + `ArrayBuffer at index ${index} is a duplicate`, "DataCloneError"); | |
| 11751 | + seen.add(item); | |
| 11752 | + } | |
| 11753 | + | |
| 11754 | + // Crypto loads after this harness, and MessagePort is also installed by a | |
| 11755 | + // later bootstrap script. Register every late type before V8 traverses the | |
| 11756 | + // graph. The delegate then sees host objects at any depth without a second | |
| 11757 | + // JavaScript traversal, which follows Deno's structured-clone design. | |
| 11758 | + if (typeof CryptoKey === "function") | |
| 11759 | + defineHostType(CryptoKey.prototype, function() { | |
| 11760 | + return { | |
| 11761 | + type: "CryptoKey", keyType: this.type, | |
| 11762 | + algorithm: this.algorithm, extractable: this.extractable, | |
| 11763 | + usages: this.usages, material: this.__celldMaterial, | |
| 11764 | + }; | |
| 11765 | + }); | |
| 11766 | + for (const constructor of [ | |
| 11767 | + URL, URLSearchParams, Headers, FormData, Request, Response, | |
| 11768 | + typeof MessagePort === "function" ? MessagePort : undefined, | |
| 11769 | + ]) defineUnsupportedType(constructor); | |
| 11770 | + | |
| 11771 | + let result; | |
| 11772 | + try { | |
| 11773 | + result = __structured_clone(value, hostBrand, deserializers); | |
| 11774 | + } catch (error) { | |
| 11775 | + if (error instanceof TypeError) | |
| 11776 | + throw new DOMException(error.message, "DataCloneError"); | |
| 11777 | + throw error; | |
| 11778 | + } | |
| 11779 | + // Validate the complete list and clone the value before detaching any | |
| 11780 | + // source. A later invalid entry therefore cannot leave an earlier buffer | |
| 11781 | + // detached after the operation fails. | |
| 11782 | + for (const item of transfer) item.transfer(); | |
| 11783 | + return result; | |
| 11784 | + }; | |
| 11785 | +} | |
| 11786 | +// Web Crypto is installed after the rest of the harness so it can use | |
| 11787 | +// DOMException, structuredClone, and Buffer. | |
| 11788 | +// `Buffer` is read at call time, which materializes the lazy global. | |
| 11789 | +const __zlibSync = (mode, data) => | |
| 11790 | + Buffer.from(__zlib(mode, Buffer.from(data))); | |
| 11791 | +__celld.__zlibModule = { | |
| 11792 | + constants: { | |
| 11793 | + Z_NO_FLUSH: 0, | |
| 11794 | + Z_PARTIAL_FLUSH: 1, | |
| 11795 | + Z_SYNC_FLUSH: 2, | |
| 11796 | + Z_FULL_FLUSH: 3, | |
| 11797 | + Z_FINISH: 4, | |
| 11798 | + Z_BLOCK: 5, | |
| 11799 | + }, | |
| 11800 | + gzipSync: (data, _options) => __zlibSync("gzip", data), | |
| 11801 | + gunzipSync: (data, _options) => __zlibSync("gunzip", data), | |
| 11802 | + deflateSync: (data, _options) => __zlibSync("deflate", data), | |
| 11803 | + inflateSync: (data, _options) => __zlibSync("inflate", data), | |
| 11804 | + deflateRawSync: (data, _options) => __zlibSync("deflateRaw", data), | |
| 11805 | + inflateRawSync: (data, _options) => __zlibSync("inflateRaw", data), | |
| 11806 | +}; | |
| 11807 | +if (!globalThis.process) globalThis.process = { | |
| 11808 | + env: {}, platform: "linux", arch: "x64", version: "v20.0.0", | |
| 11809 | + versions: { node: "20.0.0" }, argv: [], cwd: () => "/", | |
| 11810 | + stdin: { fd: 0, isTTY: false }, | |
| 11811 | + stdout: { fd: 1, isTTY: false, write: (s) => { __log(String(s)); return true; } }, | |
| 11812 | + stderr: { fd: 2, isTTY: false, write: (s) => { __log(String(s)); return true; } }, | |
| 11813 | + nextTick: (f, ...a) => queueMicrotask(() => f(...a)), | |
| 11814 | + on() {}, once() {}, off() {}, emit() {}, hrtime: () => [0, 0], | |
| 11815 | +}; | |
| 11816 | +globalThis.process.exit = (code = 0) => { | |
| 11817 | + const actorScope = __currentActorScope(); | |
| 11818 | + if (actorScope) { | |
| 11819 | + const instance = __cell.instances[actorScope]; | |
| 11820 | + if (instance?.__celldState) | |
| 11821 | + instance.__celldState._resetAfterConcurrencyFailure(); | |
| 11822 | + } | |
| 11823 | + __process_exit(Number(code) || 0, actorScope); | |
| 11824 | +}; | |
| 11825 | +globalThis.process.getBuiltinModule = | |
| 11826 | + (id) => __builtin_module(String(id)); | |
| 11827 | +if (!globalThis.global) globalThis.global = globalThis; | |
| 11828 | +// Events belong to the request, and the host owns the request. `__event_*` | |
| 11829 | +// and `__wait_until` operate on whichever context the host has made current | |
| 11830 | +// for this turn, so nothing here has to know which request is running -- and | |
| 11831 | +// two requests sharing an isolate cannot pop each other's events. | |
| 11832 | +const __registerWaitUntil = __celld.__registerWaitUntil = (promise) => { | |
| 11833 | + const tracked = Promise.resolve(promise).catch((error) => { | |
| 11834 | + console.error("waitUntil rejected", error); | |
| 11835 | + }); | |
| 11836 | + __wait_until(tracked); | |
| 11837 | +}; | |
| 11838 | +// `props` are the per-stub props a loopback service stub carries | |
| 11839 | +// (ctx.props); `exports` is built once, on first access. | |
| 11840 | +const __defaultProps = {}; | |
| 11841 | +const __entrypointContext = (props = __defaultProps) => ({ | |
| 11842 | + waitUntil: __registerWaitUntil, | |
| 11843 | + passThroughOnException() {}, | |
| 11844 | + abort: __ctxAbortCurrent, | |
| 11845 | + props, | |
| 11846 | + get exports() { return __ctxExports(); }, | |
| 11847 | +}); | |
| 11848 | +const __beginEvent = __celld.__beginEvent = (props = __defaultProps) => { | |
| 11849 | + __rpcSignalRefresh(); | |
| 11850 | + __event_begin(); | |
| 11851 | + return __entrypointContext(props); | |
| 11852 | +}; | |
| 11853 | +const __endEvent = __celld.__endEvent = () => __event_end(); | |
| 11854 | +// Workerd's writable filesystem is memory-backed and request-scoped. The | |
| 11855 | +// native IoContext owns the directory tree; this facade supplies Node's path, | |
| 11856 | +// error, Promise, and Stats shapes without exposing a host filesystem. | |
| 11857 | +const __fsPath = (value) => { | |
| 11858 | + if (value instanceof URL) { | |
| 11859 | + if (value.protocol !== "file:") { | |
| 11860 | + const error = new TypeError('The URL must be of scheme file'); | |
| 11861 | + error.code = "ERR_INVALID_URL_SCHEME"; | |
| 11862 | + throw error; | |
| 11863 | + } | |
| 11864 | + value = decodeURIComponent(value.pathname); | |
| 11865 | + } else if (globalThis.Buffer?.isBuffer(value)) { | |
| 11866 | + value = value.toString(); | |
| 11867 | + } else if (typeof value !== "string") { | |
| 11868 | + const error = new TypeError( | |
| 11869 | + 'The "path" argument must be of type string or an instance of Buffer or URL', | |
| 11870 | + ); | |
| 11871 | + error.code = "ERR_INVALID_ARG_TYPE"; | |
| 11872 | + throw error; | |
| 11873 | + } | |
| 11874 | + if (value.includes("\0")) { | |
| 11875 | + const error = new TypeError('The argument "path" must not contain null bytes'); | |
| 11876 | + error.code = "ERR_INVALID_ARG_VALUE"; | |
| 11877 | + throw error; | |
| 11878 | + } | |
| 11879 | + const absolute = value.startsWith("/") ? value : process.cwd() + "/" + value; | |
| 11880 | + const parts = []; | |
| 11881 | + for (const part of absolute.split("/")) { | |
| 11882 | + if (!part || part === ".") continue; | |
| 11883 | + if (part === "..") parts.pop(); | |
| 11884 | + else parts.push(part); | |
| 11885 | + } | |
| 11886 | + return "/" + parts.join("/"); | |
| 11887 | +}; | |
| 11888 | +const __fsError = (code, syscall, path) => { | |
| 11889 | + const e = new Error(`${code}: ${syscall} '${path}'`); | |
| 11890 | + e.errno = { EPERM: -1, ENOENT: -2, EEXIST: -17, ENOTDIR: -20 }[code]; | |
| 11891 | + e.code = code; | |
| 11892 | + e.syscall = syscall; | |
| 11893 | + e.path = path; | |
| 11894 | + return e; | |
| 11895 | +}; | |
| 11896 | +const __enoent = (path = "") => { throw __fsError("ENOENT", "open", path); }; | |
| 11897 | +const __fsStatsBadge = Symbol("fs.Stats"); | |
| 11898 | +class __FsStats { | |
| 11899 | + constructor(badge, kind, size, bigint) { | |
| 11900 | + if (badge !== __fsStatsBadge) throw new TypeError("Illegal constructor"); | |
| 11901 | + const file = kind === 3; | |
| 11902 | + this.dev = 0; | |
| 11903 | + this.ino = 0; | |
| 11904 | + // A bundle file is 0o100444 and a writable temporary directory is 0o40666, | |
| 11905 | + // matching the mode values workerd's fs-stat-test.js asserts. | |
| 11906 | + this.mode = (file ? 0o100000 : 0o40000) | 0o444 | (kind === 2 ? 0o222 : 0); | |
| 11907 | + this.nlink = 1; | |
| 11908 | + this.uid = 0; | |
| 11909 | + this.gid = 0; | |
| 11910 | + this.rdev = 0; | |
| 11911 | + this.size = size; | |
| 11912 | + this.blksize = 0; | |
| 11913 | + this.blocks = 0; | |
| 11914 | + this.atimeMs = this.mtimeMs = this.ctimeMs = this.birthtimeMs = 0; | |
| 11915 | + this.atime = new Date(0); | |
| 11916 | + this.mtime = new Date(0); | |
| 11917 | + this.ctime = new Date(0); | |
| 11918 | + this.birthtime = new Date(0); | |
| 11919 | + Object.defineProperty(this, "__kind", { value: file ? "file" : "directory" }); | |
| 11920 | + if (bigint) { | |
| 11921 | + for (const name of [ | |
| 11922 | + "dev", "ino", "mode", "nlink", "uid", "gid", "rdev", "size", | |
| 11923 | + "blksize", "blocks", "atimeMs", "mtimeMs", "ctimeMs", "birthtimeMs", | |
| 11924 | + ]) this[name] = BigInt(this[name]); | |
| 11925 | + this.atimeNs = 0n; | |
| 11926 | + this.mtimeNs = 0n; | |
| 11927 | + this.ctimeNs = 0n; | |
| 11928 | + this.birthtimeNs = 0n; | |
| 11929 | + } | |
| 11930 | + } | |
| 11931 | + isFile() { return this.__kind === "file"; } | |
| 11932 | + isDirectory() { return this.__kind === "directory"; } | |
| 11933 | + isBlockDevice() { return false; } | |
| 11934 | + isCharacterDevice() { return false; } | |
| 11935 | + isSymbolicLink() { return false; } | |
| 11936 | + isFIFO() { return false; } | |
| 11937 | + isSocket() { return false; } | |
| 11938 | +} | |
| 11939 | +const __fsOptions = (options, names) => { | |
| 11940 | + if (options === undefined) return {}; | |
| 11941 | + if (options === null || typeof options !== "object") { | |
| 11942 | + const error = new TypeError('The "options" argument must be of type object'); | |
| 11943 | + error.code = "ERR_INVALID_ARG_TYPE"; | |
| 11944 | + throw error; | |
| 11945 | + } | |
| 11946 | + for (const name of names) { | |
| 11947 | + if (options[name] !== undefined && typeof options[name] !== "boolean") { | |
| 11948 | + const error = new TypeError(`The "options.${name}" property must be of type boolean`); | |
| 11949 | + error.code = "ERR_INVALID_ARG_TYPE"; | |
| 11950 | + throw error; | |
| 11951 | + } | |
| 11952 | + } | |
| 11953 | + return options; | |
| 11954 | +}; | |
| 11955 | +const __fsMkdirSync = (value, options = {}) => { | |
| 11956 | + const path = __fsPath(value); | |
| 11957 | + if (typeof options === "number") options = { mode: options }; | |
| 11958 | + options = __fsOptions(options, ["recursive"]); | |
| 11959 | + const result = __vfs_mkdir(path, options.recursive === true); | |
| 11960 | + if (result && !result.startsWith("/")) throw __fsError(result, "mkdir", path); | |
| 11961 | + return result || undefined; | |
| 11962 | +}; | |
| 11963 | +const __fsStatSync = (value, options, syscall = "stat") => { | |
| 11964 | + const path = __fsPath(value); | |
| 11965 | + options = __fsOptions(options, ["bigint", "throwIfNoEntry"]); | |
| 11966 | + const [kind, size] = __vfs_stat(path); | |
| 11967 | + if (!kind) { | |
| 11968 | + if (options.throwIfNoEntry === false) return undefined; | |
| 11969 | + throw __fsError("ENOENT", syscall, path); | |
| 11970 | + } | |
| 11971 | + return new __FsStats(__fsStatsBadge, kind, size, options.bigint === true); | |
| 11972 | +}; | |
| 11973 | +const __fsLstatSync = (value, options) => __fsStatSync(value, options, "lstat"); | |
| 11974 | +const __fsRealpathSync = (value) => { | |
| 11975 | + const path = __fsPath(value); | |
| 11976 | + if (!__vfs_stat(path)[0]) throw __fsError("ENOENT", "realpath", path); | |
| 11977 | + return path; | |
| 11978 | +}; | |
| 11979 | +const __fsExistsSync = (value) => { | |
| 11980 | + try { return __vfs_stat(__fsPath(value))[0] !== 0; } | |
| 11981 | + catch { return false; } | |
| 11982 | +}; | |
| 11983 | +// Node returns a Buffer unless an encoding is given, as a string or as | |
| 11984 | +// `options.encoding`. Only `utf8` is decoded here; any other encoding falls | |
| 11985 | +// through to Buffer's own decoder. | |
| 11986 | +const __fsReadFileSync = (value, options) => { | |
| 11987 | + const path = __fsPath(value); | |
| 11988 | + const encoding = typeof options === "string" ? options : options?.encoding; | |
| 11989 | + const bytes = __vfs_read_file(path); | |
| 11990 | + if (bytes === undefined) { | |
| 11991 | + // A directory read fails differently from a missing path, so the stat | |
| 11992 | + // decides which error the caller sees. | |
| 11993 | + if (__vfs_stat(path)[0]) throw __fsError("EISDIR", "read", path); | |
| 11994 | + throw __fsError("ENOENT", "open", path); | |
| 11995 | + } | |
| 11996 | + const buffer = Buffer.from(bytes); | |
| 11997 | + return encoding ? buffer.toString(encoding) : buffer; | |
| 11998 | +}; | |
| 11999 | +// `fs.constants`, with the four access modes from workerd's | |
| 12000 | +// `src/node/internal/internal_fs_constants.ts`. The table carries only the | |
| 12001 | +// modes `access` reads. Every other constant belongs to an operation the | |
| 12002 | +// virtual filesystem does not implement, and that operation already fails | |
| 12003 | +// loudly at the unimplemented-builtin stub, so publishing its constants would | |
| 12004 | +// only make a caller build a mode for a call it cannot make. | |
| 12005 | +const __fsConstants = Object.freeze({ F_OK: 0, X_OK: 1, W_OK: 2, R_OK: 4 }); | |
| 12006 | +// Node validates a mode before it reaches the filesystem, so a bad mode is an | |
| 12007 | +// argument error and never a filesystem error. The range is the union of the | |
| 12008 | +// four access modes, which is what workerd's `validateMode` allows. | |
| 12009 | +const __fsMode = (mode) => { | |
| 12010 | + if (mode === undefined) return __fsConstants.F_OK; | |
| 12011 | + if (typeof mode !== "number") { | |
| 12012 | + const error = new TypeError('The "mode" argument must be of type number'); | |
| 12013 | + error.code = "ERR_INVALID_ARG_TYPE"; | |
| 12014 | + throw error; | |
| 12015 | + } | |
| 12016 | + if (!Number.isInteger(mode) || mode < 0 || mode > 7) { | |
| 12017 | + const error = new RangeError( | |
| 12018 | + `The value of "mode" is out of range. It must be >= 0 && <= 7. Received ${mode}`, | |
| 12019 | + ); | |
| 12020 | + error.code = "ERR_OUT_OF_RANGE"; | |
| 12021 | + throw error; | |
| 12022 | + } | |
| 12023 | + return mode; | |
| 12024 | +}; | |
| 12025 | +// `access` reports what the virtual filesystem can do and not a POSIX | |
| 12026 | +// permission, so it follows workerd's `accessSyncImpl`: no file is executable, | |
| 12027 | +// therefore `X_OK` always fails, and an unwritable path fails exactly like a | |
| 12028 | +// missing one, so a caller cannot tell the two apart. Kind 2 is the writable | |
| 12029 | +// tree; see `op_vfs_stat`. | |
| 12030 | +const __fsAccessSync = (value, mode) => { | |
| 12031 | + const path = __fsPath(value); | |
| 12032 | + mode = __fsMode(mode); | |
| 12033 | + const [kind] = __vfs_stat(path); | |
| 12034 | + const denied = mode & __fsConstants.X_OK | |
| 12035 | + || !kind | |
| 12036 | + || (mode & __fsConstants.W_OK && kind !== 2); | |
| 12037 | + if (denied) throw __fsError("ENOENT", "access", path); | |
| 12038 | +}; | |
| 12039 | +// The callback forms run the same synchronous core as `fs.promises`. | |
| 12040 | +// Validation and the operation are separate arguments, not one function, | |
| 12041 | +// because they fail differently: an argument error throws, and only a | |
| 12042 | +// filesystem error reaches the callback. One combined body would route both to | |
| 12043 | +// the callback and hide a caller's bug behind an error it did not expect. | |
| 12044 | +// | |
| 12045 | +// `validate()` runs before the callback check, which is workerd's order: each | |
| 12046 | +// entry point in `internal_fs_callback.ts` validates its path and its options, | |
| 12047 | +// and only then calls `callWithSingleArgCallback`. Node checks the callback | |
| 12048 | +// first, so a call that has a bad path and no callback reports the path here | |
| 12049 | +// and reports the callback in Node. Both are `ERR_INVALID_ARG_TYPE`, and the | |
| 12050 | +// runtime follows workerd. | |
| 12051 | +const __fsDeliver = (validate, run, callback, deliver) => { | |
| 12052 | + validate(); | |
| 12053 | + if (typeof callback !== "function") { | |
| 12054 | + const error = new TypeError('The "cb" argument must be of type function'); | |
| 12055 | + error.code = "ERR_INVALID_ARG_TYPE"; | |
| 12056 | + throw error; | |
| 12057 | + } | |
| 12058 | + let result; | |
| 12059 | + try { | |
| 12060 | + result = run(); | |
| 12061 | + } catch (error) { | |
| 12062 | + // A callback delivered in this turn would let a caller observe the result | |
| 12063 | + // before its own call returned, which Node never does. | |
| 12064 | + queueMicrotask(() => callback(error)); | |
| 12065 | + return; | |
| 12066 | + } | |
| 12067 | + queueMicrotask(() => deliver(result)); | |
| 12068 | +}; | |
| 12069 | +// An operation with a result calls back with `(error, result)`, and one | |
| 12070 | +// without calls back with `(error)` alone. Workerd splits the two the same way | |
| 12071 | +// (`callWithSingleArgCallback` and `callWithErrorOnlyCallback`), because a | |
| 12072 | +// caller can read `arguments.length` and see the difference. | |
| 12073 | +const __fsCallback = (validate, run, callback) => | |
| 12074 | + __fsDeliver(validate, run, callback, (result) => callback(null, result)); | |
| 12075 | +const __fsErrorOnlyCallback = (validate, run, callback) => | |
| 12076 | + __fsDeliver(validate, run, callback, () => callback(null)); | |
| 12077 | +// Node accepts `(path, callback)` or `(path, options, callback)` everywhere. | |
| 12078 | +const __fsCallbackArgs = (options, callback) => | |
| 12079 | + typeof options === "function" ? [undefined, options] : [options, callback]; | |
| 12080 | +const __fsAccess = (value, mode, callback) => { | |
| 12081 | + [mode, callback] = __fsCallbackArgs(mode, callback); | |
| 12082 | + __fsErrorOnlyCallback( | |
| 12083 | + () => { __fsPath(value); __fsMode(mode); }, | |
| 12084 | + () => __fsAccessSync(value, mode), | |
| 12085 | + callback, | |
| 12086 | + ); | |
| 12087 | +}; | |
| 12088 | +const __fsStat = (value, options, callback) => { | |
| 12089 | + [options, callback] = __fsCallbackArgs(options, callback); | |
| 12090 | + __fsCallback( | |
| 12091 | + () => { __fsPath(value); __fsOptions(options, ["bigint", "throwIfNoEntry"]); }, | |
| 12092 | + () => __fsStatSync(value, options), | |
| 12093 | + callback, | |
| 12094 | + ); | |
| 12095 | +}; | |
| 12096 | +const __fsLstat = (value, options, callback) => { | |
| 12097 | + [options, callback] = __fsCallbackArgs(options, callback); | |
| 12098 | + __fsCallback( | |
| 12099 | + () => { __fsPath(value); __fsOptions(options, ["bigint", "throwIfNoEntry"]); }, | |
| 12100 | + () => __fsLstatSync(value, options), | |
| 12101 | + callback, | |
| 12102 | + ); | |
| 12103 | +}; | |
| 12104 | +const __fsRealpath = (value, options, callback) => { | |
| 12105 | + [options, callback] = __fsCallbackArgs(options, callback); | |
| 12106 | + __fsCallback( | |
| 12107 | + () => __fsPath(value), | |
| 12108 | + () => __fsRealpathSync(value), | |
| 12109 | + callback, | |
| 12110 | + ); | |
| 12111 | +}; | |
| 12112 | +const __fsReadFile = (value, options, callback) => { | |
| 12113 | + [options, callback] = __fsCallbackArgs(options, callback); | |
| 12114 | + __fsCallback( | |
| 12115 | + () => __fsPath(value), | |
| 12116 | + () => __fsReadFileSync(value, options), | |
| 12117 | + callback, | |
| 12118 | + ); | |
| 12119 | +}; | |
| 12120 | +const __fsMkdir = (value, options, callback) => { | |
| 12121 | + [options, callback] = __fsCallbackArgs(options, callback); | |
| 12122 | + __fsCallback( | |
| 12123 | + () => { | |
| 12124 | + __fsPath(value); | |
| 12125 | + // A number is the mode, which `mkdirSync` validates but does not apply. | |
| 12126 | + if (typeof options !== "number") __fsOptions(options, ["recursive"]); | |
| 12127 | + }, | |
| 12128 | + () => __fsMkdirSync(value, options), | |
| 12129 | + callback, | |
| 12130 | + ); | |
| 12131 | +}; | |
| 12132 | +const __fsPromisesSurface = { | |
| 12133 | + // The promise form validates inside the promise, so an argument error | |
| 12134 | + // rejects instead of throwing. Workerd makes the same split, because a | |
| 12135 | + // caller of a promise API has no synchronous frame to catch. | |
| 12136 | + async access(...args) { return __fsAccessSync(...args); }, | |
| 12137 | + async mkdir(...args) { return __fsMkdirSync(...args); }, | |
| 12138 | + async stat(...args) { return __fsStatSync(...args); }, | |
| 12139 | + async lstat(...args) { return __fsLstatSync(...args); }, | |
| 12140 | + async realpath(...args) { return __fsRealpathSync(...args); }, | |
| 12141 | + async readFile(...args) { return __fsReadFileSync(...args); }, | |
| 12142 | +}; | |
| 12143 | +// A namespace import gets a fixed export set when V8 links the module, so a | |
| 12144 | +// partial module must enumerate unsupported Node exports too. A get trap alone | |
| 12145 | +// keeps default and named imports loud but silently omits these names from a | |
| 12146 | +// namespace. Keep the unsupported names lazy: materializing every stub in | |
| 12147 | +// every isolate would charge Workers that use only the implemented subset. | |
| 12148 | +const __fsNamespaceProxy = (surface, path, names, enoentNames = []) => { | |
| 12149 | + const namespaceNames = new Set([...Reflect.ownKeys(surface), ...names]); | |
| 12150 | + const enoentNameSet = new Set(enoentNames); | |
| 12151 | + return new Proxy(surface, { | |
| 12152 | + get: (target, p) => { | |
| 12153 | + if (Reflect.has(target, p)) return Reflect.get(target, p); | |
| 12154 | + if (enoentNameSet.has(p)) return __enoent; | |
| 12155 | + if (typeof p !== "string") return undefined; | |
| 12156 | + return __nodeStubFor(path + "." + p); | |
| 12157 | + }, | |
| 12158 | + ownKeys: () => [...namespaceNames], | |
| 12159 | + getOwnPropertyDescriptor: (target, p) => | |
| 12160 | + Reflect.getOwnPropertyDescriptor(target, p) ?? | |
| 12161 | + (namespaceNames.has(p) | |
| 12162 | + ? { configurable: true, enumerable: true } | |
| 12163 | + : undefined), | |
| 12164 | + }); | |
| 12165 | +}; | |
| 12166 | +const __fsPromises = __celld.__fsPromises = __fsNamespaceProxy( | |
| 12167 | + __fsPromisesSurface, | |
| 12168 | + "node:fs/promises", | |
| 12169 | + [ | |
| 12170 | + "appendFile", "chmod", "chown", "copyFile", "cp", "lchmod", "lchown", | |
| 12171 | + "link", "lutimes", "mkdtemp", "open", "opendir", "readdir", "readlink", | |
| 12172 | + "rename", "rm", "rmdir", "statfs", "symlink", "truncate", "unlink", | |
| 12173 | + "utimes", "watch", "writeFile", | |
| 12174 | + ], | |
| 12175 | +); | |
| 12176 | +const __fsSurface = { | |
| 12177 | + Stats: __FsStats, | |
| 12178 | + constants: __fsConstants, | |
| 12179 | + promises: __fsPromises, | |
| 12180 | + accessSync: __fsAccessSync, | |
| 12181 | + access: __fsAccess, | |
| 12182 | + existsSync: __fsExistsSync, | |
| 12183 | + mkdirSync: __fsMkdirSync, | |
| 12184 | + statSync: __fsStatSync, | |
| 12185 | + lstatSync: __fsLstatSync, | |
| 12186 | + realpathSync: __fsRealpathSync, | |
| 12187 | + readFileSync: __fsReadFileSync, | |
| 12188 | + stat: __fsStat, | |
| 12189 | + lstat: __fsLstat, | |
| 12190 | + realpath: __fsRealpath, | |
| 12191 | + readFile: __fsReadFile, | |
| 12192 | + mkdir: __fsMkdir, | |
| 12193 | +}; | |
| 12194 | +const __fsNamespaceNames = [ | |
| 12195 | + "Dir", "Dirent", "ReadStream", "WriteStream", "_toUnixTimestamp", | |
| 12196 | + "appendFile", "appendFileSync", "chmod", "chmodSync", "chown", "chownSync", | |
| 12197 | + "close", "closeSync", "copyFile", "copyFileSync", "cp", "cpSync", | |
| 12198 | + "createReadStream", "createWriteStream", "exists", "fchmod", "fchmodSync", | |
| 12199 | + "fchown", "fchownSync", "fdatasync", "fdatasyncSync", "fstat", "fstatSync", | |
| 12200 | + "fsync", "fsyncSync", "ftruncate", "ftruncateSync", "futimes", "futimesSync", | |
| 12201 | + "lchmod", "lchmodSync", "lchown", "lchownSync", "link", "linkSync", | |
| 12202 | + "lutimes", "lutimesSync", "mkdtemp", "mkdtempSync", "open", "openSync", | |
| 12203 | + "opendir", "opendirSync", "read", "readSync", "readdir", "readdirSync", | |
| 12204 | + "readlink", "readlinkSync", "readv", "readvSync", "rename", "renameSync", | |
| 12205 | + "rm", "rmSync", "rmdir", "rmdirSync", "statfs", "statfsSync", "symlink", | |
| 12206 | + "symlinkSync", "truncate", "truncateSync", "unlink", "unlinkSync", | |
| 12207 | + "unwatchFile", "utimes", "utimesSync", "watch", "watchFile", "write", | |
| 12208 | + "writeFile", "writeFileSync", "writeSync", "writev", "writevSync", | |
| 12209 | +]; | |
| 12210 | +// Writable file contents and every mutation remain explicit unsupported | |
| 12211 | +// surfaces until a failing application seam requires them. These two reads | |
| 12212 | +// use ENOENT so dependencies can take their no-filesystem fallback path. | |
| 12213 | +__celld.__fs = __fsNamespaceProxy( | |
| 12214 | + __fsSurface, | |
| 12215 | + "node:fs", | |
| 12216 | + __fsNamespaceNames, | |
| 12217 | + ["readdirSync", "readlinkSync"], | |
| 12218 | +); | |
| 12219 | +const __bridgeResponseStream = (body, requestControllers) => { | |
| 12220 | + const streamId = __response_stream_create(); | |
| 12221 | + const pump = (async () => { | |
| 12222 | + const reader = body.getReader(); | |
| 12223 | + const consumerClosed = __response_stream_closed(streamId) | |
| 12224 | + .then((status) => status === "cancelled" | |
| 12225 | + ? { consumerClosed: true } | |
| 12226 | + : new Promise(() => {})); | |
| 12227 | + const cancelProducer = async () => { | |
| 12228 | + const reason = new Error("The client has disconnected"); | |
| 12229 | + for (const controller of requestControllers || []) { | |
| 12230 | + if (!controller.signal.aborted) controller.abort(reason); | |
| 12231 | + } | |
| 12232 | + try { | |
| 12233 | + await reader.cancel(reason); | |
| 12234 | + } catch {} | |
| 12235 | + await __response_stream_close(streamId, ""); | |
| 12236 | + }; | |
| 12237 | + try { | |
| 12238 | + for (;;) { | |
| 12239 | + const result = await Promise.race([ | |
| 12240 | + reader.read().then((read) => ({ read })), | |
| 12241 | + consumerClosed, | |
| 12242 | + ]); | |
| 12243 | + if (result.consumerClosed) { | |
| 12244 | + await cancelProducer(); | |
| 12245 | + return; | |
| 12246 | + } | |
| 12247 | + if (result.read.done) { | |
| 12248 | + await __response_stream_close(streamId, ""); | |
| 12249 | + return; | |
| 12250 | + } | |
| 12251 | + const bytes = __bodyBytes(result.read.value); | |
| 12252 | + for (let offset = 0; offset < bytes.byteLength; offset += 64 * 1024) { | |
| 12253 | + await __response_stream_write( | |
| 12254 | + streamId, | |
| 12255 | + bytes.subarray(offset, offset + 64 * 1024), | |
| 12256 | + ); | |
| 12257 | + } | |
| 12258 | + } | |
| 12259 | + } catch (error) { | |
| 12260 | + if (String(error).includes("response stream consumer canceled")) { | |
| 12261 | + await cancelProducer(); | |
| 12262 | + return; | |
| 12263 | + } | |
| 12264 | + await __response_stream_close(streamId, String(error)); | |
| 12265 | + } | |
| 12266 | + })(); | |
| 12267 | + __registerWaitUntil(pump); | |
| 12268 | + return streamId; | |
| 12269 | +}; | |
| 12270 | +__celld.__readResponse = (r) => { | |
| 11259 | 12271 | if (!(r instanceof Response)) { |
| 11260 | 12272 | return { |
| 11261 | 12273 | status: 200, |
modifiedcrates/celld/js/headers.js+12−12View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/html_rewriter.js+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/identity_transform_stream.js+5−5View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/message_channel.js+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/modules.rs+348−165View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_assert.js+3−3View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_async_hooks.js+5−5View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_buffer.js+5−5View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_crypto.js+12−16View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_diagnostics_channel.js+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_events.js+2−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_os.js+2−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_path.js+2−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_stream.js+5−5View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_test.js+2−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_timers.js+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/node_util.js+11−11View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/r2_ops.rs+33−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/set_immediate.js+1−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/sockets.js+3−3View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/storage_ops.rs+163−20View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/streams.js+7−7View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/tcp.rs+29−8View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/text_encoding.js+6−6View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/url.js+5−5View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/url_pattern.js+2−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/url_search_params.js+5−5View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/v8_strings.rs+14−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/websocket.rs+28−10View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/writable_stream.js+9−9View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/lib.rs+44−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ltx_repl.rs+328−174View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main.rs+5469−5566View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/cli.rs+1−31View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/peer_tunnel.rs+60−32View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/websocket.rs+78−83View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/node_log.rs+5924−5711View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/node_log/recovery_progress.rs+8−1View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ownership_store.rs+1194−1104View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/pool.rs+602−633View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/protocol.rs+43−27View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/queue_batching.rs+43−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/replication.rs+46−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/runtime.rs+4143−3984View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/storage.rs+4548−4140View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/storage/wake_record.rs+105−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/telemetry.rs+863−872View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/wake.rs+657−420View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/wake_format.rs+194−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ws_client.rs+6−3View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/lib.rs+6538−6178View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/output_gate.rs+347−349View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/pressure.rs+35−21View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/rebalance.rs+10−5View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/schedule.rs+92−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/types.rs+1052−994View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/wake.rs+277−491View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/Cargo.toml+1−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/bundle.rs+136−75View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/file.rs+58−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/mod.rs+109−76View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/object_store.rs+459−393View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/compactor.rs+57−29View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/db.rs+2266−2188View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/host.rs+77−61View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica_compactor.rs+436−222View file
Diff not rendered to keep this page fast. View the file
modifieddocs/README.md+945−858View file
Diff not rendered to keep this page fast. View the file
modifieddocs/cloudflare-compat.md+472−494View file
Diff not rendered to keep this page fast. View the file
modifieddocs/guarantees.md+325−211View file
Diff not rendered to keep this page fast. View the file
modifieddocs/security.md+6−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/telemetry.md+140−126View file
Diff not rendered to keep this page fast. View the file
modifieddocs/wasm.md+23−0View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/README.md+5−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/container/Dockerfile+6−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/container/README.md+36−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/container/index.js+39−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/container/package.json+8−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/container/server.py+32−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/container/wrangler.jsonc+17−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/facets/README.md+21−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/facets/index.js+45−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/facets/wrangler.jsonc+10−0View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/opencode/README.md+1−1View file
Diff not rendered to keep this page fast. View the file
deletedexamples/opencode/package-lock.json+0−8679
Diff not rendered to keep this page fast. View the file
modifiedexamples/opencode/package.json+0−3View file
Diff not rendered to keep this page fast. View the file
deletedexamples/pi/.gitignore+0−1
Diff not rendered to keep this page fast. View the file
modifiedexamples/pi/README.md+27−26View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/pi/index.js+50−52View file
Diff not rendered to keep this page fast. View the file
deletedexamples/pi/package-lock.json+0−3011
Diff not rendered to keep this page fast. View the file
modifiedexamples/pi/package.json+0−3View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/pi/wrangler.jsonc+2−1View file
Diff not rendered to keep this page fast. View the file
addedexamples/sandbox/Dockerfile+5−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/sandbox/README.md+32−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/sandbox/index.js+46−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/sandbox/package.json+8−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/sandbox/wrangler.jsonc+18−0View file
Diff not rendered to keep this page fast. View the file